Пример #1
0
static void* command_thread(void* arg) {
    int fd;
    ssize_t n;
    char buf[STRING_BUFFER_SIZE];

    /* Almost endless loop */
    while(endProgram == 0) {

        /* wait for new command */
        fd = accept(fdSocket, NULL, NULL);
        if(fd == -1) {
            CO_error(0x15100000L);
        }

        /* Read command and send answer. */
        while((n = read(fd, buf, sizeof(buf)-1)) > 0) {
            buf[n++] = 0; /* terminate input string */
            command_process(fd, buf, n);
        }

        if(n == -1){
            CO_error(0x15800000L + errno);
        }

        /* close current communication */
        if(close(fd) == -1) {
            CO_error(0x15900000L);
        }
    }

    return NULL;
}
Пример #2
0
void
exec_no_wait(char *command, char *arg)
	{
	pid_t	pid;

	if (*command == '@')
		command_process(command + 1);
	else
		exec_command(command, arg, FALSE, &pid);
	}
Пример #3
0
/**@brief Function for application main entry.
 */
int main(void)
{
	
#ifdef OSSW_DEBUG
		init_uart();
#endif
	
	  spi_init();
	  ext_ram_init();
	  init_lcd_with_splash_screen();

		accel_init();
	
    // Initialize.
    timers_init();
		rtc_timer_init();
		buttons_init();
	  battery_init();
	
    // Initialize the SoftDevice handler module.
    SOFTDEVICE_HANDLER_INIT(NRF_CLOCK_LFCLKSRC_XTAL_20_PPM, NULL);
	
	  // splash screen
		nrf_delay_ms(500);
	
		fs_init();
		config_init();
		scr_mngr_init();
		vibration_init();
		notifications_init();
		
		stopwatch_init();
		timer_feature_init();
		
		mlcd_timers_init();
		
    // Enter main loop.
    for (;;)
    {
			  if (rtc_should_store_current_time()) {
					  rtc_store_current_time();
				}
				app_sched_execute();

				stopwatch_process();
				
				command_process();
				
				watchset_process_async_operation();
			  
				scr_mngr_draw_screen();
				
        power_manage();
    }
}
int main(int argc, char *argv[])
{
	int check;
	int SERVER_PORT = atoi(argv[2]);
	struct sockaddr_in ServAddr;

	//creating the socket
	sockfd=socket(AF_INET,SOCK_STREAM,0); //socket(internet_family,socket_type,protocol_value) retruns socket descriptor
	if(sockfd<0)	
	{
		perror("Cannot create socket!");
		return 0;
	}

	//bzero(&ServAddr,sizeof(ServAddr)); //writes n no. of null nbytes to specified location
	
	//initializing the server socket
	ServAddr.sin_family=AF_INET;
	ServAddr.sin_addr.s_addr = inet_addr(arg[1]); //using the imput IP 
	ServAddr.sin_port = htons(SERVER_PORT); //self defined server port

	if((connect(sockfd,(struct sockaddr *) &ServAddr,sizeof(ServAddr)))<0)
	{
		perror("Server is down!");
		return 0;
	}

	signal(SIGINT,signal_handler);

	printf("\n connection is established :\n ");

	while(1)
	{
		
		check=command_process(sockfd);
		if(check<0)
		{
			printf("client closing socket!..exiting!\n");
			close(sockfd);
			exit(0);
		}
		else if(check==1)
		{
			close(sockfd);
			exit(0);
		}
	}

	return 0;
}
Пример #5
0
void ble_rpc_cmd_handle(void * p_event_data, uint16_t event_size)
{
    uint32_t  err_code;
    uint32_t  rpc_cmd_length_read;
    uint8_t * p_rpc_cmd_buffer;

    err_code = hci_transport_rx_pkt_extract(&p_rpc_cmd_buffer, &rpc_cmd_length_read);
    APP_ERROR_CHECK(err_code);

    err_code = command_process(&p_rpc_cmd_buffer[RPC_CMD_RESP_OP_CODE_POS], rpc_cmd_length_read);
    APP_ERROR_CHECK(err_code);

    err_code = hci_transport_rx_pkt_consume(p_rpc_cmd_buffer);
    APP_ERROR_CHECK(err_code);
}
Пример #6
0
static enum command_return
client_process_command_list(struct client *client, bool list_ok, GSList *list)
{
    enum command_return ret = COMMAND_RETURN_OK;
    unsigned num = 0;

    for (GSList *cur = list; cur != NULL; cur = g_slist_next(cur)) {
        char *cmd = cur->data;

        g_debug("command_process_list: process command \"%s\"",
        cmd);
        ret = command_process(client, num++, cmd);
        g_debug("command_process_list: command returned %i", ret);
        if (ret != COMMAND_RETURN_OK || client_is_expired(client))
            break;
        else if (list_ok)
            client_puts(client, "list_OK\n");
    }

    return ret;
}
Пример #7
0
static bool input_process(void* context) {
	/* Start CLI & packet processing */
	Manager* manager = get_manager();

	struct timeval tv;
	tv.tv_sec = 0;
	tv.tv_usec = 0;

	fd_set temp = manager->read_fds;
	int ret = select(manager->nfds, &temp, NULL, NULL, &tv); 

	if(ret == -1) {
		perror("Selector error");
		return false;
	} else if(ret) {
		for(int i = 0; i < manager->fd_count; i++) {
			int fd = (int64_t)list_get(manager->fds, i);

			if(FD_ISSET(fd, &temp) != 0) {
				if(fd == STDIN_FILENO) {
					/* Process input command */
					command_process(fd);
				} else {
					/* Process input packet */
					Packet* packet = (Packet*)malloc(sizeof(Packet) + PACKET_BUF_SIZE);
					int size = read(fd, packet->buffer, PACKET_BUF_SIZE); 

					packet->start = 0;
					packet->end = packet->start + size;
					
					// NOTE: fd is same as network interface index.	
					EndPointPort* port = manager->nis[fd]->port;
					network_process(port, packet);
				}
			}
		}
	} 

	return true;
}
Пример #8
0
enum command_return
client_process_line(struct client *client, char *line)
{
    enum command_return ret;

    if (strcmp(line, "noidle") == 0) {
        if (client->idle_waiting) {
            /* send empty idle response and leave idle mode */
            client->idle_waiting = false;
            command_success(client);
            client_write_output(client);
        }

        /* do nothing if the client wasn't idling: the client
           has already received the full idle response from
           client_idle_notify(), which he can now evaluate */

        return COMMAND_RETURN_OK;
    } else if (client->idle_waiting) {
        /* during idle mode, clients must not send anything
           except "noidle" */
        g_warning("[%u] command \"%s\" during idle",
                  client->num, line);
        return COMMAND_RETURN_CLOSE;
    }

    if (client->cmd_list_OK >= 0) {
        if (strcmp(line, CLIENT_LIST_MODE_END) == 0) {
            g_debug("[%u] process command list",
                    client->num);

            /* for scalability reasons, we have prepended
               each new command; now we have to reverse it
               to restore the correct order */
            client->cmd_list = g_slist_reverse(client->cmd_list);

            ret = client_process_command_list(client,
                                              client->cmd_list_OK,
                                              client->cmd_list);
            g_debug("[%u] process command "
                    "list returned %i", client->num, ret);

            if (ret == COMMAND_RETURN_CLOSE ||
                    client_is_expired(client))
                return COMMAND_RETURN_CLOSE;

            if (ret == COMMAND_RETURN_OK)
                command_success(client);

            client_write_output(client);
            free_cmd_list(client->cmd_list);
            client->cmd_list = NULL;
            client->cmd_list_OK = -1;
        } else {
            size_t len = strlen(line) + 1;
            client->cmd_list_size += len;
            if (client->cmd_list_size >
                    client_max_command_list_size) {
                g_warning("[%u] command list size (%lu) "
                          "is larger than the max (%lu)",
                          client->num,
                          (unsigned long)client->cmd_list_size,
                          (unsigned long)client_max_command_list_size);
                return COMMAND_RETURN_CLOSE;
            }

            new_cmd_list_ptr(client, line);
            ret = COMMAND_RETURN_OK;
        }
    } else {
        if (strcmp(line, CLIENT_LIST_MODE_BEGIN) == 0) {
            client->cmd_list_OK = 0;
            ret = COMMAND_RETURN_OK;
        } else if (strcmp(line, CLIENT_LIST_OK_MODE_BEGIN) == 0) {
            client->cmd_list_OK = 1;
            ret = COMMAND_RETURN_OK;
        } else {
            g_debug("[%u] process command \"%s\"",
            client->num, line);
            ret = command_process(client, 0, line);
            g_debug("[%u] command returned %i",
            client->num, ret);

            if (ret == COMMAND_RETURN_CLOSE ||
            client_is_expired(client))
                return COMMAND_RETURN_CLOSE;

            if (ret == COMMAND_RETURN_OK)
                command_success(client);

            client_write_output(client);
        }
    }

    return ret;
}
Пример #9
0
void
event_process(void)
	{
	Event		*event;
	AtCommand	*at;
	SList	*list,
			*prev_link = NULL,
			*next_link,
			*expired_link,
			tmp_link;
	int		minute_tick, five_minute_tick, ten_minute_tick,
			fifteen_minute_tick, thirty_minute_tick, hour_tick, day_tick;
	struct tm		*tm_now;
	static struct tm tm_prev;
	static time_t	t_prev;

	time(&pikrellcam.t_now);
	pikrellcam.second_tick = (pikrellcam.t_now == t_prev) ? FALSE : TRUE;
	t_prev = pikrellcam.t_now;

	if (pikrellcam.second_tick)
		{
		tm_prev = pikrellcam.tm_local;
		tm_now = localtime(&pikrellcam.t_now);
		minute_tick = (tm_now->tm_min != tm_prev.tm_min)  ? TRUE : FALSE;
		pikrellcam.tm_local = *tm_now;
		}
	else
		minute_tick = FALSE;

	if (pikrellcam.state_modified || minute_tick)
		{
		pikrellcam.state_modified = FALSE;
		state_file_write();
		}

	tmp_link.next = NULL;
	for (list = event_list; list; prev_link = list, list = list->next)
		{
		/* Event loop processing is done with the list unlocked until we
		|  have an expired link that must be removed from the list so that
		|  called event functions cad add events to the list.
		|  If another thread adds an event, only the last list->next
		|  will be modified and this loop will catch it or it won't.
		*/
		event = (Event *) list->data;
		if (   (event->time == 0 && event->count == 0)
			|| event->func == NULL
		   )				/* not activated */
			continue;

		if (event->time > 0 && event->time > pikrellcam.t_now)
			continue;
		else if (event->count > 0 && --event->count > 0)
			continue;

		if (pikrellcam.verbose)
			printf("Event func -> [%s] period=%d\n",
						event->name, (int) event->period);
		if (event->func)
			(*event->func)(event->data);
		if (event->period > 0)
			event->time += event->period;
		else
			{
			pthread_mutex_lock(&event_mutex);
			expired_link = list;
			if (list == event_list)
				{
				event_list = list->next;
				tmp_link.next = list->next;
				list = &tmp_link;
				}
			else
				{
				next_link = list->next;
				list = prev_link;
				list->next = next_link;
				}
			free(expired_link->data);
			free(expired_link);
			pthread_mutex_unlock(&event_mutex);
			}
		}

	if (minute_tick)
		{
		char		*p, buf[IBUF_LEN];
		int			i, n, minute_now, minute_at, minute_offset = 0;
		static int	start = TRUE;
		static int	at_notify_fd, at_notify_wd;
		struct inotify_event *event;

		if (at_notify_fd == 0)
			{
			at_notify_fd = inotify_init();
			if (at_notify_fd > 0)
				{
				fcntl(at_notify_fd, F_SETFL,
						fcntl(at_notify_fd, F_GETFL) | O_NONBLOCK);
				at_notify_wd = inotify_add_watch(at_notify_fd,
						pikrellcam.config_dir, IN_CREATE | IN_MODIFY);
				}
			}
		else if (at_notify_wd > 0)
			{
			n = read(at_notify_fd, buf, IBUF_LEN);
			if (n > 0)
				{
				for (i = 0; i < n; i += sizeof(*event) + event->len)
					{
					event = (struct inotify_event *) &buf[i];
					if (   event->len > 0
					    && !strcmp(event->name,  PIKRELLCAM_AT_COMMANDS_CONFIG)
					   )
						at_commands_config_load(pikrellcam.at_commands_config_file);
					}
				}
			}

		tm_now = &pikrellcam.tm_local;
		minute_now = tm_now->tm_hour * 60 + tm_now->tm_min;

		five_minute_tick = ((tm_now->tm_min % 5) == 0) ? TRUE : FALSE;
		ten_minute_tick = ((tm_now->tm_min % 10) == 0) ? TRUE : FALSE;
		fifteen_minute_tick = ((tm_now->tm_min % 15) == 0) ? TRUE : FALSE;
		thirty_minute_tick = ((tm_now->tm_min % 10) == 0) ? TRUE : FALSE;
		hour_tick = (tm_now->tm_hour  != tm_prev.tm_hour)  ? TRUE : FALSE;
		day_tick =  (tm_now->tm_mday  != tm_prev.tm_mday)  ? TRUE : FALSE;

		if (day_tick || !sun.initialized)
			{
			if (sun.initialized)
				{
				char	tbuf[32];

				log_printf_no_timestamp("\n========================================================\n");
				strftime(tbuf, sizeof(tbuf), "%F", localtime(&pikrellcam.t_now));
				log_printf_no_timestamp("%s ================== New Day ==================\n", tbuf);
				log_printf_no_timestamp("========================================================\n");

				strftime(tbuf, sizeof(tbuf), "%F", localtime(&pikrellcam.t_now));
				}
			sun_times_init();
			sun.initialized = TRUE;
			log_lines();
			state_file_write();
			}

		for (list = at_command_list; list; list = list->next)
			{
			at = (AtCommand *) list->data;

			if ((p = strchr(at->at_time, '+')) != NULL)
				minute_offset = atoi(p + 1);
			else if ((p = strchr(at->at_time, '-')) != NULL)
				minute_offset = -atoi(p + 1);

			if (!strcmp(at->at_time, "start"))
				minute_at = start ? minute_now : 0;
			else if (!strcmp(at->at_time, "minute"))
				minute_at = minute_now;
			else if (!strcmp(at->at_time, "5minute"))
				minute_at = five_minute_tick ? minute_now : 0;
			else if (!strcmp(at->at_time, "10minute"))
				minute_at = ten_minute_tick ? minute_now : 0;
			else if (!strcmp(at->at_time, "15minute"))
				minute_at = fifteen_minute_tick ? minute_now : 0;
			else if (!strcmp(at->at_time, "30minute"))
				minute_at = thirty_minute_tick ? minute_now : 0;
			else if (!strcmp(at->at_time, "hour"))
				minute_at = hour_tick ? minute_now : 0;
			else if (!strncmp(at->at_time, "dawn", 4))
				minute_at = sun.dawn + minute_offset;
			else if (!strncmp(at->at_time, "dusk", 4))
				minute_at = sun.dusk + minute_offset;
			else if (!strncmp(at->at_time, "sunrise", 7))
				minute_at = sun.sunrise + minute_offset;
			else if (!strncmp(at->at_time, "sunset", 6))
				minute_at = sun.sunset + minute_offset;
			else if (!strncmp(at->at_time, "nautical_dawn", 13))
				minute_at = sun.nautical_dawn + minute_offset;
			else if (!strncmp(at->at_time, "nautical_dusk", 13))
				minute_at = sun.nautical_dusk + minute_offset;
			else
				{
				minute_at = (int) strtol(at->at_time, &p, 10) * 60;
				if (*p == ':')
					minute_at += strtol(p + 1, NULL, 10);
				else
					{
					minute_at = 0;	/* error in at_time string */
					log_printf("Error in at_command: [%s] bad at_time: [%s]\n",
							at->command, at->at_time);
					}
				}
			if (minute_now != minute_at)
				continue;

			/* Have a time match so check frequency.
			*/
			if (   !strcmp(at->frequency, "daily")
			    || (   !strcmp(at->frequency, "Sat-Sun")
			        && (tm_now->tm_wday == 0 || tm_now->tm_wday == 6)
			       )
			    || (   !strcmp(at->frequency, "Mon-Fri")
			        && tm_now->tm_wday > 0 && tm_now->tm_wday < 6
			       )
			    || (   (p = strstr(weekdays, at->frequency)) != NULL
			        && (p - weekdays) / 3 == tm_now->tm_wday
			       )
			   )
				{
				if (*(at->command) == '@')
					command_process(at->command + 1);
				else
					exec_no_wait(at->command, NULL);
				}
			}
		start = FALSE;
		if (pikrellcam.config_modified)
			config_save(pikrellcam.config_file);
		}
	}
Пример #10
0
int
main(int argc, char *argv[])
	{
	int		fifo;
	int	 	i, n;
	char	*opt, *arg, *equal_arg, *homedir, *user;
	char	*line, *eol, buf[4096];

	pgm_name = argv[0];
	bcm_host_init();
	time(&pikrellcam.t_now);

	config_set_defaults();

	for (i = 1; i < argc; i++)
		get_arg_pass1(argv[i]);

	if (!config_load(pikrellcam.config_file))
		config_save(pikrellcam.config_file);
	if (!motion_regions_config_load(pikrellcam.motion_regions_config_file))
		motion_regions_config_save(pikrellcam.motion_regions_config_file);
	if (!at_commands_config_load(pikrellcam.at_commands_config_file))
		at_commands_config_save(pikrellcam.at_commands_config_file);

	for (i = 1; i < argc; i++)
		{
		if (get_arg_pass1(argv[i]))
			continue;
		opt = argv[i];

		/* Just for initial install-pikrellcam.sh run to create config files.
		*/
		if (!strcmp(opt, "-quit"))
			exit(0);

		/* Accept: --opt arg   -opt arg    opt=arg    --opt=arg    -opt=arg
		*/
		for (i = 0; i < 2; ++i)
			if (*opt == '-')
				++opt;
		if ((equal_arg = strchr(opt, '=')) != NULL)
			{
			*equal_arg++ = '\0';
			arg = equal_arg;
			++i;
			}
		else
			arg = argv[i + 1];

		/* For camera parameters, do not set the camera, only replace
		|  values in the parameter table.
		*/
		if (   !config_set_option(opt, arg, TRUE)
		    && !mmalcam_config_parameter_set(opt, arg, FALSE)
		   )
			{
			log_printf("Bad arg: %s\n", opt);
			exit(1);
			}
		}

	homedir = getpwuid(geteuid())->pw_dir;
	user = strrchr(homedir, '/');
	pikrellcam.effective_user = strdup(user ? user + 1 : "pi");

	if (*pikrellcam.log_file != '/')
		{
		snprintf(buf, sizeof(buf), "%s/%s", pikrellcam.install_dir, pikrellcam.log_file);
		dup_string(&pikrellcam.log_file, buf);
		}
	if (*pikrellcam.media_dir != '/')
		{
		snprintf(buf, sizeof(buf), "%s/%s", pikrellcam.install_dir, pikrellcam.media_dir);
		dup_string(&pikrellcam.media_dir, buf);
		}
	strftime(buf, sizeof(buf), "%F %T", localtime(&pikrellcam.t_now));
	log_printf("\n%s ==== PiKrellCam started ====\n", buf);

	snprintf(buf, sizeof(buf), "%s/%s", pikrellcam.install_dir, "www");
	check_modes(buf, 0775);

	asprintf(&pikrellcam.command_fifo, "%s/www/FIFO", pikrellcam.install_dir);
	asprintf(&pikrellcam.script_dir, "%s/scripts", pikrellcam.install_dir);
	asprintf(&pikrellcam.mjpeg_filename, "%s/mjpeg.jpg", pikrellcam.mjpeg_dir);

	log_printf("using FIFO: %s\n", pikrellcam.command_fifo);
	log_printf("using mjpeg: %s\n", pikrellcam.mjpeg_filename);


	/* Subdirs must match www/config.php and the init script is supposed
	|  to take care of that.
	*/
	asprintf(&pikrellcam.video_dir, "%s/%s", pikrellcam.media_dir, PIKRELLCAM_VIDEO_SUBDIR);
	asprintf(&pikrellcam.still_dir, "%s/%s", pikrellcam.media_dir, PIKRELLCAM_STILL_SUBDIR);
	asprintf(&pikrellcam.timelapse_dir, "%s/%s", pikrellcam.media_dir, PIKRELLCAM_TIMELAPSE_SUBDIR);

	if (!make_dir(pikrellcam.media_dir))
		exit(1);

	snprintf(buf, sizeof(buf), "%s/scripts-dist/init $I $m $M $P $G",
								pikrellcam.install_dir);
	exec_wait(buf, NULL);

	/* User may have enabled a mount disk on media_dir
	*/
	exec_wait(pikrellcam.on_startup_cmd, NULL);
	check_modes(pikrellcam.media_dir, 0775);

	if (   !make_dir(pikrellcam.mjpeg_dir)
	    || !make_dir(pikrellcam.video_dir)
	    || !make_dir(pikrellcam.still_dir)
	    || !make_dir(pikrellcam.timelapse_dir)
	    || !make_fifo(pikrellcam.command_fifo)
	   )
		exit(1);

	if ((fifo = open(pikrellcam.command_fifo, O_RDONLY | O_NONBLOCK)) < 0)
		{
		log_printf("Failed to open FIFO: %s.  %m\n", pikrellcam.command_fifo);
		exit(1);
		}

	fcntl(fifo, F_SETFL, 0);
	read(fifo, buf, sizeof(buf));
	
	sun_times_init();
	camera_start();
	config_timelapse_load_status();

	signal(SIGINT, signal_quit);
	signal(SIGTERM, signal_quit);
	signal(SIGCHLD, event_child_signal);

	while (1)
		{
		usleep(1000000 / EVENT_LOOP_FREQUENCY);
		event_process();

		/* Process lines in the FIFO.  Single lines via an echo "xxx" > FIFO
		|  or from a web page may not have a terminating \n.
		|  Local scripts may dump multiple \n terminated lines into the FIFO.
		*/
		if ((n = read(fifo, buf, sizeof(buf) - 2)) > 0)
			{
			if (buf[n - 1] != '\n')
				buf[n++] = '\n';	/* ensures all lines in buf end in \n */
			buf[n] = '\0';
			line = buf;
			eol = strchr(line, '\n');

			while (eol > line)
				{
				*eol++ = '\0';
				command_process(line);
				while (*eol == '\n')
					++eol;
				line = eol;
				eol = strchr(line, '\n');
				}
			}
		}
	return 0;
	}
Пример #11
0
static void *command_thread_func(void *ptr)
{
    //{{{
	video_param_t vParm;
	audio_param_t aParm;
	char strVersion[64] = {0};
	char command_buffer[256] = {0};
	int ch = 0;
	int command_buffer_idx = 0;
	int command_op = 0;
	int value = 0;

	while(1)
	{
		memset(command_buffer, 0, 256); //command buffer clear
		command_buffer_idx = 0; 

		while ( (ch = getchar()) != 0x0a ) //enter key
		{
      		command_buffer[command_buffer_idx++] = ch;
			usleep(1000);
		}	
		
		command_op = command_process(command_buffer);

		switch(command_op)
		{
			case COMMAND_VIDEO_START:
				if ( jpegout == NULL )
					jpegout = fopen("result.mjpg", "wb");
				if ( h264out == NULL )
					h264out = fopen("result.h264", "wb");
				h264cnt = 0;
				h264bps = 0;
				jpegcnt = 0;
				jpegbps = 0; //kik+

				vParm.res_width = 640;
				vParm.res_height = 320;
				vParm.jpeg_quality = 80;
				vParm.isFlipEnable = 0;
				vParm.isAvataCaptureMode = 0;
				vParm.jpeg_fps_level = JPEG_FPS_LEVEL_15;
				vParm.qp = 29;
				vParm.maxbitrate = 1500 * 1024;
				vParm.iframeinterval = 0;
				isH264First = 1;
				redwood_video_start(&vParm); 
				break;
			case COMMAND_VIDEO_START_VGA:

				if ( jpegout == NULL )
					jpegout = fopen("result.mjpg", "wb");
				if ( h264out == NULL )
					h264out = fopen("result.h264", "wb");
				h264cnt = 0;
				h264bps = 0;
				jpegcnt = 0;
				jpegbps = 0; //kik+

				vParm.res_width = 640;
//				vParm.res_height = 320;
				vParm.res_height = 480;
				vParm.jpeg_quality = 80;
				vParm.isFlipEnable = 0;
				vParm.isAvataCaptureMode = 0;
//				vParm.jpeg_fps_level = JPEG_FPS_LEVEL_6;
				vParm.jpeg_fps_level = JPEG_FPS_LEVEL_15;
				vParm.qp = 39;
//				vParm.maxbitrate = 1300 * 1024;
				vParm.maxbitrate = 2000 * 1024;
				vParm.iframeinterval = 0;
				isH264First = 1;

			//	redwood_framerate_set(30);
				redwood_framerate_set(40);
				redwood_bitrate_set(1500*1024);

				redwood_video_start(&vParm); 
				break;
			case COMMAND_VIDEO_START_QVGA:

				if ( jpegout == NULL )
					jpegout = fopen("result.mjpg", "wb");
				if ( h264out == NULL )
					h264out = fopen("result.h264", "wb");
				h264cnt = 0;
				h264bps = 0;
				jpegcnt = 0;
				jpegbps = 0; //kik+

				vParm.res_width = 320;
				vParm.res_height = 240;
				vParm.jpeg_quality = 80;
				vParm.isFlipEnable = 0;
				vParm.isAvataCaptureMode = 0;
				vParm.jpeg_fps_level = JPEG_FPS_LEVEL_15;
				vParm.qp = 29;
				vParm.maxbitrate = 1500 * 1024;
				vParm.iframeinterval = 0;
				isH264First = 1;
				redwood_video_start(&vParm); 
				break;
			case COMMAND_VIDEO_START_QQVGA:

				if ( jpegout == NULL )
					jpegout = fopen("result.mjpg", "wb");
				if ( h264out == NULL )
					h264out = fopen("result.h264", "wb");
				h264cnt = 0;
				h264bps = 0;
				jpegcnt = 0;
				jpegbps = 0; //kik+

				vParm.res_width = 160;
				vParm.res_height = 120;
				vParm.jpeg_quality = 80;
				vParm.isFlipEnable = 0;
				vParm.isAvataCaptureMode = 0;
				vParm.jpeg_fps_level = JPEG_FPS_LEVEL_15;
				vParm.qp = 29;
				vParm.maxbitrate = 1500 * 1024;
				vParm.iframeinterval = 0;
				isH264First = 1;
				redwood_video_start(&vParm); 
				break;
			case COMMAND_VIDEO_START_HD:

				if ( jpegout == NULL )
					jpegout = fopen("result.mjpg", "wb");
				if ( h264out == NULL )
					h264out = fopen("result.h264", "wb");
				h264cnt = 0;
				h264bps = 0;
				jpegcnt = 0;
				jpegbps = 0; //kik+

				vParm.res_width = 1280;
				vParm.res_height = 720;
				vParm.jpeg_quality = 80;
				vParm.isFlipEnable = 0;
				vParm.isAvataCaptureMode = 0;
				vParm.jpeg_fps_level = JPEG_FPS_LEVEL_15;
				vParm.qp = 29;
				vParm.maxbitrate = 1500 * 1024;
				vParm.iframeinterval = 0;
				isH264First = 1;
				redwood_video_start(&vParm); 
				break;

			case COMMAND_VIDEO_STOP:
				redwood_video_stop(); 
				if ( jpegout )
				{
					fclose(jpegout);
					jpegout = NULL;
				}
				if ( h264out )
				{
					fclose(h264out);
					h264out = NULL;
				}
				break;
			case COMMAND_AUDIO_START:
				if ( pcmout == NULL )
					pcmout = fopen("result.pcm", "wb");
				pcmcnt = 0;
				aParm.audio_freq_type = AUDIO_FREQ_16KHZ;
				redwood_audio_start(&aParm); 
				break;
			case COMMAND_AUDIO_START_12KHZ:
				if ( pcmout == NULL )
					pcmout = fopen("result.pcm", "wb");
				pcmcnt = 0;
				aParm.audio_freq_type = AUDIO_FREQ_12KHZ;
				redwood_audio_start(&aParm); 
				break;
			case COMMAND_AUDIO_START_16KHZ:
				if ( pcmout == NULL )
					pcmout = fopen("result.pcm", "wb");
				pcmcnt = 0;
				aParm.audio_freq_type = AUDIO_FREQ_16KHZ;
				redwood_audio_start(&aParm); 
				break;
			case COMMAND_AUDIO_AGC_GAIN:
				redwood_agc_gain_set(0xD3, 0x24, 0xC1, 0xD3, 0x24, 0xC1); 
				printf("AGC gain\n");
				break;
			case COMMAND_AUDIO_STOP:
				redwood_audio_stop(); 
				if ( pcmout )
				{
					fclose( pcmout);
					pcmout = NULL;
				}
				pcmcnt = 0;
				break;
			case COMMAND_AVATA_START:
				if ( jpegout == NULL )
					jpegout = fopen("result.mjpg", "wb");
				if ( h264out == NULL )
					h264out = fopen("result.h264", "wb");
				h264cnt = 0;
				h264bps = 0;
				jpegcnt = 0;
				jpegbps = 0; //kik+
				vParm.res_width = 240;
				vParm.res_height = 240;
				vParm.jpeg_quality = 80;
				vParm.isFlipEnable = 0;
				vParm.isAvataCaptureMode = 1;
				vParm.jpeg_fps_level = JPEG_FPS_LEVEL_15;
				vParm.qp = 29;
				vParm.maxbitrate = 1500 * 1024;
				vParm.iframeinterval = 0;
				redwood_video_start(&vParm); 
				break;
			case COMMAND_ZOOM0:
				redwood_video_zoom_set(0);
				break;
			case COMMAND_ZOOM1:
				redwood_video_zoom_set(1);
				break;
			case COMMAND_ZOOM2:
				redwood_video_zoom_set(2);
				break;
			case COMMAND_ZOOM3:
				redwood_video_zoom_set(3);
				break;
			case COMMAND_CON0:
				redwood_video_contrast_set(0);
				break;
			case COMMAND_CON10:
				redwood_video_contrast_set(10);
				break;
			case COMMAND_BRI:
				value = getArgument();
				printf("Brightness argument : %d\n", value); 
				redwood_video_brightness_set(value);
				break;
			case COMMAND_WHI:
				value = getArgument();
				printf("White Balance argument : %d\n", value); 
				redwood_video_white_balance_set(value);
				break;
			case COMMAND_EXP:
				value = getArgument();
				printf("Exposure argument : %d\n", value); 
				redwood_video_exposure_set(value);
				break;
			case COMMAND_BRI0:
				redwood_video_brightness_set(0);
				break;
			case COMMAND_BRI10:
				redwood_video_brightness_set(10);
				break;
			case COMMAND_SAT0:
				redwood_video_saturation_set(0);
				break;
			case COMMAND_SAT10:
				redwood_video_saturation_set(10);
				break;
			case COMMAND_SHA:
				value = getArgument();
				printf("Sharpness argument : %d\n", value); 
				redwood_video_sharpness_set(value);
				break;
			case COMMAND_HUE0:
				redwood_video_hue_set(0);
				break;
			case COMMAND_HUE10:
				redwood_video_hue_set(10);
				break;
			case COMMAND_GAM0:
				redwood_video_gamma_set(0);
				break;
			case COMMAND_GAM10:
				redwood_video_gamma_set(10);
				break;
			case COMMAND_FW_UP:
				redwood_firmware_upgrade("./romfile");
                printf("FW_UP_FINISHED\n");
				break;
			case COMMAND_VIDEO_KEY_FRAME_REQUEST:
				redwood_keyframe_request();
				break;
			case COMMAND_VIDEO_FRAMERATE:
				value = getArgument();
				printf("Framerate  : %d fps\n", value); 
				redwood_framerate_set(value);
				break;
			case COMMAND_VIDEO_KEY_BITRATE:
				value = getArgument();
				printf("Bitrate  : %dkbps\n", value); 
				redwood_bitrate_set(value*1024);
				break;
			case COMMAND_FIRMWARE_VERSION_CHECK:
				redwood_firmware_version_check(strVersion);
				printf("FW Ver. : %s\n", strVersion);
				break;
			case COMMAND_QUIT:
				break;
			case COMMAND_UNDEFINED:
			default:
				printf("Command Undefined : [%s]\n", command_buffer);
		}
		usleep(100000);
	}
    //}}}
}
Пример #12
0
void
do_command(globalstate *gstate)

{
    int status;
    struct timeval wait = {0, 0};
    struct timeval now;
    fd_set readfds;
    unsigned char ch;

    /* calculate new refresh time */
    gstate->refresh = gstate->now;
    gstate->refresh.tv_sec += gstate->delay;
    time_get(&now);

    /* loop waiting for time to expire */
    do {
	/* calculate time to wait */
	if (gstate->delay > 0)
	{
	    wait = gstate->refresh;
	    wait.tv_usec -= now.tv_usec;
	    if (wait.tv_usec < 0)
	    {
		wait.tv_usec += 1000000;
		wait.tv_sec--;
	    }
	    wait.tv_sec -= now.tv_sec;
	}

	/* set up arguments for select on stdin (0) */
	FD_ZERO(&readfds);
	FD_SET(STDIN_FILENO, &readfds);

	/* wait for something to read or time out */
	if (select(32, &readfds, NULL, NULL, &wait) > 0)
	{
	    /* read it */
	    if (read(STDIN_FILENO, &ch, 1) != 1)
	    {
		/* read error */
		message_error(" Read error on stdin");
		quit(EX_DATAERR);
		/*NOTREACHED*/
	    }

	    /* mark pending messages as old */
	    message_mark();

	    /* dispatch */
	    status = command_process(gstate, (int)ch);
	    switch(status)
	    {
	    case CMD_ERROR:
		quit(EX_SOFTWARE);
		/*NOTREACHED*/
		
	    case CMD_REFRESH:
		return;

	    case CMD_UNKNOWN:
		message_error(" Unknown command");
		break;

	    case CMD_NA:
		message_error(" Command not available");
	    }
	}

	/* get new time */
	time_get(&now);
    } while (timercmp(&now, &(gstate->refresh), < ));
}
Пример #13
0
int main ( int argc, char **argv )

{
	command_process ( argc, argv );
	return 0;
}
Пример #14
0
static void
handle_q_packet(char *packet, int len)
{
	uint32_t addr, alen;

	if(!strncmp(packet, "qRcmd,", 6)) {
		char *data;
		int datalen;

		/* calculate size and allocate buffer for command */
		datalen = (len - 6) / 2;
		data = alloca(datalen+1);
		/* dehexify command */
		unhexify(data, packet+6, datalen);
		data[datalen] = 0;	/* add terminating null */

		int c = command_process(cur_target, data);
		if(c < 0)
			gdb_putpacketz("");
		else if(c == 0)
			gdb_putpacketz("OK");
		else
			gdb_putpacketz("E");

	} else if (!strncmp (packet, "qSupported", 10)) {
		/* Query supported protocol features */
		gdb_putpacket_f("PacketSize=%X;qXfer:memory-map:read+;qXfer:features:read+", BUF_SIZE);

	} else if (strncmp (packet, "qXfer:memory-map:read::", 23) == 0) {
		/* Read target XML memory map */
		if((!cur_target) && last_target) {
			/* Attach to last target if detached. */
			cur_target = target_attach(last_target,
						gdb_target_destroy_callback);
		}
		if (!cur_target) {
			gdb_putpacketz("E01");
			return;
		}
		handle_q_string_reply(target_mem_map(cur_target), packet + 23);

	} else if (strncmp (packet, "qXfer:features:read:target.xml:", 31) == 0) {
		/* Read target description */
		if((!cur_target) && last_target) {
			/* Attach to last target if detached. */
			cur_target = target_attach(last_target,
						gdb_target_destroy_callback);
		}
		if (!cur_target) {
			gdb_putpacketz("E01");
			return;
		}
		handle_q_string_reply(target_tdesc(cur_target), packet + 31);
	} else if (sscanf(packet, "qCRC:%" PRIx32 ",%" PRIx32, &addr, &alen) == 2) {
		if(!cur_target) {
			gdb_putpacketz("E01");
			return;
		}
		gdb_putpacket_f("C%lx", generic_crc32(cur_target, addr, alen));

	} else {
		DEBUG("*** Unsupported packet: %s\n", packet);
		gdb_putpacket("", 0);
	}
}
Пример #15
0
/*
 *  Respond to commands requests and perform the commands:
 *  For a list of commands see command_process().
 *
 *  Will fork() for longer running operations such as fullcompare and quickcompare.
 *
 *  Will load all PPMs into RAM before listening for commands.
 *
 *  Args:
 *
 * orig_socketfh    : A file handle where text is sent, typically for any operational errors.
 * sql_info         : A string with SQL connection information.
 * portno           : Which network port to listen on.
 * compare_size     : The height (and width) of the PPMs.
 * maxerr           : For images to be considered similar the difference must be below this amount.
 *
 *  Return: non-zero on error.
 */
int server_loop(FILE *log_fh, char *sql_info, int portno, int compare_size,
		unsigned int maxerr) {

	if(is_already_running(log_fh, portno)){
		error(log_fh, "Quitting.");
		return 3;
	}

	// Setup IPv4 and/or IPv6 ports to listen on.
	// Ports below first_real_client_index are for listening for new connections.
	int first_real_client_index = 0;
	int listening_socket = create_port_listen_v4(log_fh, portno);
	if (listening_socket > 0) {
		global_client_detail[first_real_client_index].fd = listening_socket;
		first_real_client_index++;
	}

	// Setup a IPV6 network socket to listen on
	listening_socket = create_port_listen_v6(log_fh, portno);
	if (listening_socket > 0) {
		global_client_detail[first_real_client_index].fd = listening_socket;
		first_real_client_index++;
	}
	if (first_real_client_index == 0) {
		error(log_fh, "Failed to start listening on network. Quitting.");
		return 2;
	}
	// Done setting up IPv4 and/or IPv6 listening ports.

	// Connect to SQL database
	PGconn *psql = ppm_sql_connect(log_fh, sql_info);
	if (!psql) {
		error(log_fh,
				"libpq error: PQconnectdb returned NULL.\nSQL details: %s",
				sql_info);
		return 1;
	}

	// All PPMs in RAM. Loaded from SQL.
	PicInfo *picinfo_list = NULL;

	// Load all PPMs from SQL into RAM.
	int rc = load(log_fh, psql, &picinfo_list);
	if (rc) {
		error(log_fh, "LOAD failed with code %d", rc);
		ppm_sql_disconnect(log_fh, psql);
		return 1;
	}

	// Setup an array of incoming file descriptors.
	int index;
	for (index = first_real_client_index; index < CLIENT_MAX; index++) {
		global_client_detail[index].fd = CLIENT_SLOT_FREE;
		global_client_detail[index].command_buffer[0] = 0;
		global_client_detail[index].pid = 0;
		// TODO global_client_detail[index].connection_timeout = TODO ;
	}
	global_active_connection_count = first_real_client_index;

	// Listening Sockets have been created.
	int server_loop = 1;

	// Setup a timeout waiting for commands.
	// We time out so that we can reap children without needing to wait for commands.
	fd_set my_fd_set;
	struct timeval timeout;

	// listen for commands
	while (server_loop) {

		/* Initialize the file descriptor set we will block on. */
		FD_ZERO(&my_fd_set);

		// Setup FD set to block on. Also maximum FD.
		int fd_max = 0;
		for (index = 0; index < CLIENT_MAX; index++) {
			// Don't add closed FDs.
			if (global_client_detail[index].fd == CLIENT_SLOT_FREE)
				continue;
			// Stop listening for new connections if we have too many.
			if ((index < first_real_client_index)
					&& (global_active_connection_count >= CLIENT_MAX))
				continue;

			FD_SET(global_client_detail[index].fd, &my_fd_set);
			fd_max = max(fd_max, global_client_detail[index].fd);
		}

		/* Initialize the timeout data structure. */
		// We do timeout so we can do housekeeping without need to wait for client input to trigger the loop.
		timeout.tv_sec = COMMAND_LISTEN_TIMEOUT;
		timeout.tv_usec = 0;

		/* select() returns the count of FDs with waiting input, or -1 if error. */
		int fd_count_with_input = TEMP_FAILURE_RETRY(
				select(fd_max + 1, &my_fd_set, NULL, NULL, &timeout));
		if (fd_count_with_input < 0) {
			error(log_fh, "select() failed. errno=%d, error=%s", errno,
					strerror(errno));
			continue;
		}

		// Housekeeping
		// Reaper: Clean up any child processes which have exited.
		pid_t late_pid;
		while ((late_pid = waitpid(-1, NULL, WNOHANG)) > 0) {
			global_child_process_count--;
			// Find the late client by pid then record it as dead.
			for (index = first_real_client_index; index < CLIENT_MAX; index++){
				if ((global_client_detail[index].fd != CLIENT_SLOT_FREE)
						 && (global_client_detail[index].pid == late_pid)) {
					global_client_detail[index].pid = 0;
					break;
				}
			}
		}

		// Housekeeping
		// TODO check for any stale client connections
		// TODO add a mechanism so that we expire connections (other than socked for new v4 and v6)
		// if they wait too long to send data.
		// Don't expire connections if the server is the one that hasn't responded.

		// There was a select() timeout, no FDs with input available.
		if (fd_count_with_input == 0)
			continue;

		// Read data from FDs.
		for (index = 0; index < CLIENT_MAX; index++) {
			// Check for valid FD.
			if (global_client_detail[index].fd == CLIENT_SLOT_FREE)
				continue;
			// Check for waiting data on FD.
			int fd = global_client_detail[index].fd;
			if (!FD_ISSET(fd, &my_fd_set))
				continue;
			// We have a new IPv4 or IPv6 connection.
			if (index < first_real_client_index) {
				int new_sockfd = accept(fd, NULL, NULL);
				if (new_sockfd < 0) {
					error(log_fh, "accept()");
					continue;
				}
				int free_slot = first_real_client_index; // lower connections are for new IPv4 and IPv6 connections.
				for (; free_slot < CLIENT_MAX; free_slot++)
					if (global_client_detail[free_slot].fd == CLIENT_SLOT_FREE)
						break;
				// Are we are out of free slots?
				if (free_slot >= CLIENT_MAX) {
					error(log_fh,
							"Internal Error: we somehow got more connections than we can handle.");
					char *mesg = "BUSY: Please come back later";
					int write_rc = write(new_sockfd, mesg, strlen(mesg));
					if (write_rc == -1) {
						error(log_fh, "Failed to tell client to go away");
					}
					close(new_sockfd);
				}
				// Register new connection.
				else {
					global_client_detail[free_slot].fd = new_sockfd;
					global_client_detail[free_slot].pid = 0;
					bzero(global_client_detail[free_slot].command_buffer,
					BUFFER_SIZE);
					global_client_detail[free_slot].cmd_offset = 0;
					global_active_connection_count++;
					// TODO anything else?
					// TODO set timeout.
				}
			} else {
				// We have data on existing connection that needs to be read.
				int client_fd = global_client_detail[index].fd;
				char *cmd_buffer = global_client_detail[index].command_buffer;
				int cmd_offset = global_client_detail[index].cmd_offset;
				// Read data.
				int read_bytes = read(client_fd, &cmd_buffer[cmd_offset], BUFFER_SIZE - cmd_offset);
				if (read_bytes < 0) {
					// kill the connection as client has most likely gone away.
					error(log_fh,
							"Failed to read from client, closing the FD.");
					close(client_fd);
					global_client_detail[index].fd = CLIENT_SLOT_FREE;
					continue;
				}
				global_client_detail[index].cmd_offset += read_bytes;
				// TODO update timeout.
				// Check if a command has been completed.
				int command_end = strcspn(cmd_buffer, "\r\n");
				if (command_end > 0) {
					cmd_buffer[command_end] = 0; // Strip trailing LF, CR, CRLF, LFCR, ...
					command_process(client_fd, cmd_buffer, &picinfo_list, psql,
							&server_loop, compare_size, maxerr);
					close(client_fd);
					global_client_detail[index].fd = CLIENT_SLOT_FREE;
					global_active_connection_count--;
				}
			}
		}
	}
	if (picinfo_list) {
		unload(&picinfo_list);
	}

	// close all sockets, including for new IPv4 and IPv6 connections.
	for (index = 0; index < CLIENT_MAX; index++)
		if (global_client_detail[index].fd != CLIENT_SLOT_FREE)
			close(global_client_detail[index].fd);

	// End of server loop
	ppm_sql_disconnect(log_fh, psql);
	return 0;
}