usb_linux.go 6.7 KB

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