/* * Add the specified device to the list of registered devices */ void DeviceManager::addDevice(Device *device) { Logger::info(device, "add device: %s (id: %#x)", device->getCommonName(), device->getId()); if (findDevice(device) == -1) { int8_t i = findDevice(NULL); if (i != -1) { devices[i] = device; } else { Logger::error(device, "unable to register device, max number of devices reached."); } } }
/** * @see findDevice(const char*) * @see open(int) */ DigitalCameraCapture::DigitalCameraCapture(const String & deviceName) { initContext(); int index = findDevice(deviceName.c_str()); if (deviceExist(index)) open(index); }
CBootloader::CBootloader() { usb_init(); if((usbhandle = findDevice()) == NULL){ fprintf(stderr, "Could not find USB device \"AVRUSBBoot\" with vid=0x%x pid=0x%x\n", USBDEV_SHARED_VENDOR, USBDEV_SHARED_PRODUCT); exit(1); } }
/** * Method called when the user clicks the "Connect" button */ bool ConnectionManager::connectDevice(DevListItem device) { DevListItem connection_device = findDevice(m_availableDevList->itemData(m_availableDevList->currentIndex(),Qt::ToolTipRole).toString()); if (!connection_device.connection) return false; QIODevice *io_dev = connection_device.connection->openDevice(connection_device.device.name); if (!io_dev) return false; io_dev->open(QIODevice::ReadWrite); // check if opening the device worked if (!io_dev->isOpen()) { return false; } // we appear to have connected to the device OK // remember the connection/device details m_connectionDevice = connection_device; m_ioDev = io_dev; connect(m_connectionDevice.connection, SIGNAL(destroyed(QObject *)), this, SLOT(onConnectionDestroyed(QObject *)), Qt::QueuedConnection); // signal interested plugins that we connected to the device emit deviceConnected(io_dev); m_connectBtn->setText("Disconnect"); m_availableDevList->setEnabled(false); // tell the monitorwidget we're conneced m_monitorWidget->connect(); return true; }
BOOL ChinavisionAPI::init(HANDLE threadExit) { //========================================== USB_INTERFACE_DESCRIPTOR ifaceDescriptor; WINUSB_PIPE_INFORMATION pipeInfo; //========================================== m_usbHandle = NULL; m_deviceHandle = NULL; m_inPipeId = 0; m_irCode = 0; m_dataReadyEvent = CreateEvent(NULL,TRUE,FALSE,NULL); m_threadExitEvent = threadExit; findDevice(); if(!_tcslen(m_deviceName)) { return FALSE; // failed to find device name } m_deviceHandle = CreateFile(m_deviceName,GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); if(m_deviceHandle==NULL) { return FALSE; } if(!WinUsb_Initialize(m_deviceHandle, &m_usbHandle)) { cleanUp(); return FALSE; } if(!WinUsb_QueryInterfaceSettings(m_usbHandle, 0, &ifaceDescriptor)) { cleanUp(); return FALSE; } for (int i=0; i<ifaceDescriptor.bNumEndpoints; i++) { if(!WinUsb_QueryPipe(m_usbHandle, 0, (UCHAR) i, &pipeInfo)) { cleanUp(); return FALSE; } if (USB_ENDPOINT_DIRECTION_IN(pipeInfo.PipeId)) { m_inPipeId = pipeInfo.PipeId; } } if (m_inPipeId==0) { cleanUp(); return FALSE; } m_threadHandle = CreateThread(NULL,0,SZThread,(void *)this,0,NULL); if(m_threadHandle) return TRUE; return FALSE; }
/* Description: handle the NetlinkEvent of usb added input: evt: NetlinkEvent output: */ int UsbSelect::handleUsbAutoSelect(NetlinkEvent *evt) { const char *pStr; const char *buf; char vid[5]; char pid[5]; bool found = false; struct usbdevice device; memset(vid, 0, 5); memset(pid, 0, 5); if (NULL == evt) { SLOGE("handleUsbAutoSelect: NetlinkEvent is null"); return -1; } buf = evt->findParam("PRODUCT"); if (NULL == buf && strlen(buf) < 9) { SLOGE("handleUsbAutoSelect: The Param of PRODUCT is wrong in NetlinkEvent"); return -1; } SLOGE("handleUsbAutoSelect: The PRODUCT is: %s ", buf); memcpy(vid, buf, 4); vid[5] = '\0'; pStr = buf + 5; memcpy(pid, pStr, 4); pid[5] = '\0'; if (strtoul(lastDevice.VID, NULL, 16) == strtoul(vid, NULL, 16) && strtoul(lastDevice.PID, NULL, 16) == strtoul(pid, NULL, 16)) { SLOGE("handleUsbAutoSelect: NetlinkEvent is the same of last one"); } else { found = findDevice(vid, pid, &device); if (found) { handleDongle(&device); return 0; } else { SLOGE("The 3Gdongle(vid = %s,pid = %s) is not found", vid, pid); return 2; } } return 3; }
int TCD2Usb::TCD2Usb_initialization(unsigned int vendor, unsigned int product) { // Initialize the USB library usb_init(); // printf("TCD2Usb::TCD2Usb_initialization: USB library initilaized\n"); // Find the buses if(usb_find_busses() < 0) { // printf("TCD2Usb::TCD2Usb_initialization: usb_find_busses failed \n"); return -TCD2USB_SYS_FIND_BUSSES_ERR; } // printf("TCD2Usb::TCD2Usb_initialization: USB system bus list updated\n"); // Find the devices if(usb_find_devices() < 0) { // printf("TCD2Usb::TCD2Usb_initialization: usb_find_devices failed \n"); return -TCD2USB_SYS_FIND_DEVICES_ERR; } // printf("TCD2Usb::TCD2Usb_initialization: USB system device list updated\n"); // Assign the device to usbdev if(!(usbdev=findDevice(vendor,product))) { // printf("TCD2Usb::TCD2Usb_initialization: No TCD2 USB device attached.\n"); return -TCD2USB_FIND_DEVICE_ERR; } // printf("TCD2Usb::TCD2Usb_initialization: TCD2 USB device found\n"); // printf("TCD2Usb::TCD2Usb_initialization: Using ID %04x:%04x on %s.%s.\n",usbdev->descriptor.idVendor,usbdev->descriptor.idProduct,usbdev->bus->dirname,usbdev->filename); // Open the USB device if( open() != 0 ) { // printf("TCD2Usb::TCD2Usb_initialization: Open failed.\n"); return -TCD2USB_OPEN_ERR; } // printf("TCD2Usb::TCD2Usb_initialization: TCD2 USB device opened\n"); // Claim the interface (This is the only class using it after all, so why not claim it now? if(claim_interface()) { // printf("TCD2Usb::TCD2Usb_initialization: Failed to claim interface 0: %s\n",usb_strerror()); return -TCD2USB_CLAIM_ERR; } // Set the alternate interface if(usb_set_altinterface(usbhdl,1)<0) { // printf("TCD2Usb::TCD2Usb_initialize: Failed to set altinterface 1: %s\n",usb_strerror()); return -TCD2USB_ALTINTERFACE_ERR; } // All's well! return 0; }
void DeviceAssociation::addDevice(DevicePresencePtr dPresence) { OC_LOG_V(DEBUG,BROKER_TAG,"addDevice()"); DevicePresencePtr foundDevice = findDevice(dPresence->getAddress()); if(foundDevice == nullptr) { OC_LOG_V(DEBUG,BROKER_TAG,"add device in deviceList"); s_deviceList.push_back(dPresence); } }
int usb_init(CCyUSBDevice* USBDevice) { bool devicePresent = findDevice(USBDevice); if (!(devicePresent && (USBDevice->VendorID != 0x0))){ myprintf("ERROR:Did not find matching device\n"); mysystem("PAUSE"); return 0; }else return 1; }
ProfileStatus getProfileState(bt_addr_struct *bd_addr, PROFILE_enum id) { int dev_id = findDevice(bd_addr); if(dev_id >= MAX_DEV_NUM) { return PROFILE_STATE_DISCONNECTED; } return g_dev_state[dev_id].state[id]; }
void DeviceAssociation::removeDevice(DevicePresencePtr dPresence) { OC_LOG_V(DEBUG,BROKER_TAG,"removeDevice()"); DevicePresencePtr foundDevice = findDevice(dPresence->getAddress()); if(foundDevice != nullptr) { OC_LOG_V(DEBUG,BROKER_TAG,"remove device in deviceList"); s_deviceList.remove(foundDevice); foundDevice.reset(); } }
void setProfileState(bt_addr_struct *bd_addr, PROFILE_enum id, ProfileStatus state) { int dev_id = findDevice(bd_addr); if(dev_id >= MAX_DEV_NUM) { return; } g_dev_state[dev_id].state[id] = state; }
void control_AllegroDogHome::_findDevices() { for (int i=0; i<_jdof; i++) { TCHAR devname[32]; _stprintf_s(devname, 32, _T("Mot%d"), i + 1); _motor[i] = findDevice(devname); _stprintf_s(devname, 32, _T("Enc%d"), i + 1); _enc[i] = findDevice(devname); } for (int i=0; i<NUM_CAN_CH; i++) { TCHAR devname[32]; _stprintf_s(devname, 32, _T("COMM%d"), i); _can[i] = findDevice(devname); } }
bool Modbus::poll(int tm) { timeval tv = { 0, tm }; modbus_set_response_timeout(_modbus, &tv); int recv_bytes = modbus_receive(_modbus, _query); if (recv_bytes == -1) { return false; } DeviceModbus* pdev = findDevice(_query[0]); if (!pdev) { LOG_ERROR("Unknown slave ID: %d", _query[0]); return false; } if (pdev->board()) pdev->board()->HandleRequest(_query, recv_bytes, pdev->modbusMap()); modbus_set_slave(_modbus, pdev->slaveId()); switch (_query[modbus_get_header_length(_modbus)]) { case MODBUS_READ_COILS: case MODBUS_READ_DISCRETE_INPUTS: case MODBUS_READ_INPUT_REGISTERS: case MODBUS_READ_HOLDING_REGISTERS: pdev->updateValues(); modbus_reply(_modbus, _query, recv_bytes, pdev->modbusMap()); break; case MODBUS_WRITE_SINGLE_COIL: //LOG_INFO("MODBUS_WRITE_SINGLE_COIL"); modbus_reply(_modbus, _query, recv_bytes, pdev->modbusMap()); break; case MODBUS_WRITE_SINGLE_REGISTER: LOG_INFO("MODBUS_WRITE_SINGLE_REGISTER"); modbus_reply(_modbus, _query, recv_bytes, pdev->modbusMap()); break; case MODBUS_WRITE_MULTIPLE_COILS: LOG_INFO("MODBUS_WRITE_MULTIPLE_COILS"); break; case MODBUS_WRITE_MULTIPLE_REGISTERS: LOG_INFO("MODBUS_WRITE_MULTIPLE_REGISTERS"); break; default: LOG_ERROR("UNKNOWN FUNCTION"); return false; } pdev->updateWidgets(); return true; }
dev_op *getDeviceOpList(bt_addr_struct *bd_addr) { int dev_id = findDevice(bd_addr); //ALOGI("%s addr:[0x%lX:0x%X:0x%X], dev_id[%d]!\n", // __FUNCTION__, bd_addr->lap, bd_addr->uap, bd_addr->nap, dev_id); if(dev_id >= MAX_DEV_NUM) { return NULL; } return &g_dev_oplist[dev_id]; }
/** * Slot called when the user clicks the connect/disconnect button */ void ConnectionManager::onConnectClicked() { // Check if we have a ioDev already created: if (!m_ioDev) { // connecting to currently selected device DevListItem device = findDevice(m_availableDevList->itemData(m_availableDevList->currentIndex(), Qt::ToolTipRole).toString()); if (device.connection) connectDevice(device); } else { // disconnecting disconnectDevice(); } }
/** * Method called when the user clicks the "Connect" button */ bool ConnectionManager::connectDevice() { devListItem connection_device = findDevice(m_availableDevList->currentText()); if (!connection_device.connection) return false; QIODevice *io_dev = connection_device.connection->openDevice(connection_device.devName); if (!io_dev) return false; io_dev->open(QIODevice::ReadWrite); // check if opening the device worked if (!io_dev->isOpen()) { qDebug() << "Error: io_dev->isOpen() returned FALSE .. could not open connection too " << connection_device.devName; // close the device try { connection_device.connection->closeDevice(connection_device.devName); } catch (...) { // handle exception qDebug() << "Exception: connection_device.connection->closeDevice(" << connection_device.devName << ")"; } return false; } // we appear to have connected to the device OK // remember the connection/device details m_connectionDevice = connection_device; m_ioDev = io_dev; // connect(m_connectionDevice.connection, SIGNAL(deviceClosed(QObject *)), this, SLOT(onConnectionClosed(QObject *))); connect(m_connectionDevice.connection, SIGNAL(destroyed(QObject *)), this, SLOT(onConnectionDestroyed(QObject *)), Qt::QueuedConnection); m_connectBtn->setText("Disconnect"); m_availableDevList->setEnabled(false); // signal interested plugins that we connected to the device emit deviceConnected(m_ioDev); return true; }
int linkStatusGet(const char* device) { int deviceId = 0; struct rte_eth_link link; if (device == NULL) { snprintf (errbuf_g, PCAP_ERRBUF_SIZE, "Invalid parameter"); return DPDKPCAP_FAILURE; } deviceId = findDevice(device, errbuf_g); rte_eth_link_get_nowait(deviceId, &link); return link.link_status; }
std::string Bluetooth5::getDeviceForAddress(std::string address, std::string adapterAddy) { std::string result; std::string adapterPath = findAdapterPath(adapterAddy); if(adapterPath == "") { DebugOut(DebugOut::Error)<<"Adapter not found ("<<adapterAddy<<")"<<endl; return ""; } std::string devicePath = findDevice(address, adapterPath); return result; }
void HMI_Client::onDataReceived() { QByteArray rxData = socket->readAll(); Packet packet; QList<Packet> packetList; bool packetsLeft = true; while(packetsLeft) //there can be more packets which came together { Packet packet; packetsLeft = packet.decode(&rxData); if(packetsLeft) packetList.append(packet); //we will separate them and put into list } foreach(Packet packet, packetList) { if(packet.getPacketType()==Packet::SENSOR_INIT || //if piece of device list received packet.getPacketType()==Packet::REGULATOR_INIT) { //TODO: avoid adding the same dev twice DeviceInterface* device; if(packet.getPacketType()==Packet::SENSOR_INIT) { device = new SensorInterface(); ScadaDevice* scadaDev = dynamic_cast<ScadaDevice*>(device); if(scadaDev->initReceived(&packet)) { deviceList->append(device); emit deviceListChanged(device); } else delete device; } } if(packet.getPacketType()==Packet::DATA) { ScadaDevice* dev = findDevice(packet.getDeviceID()); if(dev) { dev->dataReceived(&packet); } } } }
void UsbWidget::setRunning(bool on) { if ( not findDevice() ) { status->setText("Device error"); button->setChecked(false); intensity->setEnabled(false); pool_timer->stop(); return; } if ( on ) { status->setText("Device started"); setLed(true); pool_timer->start(); } else { status->setText("Device stopped"); setLed(false); pool_timer->stop(); } }
/* * Remove the specified device from the list of registered devices */ void DeviceManager::removeDevice(Device *device) { int8_t i = findDevice(NULL); if (i != -1) { devices[i] = NULL; } switch (device->getType()) { case DEVICE_THROTTLE: throttle = NULL; break; case DEVICE_BRAKE: brake = NULL; break; case DEVICE_MOTORCTRL: motorController = NULL; break; } }
pcap_t* pcap_open_live(const char *source, int snaplen, int promisc, int to_ms, char *errbuf) { pcap_t *p = NULL; int deviceId = 0; debug("Opening device %s\n", source); if (initFinished == 0) { snprintf (errbuf, PCAP_ERRBUF_SIZE, "Global DPDK init is not performed yet"); return NULL; } deviceId = findDevice(source, errbuf); if (deviceId < 0) { snprintf (errbuf, PCAP_ERRBUF_SIZE, "Did not find the device %s", source); return NULL; } if (promisc) rte_eth_promiscuous_enable(deviceId); else rte_eth_promiscuous_disable(deviceId); if (rte_eth_dev_start(deviceId) < 0) { snprintf (errbuf, PCAP_ERRBUF_SIZE, "Could not start the device %d", deviceId); return NULL; } p = malloc (sizeof(pcap_t)); memset(p, 0, sizeof(pcap_t)); p->deviceId = deviceId; return p; }
static ERL_NIF_TERM do_open(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { char deviceName[MAXBUFLEN]; long latency; ERL_NIF_TERM streamTerm; PortMidiStream **streamAlloc; PmError result; ErlNifResourceType* streamType = (ErlNifResourceType*)enif_priv_data(env); streamAlloc = (PortMidiStream**)enif_alloc_resource(streamType, sizeof(PortMidiStream*)); enif_get_string(env, argv[0], deviceName, MAXBUFLEN, ERL_NIF_LATIN1); enif_get_long(env, argv[1], &latency); if((result = findDevice(streamAlloc, deviceName, OUTPUT, latency)) != pmNoError) { ERL_NIF_TERM reason = enif_make_atom(env, makePmErrorAtom(result)); return enif_make_tuple2(env, enif_make_atom(env, "error"), reason); } streamTerm = enif_make_resource(env, streamAlloc); enif_keep_resource(streamAlloc); return enif_make_tuple2(env, enif_make_atom(env, "ok"), streamTerm); }
void connect(void) { debug("initializing USB library"); int rv = libusb_init(NULL); if (rv < 0) throw RestartNeeded(DTR("failed to initialize USB library"), 5.0, false); findDevice(); debug("initializing MCC device"); usbInit_1608G(m_udev); debug("building gain table"); usbBuildGainTable_USB1608G(m_udev, m_gain_table); uint16_t version = 0xbeef; usbFPGAVersion_USB1608G(m_udev, &version); inf(DTR("FPGA version: %02x.%02x"), version >> 0x8, version & 0xff); char serial[9] = {0}; usbGetSerialNumber_USB1608G(m_udev, serial); inf(DTR("serial number: %s"), serial); }
// Find the device, and set up to read it periodically, then send // the data out stdout so another process can pick it up and do // something reasonable with it. // int main(int argc, char **argv) { char *usage = {"usage: %s -u -n\n"}; int libusbDebug = 0; //This will turn on the DEBUG for libusb int noisy = 0; //This will print the packets as they come in libusb_device **devs; int r, err, c; ssize_t cnt; while ((c = getopt (argc, argv, "unh")) != -1) switch (c){ case 'u': libusbDebug = 1; break; case 'n': noisy = 1; break; case 'h': fprintf(stderr, usage, argv[0]); case '?': exit(1); default: exit(1); } fprintf(stderr,"%s Starting ... ",argv[0]); fprintf(stderr,"libusbDebug = %d, noisy = %d\n", libusbDebug, noisy); // The Pi linker can give you fits. If you get a linker error on // the next line, set LD_LIBRARY_PATH to /usr/local/lib fprintf(stderr,"This is not an error!! Checking linker, %s\n", libusb_strerror(0)); if (signal(SIGINT, sig_handler) == SIG_ERR) fprintf(stderr,"Couldn't set up signal handler\n"); err = libusb_init(NULL); if (err < 0){ fprintf(stderr,"Couldn't init usblib, %s\n", libusb_strerror(err)); exit(1); } // This is where you can get debug output from libusb. // just set it to LIBUSB_LOG_LEVEL_DEBUG if (libusbDebug) libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_DEBUG); else libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_INFO); cnt = libusb_get_device_list(NULL, &devs); if (cnt < 0){ fprintf(stderr,"Couldn't get device list, %s\n", libusb_strerror(err)); exit(1); } // go get the device; the device handle is saved in weatherStation struct. if (!findDevice(devs)){ fprintf(stderr,"Couldn't find the device\n"); exit(1); } // Now I've found the weather station and can start to try stuff // So, I'll get the device descriptor struct libusb_device_descriptor deviceDesc; err = libusb_get_device_descriptor(weatherStation.device, &deviceDesc); if (err){ fprintf(stderr,"Couldn't get device descriptor, %s\n", libusb_strerror(err)); exit(1); } fprintf(stderr,"got the device descriptor back\n"); // Open the device and save the handle in the weatherStation struct err = libusb_open(weatherStation.device, &weatherStation.handle); if (err){ fprintf(stderr,"Open failed, %s\n", libusb_strerror(err)); closeUpAndLeave(); } fprintf(stderr,"I was able to open it\n"); // Now that it's opened, I can free the list of all devices libusb_free_device_list(devs, 1); // Documentation says to get rid of the list // Once I have the device I need fprintf(stderr,"Released the device list\n"); err = libusb_set_auto_detach_kernel_driver(weatherStation.handle, 1); if(err){ fprintf(stderr,"Some problem with detach %s\n", libusb_strerror(err)); closeUpAndLeave(); } int activeConfig; err =libusb_get_configuration(weatherStation.handle, &activeConfig); if (err){ fprintf(stderr,"Can't get current active configuration, %s\n", libusb_strerror(err));; closeUpAndLeave(); } fprintf(stderr,"Currently active configuration is %d\n", activeConfig); if(activeConfig != 1){ err = libusb_set_configuration (weatherStation.handle, 1); if (err){ fprintf(stderr,"Cannot set configuration, %s\n", libusb_strerror(err));; closeUpAndLeave(); } fprintf(stderr,"Just did the set configuration\n"); } err = libusb_claim_interface(weatherStation.handle, 0); //claim interface 0 (the first) of device (mine had just 1) if(err) { fprintf(stderr,"Cannot claim interface, %s\n", libusb_strerror(err)); closeUpAndLeave(); } fprintf(stderr,"Claimed Interface\n"); // I don't want to just hang up and read the reports as fast as I can, so // I'll space them out a bit. It's weather, and it doesn't change very fast. sleep(1); fprintf(stderr,"Setting the device 'idle' before starting reads\n"); err = libusb_control_transfer(weatherStation.handle, 0x21, 0x0a, 0, 0, 0, 0, 1000); sleep(1); int tickcounter= 0; fprintf(stderr,"Starting reads\n"); while(1){ sleep(1); if(tickcounter++ % 10 == 0){ getit(1, noisy); } if(tickcounter % 30 == 0){ getit(2, noisy); } if (tickcounter % 15 == 0){ showit(); } } }
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; }
HIDDevice::HIDDevice(VRDevice::Factory* sFactory,VRDeviceManager* sDeviceManager,Misc::ConfigurationFile& configFile) :VRDevice(sFactory,sDeviceManager,configFile), deviceFd(-1), keyMap(0), absAxisMap(0),relAxisMap(0),axisConverters(0), reportEvents(false), buttonStates(0),valuatorStates(0) { /* First option: Open device by explicit event device file name: */ if(deviceFd<0) { std::string deviceFileName=configFile.retrieveString("./deviceFileName",""); if(deviceFileName!="") { #ifdef VERBOSE printf("HIDDevice: Opening device %s\n",deviceFileName.c_str()); fflush(stdout); #endif deviceFd=open(deviceFileName.c_str(),O_RDONLY); if(deviceFd<0) Misc::throwStdErr("HIDDevice: Unable to open device file \"%s\"",deviceFileName.c_str()); } } /* Second option: Open device by vendor ID / product ID: */ if(deviceFd<0) { std::string deviceVendorProductId=configFile.retrieveString("./deviceVendorProductId",""); if(deviceVendorProductId!="") { /* Split ID string into vendor ID / product ID: */ char* colonPtr; int vendorId=strtol(deviceVendorProductId.c_str(),&colonPtr,16); char* endPtr; int productId=strtol(colonPtr+1,&endPtr,16); if(*colonPtr!=':'||*endPtr!='\0'||vendorId<0||productId<0) Misc::throwStdErr("HIDDevice: Malformed vendorId:productId string \"%s\"",deviceVendorProductId.c_str()); #ifdef VERBOSE printf("HIDDevice: Searching device %04x:%04x\n",vendorId,productId); fflush(stdout); #endif deviceFd=findDevice(vendorId,productId); if(deviceFd<0) Misc::throwStdErr("HIDDevice: No device with vendorId:productId %04x:%04x found",vendorId,productId); } } /* Third option: Open device by device name: */ if(deviceFd<0) { std::string deviceName=configFile.retrieveString("./deviceName",""); if(deviceName!="") { #ifdef VERBOSE printf("HIDDevice: Searching device %s\n",deviceName.c_str()); fflush(stdout); #endif deviceFd=findDevice(deviceName.c_str()); if(deviceFd<0) Misc::throwStdErr("HIDDevice: No device with name \"%s\" found",deviceName.c_str()); } } /* Bail out if no device was found: */ if(deviceFd<0) Misc::throwStdErr("HIDDevice: No device specified"); /* Set number of trackers on device: */ setNumTrackers(0,configFile); /* Query all feature types of the device: */ unsigned char featureTypeBits[EV_MAX/8+1]; memset(featureTypeBits,0,EV_MAX/8+1); if(ioctl(deviceFd,EVIOCGBIT(0,sizeof(featureTypeBits)),featureTypeBits)<0) Misc::throwStdErr("HIDDevice: Unable to query device feature types"); /* Query the number of keys on the device: */ if(featureTypeBits[EV_KEY/8]&(1<<(EV_KEY%8))) { #ifdef VERBOSE printf("HIDDevice: Initializing buttons...\n"); fflush(stdout); #endif /* Query key features: */ unsigned char keyBits[KEY_MAX/8+1]; memset(keyBits,0,KEY_MAX/8+1); if(ioctl(deviceFd,EVIOCGBIT(EV_KEY,sizeof(keyBits)),keyBits)<0) Misc::throwStdErr("HIDDevice: Unable to query device key features"); /* Initialize the key translation array: */ keyMap=new int[KEY_MAX+1]; int numKeys=0; for(int i=0;i<=KEY_MAX;++i) { if(keyBits[i/8]&(1<<(i%8))) { keyMap[i]=numKeys; ++numKeys; } else keyMap[i]=-1; } /* Set number of buttons on device: */ #ifdef VERBOSE printf("HIDDevice: %d buttons found\n",numKeys); fflush(stdout); #endif setNumButtons(numKeys,configFile); } else setNumButtons(0,configFile); /* Count the number of absolute and relative axes: */ int numAxes=0; /* Query the number of absolute axes on the device: */ if(featureTypeBits[EV_ABS/8]&(1<<(EV_ABS%8))) { #ifdef VERBOSE printf("HIDDevice: Initializing absolute axes...\n"); fflush(stdout); #endif /* Query absolute axis features: */ unsigned char absAxisBits[ABS_MAX/8+1]; memset(absAxisBits,0,ABS_MAX/8+1); if(ioctl(deviceFd,EVIOCGBIT(EV_ABS,sizeof(absAxisBits)),absAxisBits)<0) Misc::throwStdErr("HIDDevice: Unable to query device absolute axis features"); /* Initialize the axis translation array: */ absAxisMap=new int[ABS_MAX+1]; int numAbsAxes=0; for(int i=0;i<=ABS_MAX;++i) { if(absAxisBits[i/8]&(1<<(i%8))) { absAxisMap[i]=numAxes; ++numAxes; ++numAbsAxes; } else absAxisMap[i]=-1; } #ifdef VERBOSE printf("HIDDevice: %d absolute axes found\n",numAbsAxes); fflush(stdout); #endif } /* Query the number of relative axes on the device: */ if(featureTypeBits[EV_REL/8]&(1<<(EV_REL%8))) { #ifdef VERBOSE printf("HIDDevice: Initializing relative axes...\n"); fflush(stdout); #endif /* Query relative axis features: */ unsigned char relAxisBits[REL_MAX/8+1]; memset(relAxisBits,0,REL_MAX/8+1); if(ioctl(deviceFd,EVIOCGBIT(EV_REL,sizeof(relAxisBits)),relAxisBits)<0) Misc::throwStdErr("HIDDevice: Unable to query device relative axis features"); /* Initialize the axis translation array: */ relAxisMap=new int[REL_MAX+1]; int numRelAxes=0; for(int i=0;i<=REL_MAX;++i) { if(relAxisBits[i/8]&(1<<(i%8))) { relAxisMap[i]=numAxes; ++numAxes; ++numRelAxes; } else relAxisMap[i]=-1; } #ifdef VERBOSE printf("HIDDevice: %d relative axes found\n",numRelAxes); fflush(stdout); #endif } /* Set number of valuators on device: */ setNumValuators(numAxes,configFile); /* Initialize axis converters: */ axisConverters=new AxisConverter[numAxes]; if(absAxisMap!=0) { /* Initialize absolute axis converters: */ #ifdef VERBOSE printf("HIDDevice: Initializing absolute axis converters\n"); fflush(stdout); #endif for(int i=0;i<=ABS_MAX;++i) if(absAxisMap[i]>=0) { /* Query configuration of this axis: */ input_absinfo absAxisConf; if(ioctl(deviceFd,EVIOCGABS(i),&absAxisConf)<0) Misc::throwStdErr("HIDDevice: Unable to query device absolute axis configuration"); #ifdef VERBOSE printf("Axis %2d: min %d, max %d, fuzz %d, flat %d\n",absAxisMap[i],absAxisConf.minimum,absAxisConf.maximum,absAxisConf.fuzz,absAxisConf.flat); fflush(stdout); #endif /* Initialize converter with queried values: */ AxisConverter& converter=axisConverters[absAxisMap[i]]; float mid=Math::mid(absAxisConf.minimum,absAxisConf.maximum); converter=AxisConverter(absAxisConf.minimum,mid-absAxisConf.flat,mid+absAxisConf.flat,absAxisConf.maximum); /* Override axis settings from configuration file: */ char axisSettingsTag[20]; snprintf(axisSettingsTag,sizeof(axisSettingsTag),"axis%dSettings",absAxisMap[i]); converter=configFile.retrieveValue<AxisConverter>(axisSettingsTag,converter); #ifdef VERBOSE printf("Axis %2d: %s\n",absAxisMap[i],Misc::ValueCoder<AxisConverter>::encode(converter).c_str()); fflush(stdout); #endif } } if(relAxisMap!=0) { /* Initialize relative axis converters: */ #ifdef VERBOSE printf("HIDDevice: Initializing relative axis converters\n"); fflush(stdout); #endif for(int i=0;i<=REL_MAX;++i) if(relAxisMap[i]>=0) { /* Initialize converter with default values: */ AxisConverter& converter=axisConverters[relAxisMap[i]]; converter=AxisConverter(-1.0f,1.0f); /* Override axis settings from configuration file: */ char axisSettingsTag[20]; snprintf(axisSettingsTag,sizeof(axisSettingsTag),"axis%dSettings",relAxisMap[i]); converter=configFile.retrieveValue<AxisConverter>(axisSettingsTag,converter); #ifdef VERBOSE printf("Axis %2d: %s\n",relAxisMap[i],Misc::ValueCoder<AxisConverter>::encode(converter).c_str()); fflush(stdout); #endif } } #if 0 /* Initialize gain arrays: */ valuatorGains=new float[getNumValuators()]; for(int i=0;i<getNumValuators();++i) { char valuatorGainTag[40]; snprintf(valuatorGainTag,sizeof(valuatorGainTag),"./valuatorGain%d",i); valuatorGains[i]=configFile.retrieveValue<float>(valuatorGainTag,1.0f); } #endif /* Initialize state arrays: */ buttonStates=new bool[getNumButtons()]; for(int i=0;i<getNumButtons();++i) buttonStates[i]=false; valuatorStates=new float[getNumValuators()]; for(int i=0;i<getNumValuators();++i) valuatorStates[i]=0.0f; /* Start device thread (HID device cannot be disabled): */ startDeviceThread(); }
void MainWindow::on_actionConnect_triggered() { emit findDevice(); }
void control_AllegroDogHome::init(int mode) { const TCHAR* prop = NULL; float* val = NULL; int* ival = NULL; prop = getProperty(_T("JDOF")); if (prop) _jdof = parse_atoi(prop); _findDevices(); _q.resize(_jdof); _q.zero(); val = new float[_jdof]; ival = new int[_jdof]; prop = getProperty(_T("dT")); if (prop) _dT = parse_atof(prop); prop = getProperty(_T("speed")); if (prop) _home_speed = _ttoi(prop); else _home_speed = 200; prop = getProperty(_T("direction")); if (prop) { for (int i=0; i<_jdof; i++) ival[i] = 0; parse_ivector(ival, _jdof, prop); for (int i=0; i<_jdof; i++) _home_direction[i] = (ival[i] == 0 ? ival[0] : ival[i]); } prop = getProperty(_T("offset")); if (prop) { for (int i=0; i<_jdof; i++) ival[i] = 0; parse_ivector(ival, _jdof, prop); for (int i=0; i<_jdof; i++) _home_offset[i] = (ival[i] == 0 ? ival[0] : ival[i]); } prop = getProperty(_T("offset_tune")); if (prop) { for (int i=0; i<_jdof; i++) ival[i] = 0; parse_ivector(ival, _jdof, prop); for (int i=0; i<_jdof; i++) _home_offset_tune[i] = (ival[i] == 0 ? ival[0] : ival[i]); } delete [] val; //////////////////////////////////////////////////// _sharedMemory = findDevice(_T("SharedMemory")); }