Esempio n. 1
0
static void
printALCInfo (void)
{
  ALCint major, minor;
  ALCdevice *device;

  if (alcIsExtensionPresent (NULL, (const ALCchar *) "ALC_ENUMERATION_EXT") ==
      AL_TRUE)
    {
      printDevices (ALC_DEVICE_SPECIFIER, "");
      printDevices (ALC_CAPTURE_DEVICE_SPECIFIER, "capture ");
    }
  else
    {
      printf ("no device enumeration available\n");
    }

  device = alcGetContextsDevice (alcGetCurrentContext ());
  checkForErrors ();

  printf ("default device: %s\n",
          getStringALC (device, ALC_DEFAULT_DEVICE_SPECIFIER));

  printf ("default capture device: %s\n",
          getStringALC (device, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER));

  alcGetIntegerv (device, ALC_MAJOR_VERSION, 1, &major);
  alcGetIntegerv (device, ALC_MAJOR_VERSION, 1, &minor);
  checkForErrors ();
  printf ("ALC version: %d.%d\n", (int) major, (int) minor);

  printExtensions ("ALC extensions", ' ',
                   getStringALC (device, ALC_EXTENSIONS));
}
Esempio n. 2
0
	//-----------------------------------------------------------------//
	void audio_io::alc_info() const
	{
		if(alcIsExtensionPresent(NULL, (const ALCchar*)"ALC_ENUMERATION_EXT") == AL_TRUE) {
			if(alcIsExtensionPresent(NULL, (const ALCchar*)"ALC_ENUMERATE_ALL_EXT") == AL_TRUE) {
				printDevices(ALC_ALL_DEVICES_SPECIFIER, "playback ");
			} else {
				printDevices(ALC_DEVICE_SPECIFIER, "playback ");
				printDevices(ALC_CAPTURE_DEVICE_SPECIFIER, "capture ");
			}
		} else {
			std::cout << boost::format("No device enumeration available\n");
		}

		ALCdevice* device = alcGetContextsDevice(alcGetCurrentContext());
		checkForErrors();

		std::cout << boost::format("Default device: %s\n")
			% alcGetString(device, ALC_DEFAULT_DEVICE_SPECIFIER);

		std::cout << boost::format("Default capture device: %s\n")
			% alcGetString(device, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);

		ALCint major, minor;
		alcGetIntegerv(device, ALC_MAJOR_VERSION, 1, &major);
		alcGetIntegerv(device, ALC_MINOR_VERSION, 1, &minor);
		checkForErrors();
		std::cout << boost::format("ALC version: %d.%d\n") % static_cast<int>(major) % static_cast<int>(minor);

		printExtensions("ALC extensions", ' ',
			alcGetString(device, ALC_EXTENSIONS));
		checkForErrors();
	}
Esempio n. 3
0
HRESULT IDirect3D9New::CreateDeviceEx(UINT Adapter,D3DDEVTYPE DeviceType,HWND hFocusWindow,DWORD BehaviorFlags,D3DPRESENT_PARAMETERS* pp,D3DDISPLAYMODEEX* pFullscreenDisplayMode,IDirect3DDevice9Ex** ppDev)
{
  dbg("IDirect3D9New::CreateDeviceEx 0x%08X", d3d);
  // TODO: Do we need to do something to pFullscreenDisplayMode?

  printDevices((IDirect3D9Ex*)d3d);
 
  IDirect3DDevice9SoftTH *d3dd = new IDirect3DDevice9SoftTH(this, (IDirect3D9Ex*)d3d, hFocusWindow, BehaviorFlags, pp);
  d3dd->setEx(true);
  HRESULT ret = d3dd->getCreateDeviceResult();
  if(ret == D3D_OK) {
    *ppDev = (IDirect3DDevice9Ex*) d3dd;
    listD3D9DeviceSoftTH.push_back(d3dd);
  } else
    delete d3dd;
  dbg("Created ex device 0x%08X", *ppDev);
  return ret;
}
Esempio n. 4
0
int main(int argc, char *argv[]) {
  int opt;
  int devices=0, libs=0, libfuncts=0, flows=0, flowfuncts=0;

  if(argc==1)
    usage();

  while((opt = getopt(argc,argv,"dlfou"))!=EOF) {
    switch(opt) {
    case 'd' :
      devices=1;
      break;
    case 'l' :
      libs=1;
      break;
    case 'f' :
      libfuncts=1;
      break;
    case 'o' :
      flows=1;
      break;
    case 'u' :
      flowfuncts=1;
      break;
    default:
      usage();
    }
  }

  if(devices)
    printDevices();

  if(flows || flowfuncts)
    printFlows(flowfuncts);

  if(libs || libfuncts) {
  	printLibs(libfuncts);
    exit(0);
  }

  return 0;
}
Esempio n. 5
0
void loop() 
{
  if(0 < Serial.readBytesUntil('\n',buffer,20)){
    // Serial.println(String(buffer)+"<");
    if(String(buffer).equals(String("list all"))){
      printDevices();
    }
    else{
      indexOfSpace = String(buffer).indexOf(' ');
      if(indexOfSpace>-1){
        targetDevice = getDevice(String(buffer).substring(0,indexOfSpace));
        if(targetDevice){
          Serial.print("PORT ");
          Serial.print(targetDevice->port, DEC);
          Serial.print(" - set to ");
          Serial.println(String(buffer).substring(indexOfSpace+1).toInt(),DEC);
          if(String("servo_1").equals(targetDevice->name)){
            servo1.write(String(buffer).substring(indexOfSpace+1).toInt());
          }
          else if(String("servo_2").equals(targetDevice->name)){
            servo2.write(String(buffer).substring(indexOfSpace+1).toInt());
          }
          else if(String("pwm").equals(targetDevice->type)){
            analogWrite((int)(targetDevice->port),String(buffer).substring(indexOfSpace+1).toInt());
          }
        }
        else{
          Serial.println("Device Not Found");
        }
      }
      else{
        Serial.print("Invalid: ");
        Serial.println(buffer);
      }      
    }
    for(int i=0; i<20; i++){
      buffer[i] = '\0';
    }
  }
} 
Esempio n. 6
0
HRESULT IDirect3D9New::CreateDevice(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pp, IDirect3DDevice9** ppDev)
{
  dbg("IDirect3D9New::CreateDevice 0x%08X", d3d);

  //return d3d->CreateDevice(Adapter, DeviceType, hFocusWindow, BehaviorFlags, pp, ppDev);

#if !USE_D3DEX
  // Direct3DEx disabled: Debug device
  bool fullscreen = pp->Windowed==0;
  D3DDISPLAYMODEEX mode = {
    sizeof(D3DDISPLAYMODEEX),
    pp->BackBufferWidth,   pp->BackBufferHeight,
    pp->FullScreen_RefreshRateInHz,  pp->BackBufferFormat,
    D3DSCANLINEORDERING_PROGRESSIVE
  };
  IDirect3DDevice9Ex *paska;
  D3DCALL( d3d->CreateDeviceEx(Adapter, DeviceType, hFocusWindow, BehaviorFlags, pp, fullscreen?&mode:NULL, &paska) );

  *ppDev = new IDirect3DDevice9New(paska, d3d);
  return D3D_OK;

#else
  // Real device

  printDevices((IDirect3D9Ex*)d3d);

  IDirect3DDevice9SoftTH *d3dd = new IDirect3DDevice9SoftTH(this, (IDirect3D9Ex*)d3d, hFocusWindow, BehaviorFlags, pp);
  d3dd->setEx(false);
  HRESULT ret = d3dd->getCreateDeviceResult();
  if(ret == D3D_OK) {
    *ppDev = (IDirect3DDevice9*) d3dd;
    listD3D9DeviceSoftTH.push_back(d3dd);
  } else {
    dbg("createdevice failed!");
    delete d3dd;
  }
  dbg("Created device 0x%08X", *ppDev);
  return ret;
#endif
}
Esempio n. 7
0
int main(int argc, char* argv[]){

    /* local vars */
    enum OPTIONS mode;
    char filename[MAX_FILENAME_LENGTH];
    FILE* devFile = NULL;
    struct SWDeviceEntry devices[USERMON_MAXDEVICES];
    int devCnt = 0;

    /* input options */
    if(argc < 2){
        mode = HEX;
        (void) argv;
    }
    else{
        if(strncmp(argv[1], "-hex", 4) == 0){
            mode = HEX;
        }
        else if(strncmp(argv[1], "-dec", 4) == 0){
            mode = DECIMAL;
        }
        else if(strncmp(argv[1], "-raw", 4) == 0){
            mode = RAW;
        }
        else if(strcmp(argv[1], "-h") == 0){
            mode = HELP;
        }
        else{
            fprintf(stderr, "Unknown option: %5s\n Try '-h'\n", argv[1]);
            exit(EXIT_FAILURE);
        }
    }

    /* Switch on Mode*/
    if((mode == HEX) || (mode == DECIMAL) || (mode == RAW)){
        
        /* Get Device Filename */
        if(buildDevFileName(filename, MAX_FILENAME_LENGTH) <= 0){
            fprintf(stderr, "printDevices: Could not create devFile name.\n");
            exit(EXIT_FAILURE);
        }
        
        /* Open Device File */
        devFile = openDevFile(filename);
        if(devFile == NULL){
            fprintf(stderr, "printDevices: Could not open devFile.\n");
            exit(EXIT_FAILURE);
        }
        
        /* Get Device Array */
        devCnt = getDevices(devices, USERMON_MAXDEVICES, devFile);
        if(devCnt < 0){
            fprintf(stderr, "printDevices: "
                    "Error gettign device list: getDevices returned %d\n",
                    devCnt);
            exit(EXIT_FAILURE);
        }
        
        /* Close Device File */
        if(closeDevFile(devFile) != 0){
            fprintf(stderr, "printDevices: Could not close devFile.\n");
            exit(EXIT_FAILURE);
        }
        devFile = NULL;

        /* Print Device Data */
        if(mode == HEX){
            if(printDevicesHex(stdout, devices, devCnt) < 0){
                fprintf(stderr, "swls: Error listing devices in HEX mode.\n");
                exit(EXIT_FAILURE);
            }
        }
        else if(mode == DECIMAL){
            if(printDevices(stdout, devices, devCnt) < 0){
                fprintf(stderr, "swls: Error listing devices in DEC mode.\n");
                exit(EXIT_FAILURE);
            }
        }
        else if(mode == RAW){
            if(printDevicesRaw(stdout, devices, devCnt) < 0){
                fprintf(stderr, "swls: Error listing devices in RAW mode.\n");
                exit(EXIT_FAILURE);
            }
        }
        else{
            fprintf(stderr, "swls: Unhandeled output mode: %d\n", mode);
            exit(EXIT_FAILURE);
        }
    }
    else if(mode == HELP){
        fprintf(stdout, "swls: List SmartWall devices\n"
                "Options:\n"
                "-hex: Output in Hex Mode\n"
                "-dec: Output in Decimal Mode\n"
                "-raw: Output in Raw Mode\n"
                "-h: Print this menu\n");
    }
    else {
        fprintf(stderr, "swls: Unhandeled mode: %d\n", mode);
        exit(EXIT_FAILURE);
    }
    
    return 0;
}
Esempio n. 8
0
vrpn_libusb::vrpn_libusb(const char *name, vrpn_Connection *c, std::string configFile) : vrpn_Button(name,c), vrpn_Analog(name,c)
{
    _devList = NULL;
    _dev = NULL;
    _vendorID = -1;
    _productID = -1;
    _entryNum = 0;
    _configNum = 0;
    _numConfigs = 0;
    _interfaceNum = 0;
    _numInterfaces = 0;
    _altSettingNum = 0;
    _numAltSettings = 0;
    _endpointNum = 0;
    _numEndpoints = 0;
    _address = 0;
    _packetSize = 0;
    _printPacket = false;
    _context = NULL;

    _error = false;

    num_buttons = 0;
    num_channel = 0;

    _driverPresent = false;

    if(!loadConfigFile(configFile))
    {
	_error = true;
	return;
    }

    if(libusb_init(&_context) < 0)
    {
	std::cerr << "Error libusb init." << std::endl;
	_error = true;
	return;
    }

    int devCount;

    if((devCount = libusb_get_device_list(NULL, &_devList)) < 0 )
    {
	std::cerr << "Error getting device list .." << std::endl;
	_error = true;
	return;	
    }

    if(_vendorID < 0 || _productID < 0)
    {
	std::cerr << "Error: vendorID/productID must be set." << std::endl;
	std::cerr << "Printing list of usb devices:" << std::endl;
	printDevices(_devList);
	_error = true;
	return;
    }

    bool usberror = false;

    _dev = findDevice(_devList);
    if(!_dev)
    {
	printConfig();
	std::cerr << "Error: device with vendorID/productID with given entry not found." << std::endl;
	std::cerr << "Printing list of usb devices:" << std::endl;
	printDevices(_devList);
	_error = true;
	return;
    }

    libusb_device_descriptor desc;
    if(libusb_get_device_descriptor(_dev,&desc) >= 0)
    {
	_numConfigs = (int)desc.bNumConfigurations;
	if(_configNum >= 0 && _configNum < _numConfigs)
	{
	    libusb_config_descriptor * cdesc;
	    if(libusb_get_config_descriptor(_dev,_configNum,&cdesc) >= 0)
	    {
		_numInterfaces = (int)cdesc->bNumInterfaces;
		if(_interfaceNum >= 0 && _interfaceNum < _numInterfaces)
		{
		    libusb_interface interface = cdesc->interface[_interfaceNum];
		    _numAltSettings = (int)interface.num_altsetting;
		    if(_altSettingNum >= 0 && _altSettingNum < _numAltSettings)
		    {
			libusb_interface_descriptor idesc = interface.altsetting[_altSettingNum];
			_numEndpoints = (int)idesc.bNumEndpoints;
			if(_endpointNum >= 0 && _endpointNum < _numEndpoints)
			{
			    libusb_endpoint_descriptor edesc = idesc.endpoint[_endpointNum];
			    _address = (int)edesc.bEndpointAddress;
			    _packetSize = (int)edesc.wMaxPacketSize;
			}
			else
			{
			    std::cerr << "Error: Invalid endpoint number." << std::endl;
			    usberror = true;
			}
		    }
		    else
		    {
			std::cerr << "Error: Invalid altSetting number." << std::endl;
			usberror = true;
		    }
		}
		else
		{
		    std::cerr << "Error: Invalid interface number." << std::endl;
		    usberror == true;
		}
	    }
	    else
	    {
		std::cerr << "Error: unable to get config descriptor." << std::endl;
		usberror = true;
	    }
	}
	else
	{
	    std::cerr << "Error: Invalid config number." << std::endl;
	    usberror = true;
	}
    }
    else
    {
	std::cerr << "Error: unable to get device descriptor." << std::endl;
	usberror = true;
    }

    printConfig();

    if(libusb_open(_dev, &_handle) < 0)
    {
	std::cerr << "Error opening device bus: " << libusb_get_bus_number(_dev) << " device: " << libusb_get_device_address(_dev) << std::endl;
	usberror = true;
    }

    if(usberror)
    {
	_error = true;
	return;
    }

    num_buttons = 0;
    for(int i = 0; i < _buttonGroups.size(); ++i)
    {
	num_buttons += _buttonGroups[i]->numButtons;
    }

    for(int i = 0; i < num_buttons; i++)
    {
	buttons[i] = 0;
	lastbuttons[i] = 0;
    }

    num_channel = _valuators.size();

    _packet = new unsigned char[_packetSize];
    for(int i = 0; i < _numInterfaces; i++)
    {
	if(libusb_kernel_driver_active(_handle, i) == 1)
	{
	    _driverPresent = true;

	    if(libusb_detach_kernel_driver(_handle, i) != 0)
	    {
		std::cerr << "Error detaching driver from interface " << i << std::endl;
	    }
	}
	else
	{
	    _driverPresent = false;
	}
    }

    if(libusb_claim_interface(_handle, _interfaceNum) != 0)
    {
	std::cerr << "Error: could not claim device interface." << std::endl;
	_error = true;
	return;
    }

    vrpn_gettimeofday(&_lastUpdateTime,NULL);

    _transfer = libusb_alloc_transfer(5);
    libusb_fill_interrupt_transfer(_transfer, _handle, _address, _packet, _packetSize, transCallback, (void*)this, 10000);
    libusb_submit_transfer(_transfer);

    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    _ti = new ThreadInit;
    _ti->context = _context;
    _ti->quit = false;
    pthread_create(&_updateThread,&attr,libusbUpdate,(void*)_ti);

    pthread_attr_destroy(&attr);

    std::cerr << "Init good." << std::endl;
}
Esempio n. 9
0
int main(void) {
    
	FILE* programHandle;
	size_t programSize, kernelSourceSize;
	char *programBuffer, *kernelSource;
    
	// get size of kernel source
	programHandle = fopen("kernel.cl", "r");
	if (programHandle == NULL)
	{
		printf("Can't open kernel file!\n");
		return 1;
	}
	fseek(programHandle, 0, SEEK_END);
	programSize = ftell(programHandle);
	rewind(programHandle);
    
	// read kernel source into buffer
	programBuffer = (char*) malloc(programSize + 1);
	programBuffer[programSize] = '\0';
	fread(programBuffer, sizeof(char), programSize, programHandle);
	fclose(programHandle);
    
    // Create game of life board and initialize it
	GameOfLife *test = new GameOfLife(COLUMNS, ROWS);
    
	test->setItem(1, 1, 1);
	test->setItem(2, 1, 1);
	test->setItem(3, 1, 1);
    
	test->setItem(14, 0, 1);
	test->setItem(15, 1, 1);
	test->setItem(13, 2, 1);
	test->setItem(14, 2, 1);
	test->setItem(15, 2, 1);
    
	//test->print();
    
	printDevices();
    
	// Get platform and device information
	cl_platform_id * platforms = NULL;
	cl_uint num_platforms;
    
	//Set up the Platform
	cl_int clStatus = clGetPlatformIDs(0, NULL, &num_platforms);
    assert(clStatus == 0);
	platforms = (cl_platform_id *) malloc(sizeof(cl_platform_id)*num_platforms);
	clStatus = clGetPlatformIDs(num_platforms, platforms, NULL);
    assert(clStatus == 0);
    
	//Get the devices list and choose the device you want to run on
	cl_device_id *device_list = NULL;
	cl_uint num_devices;
	clStatus = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_GPU, 0, NULL, &num_devices);
	device_list = (cl_device_id *) malloc(sizeof(cl_device_id)*num_devices);
	clStatus = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_GPU, num_devices, device_list, NULL);
    assert(clStatus == 0);
    
	// Create one OpenCL context for each device in the platform
	cl_context context;
	context = clCreateContext(NULL, num_devices, device_list, NULL, NULL, &clStatus);
	assert(clStatus == 0);
    
	// Create a command queue
	cl_command_queue command_queue = clCreateCommandQueue(context, device_list[0], 0, &clStatus);
	assert(clStatus == 0);
    
	// Create memory buffers on the device for matrix and result
	cl_mem matrix = clCreateBuffer(context, CL_MEM_READ_ONLY, VECTOR_SIZE * sizeof(int), NULL, &clStatus);
	assert(clStatus == 0);
    
	cl_mem result = clCreateBuffer(context, CL_MEM_WRITE_ONLY, VECTOR_SIZE * sizeof(int), NULL, &clStatus);
	assert(clStatus == 0);
    
	// Copy the Buffer matrix to the device
	clStatus = clEnqueueWriteBuffer(command_queue, matrix, CL_TRUE, 0, VECTOR_SIZE * sizeof(int), test->getRow(0), 0, NULL, NULL);
	assert(clStatus == 0);
    
	// Create a program from the kernel source
	cl_program program = clCreateProgramWithSource(context, 1, (const char **) &programBuffer, &programSize, &clStatus);
	assert(clStatus == 0);
    
	// read kernel source back in from program to check
	clGetProgramInfo(program, CL_PROGRAM_SOURCE, 0, NULL, &kernelSourceSize);
	kernelSource = (char*) malloc(kernelSourceSize);
	clGetProgramInfo(program, CL_PROGRAM_SOURCE, kernelSourceSize, kernelSource, NULL);
    // Print the kernel source
	//printf("\nKernel source:\n\n%s\n", kernelSource);
	free(kernelSource);
    
	// Build the program
	clStatus = clBuildProgram(program, 1, device_list, NULL, NULL, NULL);
    
	//assert(clStatus==0);
	if (clStatus != CL_SUCCESS) {
		size_t logSize;
		cl_build_status status;
		char *programLog;
        
		// check build error and build status first
		clGetProgramBuildInfo(program, device_list[0], CL_PROGRAM_BUILD_STATUS, sizeof(cl_build_status), &status, NULL);
        
		// check build log
		clGetProgramBuildInfo(program, device_list[0],
                              CL_PROGRAM_BUILD_LOG, 0, NULL, &logSize);
		programLog = (char*) calloc(logSize + 1, sizeof(char));
		clGetProgramBuildInfo(program, device_list[0], CL_PROGRAM_BUILD_LOG, logSize + 1, programLog, NULL);
		printf("Build failed; error=%d, status=%d, programLog:\n\n%s\n", clStatus, status, programLog);
		free(programLog);
		return 1;
	}
    
	// Create the OpenCL kernel
	cl_kernel kernel = clCreateKernel(program, "gameOfLifeKernel", &clStatus);
    assert(clStatus == 0);
    
    int rows = ROWS;
    int columns = COLUMNS;

	// Set the arguments of the kernel
    clStatus = clSetKernelArg(kernel, 0, sizeof(int *), (void *) &rows);
	assert(clStatus == 0);
    clStatus = clSetKernelArg(kernel, 1, sizeof(int *), (void *) &columns);
	assert(clStatus == 0);
	clStatus = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *) &matrix);
	assert(clStatus == 0);
	clStatus = clSetKernelArg(kernel, 3, sizeof(cl_mem), (void *) &result);
	assert(clStatus == 0);
    
	// Execute the OpenCL kernel on the list
	size_t global_size = VECTOR_SIZE; // Process the entire lists
	size_t local_size = 1; // Process one item at a time
    
    // ----- NORMAL STEP -----
    
    Timer::bit64 start, end;
    
	start = Timer::getTime();
	test->step();
	end = Timer::getTime();
    
	//test->print();
	std::cout << "Time elapsed normal step: " << end - start << std::endl;
    
	// -----------------------
    
    
	start = Timer::getTime();  // START -----
	clStatus = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL);
	assert(clStatus == 0);
    
	// Read the cl memory result on device to the host variable result
	clStatus = clEnqueueReadBuffer(command_queue, result, CL_TRUE, 0, VECTOR_SIZE * sizeof(int), test->getRow(0), 0, NULL, NULL);
	assert(clStatus == 0);
    
	// Clean up and wait for all the comands to complete.
	clStatus = clFlush(command_queue);
	assert(clStatus == 0);
	clStatus = clFinish(command_queue); // to make sure the kernel completed
	assert(clStatus == 0);
    
	end = Timer::getTime();  // END -----
    
	//test->print();
	std::cout << "Time elapsed with OpenCL: " << end - start << std::endl;
    
	// Finally release all OpenCL allocated objects and host buffers
	clStatus = clReleaseKernel(kernel);
	assert(clStatus == 0);
	clStatus = clReleaseProgram(program);
	assert(clStatus == 0);
	clStatus = clReleaseMemObject(matrix);
	assert(clStatus == 0);
	clStatus = clReleaseMemObject(result);
	assert(clStatus == 0);
	clStatus = clReleaseCommandQueue(command_queue);
	assert(clStatus == 0);
	clStatus = clReleaseContext(context);
	assert(clStatus == 0);
	free(platforms);
	free(device_list);
	delete test;
    

	std::cout << "Press Enter to continue...";
    std::cin.get();
	return 0;
    
}
Esempio n. 10
0
int main(int argc, char *argv[])
{
	std::cout << "INAV SERVER v" << INAV_VERSION << std::endl;
	std::vector<Thread *> threads;
	int returnCode;

	//Print Help
	std::string parsedString = parser( argc, argv, "-h" );
	if( parsedString.size() > 0 )
		printHelp();
	parsedString = parser( argc, argv, "--help" );
	if( parsedString.size() > 0 )
		printHelp();

	//Check for debug
	parsedString = parser( argc, argv, "-vv" );
	if( parsedString.size() > 0 )
		inav::DEBUG = true;


	//check log file
	if (!inav::log)
	{
		std::cerr << "Unable to write to log file: " << inav::logFile << std::endl;
		exit(-1);
	}
	log("INAV starting up!");

	//check command line options
	//check if we should print out pcap capabile devices
	parsedString = parser( argc, argv, "-ls" );
	if ( parsedString == "set" )
	{
		log( "Server started with -ls option printing devices and halting..." );
		printDevices();
		exit(-1);
	}

	std::string device = parser( argc, argv, "-i" );
	if( device == "set" )
	{
			log( "WARNING: device flag given but no device specified! CANNOT CONTINUE" );
			exit( -1 );
	}
	std::cout << "Device(s) set to " <<   device << std::endl;
	log( "Device(s) set to " + device );
	std::vector< std::string > devices;
	if( device.size() != 0 )
		devices = parseCommas( device );

	//Setup pcap file input
	std::string file = parser( argc, argv, "-f" );
	if( file == "set" )
	{
			log( "WARNING: input selected as pcap file with no file specified. CANNOT CONTINUE" );
			exit( -1 );
	}
	std::cout << "File(s) set to " << file << std::endl;
	log( "File(s) set to " + file );
	std::vector< std::string > files;
	if( file.size() != 0 )
		files = parseCommas( file );

	std::string cvsFile = parser( argc, argv, "-c" );
	if( cvsFile == "set" )
	{
		log( "WARNING: input for cvs files is blank. CANNOT CONTINUE" );
		exit( -1 );
	}
	std::cout << "CVSFile(s) Set To " << cvsFile << std::endl;
	log( "CVSFILE(s) Set To " + cvsFile );
  std::vector< std::string > cvsFiles;
	if( cvsFile.size() != 0 ) 
		cvsFiles = parseCommas( cvsFile );

	

	//Creating different datastructures
	SnifferData snifferTemplate( inav::coutMutex, inav::logMutex, &inav::log );
	snifferTemplate.setDevice( device );
	FilterData filterData( inav::coutMutex, inav::logMutex, &inav::log );
	GraphData graphData( inav::coutMutex, inav::logMutex, &inav::log );

	log( "Creating Sniffer Thread(s)" );
	std::vector< std::string >::iterator sitr;
	for( sitr = devices.begin(); sitr != devices.end(); ++sitr )
	{
		//Set up sniffing threads
		SnifferDataHolder snifferDataHolder;
		SnifferData *snifferData = new SnifferData( snifferTemplate );
		snifferData->setDevice( *sitr );
		snifferDataHolder.snifferData = snifferData;
		snifferDataHolder.filterData = &filterData;
		Thread* thread = new Thread( sniffer );
		thread->start( (void *) &snifferDataHolder );
		threads.push_back( thread );
	}

	log( "Creating Sniffer Offline Tread(s)" );
	for( sitr = files.begin(); sitr != files.end(); ++sitr )
	{
		//Set up pcap file threads
		SnifferDataHolder snifferDataHolder;
		SnifferData *snifferData = new SnifferData( snifferTemplate );
		snifferData->setDevice( *sitr );
		snifferDataHolder.snifferData = snifferData;
		snifferDataHolder.filterData = &filterData;

		Thread* thread = new Thread( snifferOffline );
		thread->start( (void*) &snifferDataHolder );
		threads.push_back( thread );

	}

	log( "Creating cvsFile Input Thread(s) " );
	for( sitr = cvsFiles.begin(); sitr != cvsFiles.end(); ++sitr )
	{
		//Set up pcap file threads
		SnifferDataHolder snifferDataHolder;
		SnifferData *snifferData = new SnifferData( snifferTemplate );
		snifferData->setDevice( *sitr );
		snifferDataHolder.snifferData = snifferData;
		snifferDataHolder.filterData = &filterData;

		Thread* thread = new Thread( cvsSniffer );
		thread->start( (void*)&snifferDataHolder );
		threads.push_back( thread );
	}


	//Set up Bandwidth Monitor Thread
	BandwidthDataHolder bandwidthDataHolder;
	bandwidthDataHolder.filterData = &filterData;
	bandwidthDataHolder.graphData = &graphData;
	log( "Creating Bandwidth Monitor Thread" );
	

	Thread* thread = new Thread( bandwidthMonitor );
	thread->start( (void*)&bandwidthDataHolder );
	threads.push_back( thread );

	//Set up client thread
	std::string port = parser( argc, argv, "-p" );
	int portnum = communication::ServerPort;
	if( port.size() > 0 )
	{
		log( "Seting port to " + port );
		portnum = atoi( port.c_str() );
	}
	ClientCommData clientCommData( inav::coutMutex, inav::logMutex, &inav::log, portnum );
	clientCommData.filterData = &filterData;
	clientCommData.graphData = &graphData;
	log( "Creating Communication Thread" ); 

	
	thread = new Thread( communicationChannel );
	thread->start( (void*)&clientCommData );
	threads.push_back( thread );
	

	std::string debug = parser( argc, argv, "--debug" );
	if( debug.size() > 0 )
	{
		DebugData debugData;
		debugData.filterData = &filterData;
		debugData.graphData = &graphData;

		Thread* thread = new Thread( debugThread );
		thread->start( (void*)&debugData );
		threads.push_back( thread );

	}

	//Wait for threads to exit
	//(void*) 
	std::vector<Thread*>::iterator itr;
	for( itr = threads.begin(); itr != threads.end(); ++itr )
	{
		log( "Deleting Thread... " );
		(*itr)->join();
	}
	log( "INAV server halting!" );
	return 0;
}
Esempio n. 11
0
void MainWindow::startFunctions()
{
    headersLst.append("ОУ");
    headersLst.append("Адрес");
    headersLst.append("Класс");
    treeMdl = new TreeModel(headersLst);
    ui->progressBarTree->hide();
    lblSN = new QLabel;
    lblPOVer = new QLabel();
    lblNetNum = new QLabel();
    lblNumLiter = new QLabel();
    lblStatus = new QLabel();
    lblPort = new QLabel();
    lblSysAddress = new QLabel();
    lblCoverStat = new QLabel();
    lblBindStat = new QLabel();
    lblIn1 = new QLabel();
    lblIn2 = new QLabel();
    lblNoize = new QLabel();
    lblInterView = new QLabel();
    statusBar()->addWidget(lblArrow, 0);
    statusBar()->addWidget(lblStatus, 0);
    statusBar()->addWidget(lblPort, 0);
    statusBar()->addWidget(lblCoverStat, 0);
    statusBar()->addWidget(lblBindStat, 0);
    statusBar()->addWidget(lblIn1, 0);
    statusBar()->addWidget(lblIn2, 0);
    statusBar()->addWidget(lblNoize, 0);
    statusBar()->addWidget(lblPOVer, 0);
    statusBar()->addWidget(lblSN, 0);
    statusBar()->addWidget(lblNetNum, 0);
    statusBar()->addWidget(lblNumLiter, 0);
    statusBar()->addWidget(lblSysAddress, 0);
    statusBar()->addWidget(chckBxInterView, 0);
    statusBar()->addWidget(lblInterView, 0);
    lblBindStat->setFixedSize(61, 26);
    lblNoize->setFixedSize(40, 26);
    lblCoverStat->setFixedSize(77, 26);
    lblBindStat->setStyleSheet("QLabel { background-color : white; }");
    lblNetNum->setText("Сеть:\n");
    lblNetNum->setToolTip("Номер сети");
    lblNumLiter->setText("Литера:\n");
    lblNumLiter->setToolTip("Номер литеры");
    lblSN->setText("S/N:\n");
    lblSN->setToolTip("Серийный номер контроллера");
    lblSysAddress->setText("Системный\nадрес: ");
    lblSysAddress->setToolTip("Системный адрес контроллера");
    lblPOVer->setText("Версия прошивки:\n");
    lblPOVer->setToolTip("Версия прошивки контроллера:");
    lblInterView->setText("Опрос");
    connect(ui->actUpdate, SIGNAL(triggered()), this, SLOT(slotActUpdate()));
    connect(ui->actExit, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui->actHelp, SIGNAL(triggered()), this, SLOT(help()));
    connect(ui->actSetNetParams, SIGNAL(triggered()), this, SLOT(slotSetParams()));
    connect(ui->actExit, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui->actAbout, SIGNAL(triggered()), this, SLOT(slotAboutApp()));
    connect(ui->actRestart, SIGNAL(triggered()), this, SLOT(slotReboot()));
    connect(ui->actConnectPort, SIGNAL(triggered()), this, SLOT(slotConnectTo()));
    connect(ui->pbBind, SIGNAL(clicked()), this, SLOT(slotBind()));
    connect(ui->actTree, SIGNAL(triggered()), this, SLOT(slotAskTree()));
    connect(chckBxInterView, SIGNAL(clicked(bool)), this, SLOT(slotInterview(bool)));
    connect(ui->pbSet, SIGNAL(clicked()), this, SLOT(slotSetSettings()));
    connect(ui->pbCancel, SIGNAL(clicked()), this, SLOT(slotCancelSettings()));
    connect(ui->act_showHideLog, SIGNAL(triggered(bool)), this, SLOT(slotShowHideLogAct(bool)));
    connect(ui->pbClear, SIGNAL(clicked(bool)), this, SLOT(clearTxtEdit(bool)));
    connect(ui->cmbBxCls, SIGNAL(currentIndexChanged(int)), this, SLOT(slotChangeCls(int)));
    connect(ui->cmbBxCmnd, SIGNAL(currentIndexChanged(QString)), this, SLOT(slotChangeCmnd(QString)));
    connect(ui->pbSend, SIGNAL(clicked()), this, SLOT(slotPBSend()));
    connect(ui->pages, SIGNAL(currentChanged(int)), this, SLOT(slotTabChanged(int)));
    connect(ui->pbLoad, SIGNAL(clicked()), this, SLOT(slotAskTree()));
    connect(treeMdl, SIGNAL(signalDropTreeNode(int, int, int, int, unsigned char)), this,
            SLOT(slotDropTreeNode(int, int, int, int, unsigned char)));
    answerFlag = true;
    writeInLogFlag = false;
    customCommFlag = false;
    lblCoverStat->setText("Крышка\nзакрыта");
    lblBindStat->setText("Связывания\nнет");
    lblIn1->setText("Вход 1");
    lblIn2->setText("Вход 2");
    /*this->setMouseTracking(true);
    ui->tabs->setMouseTracking(true);*/
    createDev();
    loadCommLst();
    loadDevSpecMap();
    ui->treeView->setModel(treeMdl);
    ui->treeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    ui->treeView->setDragEnabled(true);
    ui->treeView->setAcceptDrops(true);
    ui->treeView->setDropIndicatorShown(true);
    ui->treeView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->treeView->expandAll();
    updateActions();
    QVBoxLayout *vbl = new QVBoxLayout();
    vbl->addWidget(lgWgt);
    ui->logTab->setLayout(vbl);
    //connect(this, SIGNAL(signal_log_click()), logWgt, SLOT(slot_log_clicked()));
    qDebug() << "start";
    if(pb->pairObjArr.isEmpty())
        //closeApp("<u><b>Приложение будет закрыто.</b></u><i> Нет доступных подключений.</i>");
        qDebug() << "No connection";
    else {
        connect(m_sde, SIGNAL(hasChanged(QStringList)), this, SLOT(printDevices(QStringList)));
        if(pb->pairObjArr.size() > 1) {
            dsc = new DialogSelectConnection(pb);
            connect(dsc, SIGNAL(tryConnSignal(QString, QString)), this, SLOT(sendTryConn(QString, QString)));
            if(dsc->exec() != dsc->Accepted)
                closeApp("<u><b>Приложение будет закрыто.</b></u><i> Подключение не выбрано.</i>");
            delete dsc;
        }
        else {
            currPair.port = pb->pairObjArr.first().port;
            currPair.baud = pb->pairObjArr.first().baud;
            pserial = new AbstractSerial(this);
            if(!tryConnect(pserial, currPair.port, currPair.baud))
                qDebug() << "serial port is not open";
        }
        disconnect(this, SIGNAL(signPackReceive(QByteArray)), this, SLOT(parceAnswerPack(QByteArray)));
        connect(this, SIGNAL(signPackReceive(QByteArray)), this, SLOT(onPackReceiver(QByteArray)));
        connect(pserial, SIGNAL(readyRead()), this, SLOT(onProcSerialReceive()));
        pserial->enableEmitStatus(true);
        lblPort->setText(currPair.port + "\n" + currPair.baud);
        lblStatus->setText("Connected");
        //lblStatus->setBackgroundRole(QColor(Qt::green));
        MainWindow::setWindowTitle(currPair.port + " Конфигуратор Ладога-РК");
        commLst.clear();
        QTimer::singleShot(50, this, SLOT(createStartCommands()));
    }
}