usb_linux.go 6.7 KB

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