USBPrinterOutputDeviceManager.py 12 KB

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