USBPrinterOutputDeviceManager.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from UM.Signal import Signal, signalemitter
  4. from . import USBPrinterOutputDevice
  5. from UM.Application import Application
  6. from UM.Resources import Resources
  7. from UM.Logger import Logger
  8. from UM.PluginRegistry import PluginRegistry
  9. from UM.OutputDevice.OutputDevicePlugin import OutputDevicePlugin
  10. from cura.PrinterOutputDevice import ConnectionState
  11. from UM.Qt.ListModel import ListModel
  12. from UM.Message import Message
  13. from cura.CuraApplication import CuraApplication
  14. import threading
  15. import platform
  16. import glob
  17. import time
  18. import os.path
  19. from UM.Extension import Extension
  20. from PyQt5.QtQml import QQmlComponent, QQmlContext
  21. from PyQt5.QtCore import QUrl, QObject, pyqtSlot, pyqtProperty, pyqtSignal, Qt
  22. from UM.i18n import i18nCatalog
  23. i18n_catalog = i18nCatalog("cura")
  24. ## Manager class that ensures that a usbPrinteroutput device is created for every connected USB printer.
  25. @signalemitter
  26. class USBPrinterOutputDeviceManager(QObject, OutputDevicePlugin, Extension):
  27. def __init__(self, parent = None):
  28. super().__init__(parent = parent)
  29. self._serial_port_list = []
  30. self._usb_output_devices = {}
  31. self._usb_output_devices_model = None
  32. self._update_thread = threading.Thread(target = self._updateThread)
  33. self._update_thread.setDaemon(True)
  34. self._check_updates = True
  35. self._firmware_view = None
  36. Application.getInstance().applicationShuttingDown.connect(self.stop)
  37. self.addUSBOutputDeviceSignal.connect(self.addOutputDevice) #Because the model needs to be created in the same thread as the QMLEngine, we use a signal.
  38. addUSBOutputDeviceSignal = Signal()
  39. connectionStateChanged = pyqtSignal()
  40. progressChanged = pyqtSignal()
  41. firmwareUpdateChange = pyqtSignal()
  42. @pyqtProperty(float, notify = progressChanged)
  43. def progress(self):
  44. progress = 0
  45. for printer_name, device in self._usb_output_devices.items(): # TODO: @UnusedVariable "printer_name"
  46. progress += device.progress
  47. return progress / len(self._usb_output_devices)
  48. @pyqtProperty(int, notify = progressChanged)
  49. def errorCode(self):
  50. for printer_name, device in self._usb_output_devices.items(): # TODO: @UnusedVariable "printer_name"
  51. if device._error_code:
  52. return device._error_code
  53. return 0
  54. ## Return True if all printers finished firmware update
  55. @pyqtProperty(float, notify = firmwareUpdateChange)
  56. def firmwareUpdateCompleteStatus(self):
  57. complete = True
  58. for printer_name, device in self._usb_output_devices.items(): # TODO: @UnusedVariable "printer_name"
  59. if not device.firmwareUpdateFinished:
  60. complete = False
  61. return complete
  62. def start(self):
  63. self._check_updates = True
  64. self._update_thread.start()
  65. def stop(self):
  66. self._check_updates = False
  67. def _updateThread(self):
  68. while self._check_updates:
  69. result = self.getSerialPortList(only_list_usb = True)
  70. self._addRemovePorts(result)
  71. time.sleep(5)
  72. ## Show firmware interface.
  73. # This will create the view if its not already created.
  74. def spawnFirmwareInterface(self, serial_port):
  75. if self._firmware_view is None:
  76. path = QUrl.fromLocalFile(os.path.join(PluginRegistry.getInstance().getPluginPath("USBPrinting"), "FirmwareUpdateWindow.qml"))
  77. component = QQmlComponent(Application.getInstance()._engine, path)
  78. self._firmware_context = QQmlContext(Application.getInstance()._engine.rootContext())
  79. self._firmware_context.setContextProperty("manager", self)
  80. self._firmware_view = component.create(self._firmware_context)
  81. self._firmware_view.show()
  82. @pyqtSlot(str)
  83. def updateAllFirmware(self, file_name):
  84. if file_name.startswith("file://"):
  85. file_name = QUrl(file_name).toLocalFile() # File dialogs prepend the path with file://, which we don't need / want
  86. if not self._usb_output_devices:
  87. Message(i18n_catalog.i18nc("@info", "Unable to update firmware because there are no printers connected.")).show()
  88. return
  89. for printer_connection in self._usb_output_devices:
  90. self._usb_output_devices[printer_connection].resetFirmwareUpdate()
  91. self.spawnFirmwareInterface("")
  92. for printer_connection in self._usb_output_devices:
  93. try:
  94. self._usb_output_devices[printer_connection].updateFirmware(file_name)
  95. except FileNotFoundError:
  96. # Should only happen in dev environments where the resources/firmware folder is absent.
  97. self._usb_output_devices[printer_connection].setProgress(100, 100)
  98. Logger.log("w", "No firmware found for printer %s called '%s'", printer_connection, file_name)
  99. Message(i18n_catalog.i18nc("@info",
  100. "Could not find firmware required for the printer at %s.") % printer_connection).show()
  101. self._firmware_view.close()
  102. continue
  103. @pyqtSlot(str, str, result = bool)
  104. def updateFirmwareBySerial(self, serial_port, file_name):
  105. if serial_port in self._usb_output_devices:
  106. self.spawnFirmwareInterface(self._usb_output_devices[serial_port].getSerialPort())
  107. try:
  108. self._usb_output_devices[serial_port].updateFirmware(file_name)
  109. except FileNotFoundError:
  110. self._firmware_view.close()
  111. Logger.log("e", "Could not find firmware required for this machine called '%s'", file_name)
  112. return False
  113. return True
  114. return False
  115. ## Return the singleton instance of the USBPrinterManager
  116. @classmethod
  117. def getInstance(cls, engine = None, script_engine = None):
  118. # Note: Explicit use of class name to prevent issues with inheritance.
  119. if USBPrinterOutputDeviceManager._instance is None:
  120. USBPrinterOutputDeviceManager._instance = cls()
  121. return USBPrinterOutputDeviceManager._instance
  122. @pyqtSlot(result = str)
  123. def getDefaultFirmwareName(self):
  124. # Check if there is a valid global container stack
  125. global_container_stack = Application.getInstance().getGlobalContainerStack()
  126. if not global_container_stack:
  127. Logger.log("e", "There is no global container stack. Can not update firmware.")
  128. self._firmware_view.close()
  129. return ""
  130. # The bottom of the containerstack is the machine definition
  131. machine_id = global_container_stack.getBottom().id
  132. machine_has_heated_bed = global_container_stack.getProperty("machine_heated_bed", "value")
  133. if platform.system() == "Linux":
  134. baudrate = 115200
  135. else:
  136. baudrate = 250000
  137. # NOTE: The keyword used here is the id of the machine. You can find the id of your machine in the *.json file, eg.
  138. # https://github.com/Ultimaker/Cura/blob/master/resources/machines/ultimaker_original.json#L2
  139. # The *.hex files are stored at a seperate repository:
  140. # https://github.com/Ultimaker/cura-binary-data/tree/master/cura/resources/firmware
  141. machine_without_extras = {"bq_witbox" : "MarlinWitbox.hex",
  142. "bq_hephestos_2" : "MarlinHephestos2.hex",
  143. "ultimaker_original" : "MarlinUltimaker-{baudrate}.hex",
  144. "ultimaker_original_plus" : "MarlinUltimaker-UMOP-{baudrate}.hex",
  145. "ultimaker_original_dual" : "MarlinUltimaker-{baudrate}-dual.hex",
  146. "ultimaker2" : "MarlinUltimaker2.hex",
  147. "ultimaker2_go" : "MarlinUltimaker2go.hex",
  148. "ultimaker2_plus" : "MarlinUltimaker2plus.hex",
  149. "ultimaker2_extended" : "MarlinUltimaker2extended.hex",
  150. "ultimaker2_extended_plus" : "MarlinUltimaker2extended-plus.hex",
  151. }
  152. machine_with_heated_bed = {"ultimaker_original" : "MarlinUltimaker-HBK-{baudrate}.hex",
  153. "ultimaker_original_dual" : "MarlinUltimaker-HBK-{baudrate}-dual.hex",
  154. }
  155. ##TODO: Add check for multiple extruders
  156. hex_file = None
  157. if machine_id in machine_without_extras.keys(): # The machine needs to be defined here!
  158. if machine_id in machine_with_heated_bed.keys() and machine_has_heated_bed:
  159. Logger.log("d", "Choosing firmware with heated bed enabled for machine %s.", machine_id)
  160. hex_file = machine_with_heated_bed[machine_id] # Return firmware with heated bed enabled
  161. else:
  162. Logger.log("d", "Choosing basic firmware for machine %s.", machine_id)
  163. hex_file = machine_without_extras[machine_id] # Return "basic" firmware
  164. else:
  165. Logger.log("w", "There is no firmware for machine %s.", machine_id)
  166. if hex_file:
  167. return Resources.getPath(CuraApplication.ResourceTypes.Firmware, hex_file.format(baudrate=baudrate))
  168. else:
  169. Logger.log("w", "Could not find any firmware for machine %s.", machine_id)
  170. return ""
  171. ## Helper to identify serial ports (and scan for them)
  172. def _addRemovePorts(self, serial_ports):
  173. # First, find and add all new or changed keys
  174. for serial_port in list(serial_ports):
  175. if serial_port not in self._serial_port_list:
  176. self.addUSBOutputDeviceSignal.emit(serial_port) # Hack to ensure its created in main thread
  177. continue
  178. self._serial_port_list = list(serial_ports)
  179. devices_to_remove = []
  180. for port, device in self._usb_output_devices.items():
  181. if port not in self._serial_port_list:
  182. device.close()
  183. devices_to_remove.append(port)
  184. for port in devices_to_remove:
  185. del self._usb_output_devices[port]
  186. ## Because the model needs to be created in the same thread as the QMLEngine, we use a signal.
  187. def addOutputDevice(self, serial_port):
  188. device = USBPrinterOutputDevice.USBPrinterOutputDevice(serial_port)
  189. device.connectionStateChanged.connect(self._onConnectionStateChanged)
  190. device.connect()
  191. device.progressChanged.connect(self.progressChanged)
  192. device.firmwareUpdateChange.connect(self.firmwareUpdateChange)
  193. self._usb_output_devices[serial_port] = device
  194. ## If one of the states of the connected devices change, we might need to add / remove them from the global list.
  195. def _onConnectionStateChanged(self, serial_port):
  196. try:
  197. if self._usb_output_devices[serial_port].connectionState == ConnectionState.connected:
  198. self.getOutputDeviceManager().addOutputDevice(self._usb_output_devices[serial_port])
  199. else:
  200. self.getOutputDeviceManager().removeOutputDevice(serial_port)
  201. self.connectionStateChanged.emit()
  202. except KeyError:
  203. Logger.log("w", "Connection state of %s changed, but it was not found in the list")
  204. @pyqtProperty(QObject , notify = connectionStateChanged)
  205. def connectedPrinterList(self):
  206. self._usb_output_devices_model = ListModel()
  207. self._usb_output_devices_model.addRoleName(Qt.UserRole + 1, "name")
  208. self._usb_output_devices_model.addRoleName(Qt.UserRole + 2, "printer")
  209. for connection in self._usb_output_devices:
  210. if self._usb_output_devices[connection].connectionState == ConnectionState.connected:
  211. self._usb_output_devices_model.appendItem({"name": connection, "printer": self._usb_output_devices[connection]})
  212. return self._usb_output_devices_model
  213. ## Create a list of serial ports on the system.
  214. # \param only_list_usb If true, only usb ports are listed
  215. def getSerialPortList(self, only_list_usb = False):
  216. base_list = []
  217. if platform.system() == "Windows":
  218. import winreg # type: ignore @UnresolvedImport
  219. try:
  220. key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM")
  221. i = 0
  222. while True:
  223. values = winreg.EnumValue(key, i)
  224. if not only_list_usb or "USBSER" in values[0]:
  225. base_list += [values[1]]
  226. i += 1
  227. except Exception as e:
  228. pass
  229. else:
  230. if only_list_usb:
  231. base_list = base_list + glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") + glob.glob("/dev/cu.usb*") + glob.glob("/dev/tty.wchusb*") + glob.glob("/dev/cu.wchusb*")
  232. base_list = filter(lambda s: "Bluetooth" not in s, base_list) # Filter because mac sometimes puts them in the list
  233. else:
  234. base_list = base_list + glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") + glob.glob("/dev/cu.*") + glob.glob("/dev/tty.usb*") + glob.glob("/dev/tty.wchusb*") + glob.glob("/dev/cu.wchusb*") + glob.glob("/dev/rfcomm*") + glob.glob("/dev/serial/by-id/*")
  235. return list(base_list)
  236. _instance = None # type: "USBPrinterOutputDeviceManager"