您的位置:首页 > 其它

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

2014-09-24 23:21 453 查看
在项目开发当中,我们需要一个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

/* 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 < 0) {
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, 0);
if (ret < 0) {
perror("libusb_claim_interface");
devh = NULL;
libusb_close(devh);
return ret;
}
/* end */

/* open device data */
unsigned char open_data[8];
memset(open_data, 0, sizeof(open_data));
if ( 0 > libusb_control_transfer(devh, 0xa1, 0x01, 0x3000, 0x00, open_data, 0x08, 1000)) {
perror("libusb_control_transfer");
}
printf("receive data: %s\n", open_data);
int i = 0;
for(i = 0; i < 8; i++) {
printf("%02x\t", open_data[i]);
}
putchar(10);
/* end */

/* lock relay */
unsigned char lock_data[] = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
if (0 > libusb_control_transfer(devh, 0x21, 0x09, 0x0000, 0x00, lock_data, 0x08, 1000)) {
perror("libusb_control_transfer");
}
/* end */

/* delay */
sleep(2);

/* unlock relay */
unsigned char unlock_data[] = {0xfd, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
if (0 > libusb_control_transfer(devh, 0x21, 0x09, 0x3000, 0x00, unlock_data, 0x08, 1000)) {
perror("libusb_control_transfer");
}
/* end */

/* release claim interface */
libusb_release_interface(devh, 0);
/* end */

/* close device */
libusb_close(devh);

return 0;
}


后记:

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

  一句话:没有解决不了的问题!致自己,致大家,希望在挣扎中和大家一起进步。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: