USBPrinterOutputDeviceManager.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. # Copyright (c) 2015 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. from cura.MachineManagerModel import MachineManagerModel
  15. import threading
  16. import platform
  17. import glob
  18. import time
  19. import os.path
  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. class USBPrinterOutputDeviceManager(QObject, SignalEmitter, 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. ## Add menu item to top menu of the application.
  37. self.setMenuName(i18n_catalog.i18nc("@title:menu","Firmware"))
  38. self.addMenuItem(i18n_catalog.i18nc("@item:inmenu", "Update Firmware"), self.updateAllFirmware)
  39. Application.getInstance().applicationShuttingDown.connect(self.stop)
  40. self.addUSBOutputDeviceSignal.connect(self.addOutputDevice) #Because the model needs to be created in the same thread as the QMLEngine, we use a signal.
  41. addUSBOutputDeviceSignal = Signal()
  42. connectionStateChanged = pyqtSignal()
  43. progressChanged = pyqtSignal()
  44. @pyqtProperty(float, notify = progressChanged)
  45. def progress(self):
  46. progress = 0
  47. for printer_name, device in self._usb_output_devices.items(): # TODO: @UnusedVariable "printer_name"
  48. progress += device.progress
  49. return progress / len(self._usb_output_devices)
  50. def start(self):
  51. self._check_updates = True
  52. self._update_thread.start()
  53. def stop(self):
  54. self._check_updates = False
  55. try:
  56. self._update_thread.join()
  57. except RuntimeError:
  58. pass
  59. def _updateThread(self):
  60. while self._check_updates:
  61. result = self.getSerialPortList(only_list_usb = True)
  62. self._addRemovePorts(result)
  63. time.sleep(5)
  64. ## Show firmware interface.
  65. # This will create the view if its not already created.
  66. def spawnFirmwareInterface(self, serial_port):
  67. if self._firmware_view is None:
  68. path = QUrl.fromLocalFile(os.path.join(PluginRegistry.getInstance().getPluginPath("USBPrinting"), "FirmwareUpdateWindow.qml"))
  69. component = QQmlComponent(Application.getInstance()._engine, path)
  70. self._firmware_context = QQmlContext(Application.getInstance()._engine.rootContext())
  71. self._firmware_context.setContextProperty("manager", self)
  72. self._firmware_view = component.create(self._firmware_context)
  73. self._firmware_view.show()
  74. @pyqtSlot()
  75. def updateAllFirmware(self):
  76. if not self._usb_output_devices:
  77. Message(i18n_catalog.i18nc("@info","Cannot update firmware, there were no connected printers found.")).show()
  78. return
  79. self.spawnFirmwareInterface("")
  80. for printer_connection in self._usb_output_devices:
  81. try:
  82. self._usb_output_devices[printer_connection].updateFirmware(Resources.getPath(CuraApplication.ResourceTypes.Firmware, self._getDefaultFirmwareName()))
  83. except FileNotFoundError:
  84. self._usb_output_devices[printer_connection].setProgress(100, 100)
  85. Logger.log("w", "No firmware found for printer %s", printer_connection)
  86. continue
  87. @pyqtSlot(str, result = bool)
  88. def updateFirmwareBySerial(self, serial_port):
  89. if serial_port in self._usb_output_devices:
  90. self.spawnFirmwareInterface(self._usb_output_devices[serial_port].getSerialPort())
  91. try:
  92. self._usb_output_devices[serial_port].updateFirmware(Resources.getPath(CuraApplication.ResourceTypes.Firmware, self._getDefaultFirmwareName()))
  93. except FileNotFoundError:
  94. self._firmware_view.close()
  95. Logger.log("e", "Could not find firmware required for this machine")
  96. return False
  97. return True
  98. return False
  99. ## Return the singleton instance of the USBPrinterManager
  100. @classmethod
  101. def getInstance(cls, engine = None, script_engine = None):
  102. # Note: Explicit use of class name to prevent issues with inheritance.
  103. if USBPrinterOutputDeviceManager._instance is None:
  104. USBPrinterOutputDeviceManager._instance = cls()
  105. return USBPrinterOutputDeviceManager._instance
  106. def _getDefaultFirmwareName(self):
  107. machine_manager_model = MachineManagerModel()
  108. machine_id = machine_manager_model.activeDefinitionId
  109. if platform.system() == "Linux":
  110. baudrate = 115200
  111. else:
  112. baudrate = 250000
  113. # NOTE: The keyword used here is the id of the machine. You can find the id of your machine in the *.json file, eg.
  114. # https://github.com/Ultimaker/Cura/blob/master/resources/machines/ultimaker_original.json#L2
  115. # The *.hex files are stored at a seperate repository:
  116. # https://github.com/Ultimaker/cura-binary-data/tree/master/cura/resources/firmware
  117. machine_without_extras = {"bq_witbox" : "MarlinWitbox.hex",
  118. "bq_hephestos_2" : "MarlinHephestos2.hex",
  119. "ultimaker_original" : "MarlinUltimaker-{baudrate}.hex",
  120. "ultimaker_original_plus" : "MarlinUltimaker-UMOP-{baudrate}.hex",
  121. "ultimaker2" : "MarlinUltimaker2.hex",
  122. "ultimaker2_go" : "MarlinUltimaker2go.hex",
  123. "ultimaker2plus" : "MarlinUltimaker2plus.hex",
  124. "ultimaker2_extended" : "MarlinUltimaker2extended.hex",
  125. "ultimaker2_extended_plus" : "MarlinUltimaker2extended-plus.hex",
  126. }
  127. machine_with_heated_bed = {"ultimaker_original" : "MarlinUltimaker-HBK-{baudrate}.hex",
  128. }
  129. ##TODO: Add check for multiple extruders
  130. hex_file = None
  131. if machine_id in machine_without_extras.keys(): # The machine needs to be defined here!
  132. if machine_id in machine_with_heated_bed.keys() and machine_manager_model.hasHeatedBed:
  133. Logger.log("d", "Choosing firmware with heated bed enabled for machine %s.", machine_type)
  134. hex_file = machine_with_heated_bed[machine_id] # Return firmware with heated bed enabled
  135. else:
  136. Logger.log("d", "Choosing basic firmware for machine %s.", machine_id)
  137. hex_file = machine_without_extras[machine_id] # Return "basic" firmware
  138. else:
  139. Logger.log("e", "There is no firmware for machine %s.", machine_id)
  140. if hex_file:
  141. return hex_file.format(baudrate=baudrate)
  142. else:
  143. Logger.log("e", "Could not find any firmware for machine %s.", machine_id)
  144. raise FileNotFoundError()
  145. ## Helper to identify serial ports (and scan for them)
  146. def _addRemovePorts(self, serial_ports):
  147. # First, find and add all new or changed keys
  148. for serial_port in list(serial_ports):
  149. if serial_port not in self._serial_port_list:
  150. self.addUSBOutputDeviceSignal.emit(serial_port) # Hack to ensure its created in main thread
  151. continue
  152. self._serial_port_list = list(serial_ports)
  153. devices_to_remove = []
  154. for port, device in self._usb_output_devices.items():
  155. if port not in self._serial_port_list:
  156. device.close()
  157. devices_to_remove.append(port)
  158. for port in devices_to_remove:
  159. del self._usb_output_devices[port]
  160. ## Because the model needs to be created in the same thread as the QMLEngine, we use a signal.
  161. def addOutputDevice(self, serial_port):
  162. device = USBPrinterOutputDevice.USBPrinterOutputDevice(serial_port)
  163. device.connectionStateChanged.connect(self._onConnectionStateChanged)
  164. device.connect()
  165. device.progressChanged.connect(self.progressChanged)
  166. self._usb_output_devices[serial_port] = device
  167. ## If one of the states of the connected devices change, we might need to add / remove them from the global list.
  168. def _onConnectionStateChanged(self, serial_port):
  169. try:
  170. if self._usb_output_devices[serial_port].connectionState == ConnectionState.connected:
  171. self.getOutputDeviceManager().addOutputDevice(self._usb_output_devices[serial_port])
  172. else:
  173. self.getOutputDeviceManager().removeOutputDevice(serial_port)
  174. self.connectionStateChanged.emit()
  175. except KeyError:
  176. pass # no output device by this device_id found in connection list.
  177. @pyqtProperty(QObject , notify = connectionStateChanged)
  178. def connectedPrinterList(self):
  179. self._usb_output_devices_model = ListModel()
  180. self._usb_output_devices_model.addRoleName(Qt.UserRole + 1, "name")
  181. self._usb_output_devices_model.addRoleName(Qt.UserRole + 2, "printer")
  182. for connection in self._usb_output_devices:
  183. if self._usb_output_devices[connection].connectionState == ConnectionState.connected:
  184. self._usb_output_devices_model.appendItem({"name": connection, "printer": self._usb_output_devices[connection]})
  185. return self._usb_output_devices_model
  186. ## Create a list of serial ports on the system.
  187. # \param only_list_usb If true, only usb ports are listed
  188. def getSerialPortList(self, only_list_usb = False):
  189. base_list = []
  190. if platform.system() == "Windows":
  191. import winreg
  192. try:
  193. key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM")
  194. i = 0
  195. while True:
  196. values = winreg.EnumValue(key, i)
  197. if not only_list_usb or "USBSER" in values[0]:
  198. base_list += [values[1]]
  199. i += 1
  200. except Exception as e:
  201. pass
  202. else:
  203. if only_list_usb:
  204. base_list = base_list + glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") + glob.glob("/dev/cu.usb*")
  205. base_list = filter(lambda s: "Bluetooth" not in s, base_list) # Filter because mac sometimes puts them in the list
  206. else:
  207. base_list = base_list + glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") + glob.glob("/dev/cu.*") + glob.glob("/dev/tty.usb*") + glob.glob("/dev/rfcomm*") + glob.glob("/dev/serial/by-id/*")
  208. return list(base_list)
  209. _instance = None