在項目開發當中,我們需要一個usb轉繼電器的設備當開關控制無線發射設備,采購部采購時並未詳細了解Relay設備的運行環境就買了一批設備,之后發現設備廠家只提供了windows庫,而我們是要在linux中開發。無語中。。。。。。
Relay設備雖然是無驅的,可我並不知道它的協議,怎么辦呢? I have no choice ,but I have bus hound,LOL.
廠家提供了windows的管理工具,可以實現Relay的開斷,因此我通過Bus Hound截取usb數據包,得到通信協議。 LOL 可以編程咯。。。。。。
Bus Hound截取的數據包如下:
open device:
lock relay:
unlock relay:
Codes如下,只是個簡單的測試程序,並未講究編程中的那些xxxxxxxx
1 /* It is a simple testing */ 2 3 #include </usr/local/include/libusb-1.0/libusb.h> // libusb head file 4 #include <stdio.h> 5 #include <sys/types.h> 6 #include <string.h> 7 8 #define VID 0x16c0 // get of lsusb 9 #define PID 0x05df // get of lsusb 10 11 struct libusb_device_handle *devh = NULL; 12 13 //unsigned char openstr[] = {0xa1, 0x01, 0x00, 0x03, 0x00, 0x00, 0x08, 0x00}; 14 15 int main() 16 { 17 /* usb init before libusb_open* */ 18 int ret = libusb_init(NULL); 19 if (ret < 0) { 20 perror("libusb_init"); 21 return ret; 22 } 23 /* end */ 24 25 /* open device with vid and pid, must after libusb_init */ 26 devh = libusb_open_device_with_vid_pid(NULL, VID, PID); 27 if (!devh) { 28 perror("libusb_open_device_with_pid_vid"); 29 libusb_exit(NULL); 30 } 31 /* end */ 32 33 /* claim interface */ 34 ret = libusb_claim_interface(devh, 0); 35 if (ret < 0) { 36 perror("libusb_claim_interface"); 37 devh = NULL; 38 libusb_close(devh); 39 return ret; 40 } 41 /* end */ 42 43 /* open device data */ 44 unsigned char open_data[8]; 45 memset(open_data, 0, sizeof(open_data)); 46 if ( 0 > libusb_control_transfer(devh, 0xa1, 0x01, 0x3000, 0x00, open_data, 0x08, 1000)) { 47 perror("libusb_control_transfer"); 48 } 49 printf("receive data: %s\n", open_data); 50 int i = 0; 51 for(i = 0; i < 8; i++) { 52 printf("%02x\t", open_data[i]); 53 } 54 putchar(10); 55 /* end */ 56 57 /* lock relay */ 58 unsigned char lock_data[] = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; 59 if (0 > libusb_control_transfer(devh, 0x21, 0x09, 0x0000, 0x00, lock_data, 0x08, 1000)) { 60 perror("libusb_control_transfer"); 61 } 62 /* end */ 63 64 /* delay */ 65 sleep(2); 66 67 /* unlock relay */ 68 unsigned char unlock_data[] = {0xfd, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; 69 if (0 > libusb_control_transfer(devh, 0x21, 0x09, 0x3000, 0x00, unlock_data, 0x08, 1000)) { 70 perror("libusb_control_transfer"); 71 } 72 /* end */ 73 74 /* release claim interface */ 75 libusb_release_interface(devh, 0); 76 /* end */ 77 78 /* close device */ 79 libusb_close(devh); 80 81 return 0; 82 }
后記:
哈哈,開心啊,終於實現了控制Relay設備。
一句話:沒有解決不了的問題!致自己,致大家,希望在掙扎中和大家一起進步。