mac 下读写非hid的usb设备

2 篇文章 0 订阅

DeviceObject.h


#import <Foundation/Foundation.h>
#include <IOKit/usb/IOUSBLib.h>
#include <IOKit/IOCFPlugIn.h>

@interface DeviceObject : NSObject

@property(nonatomic,assign)io_object_t              notification;
@property(nonatomic,assign)IOUSBInterfaceInterface  **interface;
@property(nonatomic,assign)UInt32                   locationID;
@property(nonatomic,assign)CFStringRef				deviceName;

@property(nonatomic,assign)IOUSBDeviceInterface     **dev;
@property(nonatomic,assign)UInt8                    pipeIn;
@property(nonatomic,assign)UInt8                    pipeOut;
@property(nonatomic,assign)UInt16                   maxPacketSizeIn;
@property(nonatomic,assign)UInt16                   maxPacketSizeOut;

@end


DeviceObject.m


#import "DeviceObject.h"

@implementation DeviceObject

@synthesize notification;
@synthesize interface;
@synthesize locationID;
@synthesize deviceName;

@synthesize dev;
@synthesize pipeIn;
@synthesize pipeOut;
@synthesize maxPacketSizeIn;
@synthesize maxPacketSizeOut;

@end


UsbMonitor.h



#import <Foundation/Foundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOMessage.h>
#include <IOKit/IOCFPlugIn.h>
#include <IOKit/usb/IOUSBLib.h>
#import "DeviceObject.h"

@protocol UsbMonitorDelegate <NSObject>
@optional
- (void)usbDidPlunIn:(DeviceObject*)usbObject;
- (void)usbDidRemove:(DeviceObject*)usbObject;
@end

@interface UsbMonitor : NSObject {
}

@property(nonatomic,strong)NSMutableArray* arrayDevices;
@property(nonatomic,strong)id<UsbMonitorDelegate> delegate;

+ (UsbMonitor *)sharedUsbMonitorManager;
- (id)initWithVID:(long)vid withPID:(long)pid;
- (id)initWithVID:(long)vid withPID:(long)pid withDelegate:(id<UsbMonitorDelegate>)gate;
- (DeviceObject*)getObjectByID:(long)localid;
- (IOReturn)WriteSync:(DeviceObject*)pDev buffer:(char*) writeBuffer size:(unsigned int)size;
- (IOReturn)WriteAsync:(DeviceObject*)pDev buffer:(char*)writeBuffer size:(unsigned int)size;
- (IOReturn)ReadSync:(DeviceObject*)pDev buffer:(char*)buff size:(unsigned int)size;
- (IOReturn)ReadAsync:(DeviceObject*)pDev buffer:(char*)buff size:(unsigned int)size;
- (NSMutableArray*)getDeviceArray;

@end


UsbMonitor.m


#import "UsbMonitor.h"

@implementation UsbMonitor

@synthesize arrayDevices;
@synthesize delegate;

static UsbMonitor *sharedInstance = nil;

IONotificationPortRef	gNotifyPort;
io_iterator_t			gAddedIter;
CFRunLoopRef			gRunLoop;


void SignalHandler(int sigraised) {
    fprintf(stderr, "\nInterrupted.\n");
    exit(0);
}

void DeviceNotification(void *refCon, io_service_t service, natural_t messageType, void *messageArgument) {
    kern_return_t	kr;
    DeviceObject	*privateDataRef = (__bridge DeviceObject *) refCon;
    
    if (messageType == kIOMessageServiceIsTerminated) {
        for (DeviceObject* usbObj in [UsbMonitor sharedUsbMonitorManager].arrayDevices) {
            if (usbObj.locationID == privateDataRef.locationID) {
                NSLog(@"delete id=%08x",usbObj.locationID);
                [[UsbMonitor sharedUsbMonitorManager].arrayDevices removeObject:usbObj];
                break;
            }
        }
        
        if ([[UsbMonitor sharedUsbMonitorManager].delegate respondsToSelector:@selector(usbDidRemove:)]) {
            [[UsbMonitor sharedUsbMonitorManager].delegate usbDidRemove:privateDataRef];
        }
        
        CFRelease(privateDataRef.deviceName);
        
        if (privateDataRef.interface) {
            (*(privateDataRef.interface))->USBInterfaceClose(privateDataRef.interface);
            (*(privateDataRef.interface))->Release(privateDataRef.interface);
        }
        
        if (privateDataRef.dev) {
            (*(privateDataRef.dev))->USBDeviceClose(privateDataRef.dev);
            kr = (*privateDataRef.dev)->Release(privateDataRef.dev);
        }
        
        kr = IOObjectRelease(privateDataRef.notification);
    }
}

void DeviceAdded(void *refCon, io_iterator_t iterator) {
    kern_return_t		kr;
    io_service_t		usbDevice;
    IOCFPlugInInterface	**plugInInterface = NULL;
    SInt32				score;
    HRESULT 			res;
    
    while ((usbDevice = IOIteratorNext(iterator))) {
        io_name_t		deviceName;
        CFStringRef		deviceNameAsCFString;
        DeviceObject	*privateDataRef = [[DeviceObject alloc]init];
        UInt32			locationID;
        
        kr = IORegistryEntryGetName(usbDevice, deviceName);
        if (KERN_SUCCESS != kr) {
            deviceName[0] = '\0';
        }
        
        deviceNameAsCFString = CFStringCreateWithCString(kCFAllocatorDefault,deviceName,kCFStringEncodingASCII);
        //NSLog(@"deviceName:%@",deviceNameAsCFString);
        
        privateDataRef.deviceName = deviceNameAsCFString;
        kr = IOCreatePlugInInterfaceForService(usbDevice,kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID,&plugInInterface, &score);
        
        if ((kIOReturnSuccess != kr) || !plugInInterface) {
            NSLog(@"IOCreatePlugInInterfaceForService returned 0x%08x.",kr);
            continue;
        }
        
        IOUSBDeviceInterface     **oneDev = NULL;
        res = (*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID),(LPVOID*)&oneDev);
        privateDataRef.dev = oneDev;
        
        (*plugInInterface)->Release(plugInInterface);
        if (res || privateDataRef.dev == NULL) {
            NSLog(@"QueryInterface returned %d.\n", (int)res);
            continue;
        }
        
        kr = (*privateDataRef.dev)->GetLocationID(privateDataRef.dev, &locationID);
        if (KERN_SUCCESS != kr) {
            NSLog(@"GetLocationID returned 0x%08x.\n", kr);
            continue;
        } else {
            NSLog(@"Location ID: 0x%08x", locationID);
        }
        privateDataRef.locationID = locationID;
        
        kr = (*privateDataRef.dev)->USBDeviceOpen(privateDataRef.dev);
        if(kr != kIOReturnSuccess) {
            NSLog(@"Usb Open Fail!");
            (*privateDataRef.dev)->USBDeviceClose(privateDataRef.dev);
            (void) (*privateDataRef.dev)->Release(privateDataRef.dev);
            privateDataRef.dev = NULL;
            continue;
        }
        
        //configure device
        UInt8                numConfig;
        IOUSBConfigurationDescriptorPtr configDesc;
        
        //Get the number of configurations.
        kr = (*privateDataRef.dev)->GetNumberOfConfigurations(privateDataRef.dev, &numConfig);
        if(numConfig == 0)
            continue;
        
        //Get the configuration descriptor for index 0
        kr = (*privateDataRef.dev)->GetConfigurationDescriptorPtr(privateDataRef.dev, 0, &configDesc);
        if(kr != kIOReturnSuccess) {
            NSLog(@"Unable to get configuration descriptor for index 0 (err = %08x)\n",kr);
            continue;
        }
        kr = [[UsbMonitor sharedUsbMonitorManager] FindUSBInterface:privateDataRef];
        if (kr != kIOReturnSuccess) {
            NSLog(@"Interface Open Fail!");
            (*privateDataRef.dev)->USBDeviceClose(privateDataRef.dev);
            (*privateDataRef.dev)->Release(privateDataRef.dev);
            privateDataRef.dev = NULL;
            continue ;
        }
        
        io_object_t              oneIter;
        kr = IOServiceAddInterestNotification(gNotifyPort,usbDevice,kIOGeneralInterest,	DeviceNotification,(__bridge void*)privateDataRef,&oneIter);
        privateDataRef.notification = oneIter;
        
        if (KERN_SUCCESS != kr) {
            NSLog(@"IOServiceAddInterestNotification returned 0x%08x", kr);
        }
        
        kr = IOObjectRelease(usbDevice);
    }
}

void usbMonitorCallBack(void *refcon, IOReturn result, void *arg0) {
    if (result == kIOReturnSuccess && refcon) {
        //u32 *pLen = (u32 *)refcon;
        //*pLen = reinterpret_cast<long>arg0;
    }
    NSLog(@"read and write callback!");
    CFRunLoopStop(CFRunLoopGetCurrent());
}


+ (UsbMonitor *)sharedUsbMonitorManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (sharedInstance == nil)
            sharedInstance = [(UsbMonitor *)[super allocWithZone:NULL] init];
    });
    return sharedInstance;
}

+ (id)allocWithZone:(NSZone *)zone {
    return [self sharedUsbMonitorManager];
}

- (id)copyWithZone:(NSZone *)zone {
    return self;
}

- (id)initWithVID:(long)vid withPID:(long)pid {
    self = [super init];
    if (self) {
        arrayDevices = [NSMutableArray new];
        
        CFMutableDictionaryRef 	matchingDict;
        CFRunLoopSourceRef		runLoopSource;
        CFNumberRef				numberRef;
        kern_return_t			kr;
        long					usbVendor = vid;
        long					usbProduct = pid;
        
        matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
        if (matchingDict == NULL) {
            return nil;
        }
        
        numberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &usbVendor);
        CFDictionarySetValue(matchingDict,CFSTR(kUSBVendorID),numberRef);
        CFRelease(numberRef);
        
        numberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &usbProduct);
        CFDictionarySetValue(matchingDict,CFSTR(kUSBProductID),numberRef);
        CFRelease(numberRef);
        numberRef = NULL;
        
        gNotifyPort = IONotificationPortCreate(kIOMasterPortDefault);
        runLoopSource = IONotificationPortGetRunLoopSource(gNotifyPort);
        
        gRunLoop = CFRunLoopGetCurrent();
        CFRunLoopAddSource(gRunLoop, runLoopSource, kCFRunLoopDefaultMode);
        
        kr = IOServiceAddMatchingNotification(gNotifyPort,kIOFirstMatchNotification,matchingDict,DeviceAdded,NULL,&gAddedIter);
        
        DeviceAdded(NULL, gAddedIter);
        
        CFRunLoopRun();
        
    }
    return self;
}

- (id)initWithVID:(long)vid withPID:(long)pid withDelegate:(id<UsbMonitorDelegate>)gate {
    self = [super init];
    if (self) {
        arrayDevices = [NSMutableArray new];
        
        CFMutableDictionaryRef 	matchingDict;
        CFRunLoopSourceRef		runLoopSource;
        CFNumberRef				numberRef;
        kern_return_t			kr;
        long					usbVendor = vid;
        long					usbProduct = pid;
        delegate = gate;
//        sig_t					oldHandler;
//        
//        oldHandler = signal(SIGINT, SignalHandler);
//        if (oldHandler == SIG_ERR) {
//            fprintf(stderr, "Could not establish new signal handler.");
//        }
        
        matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
        if (matchingDict == NULL) {
            return nil;
        }
        
        numberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &usbVendor);
        CFDictionarySetValue(matchingDict,CFSTR(kUSBVendorID),numberRef);
        CFRelease(numberRef);
        
        numberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &usbProduct);
        CFDictionarySetValue(matchingDict,CFSTR(kUSBProductID),numberRef);
        CFRelease(numberRef);
        numberRef = NULL;
        
        gNotifyPort = IONotificationPortCreate(kIOMasterPortDefault);
        runLoopSource = IONotificationPortGetRunLoopSource(gNotifyPort);
        
        gRunLoop = CFRunLoopGetCurrent();
        CFRunLoopAddSource(gRunLoop, runLoopSource, kCFRunLoopDefaultMode);
        
        kr = IOServiceAddMatchingNotification(gNotifyPort,kIOFirstMatchNotification,matchingDict,DeviceAdded,NULL,&gAddedIter);
        
        DeviceAdded(NULL, gAddedIter);
        
        CFRunLoopRun();

    }
    return self;
}

-(void)dealloc {
    for (DeviceObject* dev in arrayDevices) {
        (*(dev.interface))->USBInterfaceClose(dev.interface);
        (*(dev.interface))->Release(dev.interface);
        (*(dev.dev))->USBDeviceClose(dev.dev);
        (*(dev.dev))->Release(dev.dev);
    }
    [arrayDevices removeAllObjects];
}

-(IOReturn) FindUSBInterface:(DeviceObject*)usbObject {
    IOReturn                        kr = kIOReturnError;
    IOUSBFindInterfaceRequest       request;
    io_iterator_t                   iterator;
    io_service_t                    usbInterface;
    IOCFPlugInInterface             **plugInInterface = NULL;
    IOUSBInterfaceInterface         **interface = NULL;
    HRESULT                         result;
    SInt32                          score;
    UInt8                           interfaceNumEndpoints;
    UInt8                           pipeRef;
    UInt16                          maxPacketSize = 0;
    UInt8                           pipeIn = 0xff;
    UInt8                           pipeOut = 0xff;
    UInt16                          maxPacketSizeIn = 0;
    UInt16                          maxPacketSizeOut = 0;
    
    //Iterate all usb interface
    request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
    request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
    request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
    request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
    
    //Get an iterator for the interfaces on the device
    kr = (*usbObject.dev)->CreateInterfaceIterator(usbObject.dev, &request, &iterator);
    if(kr != kIOReturnSuccess) {
        NSLog(@"Unable to CreateInterfaceIterator %08x\n", kr);
        return kr;
    }
    
    kr = kIOReturnError;
    while((usbInterface = IOIteratorNext(iterator))) {
        pipeIn = 0xff;
        pipeOut = 0xff;
        kr = IOCreatePlugInInterfaceForService(usbInterface,                                               kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID,                                               &plugInInterface, &score);
        kr = IOObjectRelease(usbInterface);
        if(kr != kIOReturnSuccess || !plugInInterface) {
            NSLog(@"Unable to create a plug-in (%08x)\n", kr);
            break;
        }
        
        result = (*plugInInterface)->QueryInterface(plugInInterface,                           CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID), (LPVOID *)&interface);
        IODestroyPlugInInterface(plugInInterface);
        if(result || !interface) {
            NSLog(@"Unable to create a interface for the device interface %08x\n",(int)result);
            break;
        }
        //kr = (*interface)->USBInterfaceClose(interface);
        kr = (*interface)->USBInterfaceOpen(interface);
        if(kr != kIOReturnSuccess) {
            NSLog(@"Unable to open interface for the device interface %08x\n", kr);
            (*interface)->USBInterfaceClose(interface);
            (void) (*interface)->Release(interface);
            interface = NULL;
            break;
        }
        kr = (*interface)->GetNumEndpoints(interface, &interfaceNumEndpoints);
        if(kr != kIOReturnSuccess) {
            (void) (*interface)->USBInterfaceClose(interface);
            (void) (*interface)->Release(interface);
            interface = NULL;
            break;
        }
        for(pipeRef = 1; pipeRef <= interfaceNumEndpoints; pipeRef++) {
            IOReturn     kr2;
            UInt8        direction;
            UInt8        number;
            UInt8        transferType;
            UInt8        interval;
            
            kr2 = (*interface)->GetPipeProperties(interface, pipeRef, &direction,&number, &transferType, &maxPacketSize, &interval);
            if(kr2 != kIOReturnSuccess) {
                NSLog(@"Unable to get properties of pipe %d (%08x)\n",pipeRef, kr2);
            } else {
                if(transferType == kUSBBulk) {
                    if(direction == kUSBIn) {
                        pipeIn = pipeRef;
                        maxPacketSizeIn = maxPacketSize;
                    }
                    else if(direction == kUSBOut) {
                        pipeOut = pipeRef;
                        maxPacketSizeOut = maxPacketSize;
                    }
                }
            }
        }
        if (pipeIn != 0xff && pipeOut != 0xff) {
            usbObject.interface = interface;
            usbObject.pipeIn = pipeIn;
            usbObject.pipeOut = pipeOut;
            usbObject.maxPacketSizeIn = maxPacketSizeIn;
            usbObject.maxPacketSizeOut = maxPacketSizeOut;
            BOOL isIn = NO;
            for (DeviceObject* obj in arrayDevices) {
                if (obj.locationID == usbObject.locationID) {
                    isIn = YES;
                    break ;
                }
            }
            if (!isIn) {
                [arrayDevices addObject:usbObject];
            }
            if ([delegate respondsToSelector:@selector(usbDidPlunIn:)]) {
                [delegate usbDidPlunIn:usbObject];
            }
            return kIOReturnSuccess;
        }
        (*interface)->USBInterfaceClose(interface);
        (*interface)->Release(interface);
        interface = NULL;
    }
    return kr;
}

- (DeviceObject*)getObjectByID:(long)localid {
    for (DeviceObject* obj in arrayDevices) {
        if (obj.locationID == localid) {
            return obj;
        }
    }
    return nil;
}

//同步
-(IOReturn)WriteSync:(DeviceObject*)pDev buffer:(char*) writeBuffer size:(unsigned int)size
{
    if (pDev && pDev.interface) {
        if(size <= pDev.maxPacketSizeOut) {
            return [self WriteAsync:pDev buffer:writeBuffer size:size];
        }
        kern_return_t kr = 0;
        char *tmp = writeBuffer;
        unsigned int nWrite = (size > pDev.maxPacketSizeOut ? pDev.maxPacketSizeOut : size);
        unsigned int nLeft = size;
        while(1) {
            if((int)nLeft <= 0) {
                break;
            }
            kr = (*(pDev.interface))->WritePipe(pDev.interface,pDev.pipeOut, (void *)tmp, nWrite);
            if(kr != kIOReturnSuccess)
                break;
            tmp += nWrite;
            nLeft -= nWrite;
            nWrite = (nLeft > pDev.maxPacketSizeOut ? pDev.maxPacketSizeOut : nLeft);
        }
        return kr;
    }
    
    return kIOReturnNoDevice;
}

//异步
-(IOReturn)WriteAsync:(DeviceObject*)pDev buffer:(char*)writeBuffer size:(unsigned int)size {
    if (pDev == nil||pDev.interface == nil) {
        return kIOReturnNoDevice;
    }
    
    IOReturn                  err;
    CFRunLoopSourceRef        cfSource;
    unsigned int*             pWrite;
    
    err = (*(pDev.interface))->CreateInterfaceAsyncEventSource(pDev.interface, &cfSource);
    if (err) {
        NSLog(@"transferData: unable to create event source, err = %08x\n", err);
        return err;
    }
    CFRunLoopAddSource(CFRunLoopGetCurrent(), cfSource, kCFRunLoopDefaultMode);
    
    err = (*(pDev.interface))->WritePipeAsync(pDev.interface, pDev.pipeOut, (void *)writeBuffer, size,                                         (IOAsyncCallback1)usbMonitorCallBack, (void*)pWrite);
    if (err != kIOReturnSuccess) {
        NSLog(@"transferData: WritePipeAsyncFailed, err = %08x\n", err);
        CFRunLoopRemoveSource(CFRunLoopGetCurrent(), cfSource, kCFRunLoopDefaultMode);
        *pWrite = 0;
        return err;
    }
    
    CFRunLoopRun();
    CFRunLoopRemoveSource(CFRunLoopGetCurrent(), cfSource, kCFRunLoopDefaultMode);
    
    return err;
}

-(IOReturn)ReadSync:(DeviceObject*)pDev buffer:(char*)buff size:(unsigned int)size {
    if (pDev && pDev.interface) {
        if(sizeof(buff) <= pDev.maxPacketSizeIn) {
            return [self ReadAsync:pDev buffer:buff size:size];
        }
        kern_return_t kr = 0;
        UInt32 nRead = pDev.maxPacketSizeIn;
        unsigned int nLeft = size;
        char *tmp = (char *)buff;
        
        while(1) {
            if((int)nLeft <= 0)
                break;
            
            kr = (*(pDev.interface))->ReadPipe(pDev.interface,                   pDev.pipeIn, (void *)tmp, &nRead);
            if(kr != kIOReturnSuccess) {
                printf("transferData: Readsync Failed, err = %08x\n", kr);
                break;
            }
            
            tmp += nRead;
            nLeft -= nRead;
            nRead = pDev.maxPacketSizeIn;
        }
        int nRet = ((int)nLeft > 0 ? nLeft : 0);
        size = size - nRet;
        return kr;
    }
    return kIOReturnNoDevice;
}

-(IOReturn)ReadAsync:(DeviceObject*)pDev buffer:(char*)buff size:(unsigned int)size {
    if (pDev == nil||pDev.interface == nil) {
        return kIOReturnNoDevice;
    }
    
    IOReturn                    err;
    CFRunLoopSourceRef          cfSource;
    unsigned int*               pRead;
    
    err = (*(pDev.interface))->CreateInterfaceAsyncEventSource(pDev.interface, &cfSource);
    if (err) {
        NSLog(@"transferData: unable to create event source, err = %08x\n", err);
        return err;
    }
    CFRunLoopAddSource(CFRunLoopGetCurrent(), cfSource, kCFRunLoopDefaultMode);
    
    err = (*(pDev.interface))->ReadPipeAsync(pDev.interface, pDev.pipeIn, buff, size,(IOAsyncCallback1)usbMonitorCallBack, (void*)pRead);
    if (err != kIOReturnSuccess) {
        NSLog(@"transferData: size %u, ReadAsyncFailed, err = %08x\n", size, err);
        CFRunLoopRemoveSource(CFRunLoopGetCurrent(), cfSource, kCFRunLoopDefaultMode);
        pRead = nil;
        pDev = nil;
        return err;
    }
    
    CFRunLoopRun();
    CFRunLoopRemoveSource(CFRunLoopGetCurrent(), cfSource, kCFRunLoopDefaultMode);
    
    return err;
}

- (NSMutableArray*)getDeviceArray {
    return arrayDevices;
}

@end


  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
赋所有源代码,开发工具vs2010 framework3.5 baidu搜索c# HidUsb都是大同小异案例,而且拿下来基本不能用。大都是围绕public static extern int CreateFile(省略众多参数..);发现没有,copy下来测试基本都是用不了的。 原因很简单:windows不允许你用程序随便就去访问硬件设备。所以在此把之前做过的基于C#开发HidUsb设备的项目整理成一个简单的小案例,分享给大家,开发环境VS2010。 该案例重点在public static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode, IntPtr lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile); 看着貌似也是用到CreateFile这个函数,其实并不然,注意到没有"SafeFileHandle",这就是重点! 这样windows是允许程序访问外接hidusb设备的。 当然具体如何运用这个函数现在已经不是您应该 关心的了,因为我已经为您把它封装成一个类,您只要调用相应的方法就OK. 例: //第一步:获取HidUsb设备信息 List slist = new List(); UsbHidDevice usbhid = new UsbHidDevice(); usbhid.GetDeviceList(ref slist); //HidUsb设备信息包含在List数据集中 注:当获取到HidUsb设备信息为:\\?\hid#vid_0e2c&pid;_0112#6&1b44c403;&0&0000;#{4d1e55b2-f16f-11cf-88cb-001111000030}, 注意该字符串里的“vid_0e2c”和“pid_0112”部分,那么: vid为0e2c, pid为:0112 //第二步:创建一个HidUsb设备访问实例 UsbHidDevice Device = new UsbHidDevice(vid, pid); //第三步:连接HidUsb设备 Boolean connBool = Device.Connect(); //第四步:实现数据接收事件 Device.DataReceived += new UsbHidDevice.DataReceivedDelegate(Device_DataReceived); //当HidUsb设备返回信息时触发此事件 void Device_DataReceived(byte[] data) { //处理接收到的数据逻辑 } //第五步:向Hid设备发送数据"0xa0 00 0x12 0x9 0x22" string txt = "0xa0 00 0x12 0x9 0x22"; //把数据转换为字节数组 byte[] data = ConvertHelper.StringToByte(txt2); byte bt = 0; CommandMessage cmdMsg = new CommandMessage(bt, data); Boolean sbool = Device.SendMessage(cmdMsg); //发送数据 //第六步:释放所有资源 Device.Dispose();
USB HID设备是一种使用USB接口进行通信的设备,它可以通过发送和接收数据来实现和计算机的交互。为了USB HID设备数据,我们需要编一个程序来实现这个功能。 首先,我们需要使用合适的编程语言和相关的库来开发这样一个程序。对于Windows系统,我们可以使用C#、C++或者Python等语言来编程序;对于Linux系统,则可以选择C语言、Python等来实现。然后,我们需要选择一个合适的USB库,比如libusb,它提供了一些用于控制USB设备的函数和结构体。 接着,我们需要编程序来进行USB设备的初始化和连接。一般来说,我们需要找到目标设备的vendor ID和product ID,然后使用相关函数来打开设备并进行数据的。 在程序运行的过程中,我们可以使用相关函数来设备发送的数据,也可以发送命令或者数据给设备。在取数据时,我们需要根据设备的协议和数据格式进行解析和处理,以确保能正确地获取到设备发送的信息。 最后,我们需要进行错误处理和资源释放。当程序出现错误时,我们需要进行相应的处理,比如关闭设备,释放相关资源等,以确保程序的稳定性和可靠性。 总的来说,编USB HID设备数据程序是一个需要考虑设备协议、数据格式等因素的复杂任务,但通过合适的编程语言和库的选择,以及认真的编程实现,我们可以成功地实现这一功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值