usb_linux.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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(0xa1, 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. log.Println(n, err)
  132. if err != nil {
  133. return nil, err
  134. } else {
  135. return buf[:n], nil
  136. }
  137. }
  138. func (hid *usbDevice) GetReport(report int) ([]byte, error) {
  139. buf := make([]byte, 256, 256)
  140. // 10100001, GET_REPORT, type*256+id, intf, len, data
  141. n, err := hid.ctrl(0xa1, 0x01, 3<<8+report, int(hid.info.Interface), buf, 1000)
  142. if err != nil {
  143. return nil, err
  144. } else {
  145. return buf[:n], nil
  146. }
  147. }
  148. func (hid *usbDevice) SetReport(report int, data []byte) error {
  149. // 00100001, SET_REPORT, type*256+id, intf, len, data
  150. _, err := hid.ctrl(0xa1, 0x09, 3<<8+report, int(hid.info.Interface), data, 1000)
  151. return err
  152. }
  153. //
  154. // Enumeration
  155. //
  156. func cast(b []byte, to interface{}) error {
  157. r := bytes.NewBuffer(b)
  158. return binary.Read(r, binary.LittleEndian, to)
  159. }
  160. func walker(path string, cb func(Device)) error {
  161. if desc, err := ioutil.ReadFile(path); err != nil {
  162. return err
  163. } else {
  164. r := bytes.NewBuffer(desc)
  165. expected := map[byte]bool{
  166. UsbDescTypeDevice: true,
  167. }
  168. devDesc := deviceDesc{}
  169. var device *usbDevice
  170. for r.Len() > 0 {
  171. if length, err := r.ReadByte(); err != nil {
  172. return err
  173. } else if err := r.UnreadByte(); err != nil {
  174. return err
  175. } else {
  176. body := make([]byte, length, length)
  177. if n, err := r.Read(body); err != nil {
  178. return err
  179. } else if n != int(length) || length < 2 {
  180. return errors.New("short read")
  181. } else {
  182. if !expected[body[1]] {
  183. continue
  184. }
  185. switch body[1] {
  186. case UsbDescTypeDevice:
  187. expected[UsbDescTypeDevice] = false
  188. expected[UsbDescTypeConfig] = true
  189. if err := cast(body, &devDesc); err != nil {
  190. return err
  191. }
  192. //info := Info{
  193. //}
  194. case UsbDescTypeConfig:
  195. expected[UsbDescTypeInterface] = true
  196. expected[UsbDescTypeReport] = false
  197. expected[UsbDescTypeEndpoint] = false
  198. // Device left from the previous config
  199. if device != nil {
  200. cb(device)
  201. device = nil
  202. }
  203. case UsbDescTypeInterface:
  204. expected[UsbDescTypeEndpoint] = true
  205. expected[UsbDescTypeReport] = true
  206. i := &interfaceDesc{}
  207. if err := cast(body, i); err != nil {
  208. return err
  209. }
  210. if i.InterfaceClass == UsbHidClass {
  211. device = &usbDevice{
  212. info: Info{
  213. Vendor: devDesc.Vendor,
  214. Product: devDesc.Product,
  215. Revision: devDesc.Revision,
  216. SubClass: i.InterfaceSubClass,
  217. Protocol: i.InterfaceProtocol,
  218. Interface: i.Number,
  219. },
  220. path: path,
  221. }
  222. }
  223. case UsbDescTypeEndpoint:
  224. if device != nil {
  225. e := &endpointDesc{}
  226. if err := cast(body, e); err != nil {
  227. return err
  228. }
  229. if e.Address > 0x80 && device.epIn == 0 {
  230. device.epIn = int(e.Address)
  231. } else if e.Address < 0x80 && device.epOut == 0 {
  232. device.epOut = int(e.Address)
  233. }
  234. }
  235. }
  236. }
  237. }
  238. }
  239. if device != nil {
  240. cb(device)
  241. }
  242. }
  243. return nil
  244. }
  245. func UsbWalk(cb func(Device)) {
  246. filepath.Walk(DevBusUsb, func(f string, fi os.FileInfo, _ error) error {
  247. if fi.IsDir() {
  248. return nil
  249. }
  250. if err := walker(f, cb); err != nil {
  251. log.Println("UsbWalk: ", err)
  252. }
  253. return nil
  254. })
  255. }