usb_linux.go 6.5 KB

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