usb_linux.go 6.6 KB

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