hardware_access_usb.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. """
  2. # TOP2049 Open Source programming suite
  3. #
  4. # Lowlevel USB hardware access.
  5. #
  6. # Copyright (c) 2012 Michael Buesch <m@bues.ch>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. """
  22. from .util import *
  23. from .command_queue import *
  24. try:
  25. import usb.core
  26. import usb.util
  27. except (ImportError) as e:
  28. print("Python USB (PyUSB) support module not found.\n"
  29. "Please install python-usb.")
  30. sys.exit(1)
  31. class FoundUSBDev(object):
  32. def __init__(self, usbdev):
  33. self.usbdev = usbdev
  34. class HardwareAccessUSB(CommandQueue):
  35. "Lowlevel USB hardware access"
  36. TIMEOUT_MSEC = 2000
  37. @classmethod
  38. def scan(cls, checkCallback):
  39. "Scan for devices. Returns a list of FoundUSBDev()."
  40. devices = list(usb.core.find(find_all = True,
  41. custom_match = checkCallback))
  42. devices = [ FoundUSBDev(dev) for dev in devices ]
  43. return devices
  44. def __init__(self, usbdev, maxPacketBytes, noQueue,
  45. doRawDump=False):
  46. CommandQueue.__init__(self,
  47. maxPacketBytes = maxPacketBytes,
  48. synchronous = noQueue)
  49. self.doRawDump = doRawDump
  50. self.usbdev = usbdev
  51. self.__initUSB()
  52. def __initUSB(self):
  53. try:
  54. config = self.usbdev.configurations()[0]
  55. interface = config.interfaces()[0]
  56. # Find the endpoints
  57. self.bulkOut = None
  58. self.bulkIn = None
  59. for ep in interface.endpoints():
  60. if not self.bulkIn and \
  61. usb.util.endpoint_type(ep.bmAttributes) == usb.util.ENDPOINT_TYPE_BULK and \
  62. usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_IN:
  63. self.bulkIn = ep
  64. if not self.bulkOut and \
  65. usb.util.endpoint_type(ep.bmAttributes) == usb.util.ENDPOINT_TYPE_BULK and \
  66. usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_OUT:
  67. self.bulkOut = ep
  68. if not self.bulkIn or not self.bulkOut:
  69. raise TOPException("Did not find all USB EPs")
  70. self.usbdev.set_configuration(config)
  71. self.bulkIn.clear_halt()
  72. self.bulkOut.clear_halt()
  73. except (usb.core.USBError) as e:
  74. raise TOPException("USB error: " + str(e))
  75. def shutdown(self):
  76. "Shutdown the USB connection"
  77. try:
  78. usb.util.dispose_resources(self.usbdev)
  79. except (usb.core.USBError) as e:
  80. raise TOPException("USB error: " + str(e))
  81. def send(self, data):
  82. try:
  83. assert(len(data) <= self.maxPacketBytes)
  84. if self.doRawDump:
  85. print("Sending command:")
  86. dumpMem(data)
  87. nrWritten = self.usbdev.write(
  88. self.bulkOut.bEndpointAddress,
  89. data,
  90. self.TIMEOUT_MSEC)
  91. if nrWritten != len(data):
  92. raise TOPException("USB bulk write error: "
  93. "short write")
  94. except (usb.core.USBError) as e:
  95. raise TOPException("USB bulk write error: " + str(e))
  96. def receive(self, size):
  97. """Receive 'size' bytes on the bulk-in ep."""
  98. # If there are blocked commands in the queue, send them now.
  99. self.flushCommands()
  100. try:
  101. ep = self.bulkIn.bEndpointAddress
  102. data = b"".join([ int2byte(b) for b in
  103. self.usbdev.read(ep, size,
  104. self.TIMEOUT_MSEC) ])
  105. if len(data) != size:
  106. raise TOPException("USB bulk read error: Could not read the " +\
  107. "requested number of bytes (req %d, got %d)" % (size, len(data)))
  108. if self.doRawDump:
  109. print("Received data:")
  110. dumpMem(data)
  111. except (usb.core.USBError) as e:
  112. raise TOPException("USB bulk read error: " + str(e))
  113. return data