7 Copyright (C) 2005-2008, Chris Frey
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18 See the GNU General Public License in the COPYING file at the
19 root directory of this project for more details.
33 #ifndef __DEBUG_MODE__
34 #define __DEBUG_MODE__
40 ///////////////////////////////////////////////////////////////////////////////
41 // Usb::Error exception class
43 static std::string
GetErrorString(int libusb_errcode
, const std::string
&str
)
45 std::ostringstream oss
;
48 if( libusb_errcode
) {
49 oss
<< std::setbase(10) << libusb_errcode
<< ", ";
52 // oss << strerror(-libusb_errno) << "): "
53 oss
<< usb_strerror() << "): ";
58 Error::Error(const std::string
&str
)
59 : Barry::Error(GetErrorString(0, str
))
64 Error::Error(int libusb_errcode
, const std::string
&str
)
65 : Barry::Error(GetErrorString(libusb_errcode
, str
))
66 , m_libusb_errcode(libusb_errcode
)
71 ///////////////////////////////////////////////////////////////////////////////
74 Match::Match(int vendor
, int product
,
75 const char *busname
, const char *devname
)
85 m_busses
= usb_get_busses();
92 bool Match::ToNum(const char *str
, long &num
)
95 num
= strtol(str
, &end
, 10);
96 return num
>= 0 && // no negative numbers
97 num
!= LONG_MIN
&& num
!= LONG_MAX
&& // no overflow
98 str
!= end
&& *end
== '\0'; // whole string valid
102 // Linux treats bus and device path names as numbers, sometimes left
103 // padded with zeros. Other platforms, such as Windows, use strings,
104 // such as "bus-1" or similar.
106 // Here we try to convert each string to a number, and if successful,
107 // compare them. If unable to convert, then compare as strings.
108 // This way, "3" == "003" and "bus-foobar" == "bus-foobar".
110 bool Match::NameCompare(const char *n1
, const char *n2
)
113 if( ToNum(n1
, l1
) && ToNum(n2
, l2
) ) {
117 return strcmp(n1
, n2
) == 0;
121 bool Match::next_device(Usb::DeviceIDType
*devid
)
123 for( ; m_busses
; m_busses
= m_busses
->next
) {
125 // only search on given bus
126 if( m_busname
&& !NameCompare(m_busname
, m_busses
->dirname
) )
130 m_dev
= m_busses
->devices
;
132 for( ; m_dev
; m_dev
= m_dev
->next
) {
134 // search for specific device
135 if( m_devname
&& !NameCompare(m_devname
, m_dev
->filename
) )
139 if( m_dev
->descriptor
.idVendor
== m_vendor
&&
140 m_dev
->descriptor
.idProduct
== m_product
) {
144 // advance for next time
147 m_busses
= m_busses
->next
;
158 ///////////////////////////////////////////////////////////////////////////////
161 Device::Device(Usb::DeviceIDType id
, int timeout
)
165 dout("usb_open(" << std::dec
<< id
<< ")");
166 m_handle
= usb_open(id
);
168 throw Error("open failed");
173 dout("usb_close(" << std::dec
<< m_handle
<< ")");
177 bool Device::SetConfiguration(unsigned char cfg
)
179 dout("usb_set_configuration(" << std::dec
<< m_handle
<< "," << std::dec
<< (unsigned int) cfg
<< ")");
180 int ret
= usb_set_configuration(m_handle
, cfg
);
185 bool Device::ClearHalt(int ep
)
187 dout("usb_clear_halt(" << std::dec
<< m_handle
<< "," << std::dec
<< ep
<< ")");
188 int ret
= usb_clear_halt(m_handle
, ep
);
195 dout("usb_reset(" << std::dec
<< m_handle
<< ")");
196 int ret
= usb_reset(m_handle
);
201 bool Device::BulkRead(int ep
, Barry::Data
&data
, int timeout
)
205 ret
= usb_bulk_read(m_handle
, ep
,
206 (char*) data
.GetBuffer(), data
.GetBufSize(),
207 timeout
== -1 ? m_timeout
: timeout
);
208 if( ret
< 0 && ret
!= -EINTR
&& ret
!= -EAGAIN
) {
210 if( ret
== -ETIMEDOUT
)
211 throw Timeout(ret
, "Timeout in usb_bulk_read");
213 throw Error(ret
, "Error in usb_bulk_read");
215 data
.ReleaseBuffer(ret
);
216 } while( ret
== -EINTR
|| ret
== -EAGAIN
);
221 bool Device::BulkWrite(int ep
, const Barry::Data
&data
, int timeout
)
223 ddout("BulkWrite to endpoint " << std::dec
<< ep
<< ":\n" << data
);
226 ret
= usb_bulk_write(m_handle
, ep
,
227 (char*) data
.GetData(), data
.GetSize(),
228 timeout
== -1 ? m_timeout
: timeout
);
229 if( ret
< 0 && ret
!= -EINTR
&& ret
!= -EAGAIN
) {
231 if( ret
== -ETIMEDOUT
)
232 throw Timeout(ret
, "Timeout in usb_bulk_write");
234 throw Error(ret
, "Error in usb_bulk_write");
236 } while( ret
== -EINTR
|| ret
== -EAGAIN
);
241 bool Device::BulkWrite(int ep
, const void *data
, size_t size
, int timeout
)
243 #ifdef __DEBUG_MODE__
244 Barry::Data
dump(data
, size
);
245 ddout("BulkWrite to endpoint " << std::dec
<< ep
<< ":\n" << dump
);
250 ret
= usb_bulk_write(m_handle
, ep
,
252 timeout
== -1 ? m_timeout
: timeout
);
253 if( ret
< 0 && ret
!= -EINTR
&& ret
!= -EAGAIN
) {
255 if( ret
== -ETIMEDOUT
)
256 throw Timeout(ret
, "Timeout in usb_bulk_read");
258 throw Error(ret
, "Error in usb_bulk_read");
260 } while( ret
== -EINTR
|| ret
== -EAGAIN
);
265 bool Device::InterruptRead(int ep
, Barry::Data
&data
, int timeout
)
269 ret
= usb_interrupt_read(m_handle
, ep
,
270 (char*) data
.GetBuffer(), data
.GetBufSize(),
271 timeout
== -1 ? m_timeout
: timeout
);
272 if( ret
< 0 && ret
!= -EINTR
&& ret
!= -EAGAIN
) {
274 if( ret
== -ETIMEDOUT
)
275 throw Timeout(ret
, "Timeout in usb_bulk_read");
277 throw Error(ret
, "Error in usb_bulk_read");
279 data
.ReleaseBuffer(ret
);
280 } while( ret
== -EINTR
|| ret
== -EAGAIN
);
285 bool Device::InterruptWrite(int ep
, const Barry::Data
&data
, int timeout
)
287 ddout("InterruptWrite to endpoint " << std::dec
<< ep
<< ":\n" << data
);
291 ret
= usb_interrupt_write(m_handle
, ep
,
292 (char*) data
.GetData(), data
.GetSize(),
293 timeout
== -1 ? m_timeout
: timeout
);
294 if( ret
< 0 && ret
!= -EINTR
&& ret
!= -EAGAIN
) {
296 if( ret
== -ETIMEDOUT
)
297 throw Timeout(ret
, "Timeout in usb_bulk_read");
299 throw Error(ret
, "Error in usb_bulk_read");
301 } while( ret
== -EINTR
|| ret
== -EAGAIN
);
309 /// Reads anything available on the given endpoint, with a low timeout,
310 /// in order to clear any pending reads.
312 void Device::BulkDrain(int ep
, int timeout
)
316 while( BulkRead(ep
, data
, timeout
) )
319 catch( Usb::Error
& ) {}
325 /// Uses the GET_CONFIGURATION control message to determine the currently
326 /// selected USB configuration, returning it in the cfg argument.
327 /// If unsuccessful, returns false.
329 bool Device::GetConfiguration(unsigned char &cfg
)
331 int result
= usb_control_msg(m_handle
, 0x80, USB_REQ_GET_CONFIGURATION
, 0, 0,
332 (char*) &cfg
, 1, m_timeout
);
333 m_lasterror
= result
;
339 ///////////////////////////////////////////////////////////////////////////////
342 Interface::Interface(Device
&dev
, int iface
)
343 : m_dev(dev
), m_iface(iface
)
345 dout("usb_claim_interface(" << dev
.GetHandle() << "," << std::dec
<< iface
<< ")");
346 int ret
= usb_claim_interface(dev
.GetHandle(), iface
);
348 throw Error(ret
, "claim interface failed");
351 Interface::~Interface()
353 dout("usb_release_interface(" << m_dev
.GetHandle() << "," << std::dec
<< m_iface
<< ")");
354 usb_release_interface(m_dev
.GetHandle(), m_iface
);
359 ///////////////////////////////////////////////////////////////////////////////
362 bool EndpointDiscovery::Discover(struct usb_interface_descriptor
*interface
, int epcount
)
370 if( !interface
|| !interface
->endpoint
) {
371 dout("EndpointDiscovery::Discover: empty interface pointer");
375 for( int i
= 0; i
< epcount
; i
++ ) {
377 usb_endpoint_descriptor desc
;
378 desc
= interface
->endpoint
[i
];
379 dout(" endpoint_desc #" << i
<< " loaded"
380 << "\nbLength: " << (unsigned ) desc
.bLength
381 << "\nbDescriptorType: " << (unsigned ) desc
.bDescriptorType
382 << "\nbEndpointAddress: " << (unsigned ) desc
.bEndpointAddress
383 << "\nbmAttributes: " << (unsigned ) desc
.bmAttributes
384 << "\nwMaxPacketSize: " << (unsigned ) desc
.wMaxPacketSize
385 << "\nbInterval: " << (unsigned ) desc
.bInterval
386 << "\nbRefresh: " << (unsigned ) desc
.bRefresh
387 << "\nbSynchAddress: " << (unsigned ) desc
.bSynchAddress
392 (*this)[desc
.bEndpointAddress
] = desc
;
393 dout(" endpoint added to map with bEndpointAddress: " << (unsigned int)desc
.bEndpointAddress
);
395 // parse the endpoint into read/write sets, if possible,
396 // going in discovery order...
398 // - endpoints of related utility will be grouped
399 // - endpoints with same type will be grouped
400 // - endpoints that do not meet the above assumptions
401 // do not belong in a pair
402 unsigned char type
= desc
.bmAttributes
& USB_ENDPOINT_TYPE_MASK
;
403 if( desc
.bEndpointAddress
& USB_ENDPOINT_DIR_MASK
) {
405 pair
.read
= desc
.bEndpointAddress
;
406 dout(" pair.read = " << (unsigned int)pair
.read
);
407 if( pair
.IsTypeSet() && pair
.type
!= type
) {
408 // if type is already set, we must start over
414 pair
.write
= desc
.bEndpointAddress
;
415 dout(" pair.write = " << (unsigned int)pair
.write
);
416 if( pair
.IsTypeSet() && pair
.type
!= type
) {
417 // if type is already set, we must start over
421 // save the type last
423 dout(" pair.type = " << (unsigned int)pair
.type
);
425 // if pair is complete, add to array
426 if( pair
.IsComplete() ) {
427 m_endpoints
.push_back(pair
);
428 dout(" pair added! ("
429 << "read: " << (unsigned int)pair
.read
<< ","
430 << "write: " << (unsigned int)pair
.write
<< ","
431 << "type: " << (unsigned int)pair
.type
<< ")");
432 pair
= EndpointPair(); // clear
436 // just for debugging purposes, check for extra descriptors, and
437 // dump them to dout if they exist
438 if( interface
->extra
) {
439 dout("while parsing endpoints, found a block of extra descriptors:");
440 Barry::Data
data(interface
->extra
, interface
->extralen
);
444 return m_valid
= true;
448 ///////////////////////////////////////////////////////////////////////////////
449 // InterfaceDiscovery
451 bool InterfaceDiscovery::DiscoverInterface(struct usb_interface
*interface
)
453 if( !interface
->altsetting
) {
454 dout("InterfaceDiscovery::DiscoverIterface: empty altsetting");
455 // some devices are buggy and return a higher bNumInterfaces
456 // than the number of interfaces available... in this case
457 // we just skip and continue
461 for( int i
= 0; i
< interface
->num_altsetting
; i
++ ) {
464 desc
.desc
= interface
->altsetting
[i
];
465 dout(" interface_desc #" << i
<< " loaded"
466 << "\nbLength: " << (unsigned) desc
.desc
.bLength
467 << "\nbDescriptorType: " << (unsigned) desc
.desc
.bDescriptorType
468 << "\nbInterfaceNumber: " << (unsigned) desc
.desc
.bInterfaceNumber
469 << "\nbAlternateSetting: " << (unsigned) desc
.desc
.bAlternateSetting
470 << "\nbNumEndpoints: " << (unsigned) desc
.desc
.bNumEndpoints
471 << "\nbInterfaceClass: " << (unsigned) desc
.desc
.bInterfaceClass
472 << "\nbInterfaceSubClass: " << (unsigned) desc
.desc
.bInterfaceSubClass
473 << "\nbInterfaceProtocol: " << (unsigned) desc
.desc
.bInterfaceProtocol
474 << "\niInterface: " << (unsigned) desc
.desc
.iInterface
478 // load all endpoints on this interface
479 if( !desc
.endpoints
.Discover(&desc
.desc
, desc
.desc
.bNumEndpoints
) ) {
480 dout(" endpoint discovery failed for bInterfaceNumber: " << (unsigned int)desc
.desc
.bInterfaceNumber
<< ", not added to map.");
485 (*this)[desc
.desc
.bInterfaceNumber
] = desc
;
486 dout(" interface added to map with bInterfaceNumber: " << (unsigned int)desc
.desc
.bInterfaceNumber
);
491 bool InterfaceDiscovery::Discover(Usb::DeviceIDType devid
, int cfgidx
, int ifcount
)
497 if( !devid
|| !devid
->config
|| !devid
->config
[cfgidx
].interface
) {
498 dout("InterfaceDiscovery::Discover: empty devid/config/interface");
502 for( int i
= 0; i
< ifcount
; i
++ ) {
503 if( !DiscoverInterface(&devid
->config
[cfgidx
].interface
[i
]) )
507 return m_valid
= true;
511 ///////////////////////////////////////////////////////////////////////////////
514 bool ConfigDiscovery::Discover(Usb::DeviceIDType devid
, int cfgcount
)
520 for( int i
= 0; i
< cfgcount
; i
++ ) {
523 if( !devid
|| !devid
->config
) {
524 dout("ConfigDiscovery::Discover: empty devid or config");
527 desc
.desc
= devid
->config
[i
];
528 dout(" config_desc #" << i
<< " loaded"
529 << "\nbLength: " << (unsigned int) desc
.desc
.bLength
530 << "\nbDescriptorType: " << (unsigned int) desc
.desc
.bDescriptorType
531 << "\nwTotalLength: " << (unsigned int) desc
.desc
.wTotalLength
532 << "\nbNumInterfaces: " << (unsigned int) desc
.desc
.bNumInterfaces
533 << "\nbConfigurationValue: " << (unsigned int) desc
.desc
.bConfigurationValue
534 << "\niConfiguration: " << (unsigned int) desc
.desc
.iConfiguration
535 << "\nbmAttributes: " << (unsigned int) desc
.desc
.bmAttributes
536 << "\nMaxPower: " << (unsigned int) desc
.desc
.MaxPower
540 // just for debugging purposes, check for extra descriptors, and
541 // dump them to dout if they exist
542 if( desc
.desc
.extra
) {
543 dout("while parsing config descriptor, found a block of extra descriptors:");
544 Barry::Data
data(desc
.desc
.extra
, desc
.desc
.extralen
);
548 // load all interfaces on this configuration
549 if( !desc
.interfaces
.Discover(devid
, i
, desc
.desc
.bNumInterfaces
) ) {
550 dout(" config discovery failed for bConfigurationValue: " << (unsigned int)desc
.desc
.bConfigurationValue
<< ", not added to map.");
555 (*this)[desc
.desc
.bConfigurationValue
] = desc
;
556 dout(" config added to map with bConfigurationValue: " << (unsigned int)desc
.desc
.bConfigurationValue
);
559 return m_valid
= true;
563 ///////////////////////////////////////////////////////////////////////////////
566 DeviceDiscovery::DeviceDiscovery(Usb::DeviceIDType devid
)
572 bool DeviceDiscovery::Discover(Usb::DeviceIDType devid
)
578 // copy the descriptor over to our memory
580 dout("DeviceDiscovery::Discover: empty devid");
584 desc
= devid
->descriptor
;
585 dout("device_desc loaded"
586 << "\nbLength: " << (unsigned int) desc
.bLength
587 << "\nbDescriptorType: " << (unsigned int) desc
.bDescriptorType
588 << "\nbcdUSB: " << (unsigned int) desc
.bcdUSB
589 << "\nbDeviceClass: " << (unsigned int) desc
.bDeviceClass
590 << "\nbDeviceSubClass: " << (unsigned int) desc
.bDeviceSubClass
591 << "\nbDeviceProtocol: " << (unsigned int) desc
.bDeviceProtocol
592 << "\nbMaxPacketSize0: " << (unsigned int) desc
.bMaxPacketSize0
593 << "\nidVendor: " << (unsigned int) desc
.idVendor
594 << "\nidProduct: " << (unsigned int) desc
.idProduct
595 << "\nbcdDevice: " << (unsigned int) desc
.bcdDevice
596 << "\niManufacturer: " << (unsigned int) desc
.iManufacturer
597 << "\niProduct: " << (unsigned int) desc
.iProduct
598 << "\niSerialNumber: " << (unsigned int) desc
.iSerialNumber
599 << "\nbNumConfigurations: " << (unsigned int) desc
.bNumConfigurations
603 m_valid
= configs
.Discover(devid
, desc
.bNumConfigurations
);