usb_linux.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. package hid
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "errors"
  6. "io/ioutil"
  7. "log"
  8. "os"
  9. "path/filepath"
  10. "syscall"
  11. "time"
  12. "unsafe"
  13. )
  14. type usbDevice struct {
  15. info Info
  16. f *os.File
  17. epIn int
  18. epOut int
  19. inputPacketSize uint16
  20. outputPacketSize uint16
  21. path string
  22. }
  23. func (hid *usbDevice) Open() (err error) {
  24. if hid.f != nil {
  25. return errors.New("device is already opened")
  26. }
  27. if hid.f, err = os.OpenFile(hid.path, os.O_RDWR, 0644); err != nil {
  28. return
  29. } else {
  30. return hid.claim()
  31. }
  32. }
  33. func (hid *usbDevice) Close() {
  34. if hid.f != nil {
  35. hid.release()
  36. hid.f.Close()
  37. hid.f = nil
  38. }
  39. }
  40. func (hid *usbDevice) Info() Info {
  41. return hid.info
  42. }
  43. func (hid *usbDevice) ioctl(n uint32, arg interface{}) (int, error) {
  44. b := new(bytes.Buffer)
  45. if err := binary.Write(b, binary.LittleEndian, arg); err != nil {
  46. return -1, err
  47. }
  48. r, _, err := syscall.Syscall6(syscall.SYS_IOCTL,
  49. uintptr(hid.f.Fd()), uintptr(n),
  50. uintptr(unsafe.Pointer(&(b.Bytes()[0]))), 0, 0, 0)
  51. return int(r), err
  52. }
  53. func (hid *usbDevice) claim() error {
  54. ifno := uint32(hid.info.Interface)
  55. if r, errno := hid.ioctl(USBDEVFS_IOCTL, &usbfsIoctl{
  56. Interface: ifno,
  57. IoctlCode: USBDEVFS_DISCONNECT,
  58. Data: 0,
  59. }); r == -1 {
  60. log.Println("driver disconnect failed:", r, errno)
  61. }
  62. if r, errno := hid.ioctl(USBDEVFS_CLAIM, &ifno); r == -1 {
  63. return errno
  64. } else {
  65. return nil
  66. }
  67. return nil
  68. }
  69. func (hid *usbDevice) release() error {
  70. ifno := uint32(hid.info.Interface)
  71. if r, errno := hid.ioctl(USBDEVFS_RELEASE, &ifno); r == -1 {
  72. return errno
  73. }
  74. if r, errno := hid.ioctl(USBDEVFS_IOCTL, &usbfsIoctl{
  75. Interface: ifno,
  76. IoctlCode: USBDEVFS_CONNECT,
  77. Data: 0,
  78. }); r == -1 {
  79. log.Println("driver connect failed:", r, errno)
  80. }
  81. return nil
  82. }
  83. func (hid *usbDevice) ctrl(rtype, req, val, index int, data []byte, t int) (int, error) {
  84. s := usbfsCtrl{
  85. ReqType: uint8(rtype),
  86. Req: uint8(req),
  87. Value: uint16(val),
  88. Index: uint16(index),
  89. Len: uint16(len(data)),
  90. Timeout: uint32(t),
  91. Data: slicePtr(data),
  92. }
  93. if r, err := hid.ioctl(USBDEVFS_CONTROL, &s); r == -1 {
  94. return -1, err
  95. } else {
  96. return r, nil
  97. }
  98. }
  99. func (hid *usbDevice) intr(ep int, data []byte, t int) (int, error) {
  100. if r, err := hid.ioctl(USBDEVFS_BULK, &usbfsBulk{
  101. Endpoint: uint32(ep),
  102. Len: uint32(len(data)),
  103. Timeout: uint32(t),
  104. Data: slicePtr(data),
  105. }); r == -1 {
  106. return -1, err
  107. } else {
  108. return r, nil
  109. }
  110. }
  111. func (hid *usbDevice) Read(timeout time.Duration) ([]byte, error) {
  112. data := make([]byte, hid.inputPacketSize, hid.inputPacketSize)
  113. ms := timeout / (1 * time.Millisecond)
  114. n, err := hid.intr(hid.epIn, data, int(ms))
  115. if err == nil {
  116. return data[:n], nil
  117. } else {
  118. return nil, err
  119. }
  120. }
  121. func (hid *usbDevice) Write(data []byte, timeout time.Duration) (int, error) {
  122. if hid.epOut > 0 {
  123. ms := timeout / (1 * time.Millisecond)
  124. return hid.intr(hid.epOut, data, int(ms))
  125. } else {
  126. return hid.ctrl(0x21, 0x09, 2<<8+0, int(hid.info.Interface), data, len(data))
  127. }
  128. }
  129. func (hid *usbDevice) HIDReport() ([]byte, error) {
  130. buf := make([]byte, 256, 256)
  131. // In transfer, recepient interface, GetDescriptor, HidReport type
  132. n, err := hid.ctrl(0x81, 0x06, 0x22<<8+int(hid.info.Interface), 0, buf, 1000)
  133. if err != nil {
  134. return nil, err
  135. } else {
  136. return buf[:n], nil
  137. }
  138. }
  139. func (hid *usbDevice) GetReport(report int) ([]byte, error) {
  140. buf := make([]byte, 256, 256)
  141. // 10100001, GET_REPORT, type*256+id, intf, len, data
  142. n, err := hid.ctrl(0xa1, 0x01, 3<<8+report, int(hid.info.Interface), buf, 1000)
  143. if err != nil {
  144. return nil, err
  145. } else {
  146. return buf[:n], nil
  147. }
  148. }
  149. func (hid *usbDevice) SetReport(report int, data []byte) error {
  150. // 00100001, SET_REPORT, type*256+id, intf, len, data
  151. _, err := hid.ctrl(0x21, 0x09, 3<<8+report, int(hid.info.Interface), data, 1000)
  152. return err
  153. }
  154. //
  155. // Enumeration
  156. //
  157. func cast(b []byte, to interface{}) error {
  158. r := bytes.NewBuffer(b)
  159. return binary.Read(r, binary.LittleEndian, to)
  160. }
  161. func walker(path string, cb func(Device)) error {
  162. if desc, err := ioutil.ReadFile(path); err != nil {
  163. return err
  164. } else {
  165. r := bytes.NewBuffer(desc)
  166. expected := map[byte]bool{
  167. UsbDescTypeDevice: true,
  168. }
  169. devDesc := deviceDesc{}
  170. var device *usbDevice
  171. for r.Len() > 0 {
  172. if length, err := r.ReadByte(); err != nil {
  173. return err
  174. } else if err := r.UnreadByte(); err != nil {
  175. return err
  176. } else {
  177. body := make([]byte, length, length)
  178. if n, err := r.Read(body); err != nil {
  179. return err
  180. } else if n != int(length) || length < 2 {
  181. return errors.New("short read")
  182. } else {
  183. if !expected[body[1]] {
  184. continue
  185. }
  186. switch body[1] {
  187. case UsbDescTypeDevice:
  188. expected[UsbDescTypeDevice] = false
  189. expected[UsbDescTypeConfig] = true
  190. if err := cast(body, &devDesc); err != nil {
  191. return err
  192. }
  193. //info := Info{
  194. //}
  195. case UsbDescTypeConfig:
  196. expected[UsbDescTypeInterface] = true
  197. expected[UsbDescTypeReport] = false
  198. expected[UsbDescTypeEndpoint] = false
  199. // Device left from the previous config
  200. if device != nil {
  201. cb(device)
  202. device = nil
  203. }
  204. case UsbDescTypeInterface:
  205. expected[UsbDescTypeEndpoint] = true
  206. expected[UsbDescTypeReport] = true
  207. i := &interfaceDesc{}
  208. if err := cast(body, i); err != nil {
  209. return err
  210. }
  211. if i.InterfaceClass == UsbHidClass {
  212. device = &usbDevice{
  213. info: Info{
  214. Vendor: devDesc.Vendor,
  215. Product: devDesc.Product,
  216. Revision: devDesc.Revision,
  217. SubClass: i.InterfaceSubClass,
  218. Protocol: i.InterfaceProtocol,
  219. Interface: i.Number,
  220. },
  221. path: path,
  222. }
  223. }
  224. case UsbDescTypeEndpoint:
  225. if device != nil {
  226. e := &endpointDesc{}
  227. if err := cast(body, e); err != nil {
  228. return err
  229. }
  230. if e.Address > 0x80 && device.epIn == 0 {
  231. device.epIn = int(e.Address)
  232. device.inputPacketSize = e.MaxPacketSize
  233. } else if e.Address < 0x80 && device.epOut == 0 {
  234. device.epOut = int(e.Address)
  235. device.outputPacketSize = e.MaxPacketSize
  236. }
  237. }
  238. }
  239. }
  240. }
  241. }
  242. if device != nil {
  243. cb(device)
  244. }
  245. }
  246. return nil
  247. }
  248. func UsbWalk(cb func(Device)) {
  249. filepath.Walk(DevBusUsb, func(f string, fi os.FileInfo, err error) error {
  250. if err != nil || fi.IsDir() {
  251. return nil
  252. }
  253. if err := walker(f, cb); err != nil {
  254. log.Println("UsbWalk: ", err)
  255. }
  256. return nil
  257. })
  258. }