USBPrinterOutputDeviceManager.py 12 KB

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