USBPrinterOutputDeviceManager.py 13 KB

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