int main(int argc, char **argv){
	int do_list_formats = 0;
	dev_name = "/dev/video0";
	int input = 100;
	int command = V4L2_CID_GAMMA;
	int doCommand = 0;
	imageName = "img.png";
	
	while(1){
		int index;
		int c;
		
		c = getopt_long(argc, argv, short_options, long_options, &index);
		
		if(-1 == c){
			break;
		}
		
		switch(c){
			case 0: /* getopt_long() flag */
				break;
			case 'd':
				dev_name = optarg;
				break;
			case 'h':
				usage(stdout, argc, argv);
				exit(EXIT_SUCCESS);
			case 'l':
				do_list_formats = 1;
				break;
			case 'a':
				command = V4L2_CID_EXPOSURE_AUTO;
				input = atoi(optarg);
				doCommand = 1;
				break;
			case 'e':
				command = V4L2_CID_EXPOSURE_ABSOLUTE;
				input = atoi(optarg);
				doCommand = 1;
				break;
			case 'i':
				command = V4L2_CID_GAIN;
				input = atoi(optarg);
				doCommand = 1;
				break;
			case 'g':
				command = V4L2_CID_GAMMA;
				input = atoi(optarg);
				doCommand = 1;
				break;
			case 'o':
				imageName = optarg;
				break;
			case 't':
				imageName = NULL;
				break;
			default:
				usage(stderr, argc, argv);
				exit(EXIT_FAILURE);
		}
	}
	
	open_device();
	
	if(doCommand){
		int temp = 0;
		getControl(&temp, command);
		printf("Executing command 0x%X, previous value: %d ", command, temp);
		setControl(input, command);
		getControl(&temp, command);
		printf("current value: %d\n", temp);
		close_device();
		exit(EXIT_SUCCESS);
	}
	
	if(do_list_formats){
		list_format_info();
		close_device();
		exit(EXIT_SUCCESS);
	}
	
	init_device();
	start_capturing();
	mainloop();
	stop_capturing();
	uninit_device();
	
	printf("\n");
	close_device();
	exit(EXIT_SUCCESS);
	
	return 0;
}
/** The first time we are called, start the filter graph running in continuous
    mode and grab the first image that comes out.  Later times, grab each new
    image as it comes.  The "mode" parameter tells what mode we are in:
      Mode 0 = Run()
      Mode 1 = Pause()
    */
bool directx_camera_server::read_one_frame(unsigned minX, unsigned maxX,
                                           unsigned minY, unsigned maxY,
                                           unsigned exposure_millisecs) {
    HRESULT hr;

    if (!_status) {
        return false;
    };

#ifdef HACK_TO_REOPEN
    open_and_find_parameters();
    _started_graph = false;
#endif

    // If we have not yet started the media graph running, set up the callback
    // handler for the sample grabber filter so that we will hear about each
    // frame
    // as it comes in.  Then set the filter graph running.
    if (!_started_graph) {
        // Run the graph and wait until it captures a frame into its buffer
        switch (_mode) {
        case 0: // Case 0 = run
            hr = _pMediaControl->Run();
            break;
        case 1: // Case 1 = paused
            hr = _pMediaControl->Pause();
            break;
        default:
            fprintf(
                stderr,
                "directx_camera_server::read_one_frame(): Unknown mode (%d)\n",
                _mode);
            _status = false;
            return false;
        }
        if ((hr != S_OK) && (hr != S_FALSE)) {
            fprintf(stderr, "directx_camera_server::read_one_frame(): Can't "
                            "run filter graph\n");
            _status = false;
            return false;
        }

        _started_graph = true;
    }

    // XXX Should the app be allowed to set the timeout period?
    const int TIMEOUT_MSECS = 500;

    // Wait until there is a sample ready in the callback handler.  If there is,
    // copy it into our buffer and then tell it we are done processing the
    // sample.
    // If it takes too long, time out.
    BYTE *imageLocation;
    auto imageReady = sampleExchange_->waitForSample(
        std::chrono::milliseconds(TIMEOUT_MSECS));

    if (!imageReady) {
#ifdef DEBUG
        fprintf(stderr, "directx_camera_server::read_one_frame(): Timeout "
                        "when reading image\n");
#endif
        return false;
    }

    // If we are in mode 2, then we pause the graph after we captured one image.
    if (_mode == 2) {
        _pMediaControl->Pause();
        _mode = 1;
    }

    auto sampleWrapper = sampleExchange_->get();
    if (FAILED(sampleWrapper.get().GetPointer(&imageLocation))) {
        fprintf(stderr,
                "directx_camera_server::read_one_frame(): Can't get buffer\n");
        _status = false;
        return false;
    }
    // Step through each line of the video and copy it into the buffer.  We
    // do one line at a time here because there can be padding at the end of
    // each line on some video formats.
    for (DWORD iRow = 0; iRow < _num_rows; iRow++) {
        memcpy(_buffer.data() + _num_columns * 3 * iRow,
               imageLocation + _stride * iRow, _num_columns * 3);
    }

#ifdef HACK_TO_REOPEN
    close_device();
#endif
    return true;
}
Exemple #3
0
static int v4l2_case_measure(void* user_ptr, int test_num)
{
	FUNC_ENTER();
	int max_width;
	int max_height;
	v4l2_data* data = (v4l2_data*)user_ptr;

	BLTS_DEBUG("Test number %i:\n", test_num);
	if(!open_device (data->device))
	{
		BLTS_DEBUG("Can't open device %s\n", data->device->dev_name);
		FUNC_LEAVE();
		return -1;
	}

	if(init_device (data->device, MAX_WIDTH, MAX_HEIGHT))
	{
		BLTS_DEBUG("Maximum resolution is: %ix%i\n", data->device->format.fmt.pix.width, data->device->format.fmt.pix.height);
		BLTS_DEBUG("Measuring FPS on maximum resolution\n");

		max_width = data->device->format.fmt.pix.width;
		max_height = data->device->format.fmt.pix.height;
		BLTS_DEBUG("-----------------------\n");
		BLTS_DEBUG("%ix%i resolution\n", max_width, max_height);
		BLTS_DEBUG("-----------------------\n");

		if(!start_capturing (data->device))
			goto err;
		mainloop (data->device, LOOPS);

		stop_capturing (data->device);
		uninit_device (data->device);
		close_device (data->device);
	}
	else
	{
		BLTS_DEBUG("Can't initialize device\n");
		goto err;
	}

	BLTS_DEBUG("Stepping down resolutions and calculating FPS\n");

	int step_size_x, step_size_y, i, x, y;


	step_size_x = max_width / 10;
	step_size_y = max_height / 10;

	for(i=1; i<8; i++)
	{
		x = max_width - step_size_x * i;
		y = max_height - step_size_y * i;
		BLTS_DEBUG("-----------------------\n");
		BLTS_DEBUG("%ix%i resolution\n", x, y);
		BLTS_DEBUG("-----------------------\n");
		if(!open_device (data->device))
			goto err;

		if(init_device (data->device, x, y))
		{
			BLTS_DEBUG("Resolution is: %ix%i\n", x, y);
			if(!start_capturing (data->device))
				goto err;

			if(!mainloop (data->device, LOOPS))
				goto err;

			stop_capturing (data->device);
			uninit_device (data->device);
		}
		else
		{
			BLTS_DEBUG("Can't initialize device\n");
			goto err;
		}

		close_device (data->device);
	}
	FUNC_LEAVE();
	return 0;

err:
	stop_capturing(data->device);
	uninit_device(data->device);
	close_device(data->device);
	FUNC_LEAVE();
	return -1;
}
Webcam::~Webcam()
{
   close_device();
   delete webcam_info;
}
Exemple #5
0
int main(int argc, char **argv) {
	/*Assumes args are in order !!!!
	1: V4L2 dev name, 2: height, 3: width, 4: channel
	5: standard, 6: jpeg_quality, 7: verbosity, 8: log source, 9: log_level
	*/
	struct video_device *d;
	struct capture_device *cdev;
	int sockfd, port;
	jpeg_quality = JPEG_QUALITY;
	int fmts[NB_SUPPORTED_FORMATS] = SUPPORTED_FORMATS;

	//catch ctrl-c
	signal (SIGINT, catch_int);
	signal (SIGPIPE, SIG_IGN );

	//Parse cmd line options
	if(argc != NB_ARGS) {
		print_usage();
		exit(1);
	}

	jpeg_quality = atoi(argv[6]);
	requested_fps = atoi(argv[7]);
	verbosity = atoi(argv[8]);
	port = atoi(argv[9]);

#ifdef DEBUG
	log_source = atoi(argv[10]);
	log_level = atoi(argv[11]);
#endif

	d = open_device(argv[1]);
	if(d==NULL){
		info(LOG_ERR, "Cant open device %s",argv[1]);
		exit(1);
	}

	//create capture device
	cdev = init_capture_device(d, atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), 5);
	if(cdev==NULL) {
		info(LOG_ERR, "Failed to initialise video device\n");
		info(LOG_ERR, "Recompile libv4l with debugging enabled (see README)\n");
		info(LOG_ERR, "to see why/where the initialisation fails.\n");
		exit(1);
	}

	//Set capture param (image format, color, size, crop...)
	if ((*cdev->actions->set_cap_param)(d, fmts , NB_SUPPORTED_FORMATS)!=0) {
		info(LOG_ERR, "Unable to set capture parameters. It could be due to:\n");
		info(LOG_ERR, " - the chosen width and height,\n - the driver not supporting the image formats libv4l tried\n");
		info(LOG_ERR, "Recompile libv4l with debugging enabled (see README)\n");
		info(LOG_ERR, "to see why/where the setup fails.\n");
		free_capture_device(d);
		close_device(d);
		exit(1);
	}

	info(LOG_INFO, "Capturing at %dx%d\n", cdev->width, cdev->height);

	//Prepare capture:Allocates v4l2 buffers, mmap buffers, enqueue buffers
	if ((*cdev->actions->init_capture)(d)) {
		info(LOG_ERR, "Failed to setup capture\n");
		free_capture_device(d);
		close_device(d);
		exit(1);
	}

	info(LOG_INFO, "Using palette %s\n", libv4l_palettes[cdev->palette].name);

	//init tcp server
	sockfd = setup_tcp_server_sock(port);

	//main loop
	main_loop(sockfd, d);

	//close tcp socket
	close(sockfd);

	//Deallocates V4l2 buffers
	(*cdev->actions->free_capture)(d);

	//delete cdev
	free_capture_device(d);

	//close device
	close_device(d);

	return 0;
}
Exemple #6
0
int servant(const char *diskname, int mode, const void* argp)
{
	struct sector_mbox_s *s_mbox = NULL;
	struct sector_node_s *s_node = NULL;
	struct sector_header_s	*s_header = NULL;
	int mbox;
	int rc = 0;
	time_t t0, t1, latency;
	union sigval signal_value;
	sigset_t servant_masks;
	struct sbd_context *st;
	pid_t ppid;
	char uuid[37];
	const struct servants_list_item *s = argp;

	if (!diskname) {
		cl_log(LOG_ERR, "Empty disk name %s.", diskname);
		return -1;
	}

	cl_log(LOG_INFO, "Servant starting for device %s", diskname);

	/* Block most of the signals */
	sigfillset(&servant_masks);
	sigdelset(&servant_masks, SIGKILL);
	sigdelset(&servant_masks, SIGFPE);
	sigdelset(&servant_masks, SIGILL);
	sigdelset(&servant_masks, SIGSEGV);
	sigdelset(&servant_masks, SIGBUS);
	sigdelset(&servant_masks, SIGALRM);
	/* FIXME: check error */
	sigprocmask(SIG_SETMASK, &servant_masks, NULL);

	atexit(servant_exit);
	servant_inform_parent = 1;

	st = open_device(diskname, LOG_WARNING);
	if (!st) {
		return -1;
	}

	s_header = header_get(st);
	if (!s_header) {
		cl_log(LOG_ERR, "Not a valid header on %s", diskname);
		return -1;
	}

	if (servant_check_timeout_inconsistent(s_header) < 0) {
		cl_log(LOG_ERR, "Timeouts on %s do not match first device",
				diskname);
		return -1;
	}

	if (s_header->minor_version > 0) {
		uuid_unparse_lower(s_header->uuid, uuid);
		cl_log(LOG_INFO, "Device %s uuid: %s", diskname, uuid);
	}

	mbox = slot_allocate(st, local_uname);
	if (mbox < 0) {
		cl_log(LOG_ERR,
		       "No slot allocated, and automatic allocation failed for disk %s.",
		       diskname);
		rc = -1;
		goto out;
	}
	s_node = sector_alloc();
	if (slot_read(st, mbox, s_node) < 0) {
		cl_log(LOG_ERR, "Unable to read node entry on %s",
				diskname);
		exit(1);
	}

	DBGLOG(LOG_INFO, "Monitoring slot %d on disk %s", mbox, diskname);
	if (s_header->minor_version == 0) {
		set_proc_title("sbd: watcher: %s - slot: %d", diskname, mbox);
	} else {
		set_proc_title("sbd: watcher: %s - slot: %d - uuid: %s",
				diskname, mbox, uuid);
	}

	s_mbox = sector_alloc();
	if (s->first_start) {
		if (mode > 0) {
			if (mbox_read(st, mbox, s_mbox) < 0) {
				cl_log(LOG_ERR, "mbox read failed during start-up in servant.");
				rc = -1;
				goto out;
			}
			if (s_mbox->cmd != SBD_MSG_EXIT &&
					s_mbox->cmd != SBD_MSG_EMPTY) {
				/* Not a clean stop. Abort start-up */
				cl_log(LOG_WARNING, "Found fencing message - aborting start-up. Manual intervention required!");
				ppid = getppid();
				sigqueue(ppid, SIG_EXITREQ, signal_value);
				rc = 0;
				goto out;
			}
		}
		DBGLOG(LOG_INFO, "First servant start - zeroing inbox");
		memset(s_mbox, 0, sizeof(*s_mbox));
		if (mbox_write(st, mbox, s_mbox) < 0) {
			rc = -1;
			goto out;
		}
	}

	memset(&signal_value, 0, sizeof(signal_value));

	while (1) {
		struct sector_header_s	*s_header_retry = NULL;
		struct sector_node_s	*s_node_retry = NULL;

		t0 = time(NULL);
		sleep(timeout_loop);

		ppid = getppid();

		if (ppid == 1) {
			/* Our parent died unexpectedly. Triggering
			 * self-fence. */
			do_reset();
		}

		/* These attempts are, by definition, somewhat racy. If
		 * the device is wiped out or corrupted between here and
		 * us reading our mbox, there is nothing we can do about
		 * that. But at least we tried. */
		s_header_retry = header_get(st);
		if (!s_header_retry) {
			cl_log(LOG_ERR, "No longer found a valid header on %s", diskname);
			exit(1);
		}
		if (memcmp(s_header, s_header_retry, sizeof(*s_header)) != 0) {
			cl_log(LOG_ERR, "Header on %s changed since start-up!", diskname);
			exit(1);
		}
		free(s_header_retry);

		s_node_retry = sector_alloc();
		if (slot_read(st, mbox, s_node_retry) < 0) {
			cl_log(LOG_ERR, "slot read failed in servant.");
			exit(1);
		}
		if (memcmp(s_node, s_node_retry, sizeof(*s_node)) != 0) {
			cl_log(LOG_ERR, "Node entry on %s changed since start-up!", diskname);
			exit(1);
		}
		free(s_node_retry);

		if (mbox_read(st, mbox, s_mbox) < 0) {
			cl_log(LOG_ERR, "mbox read failed in servant.");
			exit(1);
		}

		if (s_mbox->cmd > 0) {
			cl_log(LOG_INFO,
			       "Received command %s from %s on disk %s",
			       char2cmd(s_mbox->cmd), s_mbox->from, diskname);

			switch (s_mbox->cmd) {
			case SBD_MSG_TEST:
				memset(s_mbox, 0, sizeof(*s_mbox));
				mbox_write(st, mbox, s_mbox);
				sigqueue(ppid, SIG_TEST, signal_value);
				break;
			case SBD_MSG_RESET:
				do_reset();
				break;
			case SBD_MSG_OFF:
				do_off();
				break;
			case SBD_MSG_EXIT:
				sigqueue(ppid, SIG_EXITREQ, signal_value);
				break;
			case SBD_MSG_CRASHDUMP:
				do_crashdump();
				break;
			default:
				/* FIXME:
				   An "unknown" message might result
				   from a partial write.
				   log it and clear the slot.
				 */
				cl_log(LOG_ERR, "Unknown message on disk %s",
				       diskname);
				memset(s_mbox, 0, sizeof(*s_mbox));
				mbox_write(st, mbox, s_mbox);
				break;
			}
		}
		sigqueue(ppid, SIG_LIVENESS, signal_value);

		t1 = time(NULL);
		latency = t1 - t0;
		if (timeout_watchdog_warn && (latency > timeout_watchdog_warn)) {
			cl_log(LOG_WARNING,
			       "Latency: %d exceeded threshold %d on disk %s",
			       (int)latency, (int)timeout_watchdog_warn,
			       diskname);
		} else if (debug) {
			DBGLOG(LOG_INFO, "Latency: %d on disk %s", (int)latency,
			       diskname);
		}
	}
 out:
	free(s_mbox);
	close_device(st);
	if (rc == 0) {
		servant_inform_parent = 0;
	}
	return rc;
}
Exemple #7
0
int main(int argc, char** argv) {
	struct capture_device *c;
	struct video_device *v;
	void *d;
	int size, std=0, channel=0, width=0, height=0, nb_frames = 0, fmt=-1;

	if(argc!=7 && argc!=8) {
		printf("Usage: %s <video_device_file> <number_of_frames> <standard> "
				"<input> <width> <height> [ format ]\n", argv[0]);
		printf("This program captures a number of frames from a video device "
				"and saves them in separate files");
		printf("The following arguments are required in this order:\n");
		printf("The video device file to be tested.\n");
		printf("The number of frames to be captured\n");
		printf("The video standard and input number.\n");
		printf("Video standards: webcam:0 - PAL:1 - SECAM:2 - NTSC:3\n");
		printf("The capture resolution (width and height)\n");
		printf("The last argument is optional and is an image format index. "
				"To see what formats are supported by a video device, run "
				"'./list-caps /dev/videoXX' and check the "
				"'Printing device info' section at the bottom.\n");
		printf("Arguments must be in the specified order !!!\n");
		return -1;
	}

	nb_frames = atoi(argv[2]);
	printf("This program will capture %d frame(s) from %s\n", nb_frames, argv[1]);

	std = atoi(argv[3]);
	channel = atoi(argv[4]);
	width = atoi(argv[5]);
	height = atoi(argv[6]);
	printf("Trying %dx%d standard %d, channel %d",width,height,std, channel);

	if(argc==8){
		fmt = atoi(argv[7]);
		printf(", image format %s (%d)",libvideo_palettes[fmt].name, fmt);
	}

	printf("\nMake sure your video source is connected, and press <Enter>, or Ctrl-C to abort now.");
	getchar();

	v = open_device(argv[1]);
	if(v==NULL){
		printf("Error opening device %s", argv[1]);
		return -1;
	}
	c = init_capture_device(v, width, height ,channel, std,2);

	if(c==NULL) {
		printf("Error initialising device.\n");
		close_device(v);
		return -1;
	}

	if(fmt!=-1){
		if((*c->actions->set_cap_param)(v, &fmt, 1)){
			free_capture_device(v);
			close_device(v);
			printf("Cant set capture parameters\n");
			return -1;
		}
	}else {
		if((*c->actions->set_cap_param)(v, NULL, 0)){
			free_capture_device(v);
			close_device(v);
			printf("Cant set capture parameters\n");
			return -1;
		}
	}


	printf("Capturing from %s at %dx%d.\n", argv[1], c->width,c->height);
	width = c->width;
	height = c->height;
	printf("Image format %s, size: %d\n", libvideo_palettes[c->palette].name, c->imagesize);

	if((*c->actions->init_capture)(v)<0){
		free_capture_device(v);
		close_device(v);
		printf("Cant initialise capture ");
		return -1;
	}

	if((*c->actions->start_capture)(v)<0){
		(*c->actions->free_capture)(v);
		free_capture_device(v);
		close_device(v);
		printf("Cant start capture");
		return -1;
	}

	while(nb_frames-->0){
		//get frame from v4l2
		if((d = (*c->actions->dequeue_buffer)(v, &size)) != NULL) {
			write_frame(d, size);
			//Put frame
			(*c->actions->enqueue_buffer)(v);
		} else {
			printf("Cant get buffer ");
			break;
		}
	}

	if((*c->actions->stop_capture)(v)<0)
		fprintf(stderr, "Error stopping capture\n");

	(*c->actions->free_capture)(v);
	free_capture_device(v);
	close_device(v);

	return 0;
}
AkmSensor::AkmSensor()
: SensorBase(AKM_DEVICE_NAME, "compass"),
      mEnabled(0),
      mPendingMask(0),
      mInputReader(32)
{
    memset(mPendingEvents, 0, sizeof(mPendingEvents));

    mPendingEvents[Accelerometer].version = sizeof(sensors_event_t);
    mPendingEvents[Accelerometer].sensor = ID_A;
    mPendingEvents[Accelerometer].type = SENSOR_TYPE_ACCELEROMETER;
    mPendingEvents[Accelerometer].acceleration.status = SENSOR_STATUS_ACCURACY_HIGH;

    mPendingEvents[MagneticField].version = sizeof(sensors_event_t);
    mPendingEvents[MagneticField].sensor = ID_M;
    mPendingEvents[MagneticField].type = SENSOR_TYPE_MAGNETIC_FIELD;
    mPendingEvents[MagneticField].magnetic.status = SENSOR_STATUS_ACCURACY_HIGH;

    mPendingEvents[Orientation  ].version = sizeof(sensors_event_t);
    mPendingEvents[Orientation  ].sensor = ID_O;
    mPendingEvents[Orientation  ].type = SENSOR_TYPE_ORIENTATION;
    mPendingEvents[Orientation  ].orientation.status = SENSOR_STATUS_ACCURACY_HIGH;

    for (int i=0 ; i<numSensors ; i++)
        mDelays[i] = 200000000; // 200 ms by default

    // read the actual value of all sensors if they're enabled already
    struct input_absinfo absinfo;
    short flags = 0;

    open_device();

    if (!ioctl(dev_fd, ECS_IOCTL_APP_GET_AFLAG, &flags)) {
        if (flags)  {
            mEnabled |= 1<<Accelerometer;
            if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_ACCEL_X), &absinfo)) {
                mPendingEvents[Accelerometer].acceleration.x = absinfo.value * CONVERT_A_X;
            }
            if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_ACCEL_Y), &absinfo)) {
                mPendingEvents[Accelerometer].acceleration.y = absinfo.value * CONVERT_A_Y;
            }
            if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_ACCEL_Z), &absinfo)) {
                mPendingEvents[Accelerometer].acceleration.z = absinfo.value * CONVERT_A_Z;
            }
        }
    }
    if (!ioctl(dev_fd, ECS_IOCTL_APP_GET_MVFLAG, &flags)) {
        if (flags)  {
            mEnabled |= 1<<MagneticField;
            if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_MAGV_X), &absinfo)) {
                mPendingEvents[MagneticField].magnetic.x = absinfo.value * CONVERT_M_X;
            }
            if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_MAGV_Y), &absinfo)) {
                mPendingEvents[MagneticField].magnetic.y = absinfo.value * CONVERT_M_Y;
            }
            if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_MAGV_Z), &absinfo)) {
                mPendingEvents[MagneticField].magnetic.z = absinfo.value * CONVERT_M_Z;
            }
        }
    }
    if (!ioctl(dev_fd, ECS_IOCTL_APP_GET_MFLAG, &flags)) {
        if (flags)  {
            mEnabled |= 1<<Orientation;
            if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_YAW), &absinfo)) {
                mPendingEvents[Orientation].orientation.azimuth = absinfo.value;
            }
            if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_PITCH), &absinfo)) {
                mPendingEvents[Orientation].orientation.pitch = absinfo.value;
            }
            if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_ROLL), &absinfo)) {
                mPendingEvents[Orientation].orientation.roll = -absinfo.value;
            }
            if (!ioctl(data_fd, EVIOCGABS(EVENT_TYPE_ORIENT_STATUS), &absinfo)) {
                mPendingEvents[Orientation].orientation.status = uint8_t(absinfo.value & SENSOR_STATE_MASK);
            }
        }
    }

    // disable temperature sensor, since it is not reported
    flags = 0;
    ioctl(dev_fd, ECS_IOCTL_APP_SET_TFLAG, &flags);

    if (!mEnabled) {
        close_device();
    }
}
Exemple #9
0
int main(int argc, char** argv) {
	struct capture_device *c;
	struct control_list *l;
	struct v4l2_queryctrl *qc;
	struct video_device *v;
	int std=0, channel=0, i, j;

	if(argc!=2 && argc!=4) {
		printf("This program requires the path to the video device file to be tested.\n");
		printf("The optional second and third arguments are a video standard and channel.\n");
		printf("Usage: %s <video_device_file> [standard channel]\n", argv[0]);
		printf("Video standards: webcam:0 - PAL:1 - SECAM:2 - NTSC:3\n");
		return -1;
	}


	if (argc==4){
		std = atoi(argv[2]);
		channel = atoi(argv[3]);
		printf("Using standard %d, channel %d\n",std, channel);
	}

	v = open_device(argv[1]);
	if(v==NULL){
		printf("Error opening device\n");
		return -1;
	}
	c = init_capture_device(v,MAX_WIDTH,MAX_HEIGHT,channel,std,3);
	c->actions->list_cap(v->fd);
	free_capture_device(v);
	l = get_control_list(v);
	printf("Listing available controls (%d)\n", l->count);
	for(i=0;i<l->count; i++){
		qc = l->controls[i].v4l2_ctrl;
		printf("Control: id: 0x%x - name: %s - min: %d -max: %d - step: %d - type: %d(%s) - flags: %d (%s%s%s%s%s%s)\n",
				qc->id, (char *) &qc->name, qc->minimum, qc->maximum, qc->step, qc->type,
				qc->type == V4L2_CTRL_TYPE_INTEGER ? "Integer" :
				qc->type == V4L2_CTRL_TYPE_BOOLEAN ? "Boolean" :
				qc->type == V4L2_CTRL_TYPE_MENU ? "Menu" :
				qc->type == V4L2_CTRL_TYPE_BUTTON ? "Button" :
				qc->type == V4L2_CTRL_TYPE_INTEGER64 ? "Integer64" :
				qc->type == V4L2_CTRL_TYPE_CTRL_CLASS ? "Class" :
				qc->type == V4L2_CTRL_TYPE_STRING ? "String" :
				qc->type == V4L2_CTRL_TYPE_BITMASK ? "Bitmask" : "",
				qc->flags,
				qc->flags & V4L2_CTRL_FLAG_DISABLED ? "Disabled " : "",
				qc->flags & V4L2_CTRL_FLAG_GRABBED ? "Grabbed " : "",
				qc->flags & V4L2_CTRL_FLAG_READ_ONLY ? "ReadOnly " : "",
				qc->flags & V4L2_CTRL_FLAG_UPDATE ? "Update " : "",
				qc->flags & V4L2_CTRL_FLAG_INACTIVE ? "Inactive " : "",
				qc->flags & V4L2_CTRL_FLAG_SLIDER ? "slider " : "",
				qc->flags & V4L2_CTRL_FLAG_WRITE_ONLY ? "Write only" : "");

		if(l->controls[i].count_menu!=0){
			printf("Menu items (%d) %s\n", l->controls[i].count_menu, l->controls[i].v4l2_ctrl->step==1?"contiguous":"non-contiguous");
			for(j=0; j<l->controls[i].count_menu; j++)
				printf("\tMenu item: %s - %d\n", l->controls[i].v4l2_menu[j].name, l->controls[i].v4l2_menu[j].index);

		}
	}

	get_device_info(v);
	print_device_info(v);
	release_device_info(v);

	release_control_list(v);

	close_device(v);

	return 0;
}
void closeDevice(void) {
  close_device(cntx);
}
EnclaveCreatorHW::~EnclaveCreatorHW()
{
    close_device();
}
Exemple #12
0
// thread main!
int uart_unix_main(void* arg)
{
    dthread_t* self = (dthread_t*) arg;
    dthread_t* other = (dthread_t*) self->arg;
    dmessage_t* mp = NULL;
    dthread_poll_event_t ev, *evp;
    size_t nev;
    dterm_t term;
    uart_ctx_t ctx;
    ErlDrvTermData mp_from;
    ErlDrvTermData mp_ref;
    dthread_t*     mp_source;
    int tmo;
    int r;

    DEBUGF("uart_unix: thread started");

    uart_init(&ctx, self, other);

    dterm_init(&term);

again_tmo:
    tmo = next_timeout(&ctx);
again:
    nev = 0;
    evp = NULL;
    if (ctx.fd >= 0) {
	ev.event = (ErlDrvEvent) ((long)ctx.fd);
	ev.events = 0;
	if ((ctx.option.active != UART_PASSIVE) || ctx.recv)
	    ev.events |= ERL_DRV_READ;
	if (ctx.oq.mesg)
	    ev.events |= ERL_DRV_WRITE;
	if (ev.events) {
	    evp = &ev;
	    nev = 1;
	}
	DEBUGF("ctx.fd=%d, ev.events=%d", ctx.fd, ev.events);

    }

    DEBUGF("uart_unix_main: nev=%d, events=%x, timeout = %d",
	   nev, ev.events, tmo);
    r = dthread_poll(self, evp, &nev, tmo);

    if (r < 0) {
	DEBUGF("uart_unix_main: dthread_poll failed=%d", r);
	goto again_tmo;
    }
    else {
	DEBUGF("uart_unix_main: nev=%d, r=%d", nev, r);

	if (evp && (nev == 1)) {
	    if (evp->revents & ERL_DRV_WRITE)
		process_output(&ctx, self);
	    if (evp->revents & ERL_DRV_READ) {
		while((process_input(&ctx, self, 0) == 1) &&
		      (ctx.option.active != UART_PASSIVE))
		    ;
	    }
	}
	tmo = next_timeout(&ctx);
	DEBUGF("uart_unix_main: timeout = %d", tmo);
	if (ctx.recv) {
	    if (tmo == 0) {
		uart_async_error_am(&ctx, ctx.dport, ctx.caller, am_timeout);
		clear_timeout(&ctx);
		ctx.remain = 0;
	    }
	}
	if (r == 0)
	    goto again;

	// r>0 (number of messages)
	DEBUGF("about to receive message r=%d", r);
	if ((mp = dthread_recv(self, NULL)) == NULL) {
	    DEBUGF("uart_unix_main: message was NULL");
	    goto again;
	}
	mp_from = mp->from;
	mp_ref  = mp->ref;
	mp_source = mp->source;

	switch (mp->cmd) {
	case DTHREAD_STOP:
	    DEBUGF("uart_unix_main: STOP");
	    close_device(&ctx);
	    uart_final(&ctx);
	    dmessage_free(mp);
	    DEBUGF("uart_unix_main: EXIT");
	    dthread_exit(0);
	    break;

	case DTHREAD_OUTPUT: // async send!
	    DEBUGF("uart_unix_main: OUTPUT");
	    if (ctx.fd < 0) {
		dmessage_free(mp);
		goto again;
	    }
	    if (enq_output(&ctx, self, mp, 0) < 0) {
		mp = NULL;
		goto error;
	    }
	    goto again;

	case UART_CMD_CLOSE:
	    DEBUGF("uart_unix_main: CLOSE");
	    close_device(&ctx);
	    goto ok;

	case UART_CMD_SEND: // sync send
	    DEBUGF("uart_unix_main: SEND");
	    if (ctx.fd < 0) goto ebadf;
	    if (enq_output(&ctx, self, mp, mp_from) < 0) {
		mp = NULL;
		goto error;
	    }
	    goto again;

	case UART_CMD_SENDCHAR: // sync send
	    DEBUGF("uart_unix_main: SENDCHAR");
	    if (ctx.fd < 0) goto ebadf;
	    if (enq_output(&ctx, self, mp, mp_from) < 0) {
		mp = NULL;
		goto error;
	    }
	    goto again;

	case UART_CMD_RECV: {  // <<Time:32, Length:32>> Time=0xffffffff=inf
	    uint32_t tm;
	    int len;
	    DEBUGF("uart_unix_main: RECV");
	    if (ctx.fd < 0) goto ebadf;
	    if (ctx.recv) goto ealready;
	    if (mp->used != 8) goto badarg;
	    if (ctx.option.active != UART_PASSIVE) goto badarg;
	    tm = get_uint32((uint8_t*) mp->buffer);
	    len = (int) get_uint32((uint8_t*) (mp->buffer+4));
	    if ((len < 0) || (len > UART_MAX_PACKET_SIZE)) goto badarg;
	    ctx.ref = mp_ref;
	    ctx.caller = mp_from;
	    set_timeout(&ctx, tm);
	    ctx.recv = 1;
	    DEBUGF("recv timeout %lu", tm);
	    process_input(&ctx, self, len);
	    dmessage_free(mp);
	    goto again_tmo;
	}

	case UART_CMD_UNRECV: {  // argument is data to push back
	    uart_buf_push(&ctx.ib, mp->buffer, mp->used);
	    DEBUGF("unrecived %d bytes", ctx.ib.ptr - ctx.ib.ptr_start);
	    if (ctx.option.active != UART_PASSIVE) {
		while((process_input(&ctx, self, 0) == 1) &&
		      (ctx.option.active != UART_PASSIVE))
		    ;
	    }
	    goto ok;
	}

	case UART_CMD_SETOPTS: {
	    uart_com_state_t state  = ctx.state;
	    uart_opt_t       option = ctx.option;
	    uint32_t         sflags = ctx.sflags;

	    // parse & update options in state,option and sflag
	    if (uart_parse_opts(mp->buffer, mp->used,
				&state, &option, &sflags) < 0)
		goto badarg;

	    //  apply the changed values
	    if ((r=apply_opts(&ctx, &state, &option, sflags)) < 0)
		goto error;

	    if (r == 1) {
		while((process_input(&ctx, self, 0) == 1) &&
		      (ctx.option.active != UART_PASSIVE))
		    ;
	    }
	    goto ok;
	}

	case UART_CMD_GETOPTS: {
	    dterm_mark_t m1;
	    dterm_mark_t m2;
	    // {Ref, {ok,List}} || {Ref, {error,Reason}}
	    dterm_tuple_begin(&term, &m1); {
		dterm_uint(&term, mp_ref);
		dterm_tuple_begin(&term, &m2); {
		    dterm_atom(&term, am_ok);
		    if (uart_get_opts(&term, &ctx,(uint8_t*)mp->buffer,mp->used) < 0) {
			dterm_reset(&term);
			goto badarg;
		    }
		}
		dterm_tuple_end(&term, &m2);
	    }
	    dterm_tuple_end(&term, &m1);
	    dthread_port_send_dterm(mp_source, self, mp_from, &term);
	    dterm_reset(&term);
	    dmessage_free(mp);
	    goto again;
	}

	case UART_CMD_GET_MODEM: {
	    dterm_mark_t m1;
	    dterm_mark_t m2;
	    uart_modem_state_t mstate;
	    if (ctx.fd < 0) goto ebadf;
	    if (get_modem_state(ctx.fd, &mstate) < 0) goto error;

	    dterm_tuple_begin(&term, &m1); {
		dterm_uint(&term, mp_ref);
		dterm_tuple_begin(&term, &m2); {
		    dterm_atom(&term, am_ok);
		    modem_state_dterm(&term, mstate);
		}
		dterm_tuple_end(&term, &m2);
	    }
	    dterm_tuple_end(&term, &m1);
	    dthread_port_send_dterm(mp_source, self, mp_from, &term);
	    dterm_reset(&term);
	    dmessage_free(mp);
	    goto again;
	}

	case UART_CMD_SET_MODEM: {
	    uart_modem_state_t mstate;
	    if (ctx.fd < 0) goto ebadf;
	    if (mp->used != 4) goto badarg;
	    mstate = (uart_modem_state_t) get_uint32((uint8_t*) mp->buffer);
	    if (set_modem_state(ctx.fd, mstate, 1) < 0) goto error;
	    goto ok;
	}

	case UART_CMD_CLR_MODEM: {
	    uart_modem_state_t mstate;
	    if (ctx.fd < 0) goto ebadf;
	    if (mp->used != 4) goto badarg;
	    mstate = (uart_modem_state_t) get_uint32((uint8_t*) mp->buffer);
	    if (set_modem_state(ctx.fd, mstate, 0) < 0) goto error;
	    goto ok;
	}

	case UART_CMD_HANGUP: {
	    struct termios tio;
	    int r;
	    if (ctx.fd < 0) goto ebadf;
	    if (mp->used != 0) goto badarg;
	    if ((r = tcgetattr(ctx.fd, &tio)) < 0) {
		INFOF("tcgetattr: error=%s\n", strerror(errno));
		goto badarg;
	    }
	    cfsetispeed(&tio, B0);
	    cfsetospeed(&tio, B0);
	    if ((r = tcsetattr(ctx.fd, TCSANOW, &tio)) < 0) {
		INFOF("tcsetattr: error=%s\n", strerror(errno));
		goto badarg;
	    }
	    goto ok;
	}

	case UART_CMD_BREAK: {
	    int duration;
	    if (ctx.fd < 0) goto ebadf;
	    if (mp->used != 4) goto badarg;
	    duration = (int) get_uint32((uint8_t*) mp->buffer);
	    if (tcsendbreak(ctx.fd, duration) < 0)
		goto error;
	    goto ok;
	}

	case UART_CMD_FLOW:
	    if (ctx.fd < 0) goto ebadf;
	    if (mp->used != 1) goto badarg;
	    switch(mp->buffer[0]) {
	    case 0: r = tcflow(ctx.fd, TCIOFF); break;
	    case 1: r = tcflow(ctx.fd, TCION); break;
	    case 2: r = tcflow(ctx.fd, TCOOFF); break;
	    case 3: r = tcflow(ctx.fd, TCOON); break;
	    default: goto badarg; break;
	    }
	    if (r < 0)
		goto error;
	    goto ok;

	default:
	    goto badarg;
	}
    }

ok:
    dthread_port_send_ok(mp_source, self,  mp_from, mp_ref);
    if (mp) dmessage_free(mp);
    goto again;

ebadf:
    errno = EBADF;
    goto error;
badarg:
    errno = EINVAL;
    goto error;
ealready:
    errno = EALREADY;
    goto error;

error:
    dthread_port_send_error(mp_source, self, mp_from, mp_ref,
			    uart_errno(&ctx));
    if (mp) dmessage_free(mp);
    goto again;
}
Exemple #13
0
static int apply_opts(uart_ctx_t* ctx,
		      uart_com_state_t* state, uart_opt_t* option,
		      int32_t sflags)
{
    int old_active;
    unsigned int old_htype;

    if ((sflags & (1 << UART_OPT_DEVICE)) &&
	(strcmp(option->device_name, ctx->option.device_name) != 0)) {

	close_device(ctx);
	sflags  = 0;
	if (open_device(ctx, option->device_name) < 0)
	    return -1;
#ifdef DEBUG
	// com_state_dump(stderr, state);
#endif
	if (set_com_state(ctx->fd, state) < 0) {
	    DEBUGF("set_opts: uart_set_com_state failed");
	    return -1;
	}
	if (get_com_state(ctx->fd, state) >= 0) {
	    DEBUGF("set_opts: com_state: after");
#ifdef DEBUG
	    // com_state_dump(stderr, state);
#endif
	}
	else {
	    DEBUGF("apply_opts: get_com_state failed");
	}
    }
    else if (sflags & UART_OPT_COMM) {
	if (ctx->fd >= 0) {
	    // DEBUGF("set_opts: com_state before:");
	    // com_state_dump(stderr, state);
	    if (set_com_state(ctx->fd, state) < 0)
		return -1;
	    sflags = 0;
	    if (get_com_state(ctx->fd, state) >= 0) {
		// DEBUGF("set_opts: com_state: after");
#ifdef DEBUG
		// com_state_dump(stderr, state);
#endif
	    }
	}
    }

    old_active = ctx->option.active;
    old_htype = ctx->option.htype;

    ctx->sflags = sflags;
    ctx->state  = *state;
    ctx->option = *option;

    if (ctx->fd >= 0) {
	if (ctx->option.active) {
	    if (!old_active || (ctx->option.htype != old_htype))
		return 1;
	    ctx->remain = 0; // CHECK ME
	    return 0;
	}
    }
    return 0;
}
LightSensor::~LightSensor() {
    close_device();
}
Exemple #15
0
static int mode_command(int argc, const char* argv[]) {
    int fd;
    zx_handle_t svc;
    zx_status_t status = open_usb_device(&fd, &svc);
    if (status != ZX_OK) {
        return status;
    }

    zx_status_t status2;

    if (argc == 1) {
        // print current mode
        usb_mode_t mode;
        status = fuchsia_hardware_usb_peripheral_DeviceGetMode(svc, &status2, &mode);
        if (status == ZX_OK) status = status2;
        if (status != ZX_OK) {
            fprintf(stderr, "fuchsia_hardware_usb_peripheral_DeviceGetMode failed: %d\n", status);
        } else {
            switch (mode) {
            case USB_MODE_NONE:
                printf("NONE\n");
                break;
            case USB_MODE_HOST:
                printf("HOST\n");
                break;
            case USB_MODE_PERIPHERAL:
                printf("PERIPHERAL\n");
                break;
            case USB_MODE_OTG:
                printf("OTG\n");
                break;
            default:
                printf("unknown mode %d\n", mode);
                break;
            }
         }
    } else {
        usb_mode_t mode;
        if (strcasecmp(argv[1], "none") == 0) {
            mode = USB_MODE_NONE;
        } else if (strcasecmp(argv[1], "host") == 0) {
            mode = USB_MODE_HOST;
        } else if (strcasecmp(argv[1], "peripheral") == 0) {
            mode = USB_MODE_PERIPHERAL;
        } else if (strcasecmp(argv[1], "otg") == 0) {
            mode = USB_MODE_OTG;
        } else {
            fprintf(stderr, "unknown USB mode %s\n", argv[1]);
            status = ZX_ERR_INVALID_ARGS;
        }

        if (status == ZX_OK) {
            status = fuchsia_hardware_usb_peripheral_DeviceSetMode(svc, mode, &status2);
            if (status == ZX_OK) status = status2;
            if (status != ZX_OK) {
                fprintf(stderr, "fuchsia_hardware_usb_peripheral_DeviceSetMode failed: %d\n",
                        status);
            }
        }
    }

    close_device(fd, svc);
    return status;
}
Exemple #16
0
int main(int argc, char **argv)
{
	int w, h;

	w = 640;
	h = 480;
	for (;;) {
		int index;
		int c;

		c = getopt_long(argc, argv, short_options, long_options,
				&index);
		if (c < 0)
			break;

		switch (c) {
		case 0:	/* getopt_long() flag */
			break;
		case 'd':
			dev_name = optarg;
			break;
		case 'f':
			if (sscanf(optarg, "%dx%d", &w, &h) != 2) {
				fprintf(stderr, "Invalid image format\n");
				exit(EXIT_FAILURE);
			}
			break;
		case 'g':
			grab = 1;
			break;
		case 'h':
			usage(stdout, argc, argv);
			exit(EXIT_SUCCESS);
		case 'i':
			info = 1;
			break;
		case 'm':
			switch (optarg[0]) {
			case 'm':
				io = V4L2_MEMORY_MMAP;
				break;
			case 'r':
				io = IO_METHOD_READ;
				break;
			case 'u':
				io = V4L2_MEMORY_USERPTR;
				break;
			default:
				usage(stderr, argc, argv);
				exit(EXIT_FAILURE);
			}
			break;
		default:
			usage(stderr, argc, argv);
			exit(EXIT_FAILURE);
		}
	}
	if (optind < argc)
		dev_name = argv[optind];

	open_device();
	init_device(w, h);
	start_capturing();
	if (info) {
		if (io != V4L2_MEMORY_MMAP)
			info = NFRAMES;
		gettimeofday(&cur_time, 0);
	}
#ifdef WITH_GTK
	if (grab)
		get_frame();
	else
		main_frontend(argc, argv);
#else
	mainloop();
#endif
	stop_capturing();
	uninit_device();
	close_device();
	return 0;
}
ProximitySensor::~ProximitySensor()
{
    close_device();
}
Exemple #18
0
int main(int argc, char **argv)
{
	int value;
	dev_name = "/dev/video0";

	for (;;) {
		int index;
		int c;

		c = getopt_long(argc, argv,
				short_options, long_options, &index);

		if (-1 == c)
			break;

		switch (c) {
		case 0:	/* getopt_long() flag */
			break;

		case 'd':
			dev_name = optarg;
			break;

		case 'c':
			value = atoi(optarg);
			capture_count = value > 0 ? value : MAX_CAPTURE;
			break;

		case 'h':
			usage(stdout, argc, argv);
			exit(EXIT_SUCCESS);

		case 'm':
			io = IO_METHOD_MMAP;
			break;

		case 'r':
			io = IO_METHOD_READ;
			break;

		case 'u':
			io = IO_METHOD_USERPTR;
			break;

		case 'i':
			value = atoi(optarg);
			still_capture_interval = value > 0 ? value : CAPTURE_INTERVAL;
			break;

		case 's':
			still_dump_file = 1;
			break;

		case 'x':
			value = atoi(optarg);
			if (value > 0) {
				sw = value;
				still_size_fixed = 1;
			}
			break;

		case 'y':
			value = atoi(optarg);
			if (value > 0) {
				sh = value;
				still_size_fixed = 1;
			}
			break;

		default:
			usage(stderr, argc, argv);
			exit(EXIT_FAILURE);
		}
	}

	open_device();

	init_device();

	start_capturing();

	mainloop();

	stop_capturing();

	uninit_device();

	close_device();

	exit(EXIT_SUCCESS);

	return 0;
}
Exemple #19
0
void cmd_ccur_device(WINDOW *window, ToxWindow *self, Tox *m, int argc, char (*argv)[MAX_STR_SIZE])
{
    const char *error_str;

    if ( argc != 2 ) {
        if ( argc < 1 ) error_str = "Type must be specified!";
        else if ( argc < 2 ) error_str = "Must have id!";
        else error_str = "Only two arguments allowed!";

        goto on_error;
    }

    DeviceType type;

    if ( strcmp(argv[1], "in") == 0 ) /* Input devices */
        type = input;

    else if ( strcmp(argv[1], "out") == 0 ) /* Output devices */
        type = output;

    else {
        line_info_add(self, NULL, NULL, NULL, SYS_MSG, 0, 0, "Invalid type: %s", argv[1]);
        return;
    }


    char *end;
    long int selection = strtol(argv[2], &end, 10);

    if ( *end ) {
        error_str = "Invalid input";
        goto on_error;
    }

    if ( selection_valid(type, selection) == de_InvalidSelection ) {
        error_str="Invalid selection!";
        goto on_error;
    }

    /* If call is active, change device */
    if ( self->call_idx > -1) {
        Call* this_call = &ASettins.calls[self->call_idx];
        if (this_call->ttas) {

            ToxAvCSettings csettings;
            toxav_get_peer_csettings(ASettins.av, self->call_idx, 0, &csettings);

            if (type == output) {
                pthread_mutex_lock(&this_call->mutex);
                close_device(output, this_call->out_idx);
                this_call->has_output = open_device(output, selection, &this_call->out_idx,
                    csettings.audio_sample_rate, csettings.audio_frame_duration, csettings.audio_channels)
                    == de_None ? 1 : 0;
                pthread_mutex_unlock(&this_call->mutex);
            }
            else {
                /* TODO: check for failure */
                close_device(input, this_call->in_idx);
                open_device(input, selection, &this_call->in_idx, csettings.audio_sample_rate,
                    csettings.audio_frame_duration, csettings.audio_channels);
                /* Set VAD as true for all; TODO: Make it more dynamic */
                register_device_callback(self->call_idx, this_call->in_idx, read_device_callback, &self->call_idx, true);
            }
        }
    }

    self->device_selection[type] = selection;

    return;
    on_error:
    print_err (self, error_str);
}
Exemple #20
0
void do_packet_capture(void)
{
//    int 				ret;
    static uint8_t 		*bottom = NULL;
    static uint8_t 		*top = NULL;
    ULONG total_read, 	buffer_len, read_size, diff;

    /*
     * The main Dag capture loop, wait for data and deliver.
     */
    while( loop_continue )
    {
#if 0
        top = dag_advance_stream(dag_fd, dag_devnum, &bottom);
        if(top == NULL) {
            dagutil_panic("dag_advance_stream %s:%u: %s\n", dagname, dag_devnum, strerror(errno));
            log_print(LOGN_CRI, "%s: FAIL[dag_start_stream] [%s]", __FUNCTION__, strerror(errno));
            close_device();
            exit(errno);
        }
#endif

        diff = top - bottom;
        if( diff > 0 ) {
            /* read multiple packets */
            buffer_len = diff;
            total_read = 0;
            while( total_read < diff )
            {
                read_size = read_one_packet(&bottom[total_read], buffer_len, 0 );
                if( read_size < 0 ) {
                    close_device();
                    exit(-1);
                }
                else if( read_size == 0 )
                    break;

                total_read += read_size;
                buffer_len -= read_size;
            }

            bottom += total_read;
        }
        else {
#if 0
            curTime = time(NULL);
            if(oldTime + 5 < curTime) {
                if(Send_Node_Cnt && Send_Node_Cnt == Diff_Node_Cnt) {
                    /* Send Buffring Packet  */
                    if((ret = Send_CAPD_Data(pstMEMSINFO, myqid, NULL, 0)) < 0) {
                        log_print(LOGN_CRI, "[%s.%d] Send_CAPD_Data [%d][%s]", __FUNCTION__, __LINE__, ret, strerror(-ret));
                    }
                    Collection_Cnt = 50;    // COLLECTIONCNT_MIN 으로 설정
                }
                Diff_Node_Cnt = Send_Node_Cnt;
                oldTime = curTime;
            }
#endif
            usleep(0);
        }

        /* CHECK ACTIVE & STANDBY STATUS */
        curTime = time(NULL);
        if( chkTime != curTime ) {

            if( stPortStatus[0].uiLastCnt == stPortStatus[0].uiCurrCnt ) {
                stPortStatus[0].uiRetryCnt++;

                if( stPortStatus[0].uiRetryCnt > 2 ) {
                    fidb->mirrorsts[0] = CRITICAL;

                    if( fidb->mirrorActsts[0] == DEF_ACTIVE && fidb->mirrorsts[1] != CRITICAL ) {
                        fidb->mirrorActsts[0] = DEF_STANDBY;
                        fidb->mirrorActsts[1] = DEF_ACTIVE;

                        log_print( LOGN_CRI, "CHANGE ACTIVE 0 -> 1..");
                    }
                }
            }
            else {
                fidb->mirrorsts[0] = NORMAL;
                stPortStatus[0].uiRetryCnt = 0;
                stPortStatus[0].uiLastCnt = stPortStatus[0].uiCurrCnt;
            }

            if( stPortStatus[1].uiLastCnt == stPortStatus[1].uiCurrCnt ) {
                stPortStatus[1].uiRetryCnt++;

                if( stPortStatus[1].uiRetryCnt > 2 ) {
                    fidb->mirrorsts[1] = CRITICAL;

                    if( fidb->mirrorActsts[1] == DEF_ACTIVE && fidb->mirrorsts[0] != CRITICAL ) {
                        fidb->mirrorActsts[1] = DEF_STANDBY;
                        fidb->mirrorActsts[0] = DEF_ACTIVE;

                        log_print( LOGN_CRI, "CHANGE ACTIVE 1 -> 0..");
                    }
                }
            }
            else {
                fidb->mirrorsts[1] = NORMAL;
                stPortStatus[1].uiRetryCnt = 0;
                stPortStatus[1].uiLastCnt = stPortStatus[1].uiCurrCnt;
            }

            chkTime = curTime;

            log_print( LOGN_DEBUG, "[0] STS:0X%02X ACT:%u [1] STS:0X%02X ACT:%u",
                       fidb->mirrorsts[0], fidb->mirrorActsts[0], fidb->mirrorsts[1], fidb->mirrorActsts[1] );
        }
    }
}
Exemple #21
0
int Webcam::reopen_device()
{
   close_device();
   return  open_device();
}
Exemple #22
0
int main(int argc, char **argv)
{
	int w;
    int h;
    int bpp;
    GIOChannel *io;

    /* default to the gtk interface if available */
    n_ui.frame = 0;
    n_ui.num_frames = 0;
    n_ui.grab = 0;
#ifdef HAVE_GTK
    gui_update_function = gui_gtk_update;
    gui_init_function = gui_gtk_init;
#else
    gui_update_function = gui_none_update;
    gui_init_function = gui_none_init;
#endif

	w = 640;
	h = 480;
    bpp = 24;
	for (;;) {
		int index;
		int c;

		c = getopt_long(argc, argv, short_options, long_options,
				&index);
		if (c < 0)
			break;

		switch (c) {
		case 0:	/* getopt_long() flag */
			break;
		case 'd':
			dev_name = optarg;
			break;
		case 's':
			if (sscanf(optarg, "%dx%d", &w, &h) != 2) {
				fprintf(stderr, "Invalid image size\n");
				exit(EXIT_FAILURE);
			}
			break;
		case 'g':
            n_ui.grab = 1;
			break;
        case 'u':
            if (strcmp(optarg, "none") == 0) {
                gui_update_function = gui_none_update;
                gui_init_function = gui_none_init;
            }
            if (strcmp(optarg, "gtk") == 0) {
#ifdef HAVE_GTK
                gui_update_function = gui_gtk_update;
                gui_init_function = gui_gtk_init;
#else
				fprintf(stderr, "Not compiled with gtk support\n");
				exit(EXIT_FAILURE);
#endif
            }
            if (strcmp(optarg, "console") == 0) {
#ifdef HAVE_CACA
                gui_update_function = gui_console_update;
                gui_init_function = gui_console_init;
#else
				fprintf(stderr, "Not compiled with console support\n");
				exit(EXIT_FAILURE);
#endif
            }
            break;
		case 'n':
			n_ui.num_frames = strtol(optarg, NULL, 10);
            if (n_ui.num_frames <= 0 || errno == EINVAL)
                n_ui.num_frames = DEFAULT_NUM_FRAMES;
			break;
		case 'h':
			usage(stdout, argc, argv);
			exit(EXIT_SUCCESS);
		case 'm':
			switch (optarg[0]) {
			case 'm':
				io = V4L2_MEMORY_MMAP;
				break;
			case 'r':
				io = IO_METHOD_READ;
				break;
			case 'u':
				io = V4L2_MEMORY_USERPTR;
				break;
			default:
				usage(stderr, argc, argv);
				exit(EXIT_FAILURE);
			}
			break;
        case '0':
            open_socket( optarg );
            break;
		default:
			usage(stderr, argc, argv);
			exit(EXIT_FAILURE);
		}
	}

	open_device();
	init_device(w, h);
	start_capturing();

    if (n_ui.num_frames > 0)
	    printf("capturing %d frames\n", n_ui.num_frames);

	get_frame();

    gui_init_function(argc, argv, w, h, bpp);

    io = g_io_channel_unix_new(fd);
    g_io_add_watch(io,
            G_IO_IN,
            (GIOFunc)frame_ready,
            NULL);

    loop = g_main_loop_new(NULL, TRUE);
    g_main_loop_run(loop);

	stop_capturing();
	uninit_device();
	close_device();
	return 0;
}
Exemple #23
0
int main(int argc, char **argv)
{
        dev_name = "/dev/video0";

        for (;;) {
                int idx;
                int c;

                c = getopt_long(argc, argv,
                                short_options, long_options, &idx);

                if (-1 == c)
                        break;

                switch (c) {
                case 0: /* getopt_long() flag */
                        break;

                case 'd':
                        dev_name = optarg;
                        break;

                case 'h':
                        usage(stdout, argc, argv);
                        exit(EXIT_SUCCESS);

                case 'm':
                        io = IO_METHOD_MMAP;
                        break;

                case 'r':
                        io = IO_METHOD_READ;
                        break;

                case 'u':
                        io = IO_METHOD_USERPTR;
                        break;

                case 'o':
                        out_buf++;
                        break;

                case 'f':
                        force_format=1;
                        break;

		case 'F':
			force_format=2;
			break;

                case 'c':
                        errno = 0;
                        frame_count = strtol(optarg, NULL, 0);
                        if (errno)
                                errno_exit(optarg);
                        break;

                default:
                        usage(stderr, argc, argv);
                        exit(EXIT_FAILURE);
                }
        }

        open_device();
        init_device();
        start_capturing();
        mainloop();
        stop_capturing();
        uninit_device();
        close_device();
        fprintf(stderr, "\n");
        return 0;
}
Exemple #24
0
void
video_specific_die()
{
    uninit_device ();
    close_device ();
}
Exemple #25
0
int main(int argc, char **argv)
{
  dev_name = "/dev/video0";
  

  if (argc == 1)
    {
      usage(stdout, argc, argv);
      exit(EXIT_SUCCESS);
    }

  for (;; ) {
    int idx;
    int c;
    
    c = getopt_long(argc, argv,
		    short_options, long_options, &idx);
    
    if (-1 == c)
      break;

    switch (c) {
    case 0: /* getopt_long() flag */
      break;
      
    case 'd':
      dev_name = optarg;
      break;
      
    case 'h':
      usage(stdout, argc, argv);
      exit(EXIT_SUCCESS);
      
    case 'i':
      iframe = 1;
      break;
      
    case 'r':
      if (!strcmp(optarg, "VBR"))
	rcmode = RATECONTROL_VBR;
      
      if (!strcmp(optarg, "CBR"))
	rcmode = RATECONTROL_CBR;
      
      if (!strcmp(optarg, "QP"))
	rcmode = RATECONTROL_CONST_QP;
      
      if (rcmode < 0)
	{
	  fprintf(stderr, "Unknown RC mode.\n");
	  usage(stdout, argc, argv);
	  exit(EXIT_SUCCESS);
	}
      
      break;
      
    case 'b':
      errno = 0;
      bitrate = strtol(optarg, NULL, 0);
      if (errno)
	errno_exit(optarg);
      break;

    case 'q':
      errno = 0;
      qp = strtol(optarg, NULL, 0);
      if (errno)
	errno_exit(optarg);
      break;
      
    default:
      usage(stderr, argc, argv);
      exit(EXIT_FAILURE);
    }
  }
  
  open_device();
  
  if (bitrate > 0)
    setBitrate(bitrate / 8, bitrate / 8);
  
  if (iframe)
    setNextFrame(0x01);
  
  if (rcmode >= 0)
    setRCMode(rcmode);

  if (qp > 0)
    setQP(0, qp, qp);

  close_device();
  return 0;
}
void update(void* instance)
{
  InstancePtr inst = (InstancePtr) instance;
  MyInstancePtr my = inst->my;
  int xsize = trim_int(inst->in_x_size->number, 0 , 1024);
  int ysize = trim_int(inst->in_y_size->number, 0 , 1024);

  int device_num = trim_int(inst->in_device->number, 0, MAX_DEVICES-1);
    
  //check if device changed
  if (my->device_num != device_num || my->drv == 0 ||
      !my->drv->is_open())
    {
      try
        {
          if (my->device_num != -1)
            {
              my->drv = 0;
              close_device(my->device_num);			  
            }
          
          my->drv = open_device(device_num);
          my->device_num = device_num;
        }
      catch (std::exception& e)
        {
          my->device_num = -1;
          s_log(0, e.what());
        }
    }
  
  try
    {
      
  if (my->drv == 0 || !my->drv->is_open())
    throw std::runtime_error("no usable capture device");

  bool new_frame = true;
  int capture_width;
  int capture_height;
  my->drv->status(capture_width, capture_height, new_frame);
  if (xsize == 0 || ysize == 0)
    {
      // set xsize and ysize to the format of the capture device
      xsize = capture_width;
      ysize = capture_height;
    }   

  if (new_frame == false)
    return;

  // resize output
  FrameBufferAttributes attribs;
  attribs.xsize = xsize;
  attribs.ysize = ysize;
  framebuffer_changeAttributes(inst->out_result, &attribs);

      my->drv->decode_frame(inst->out_result->framebuffer,
                            xsize, ysize);
    }
  catch (std::exception& e)
    {	          
      s_log(0, e.what());
	  
      // set error dummy
      FrameBufferAttributes attribs;
      attribs.xsize=1;
      attribs.ysize=1;
      framebuffer_changeAttributes(inst->out_result,&attribs);
      // set black background
      *(inst->out_result->data)=0x00000000;         
      return;
    }
}
Exemple #27
0
static int v4l2_case_vary_frame_rate(void* user_ptr, int test_num)
{
	v4l2_data* data = (v4l2_data*)user_ptr;
	int ret = 0;

	float initial_fps = 0.0;
	float initial_cfps = 0.0; /* calculated fps for original value */

	float target_fps = data->device->frame_rate;
	float target_cfps = 0.0; /* calculated fps for new value */

	boolean reset = FALSE;

	if (!open_device(data->device))
	{
		BLTS_DEBUG("Can't open device %s\n", data->device->dev_name);
		return -1;
	}

	/* find out initial frame rate */
	if(get_framerate_fps(data->device, &initial_fps) != 0)
	{
		BLTS_DEBUG("Can't get initial fps\n");
		goto err;
	}

	/* test frame rate with initial values */
	if(test_frame_rate(data->device, &initial_fps, &initial_cfps) != 0)
	{
		BLTS_DEBUG("Can't test initial frame rate\n");
		goto err;
	}

	/* try to set new frame rate values */
	if(set_framerate_fps(data->device, &target_fps) != 0)
	{
		BLTS_DEBUG("Can't set new frame rate\n");
		reset = TRUE;
		goto err;
	}

	/* test frame rate with new values */
	if(test_frame_rate(data->device, &target_fps, &target_cfps) != 0)
	{
		BLTS_DEBUG("Can't test new frame rate\n");
		reset = TRUE;
		goto err;
	}

	/* sanity check for test times */
	if(initial_fps < target_fps)
		ret = ((initial_cfps < target_cfps))?0:-1;
	else if (initial_fps > target_fps)
		ret = ((initial_cfps > target_cfps))?0:-1;
	else
		ret = 0;

	/* reset initial frame rate */
	set_framerate(data->device, 0, 0, &initial_fps);
	close_device(data->device);

	return ret;
err:
	if(reset)
		set_framerate(data->device, 0, 0, &initial_fps);
	close_device(data->device);
	return -1;
}
Exemple #28
0
void *transmission(void *arg)
{
#define lock pthread_mutex_lock(&this_call->mutex)
#define unlock pthread_mutex_unlock(&this_call->mutex)

    ToxWindow* self = arg;
    int32_t call_index = self->call_idx;

    /* Missing audio support */
    if ( !ASettins.av ) _cbend;

    Call* this_call = &ASettins.calls[call_index];

    int32_t dec_frame_len;
    int16_t PCM[frame_size];
    this_call->has_output = 1;
    
    if ( open_primary_device(input, &this_call->in_idx) != de_None ) 
        line_info_add(self, NULL, NULL, NULL, "Failed to open input device!", SYS_MSG, 0, 0);
    if ( register_device_callback(call_index, this_call->in_idx, read_device_callback, &call_index, _True) != de_None) 
        /* Set VAD as true for all; TODO: Make it more dynamic */
        line_info_add(self, NULL, NULL, NULL, "Failed to register input handler!", SYS_MSG, 0, 0);
    
    if ( open_primary_device(output, &this_call->out_idx) != de_None ) {
        line_info_add(self, NULL, NULL, NULL, "Failed to open output device!", SYS_MSG, 0, 0);
        this_call->has_output = 0;
    }
    /* Start transmission */
    while (this_call->ttas) {
        
        lock;
        if ( this_call->has_output ) {
            
            if (playback_device_ready(this_call->out_idx) == de_Busy) {
                unlock;
                continue;
            }
            
            dec_frame_len = toxav_recv_audio(ASettins.av, call_index, frame_size, PCM);

            /* Play the packet */
            if (dec_frame_len > 0) {
                write_out(this_call->out_idx, PCM, dec_frame_len, av_DefaultSettings.audio_channels);
            }
            else if (dec_frame_len != 0) {
                /* >implying it'll ever get an error */
            }
            
        }
        unlock;
        
        usleep(1000);
    }

cleanup:
    if ( this_call->in_idx != -1 ) if ( close_device(input, this_call->in_idx) != de_None )
        line_info_add(self, NULL, NULL, NULL, "Failed to close input device!", SYS_MSG, 0, 0);
    
    if ( this_call->out_idx != -1 ) if ( close_device(output, this_call->out_idx) != de_None )
        line_info_add(self, NULL, NULL, NULL, "Failed to close output device!", SYS_MSG, 0, 0);
    
    set_call(this_call, _False);
    
    _cbend;
}
Exemple #29
0
int
main(int argc,
     char** argv)
{
  devices[n_devices-1].dev_name = "/dev/video0";

  int dev_cnt = 0;
  for (;;) {
    int index;
    int c;

    c = getopt_long(argc, argv,
                    short_options, long_options,
                    &index);

    if (-1 == c)
      break;

    switch (c) {
    case 0: /* getopt_long() flag */
      break;

    case 'd':
      if (dev_cnt == MAX_DEVICES)
      {
        fprintf(stderr, "too many devices\n");
        exit(EXIT_FAILURE);
      }
      if (dev_cnt)
      {
        n_devices++;
      }
      dev_cnt++;
      devices[n_devices-1].dev_name = optarg;
      break;

    case 'h':
      usage(stdout, argc, argv);
      exit(EXIT_SUCCESS);

    case 'm':
      devices[n_devices-1].io = IO_METHOD_MMAP;
      break;

    case 'r':
      devices[n_devices-1].io = IO_METHOD_READ;
      break;

    case 'b':
      devices[n_devices-1].base_name = optarg;
      break;

    default:
      usage(stderr, argc, argv);
      exit(EXIT_FAILURE);
    }
  }

  int i;
  for (i = 0; i< n_devices; ++i)
  {
    open_device(&devices[i]);
    init_device(&devices[i]);
  }

  for (i = 0; i< n_devices; ++i)
  {
    start_capturing(&devices[i]);
  }

  mainloop();

  for (i = 0; i< n_devices; ++i)
  {
    stop_capturing(&devices[i]);
    uninit_device(&devices[i]);
    close_device(&devices[i]);
  }

  exit(EXIT_SUCCESS);

  return 0;
}
Exemple #30
0
int main(int argc, char **argv)
{
	struct numachip_device **devices;
	//struct numachip_context *cntxt;
	struct numachip_context **cntxt;
	int counter=0, i=0;
	int num_devices; 
    
	if (argc<2) {
		usage();
		return(-1);
	}
  
	devices = numachip_get_device_list(&num_devices);
	DEBUG_STATEMENT(printf("Found %d NumaChip devices\n", num_devices));
    
	if (!devices)
		return -1;

	DEBUG_STATEMENT(printf("sizeof(struct numachip_context *) %ld\n", sizeof(struct numachip_context *)));
	cntxt = malloc(num_devices * sizeof(struct numachip_context *));

	for(i=0; i<num_devices; i++) {
		cntxt[i] = numachip_open_device(devices[i]);
	}
    
	numachip_free_device_list(devices);
	
    
	if (!cntxt[0])
		return -1;

    
    
	/* Get the parameters */
	for (counter=1; (int)counter<argc; counter++) {
		if (!strcmp("-dump-scc-csr",argv[counter])) {
			dump_scc_csr(cntxt[0]);
			dump_scc_csr(cntxt[1]);
			continue;
		}
	
		if (!strcmp("-dump-phy-regs",argv[counter])) {
			phy_regs(cntxt[0]);
			phy_regs(cntxt[1]);
			continue;
		}

		if (!strcmp("-setup-tracer",argv[counter])) {	    
			tracer_setup(*cntxt);
			continue;
		}

		if (!strcmp("-tracer-result",argv[counter])) {	    
			tracer_result(*cntxt);	    
			continue;
		}
	

		if (!strcmp("-count-start",argv[counter])) {	    
			count_api_start(cntxt, num_devices);
			continue;
		}

		if (!strcmp("-count-stop",argv[counter])) {	    
			count_api_stop(cntxt, num_devices);
			continue;
		}
	

		if (!strcmp("-count-rate",argv[counter])) {
			count_api_stop(cntxt, num_devices);
			count_api_start(cntxt, num_devices);
			count_rate(cntxt, num_devices);

			continue;
		}

	}

    
	for(i=0; i<num_devices; i++) {
		close_device(cntxt[i]);
	}
	free(cntxt);
    
	return  0;
}