hardware_access_usb.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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 python3-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. # Find the endpoints
  55. self.bulkOut = None
  56. self.bulkIn = None
  57. selectedConfig = None
  58. selectedInterface = None
  59. for config in self.usbdev.configurations():
  60. for interface in config.interfaces():
  61. for ep in interface.endpoints():
  62. if self.bulkIn is None and \
  63. usb.util.endpoint_type(ep.bmAttributes) == usb.util.ENDPOINT_TYPE_BULK and \
  64. usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_IN:
  65. self.bulkIn = ep
  66. selectedConfig = config
  67. selectedInterface = interface
  68. if self.bulkOut is None and \
  69. usb.util.endpoint_type(ep.bmAttributes) == usb.util.ENDPOINT_TYPE_BULK and \
  70. usb.util.endpoint_direction(ep.bEndpointAddress) == usb.util.ENDPOINT_OUT:
  71. self.bulkOut = ep
  72. selectedConfig = config
  73. selectedInterface = interface
  74. if selectedInterface is not None:
  75. break
  76. if selectedConfig is not None:
  77. break
  78. if self.bulkIn is None or self.bulkOut is None or \
  79. selectedConfig is None or selectedInterface is None:
  80. raise TOPException("Did not find all USB EPs")
  81. bInterfaceNumber = selectedInterface.bInterfaceNumber
  82. # If some kernel driver attached to our device, detach it.
  83. if self.usbdev.is_kernel_driver_active(bInterfaceNumber):
  84. try:
  85. self.usbdev.detach_kernel_driver(bInterfaceNumber)
  86. except usb.core.USBError as e:
  87. raise TOPException("USB error: "
  88. "Failed to detach kernel driver: " + str(e))
  89. self.usbdev.set_configuration(selectedConfig)
  90. self.bulkIn.clear_halt()
  91. self.bulkOut.clear_halt()
  92. except usb.core.USBError as e:
  93. raise TOPException("USB error: " + str(e))
  94. def shutdown(self):
  95. "Shutdown the USB connection"
  96. try:
  97. usb.util.dispose_resources(self.usbdev)
  98. except (usb.core.USBError) as e:
  99. raise TOPException("USB error: " + str(e))
  100. def send(self, data):
  101. try:
  102. assert(len(data) <= self.maxPacketBytes)
  103. if self.doRawDump:
  104. print("Sending command:")
  105. dumpMem(data)
  106. nrWritten = self.usbdev.write(
  107. self.bulkOut.bEndpointAddress,
  108. data,
  109. self.TIMEOUT_MSEC)
  110. if nrWritten != len(data):
  111. raise TOPException("USB bulk write error: "
  112. "short write")
  113. except (usb.core.USBError) as e:
  114. raise TOPException("USB bulk write error: " + str(e))
  115. def receive(self, size):
  116. """Receive 'size' bytes on the bulk-in ep."""
  117. # If there are blocked commands in the queue, send them now.
  118. self.flushCommands()
  119. try:
  120. ep = self.bulkIn.bEndpointAddress
  121. data = b"".join([ int2byte(b) for b in
  122. self.usbdev.read(ep, size,
  123. self.TIMEOUT_MSEC) ])
  124. if len(data) != size:
  125. raise TOPException("USB bulk read error: Could not read the " +\
  126. "requested number of bytes (req %d, got %d)" % (size, len(data)))
  127. if self.doRawDump:
  128. print("Received data:")
  129. dumpMem(data)
  130. except (usb.core.USBError) as e:
  131. raise TOPException("USB bulk read error: " + str(e))
  132. return data