Linux:复位USB设备
文章目录
- Linux:复位USB设备
- 前言
- 一、基本原理
- 二、代码实例
- 总结
前言
在Ubuntu16.04下开发SDR设备数据处理程序时,msi.sdr设备有时运行几个小时后就会出现获取数据失败的情况,猜测是设备本身的问题。问题的处理方式是需要重新插拔一下设备,这样十分麻烦。
要解决此问题,要么就找出sdr设备出现此问题的原因,或者采用复位USB的方式解决此问题。
本文主要介绍采用复位USB的方式解决此问题。
提示:以下是本篇文章正文内容,下面案例可供参考
一、基本原理
复位指定USB需要知道指定USB设备属于哪个主设备控制器,对应的设备号是多少。获取这两个关键参数后利用ioctl函数以文件io的形式实现USB复位操作。
在终端键入 lsusb 命令,可以看到msi.sdr在系统中的idProduct为2500,对应的USB主控制器为001,设备名为008。 可知msi.sdr设备在Linux系统中设备名是:/dev/bus/usb/001/008.
cs@cs:~$ lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 0403:6001 Future Technology Devices International, Ltd FT232 USB-Serial (UART) IC
Bus 001 Device 008: ID 1df7:2500
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
cs@cs:~$
当然,不同的Linux机器的主控制器与设备名并不一致,因此可以设计一个以idProduct为关键字,自动获取主控制器与对应设备号的复位USB小程序。
二、代码实例
代码如下(示例):
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <linux/usbdevice_fs.h>
int execute_cmd(const char *cmd, char *dest_buf)
{
FILE *fp = NULL;
char temp_buf[1024] = {0};
if((fp = popen(cmd, "r")) == NULL)
{
fprintf(stderr, "Command failed to execute:%s", strerror(errno));
return -1;
}
while(1)
{
if (fgets(temp_buf, sizeof(temp_buf), fp) != NULL)
{
strcat(dest_buf, temp_buf);
if(strlen(dest_buf) > 1024)
break;
}
else
{
break;
}
}
pclose(fp);
return 0;
}
void find_Bus_Device(char *src, const char * idProduct, char *file_path)
{
char *str = NULL;
while((str = strsep(&src, "\r\n")) != NULL)
{
if(strstr(str, idProduct)!= NULL)
{
printf("%s\n", str);
char Bus[4] = {0};
char Device[4] = {0};
memcpy(Bus, &str[4], sizeof(Bus));
memcpy(Device, &str[15], sizeof(Device));
Bus[3] = '\0';
Device[3] = '\0';
printf("Bus = %s Device = %s\n", Bus, Device);
sprintf(file_path, "/dev/bus/usb/%s/%s", Bus, Device);
printf("file path = %s\n", file_path);
}
}
}
int reset_sdr(const char *file_path)
{
int fd = 0;
int ret = 0;
fd = open(file_path, O_WRONLY);
if (fd < 0)
{
perror("Failed to open file");
return -1;
}
printf("Resetting USB device %s\n", file_path);
ret = ioctl(fd, USBDEVFS_RESET, 0);
if (ret < 0)
{
perror("The ioctl operation failed");
return -1;
}
close(fd);
return 0;
}
int main()
{
int ret = 0;
const char *cmd = "lsusb";
const char *idProduct = "2500";
char dest_buf[1024] = {0};
char *ptr = dest_buf;
char file_path[32] = {0};
execute_cmd(cmd, dest_buf);
find_Bus_Device(ptr, idProduct, file_path);
ret = reset_sdr(file_path);
if(ret == 0)
{
printf("Reset successful\n");
}
return 0;
}
总结
实测在msi.sdr设备运行异常时,使用此程序能正常复位USB设备。举一反三,复位其它USB设备也可以参考此程序实现。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)