void vrpn_HidInterface::update() { if (!_working) { //fprintf(stderr,"vrpn_HidInterface::update(): Interface not currently working\n"); return; } // Maximum packet size for USB is 512 characters. vrpn_uint8 inbuf[512]; if (inbuf == NULL) { fprintf(stderr,"vrpn_HidInterface::update(): Out of memory\n"); return; } int ret = hid_read(_device, inbuf, sizeof(inbuf)); if (ret < 0) { fprintf(stderr,"vrpn_HidInterface::update(): Read error\n"); return; } // Handle any data we got. This can include fewer bytes than we // asked for. if (ret > 0) { vrpn_uint8 *data = static_cast<vrpn_uint8 *>(static_cast<void*>(inbuf)); on_data_received(ret, data); } }
int read(hid_device *device, unsigned char *data, size_t length) { return hid_executor->await([=] { return hid_read(device, data, length); }); }
uint16_t get_pot1_val() { static unsigned char CMD = 0x37; int response; // Request state (cmd 0x37). The first byte is the report number (0x0). buf[0] = 0x0; buf[1] = CMD; response = hid_write(handle, buf, 64); if(response < 0) { printf("Error sending command %x", CMD); return -1; } // Read in the requested state response = hid_read(handle, buf, 64); if(response < 0) { printf("Error reading response for command %x", CMD); return -1; } return merge_uint8(buf[1], buf[2]); // Print out the returned buffer. // for (i = 0; i < 3; i++) // printf("buf[%d]: %d\n", i, buf[i]); }
void vrpn_HidInterface::update() { if (!_working) { //fprintf(stderr,"vrpn_HidInterface::update(): Interface not currently working\n"); return; } // Maximum packet size for USB is 512 characters. vrpn_uint8 inbuf[512]; if (inbuf == NULL) { fprintf(stderr,"vrpn_HidInterface::update(): Out of memory\n"); return; } int ret = hid_read(_device, inbuf, sizeof(inbuf)); if (ret < 0) { fprintf(stderr,"vrpn_HidInterface::update(): Read error\n"); fprintf(stderr," (On one version of Red Hat Linux, this was from not having libusb-devel installed when configuring in CMake.)\n"); return; } // Handle any data we got. This can include fewer bytes than we // asked for. if (ret > 0) { vrpn_uint8 *data = static_cast<vrpn_uint8 *>(static_cast<void*>(inbuf)); on_data_received(ret, data); } }
bool get_push1_state() { static unsigned char CMD = 0x81; int response; // Request state (cmd 0x81). The first byte is the report number (0x0). buf[0] = 0x0; buf[1] = CMD; response = hid_write(handle, buf, 64); if(response < 0) { printf("Error sending command %x", CMD); return false; } // Read requested state response = hid_read(handle, buf, 64); if(response < 0) { printf("Error reading response for command %x", CMD); return false; } // Print out the returned buffer. // for (i = 0; i < 2; i++) // printf("buf[%d]: %d\n", i, buf[i]); return !buf[1]; }
/********************************************************************* * 転送速度ベンチマーク ********************************************************************* * int cnt : PINGを打つ回数. * int psize: PINGパケットの大きさ(現在はサポートされない) */ void UsbBench(int cnt,int psize) { int i,n,rc; int time1, rate; #ifdef __GNUC__ long long total=0; #else long total=0; #endif int nBytes; int time0; #if READ_BENCH nBytes = HidLength1-1 ; //登りパケットのみ計測. #else nBytes = HidLength1-1 + HidLength1-1 ; //現在固定. #endif // 1回のPingは 63byteのQueryと63バイトのリターン. printf("hid write start\n"); time0 = clock(); #if READ_BENCH hid_read_mode(1,0); #endif for(i=0;i<cnt;i++) { n = i & 0xff; #if READ_BENCH rc = hid_read(i); #else rc = hid_ping(n); if(rc != n) { printf("hid ping mismatch error (%x != %x)\n",rc,n); exit(EXIT_FAILURE); } #endif total += nBytes; } #if READ_BENCH hid_read_mode(0,0); #endif time1 = clock() - time0; if (time1 == 0) { time1 = 2; } rate = (int)((total * 1000) / time1); if (total > 1024*1024) { printf("hid write end, %8.3lf MB/%8.2lf s, %6.3lf kB/s\n", (double)total/(1024*1024), (double)time1/1000, (double)rate/1024); } else if (total > 1024) { printf("hid write end, %8.3lf kB/%8.2lf s, %6.3lf kB/s\n", (double)total/1024, (double)time1/1000, (double)rate/1024); } else { printf("hid write end, %8d B/%8d ms, %6.3lf kB/s\n", (int)total, time1, (double)rate/1024); } }
int mcp_panel_open() { int res = 0; mcpHandle = hid_open(VENDOR_ID, MCP_PROD_ID, NULL); if (!mcpHandle) { XPLMDebugString("-> CP: mcp_driver.panel_open: unable to open device.\n"); return -1; } wchar_t wstr[MAX_STR]; res = hid_get_manufacturer_string(mcpHandle, wstr, MAX_STR); sprintf(tmp, "-> CP: mcp_driver.panel_open: Manufacturer String %ls\n", wstr); XPLMDebugString(tmp); hid_set_nonblocking(mcpHandle, 1); res = hid_read(mcpHandle, mcp_in_buf, MCP_IN_BUF_SIZE); if (res < 0) { sprintf(tmp, "-> CP: mcp_driver.panel_open: Error: %ls\n", hid_error(mcpHandle)); XPLMDebugString(tmp); } res = hid_send_feature_report(mcpHandle, mcp_all_on_panel, sizeof(mcp_all_on_panel)); res = hid_send_feature_report(mcpHandle, mcp_course_left, sizeof(mcp_course_left)); res = hid_send_feature_report(mcpHandle, mcp_course_right, sizeof(mcp_course_right)); res = hid_send_feature_report(mcpHandle, mcp_ias_mach, sizeof(mcp_ias_mach)); res = hid_send_feature_report(mcpHandle, mcp_heading, sizeof(mcp_heading)); res = hid_send_feature_report(mcpHandle, mcp_altitude, sizeof(mcp_altitude)); res = hid_send_feature_report(mcpHandle, mcp_vert_speed, sizeof(mcp_vert_speed)); if (res < 0) { sprintf(tmp, "-> CP: mcp_driver.panel_open: Error: %ls\n", hid_error(mcpHandle)); XPLMDebugString(tmp); } return 0; }
static void update_device(ohmd_device* device) { rift_priv* priv = rift_priv_get(device); unsigned char buffer[FEATURE_BUFFER_SIZE]; // Handle keep alive messages double t = ohmd_get_tick(); if(t - priv->last_keep_alive >= (double)priv->sensor_config.keep_alive_interval / 1000.0 - .2){ // send keep alive message pkt_keep_alive keep_alive = { 0, priv->sensor_config.keep_alive_interval }; int ka_size = encode_keep_alive(buffer, &keep_alive); send_feature_report(priv, buffer, ka_size); // Update the time of the last keep alive we have sent. priv->last_keep_alive = t; } // Read all the messages from the device. while(true){ int size = hid_read(priv->handle, buffer, FEATURE_BUFFER_SIZE); if(size < 0){ LOGE("error reading from device"); return; } else if(size == 0) { return; // No more messages, return. } // currently the only message type the hardware supports (I think) if(buffer[0] == RIFT_IRQ_SENSORS){ handle_tracker_sensor_msg(priv, buffer, size); }else{ LOGE("unknown message type: %u", buffer[0]); } } }
//----------------------------------------------------------------------------- void HIDDevice::OnEvent(int i, int fd) { OVR_UNUSED(i); int bytes = 0; if(DeviceHandle){ bytes = hid_read(DeviceHandle, ReadBuffer, ReadBufferSize); } // We have data to read from the device //int bytes = read(fd, ReadBuffer, ReadBufferSize); if (bytes >= 0) { // TODO: I need to handle partial messages and package reconstruction if(bytes > 0){ if (Handler) { Handler->OnInputReport(ReadBuffer, bytes); } } } else { // Close the device on read error. closeDeviceOnIOError(); } }
void print_string(unsigned char data[]) { int r = 0, tr = 0, ind = 2; int len = data[0] - 2; const char *str = NULL; while (len > 0) { if (ind == 8) { r = hid_read(dev, data, 8); if (r < 0) { fatal("error reading data (%ls)", hid_error(dev)); } if (tr != 8) { fatal("expected 8 bytes, received: %d", tr); } ind = 0; } str = decode_byte(data[ind]); if (strlen(str) > 1) { printf("<%s>", str); } else { printf("%s", str); } len--; ind++; } }
Comm::ErrorCode Comm::ReceivePacket(unsigned char *data, int size) { QTime timeoutTimer; int res = 0, timeout = 3; timeoutTimer.start(); while(res < 1) { res = hid_read(boot_device, data, size); if(timeoutTimer.elapsed() > SyncWaitTime) { timeoutTimer.start(); timeout--; } // If timed out twice, or return error then close device and return failure if(timeout == 0) { qWarning("Timeout."); return Timeout; } if(res == -1) { qWarning("Read failed."); close(); return Fail; } } return Success; }
//----------------------------------------------------------------------------- int dbg_dap_cmd(uint8_t *data, int size, int rsize) { char cmd = data[0]; int res; memset(hid_buffer, 0xff, report_size + 1); hid_buffer[0] = 0x00; // Report ID memcpy(&hid_buffer[1], data, rsize); res = hid_write(handle, hid_buffer, report_size + 1); if (res < 0) { printf("Error: %ls\n", hid_error(handle)); perror_exit("debugger write()"); } res = hid_read(handle, hid_buffer, report_size + 1); if (res < 0) perror_exit("debugger read()"); check(res, "empty response received"); check(hid_buffer[0] == cmd, "invalid response received"); res--; memcpy(data, &hid_buffer[1], (size < res) ? size : res); return res; }
/** *** Flush queue **/ void hid_flush(hid_device* handle) { unsigned char hid_buf[FAN_SIZE]; // Flush the report queue hid_set_nonblocking(handle, 1); while( hid_read(handle, hid_buf, sizeof(hid_buf) > 0)); hid_set_nonblocking(handle, 0); }
void readTask(void) { #ifdef NONBLOCK dataIn = 0; while (dataIn == 0) { dataIn = hid_read(hHID, buffer, sizeof(buffer)); if (_kbhit()) return; } #else dataIn = hid_read(hHID, buffer, sizeof(buffer)); #endif for (int i = 0; i < dataIn/2; i++) { printf("%04x\n", buffer[2*i]<<8|buffer[2*i+1]); fprintf(fOutput, "%04x\n", buffer[2*i]<<8|buffer[2*i+1]); } printf("\n"); fprintf(fOutput, "\n"); }
int read_usb_packet(dldev_t *dev, u8 *packet, u16 len) { if(hid_read(dev->usb.handle, packet, len) == -1){ ERROR("can't read packet"); return -1; } return 0; }
void Sbs2EmocapDataReader::execute() { int counter = 0; int cc = 0; int uu = 0; int res = 0; while(1) { if(!running) return; #ifdef Q_OS_MAC if (testDummyRead) { counter = (counter +1)%1024000; if (counter > 0) continue; } else { res = hid_read(handle, (unsigned char*)buffer_main, sizeof(buffer_main)); if (res > 0) cc = 1; if (res == -1) { uu += (1-cc); if (uu == 100000) { resetHandle(); uu = 0; } continue; } } #else if (testDummyRead) { counter = (counter +1)%1024000; if (counter > 0) continue; } else { rawFile.read(buffer_main, 32); } #endif ++framesRead; sbs2EmotivDecryptor->decrypt(buffer_main,buffer_final); sbs2Packets[currentIndex] -> update(buffer_final); sbs2Callback->getData(sbs2Packets[currentIndex]); currentIndex = (currentIndex+1)%256; } }
/************************************************************************//** * \brief Services USB communciation with the Manta * * HandleEvents should be called periodically to poll all connected Mantas for * incoming USB frames as well as to send any messages that have been queued * up with WriteFrame(). It should be called at least once every 6ms, but you * may get improved results polling as fast as every 1ms if your application * supports it. * * Note: Because WriteFrame() accesses the same message queue that HandleEvents() * does, they should be protected from each other by a mutex on the application * level if they're being called from parallel threads. ****************************************************************************/ void MantaUSB::HandleEvents(void) { list<MantaUSB *>::iterator i = mantaList.begin(); /* read from each manta and trigger any events */ while(mantaList.end() != i) { MantaUSB *current = *i; if(current->IsConnected()) { int bytesRead; int8_t inFrame[InPacketLen]; bytesRead = hid_read(current->DeviceHandle, reinterpret_cast<uint8_t *>(inFrame), InPacketLen); if(bytesRead < 0) { current->DebugPrint("%s-%d: Read error on Manta %d", __FILE__, __LINE__, current->GetSerialNumber()); throw(MantaCommunicationException(current)); } else if(bytesRead) { current->FrameReceived(inFrame); } } ++i; } /* pop one item off the transmit queue and send down to its target */ if(! txQueue.empty()) { int bytesWritten; MantaTxQueueEntry *txMessage = txQueue.front(); txQueue.pop_front(); bytesWritten = hid_write(txMessage->TargetManta->DeviceHandle, txMessage->OutFrame, OutPacketLen + 1); txMessage->TargetManta->DebugPrint("%s-%d: Frame Written to Manta %d", __FILE__, __LINE__, txMessage->TargetManta->GetSerialNumber()); for(int i = 0; i < 16; i += 8) { uint8_t *frame = txMessage->OutFrame + 1; txMessage->TargetManta->DebugPrint("\t\t%x %x %x %x %x %x %x %x", frame[i], frame[i+1], frame[i+2], frame[i+3], frame[i+4], frame[i+5], frame[i+6], frame[i+7]); } delete txMessage; if(bytesWritten < 0) { txMessage->TargetManta->DebugPrint("%s-%d: Write error on Manta %d", __FILE__, __LINE__, txMessage->TargetManta->GetSerialNumber()); throw(MantaCommunicationException(txMessage->TargetManta)); } } }
int USBInterface::ReciveBuffer() { CleanBufferIN(); if(HIDisOpen) { //res = hid_read_timeout(DeviceHandle, BufferIN, 65,1); res = hid_read(DeviceHandle, BufferIN, 65); return res; } else return -1; }
void HID_PnP::PollUSB() { buf[0] = 0x00; memset((void*)&buf[2], 0x00, sizeof(buf) - 2); if (isConnected == false) { device = hid_open(0x04d8, 0x003f, NULL); if (device) { isConnected = true; hid_set_nonblocking(device, true); timer->start(15); } } else { if(toggleLeds == true) { toggleLeds = false; buf[1] = 0x80; if (hid_write(device, buf, sizeof(buf)) == -1) { CloseDevice(); return; } buf[0] = 0x00; buf[1] = 0x37; memset((void*)&buf[2], 0x00, sizeof(buf) - 2); } if (hid_write(device, buf, sizeof(buf)) == -1) { CloseDevice(); return; } if(hid_read(device, buf, sizeof(buf)) == -1) { CloseDevice(); return; } if(buf[0] == 0x37) { potentiometerValue = (buf[2]<<8) + buf[1]; buf[1] = 0x81; } else if(buf[0] == 0x81) { pushbuttonStatus = (buf[1] == 0x00); buf[1] = 0x37; } } hid_comm_update(isConnected, pushbuttonStatus, potentiometerValue); }
int mcp_panel_read_non_blocking(unsigned char *buf) { int res = 0; if (mcpHandle) { hid_set_nonblocking(mcpHandle, 1); res = hid_read(mcpHandle, buf, MCP_IN_BUF_SIZE); if (res < 0) { sprintf(tmp, "-> CP: mcp_driver.panel_read_non_blocking: Error: %ls\n", hid_error(mcpHandle)); XPLMDebugString(tmp); } } return res; }
// ***** Multi Panel Process ****** void process_multi_panel() { process_multi_menu(); // ******* Only do a read if something new to be read ******** hid_set_nonblocking(multihandle, 1); int multi_safety_cntr = 30; do{ multires = hid_read(multihandle, multibuf, sizeof(multibuf)); process_alt_switch(); process_vs_switch(); process_ias_switch(); process_hdg_switch(); process_crs_switch(); process_autothrottle_switch(); process_ap_master_switch(); process_hdg_button(); process_nav_button(); process_ias_button(); process_alt_button(); process_vs_button(); process_apr_button(); process_rev_button(); process_flaps_switch(); process_trim_wheel(); if(multires > 0){ process_multi_flash(); process_multi_blank_display(); process_multi_display(); hid_send_feature_report(multihandle, multiwbuf, sizeof(multiwbuf)); } --multi_safety_cntr; }while((multires > 0) && (multi_safety_cntr > 0)); process_multi_flash(); process_multi_blank_display(); process_multi_display(); // ******* Write on changes or timeout ******** if ((lastmultiseldis != multiseldis) || (lastbtnleds != btnleds) || (multinowrite > 50)) { mulres = hid_send_feature_report(multihandle, multiwbuf, sizeof(multiwbuf)); multinowrite = 1; lastmultiseldis = multiseldis; lastbtnleds = btnleds; }else{ multinowrite++; } return; }
/** @brief Read an Input report from a HID device. Input reports are returned to the host through the INTERRUPT IN endpoint. The first byte will contain the Report number if the device uses numbered reports. @ingroup API @param device A device handle returned from hid_open(). @param data A buffer to put the read data into. @param length The number of bytes to read. For devices with multiple reports, make sure to read an extra byte for the report number. @returns This function returns the actual number of bytes read and -1 on error. */ int UsbHid::recvRawInReport(QByteArray &inData) { int res = -1; if (hidDevice != 0) { do { res = hid_read(hidDevice, (unsigned char*)inData.data(), inData.size()); if (!res) usleep(1); } while (!res); } return res; }
int cb_panel_read_non_blocking(unsigned char *buf) { int res = 0; if (cbHandle) { hid_set_nonblocking(cbHandle, 1); res = hid_read(cbHandle, buf, CB_IN_BUF_SIZE); if (res < 0) { sprintf(tmp, "-> CP: cb_driver.panel_read_non_blocking: Error: %ls\n", hid_error(cbHandle)); printf(tmp); } } return res; }
USING_PTYPES /** * */ void rp_init(hid_device* hid) { LPRINTF("Saitek ProPanels Plugin: rp_init\n"); uint8_t buf[4]; hid_set_nonblocking(hid, (int)true); hid_read(hid, buf, sizeof(buf)); hid_send_feature_report(hid, rp_blank_panel, sizeof(rp_blank_panel)); hid_set_nonblocking(hid, (int)false); }
void HID_read(unsigned char *buff, int size) { int ret = 0; ret = hid_read(target, buff, size); if (ret >= 0) { int i; printf("\n"); for (i = 0; i < ret; i++) printf("%x\t", buff[i]); printf("\n"); } else { DBG_ERR("HID_read error"); } }
bool DeviceHandleHIDAPI::read(Transfer& transfer_, uint8_t) { int nBytesRead = hid_read(m_pCurrentDevice, m_inputBuffer.data(), kInputBufferSize); if (nBytesRead == 0) { // No data available return true; } else if (nBytesRead > 0) { transfer_.setData(m_inputBuffer.data(), nBytesRead); return transfer_; } return false; }
void TaquitoClient::read(){ // std::cout << "reading" << std::endl; if(USBHandle == NULL) return; unsigned char buf[sizeof(data)*2]; memset(buf, 0, sizeof(buf)); int res = hid_read(USBHandle, buf, sizeof(buf)); if(res > 0){ // if result is bigger than zero, then it's data // print data on std out for(int i=0; i<sizeof(data); ++i) data[i] = (buf[i*2] << 8) | buf[i*2+1]; }else if(res < 0){ // if result is smaller than zero, then it's an error, so disconnect USBHandle = NULL; std::cerr << "read error" << std::endl; throw TaquitoError(); } }
void SwitchPanel::checkInputs() { static unsigned char inBuffer[5]; if (!handle) { return; } VESSEL *vessel = oapiGetFocusInterface(); // Get current vessel int bytesRead = hid_read(handle, inBuffer, sizeof(inBuffer)); if (vessel!=NULL) // check if pointer is valid { //0x04 >> gear up //0x08 >> gear down if (bytesRead==3) { char keyByte = inBuffer[2]; if (keyByte & 0x04) { // gear up setGear(vessel, true); } if (keyByte & 0x08) { // gear down setGear(vessel, false); } } } }
int main(int argc, char* argv[]){ hid_device *handle; unsigned char resbuf[8]; if(argc < 3){ usage(); return 1; } host = argv[1]; port = atoi(argv[2]); printf("Opening ONTRAK device...\n"); handle = hid_open(VENDOR_ID, DEVICE_ID, NULL); hid_set_nonblocking(handle, 0); //blocking mode ftw printf("Device opened and set to blocking mode."); UdpTransmitSocket transmitSocket( IpEndpointName( host, port ) ); while(true){ send_ontrak_command(handle); int res = hid_read(handle, resbuf, 8); if(res <= 0){ printf("ERROR reading\n"); } else{ fprintf(stdout, "."); fflush(stdout); if(++dots > 80){ printf("\n"); dots = 0; } int state = atoi((const char*)resbuf+1); // printf("%d\n", state); if(state != last_state){ last_state = state; send_osc(transmitSocket, state); } } usleep(POLL_SLEEP_MS * 1000); } }
JNIEXPORT jint JNICALL Java_com_codeminders_hidapi_HIDDevice_read (JNIEnv *env, jobject self, jbyteArray data) { hid_device *peer = getPeer(env, self); if(!peer) { throwIOException(env, peer); return 0; /* not an error, freed previously */ } jsize bufsize = env->GetArrayLength(data); jbyte *buf = env->GetByteArrayElements(data, NULL); int read = hid_read(peer, (unsigned char*) buf, bufsize); env->ReleaseByteArrayElements(data, buf, read==-1?JNI_ABORT:0); if(read==-1) { throwIOException(env, peer); return 0; /* not an error, freed previously */ } return read; }