截取usb数据包,控制usb设备----Relay设备

时间:2023-11-10 16:20:02

在项目开发当中,我们需要一个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:

截取usb数据包,控制usb设备----Relay设备

lock relay:

截取usb数据包,控制usb设备----Relay设备

unlock relay:

截取usb数据包,控制usb设备----Relay设备

Codes如下,只是个简单的测试程序,并未讲究编程中的那些xxxxxxxx

 /* It is a simple testing */

 #include </usr/local/include/libusb-1.0/libusb.h>  // libusb head file
#include <stdio.h>
#include <sys/types.h>
#include <string.h> #define VID 0x16c0 // get of lsusb
#define PID 0x05df // get of lsusb struct libusb_device_handle *devh = NULL; //unsigned char openstr[] = {0xa1, 0x01, 0x00, 0x03, 0x00, 0x00, 0x08, 0x00}; int main()
{
/* usb init before libusb_open* */
int ret = libusb_init(NULL);
if (ret < ) {
perror("libusb_init");
return ret;
}
/* end */ /* open device with vid and pid, must after libusb_init */
devh = libusb_open_device_with_vid_pid(NULL, VID, PID);
if (!devh) {
perror("libusb_open_device_with_pid_vid");
libusb_exit(NULL);
}
/* end */ /* claim interface */
ret = libusb_claim_interface(devh, );
if (ret < ) {
perror("libusb_claim_interface");
devh = NULL;
libusb_close(devh);
return ret;
}
/* end */ /* open device data */
unsigned char open_data[];
memset(open_data, , sizeof(open_data));
if ( > libusb_control_transfer(devh, 0xa1, 0x01, 0x3000, 0x00, open_data, 0x08, )) {
perror("libusb_control_transfer");
}
printf("receive data: %s\n", open_data);
int i = ;
for(i = ; i < ; i++) {
printf("%02x\t", open_data[i]);
}
putchar();
/* end */ /* lock relay */
unsigned char lock_data[] = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
if ( > libusb_control_transfer(devh, 0x21, 0x09, 0x0000, 0x00, lock_data, 0x08, )) {
perror("libusb_control_transfer");
}
/* end */ /* delay */
sleep(); /* unlock relay */
unsigned char unlock_data[] = {0xfd, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
if ( > libusb_control_transfer(devh, 0x21, 0x09, 0x3000, 0x00, unlock_data, 0x08, )) {
perror("libusb_control_transfer");
}
/* end */ /* release claim interface */
libusb_release_interface(devh, );
/* end */ /* close device */
libusb_close(devh); return ;
}

后记:

  哈哈,开心啊,终于实现了控制Relay设备。

  一句话:没有解决不了的问题!致自己,致大家,希望在挣扎中和大家一起进步。