usb_linux.go 6.2 KB

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