USBPrinterOutputDeviceManager.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. addUSBOutputDeviceSignal = Signal()
  27. progressChanged = pyqtSignal()
  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. def start(self):
  40. self._check_updates = True
  41. self._update_thread.start()
  42. def stop(self):
  43. self._check_updates = False
  44. def _onConnectionStateChanged(self, serial_port):
  45. if serial_port not in self._usb_output_devices:
  46. return
  47. changed_device = self._usb_output_devices[serial_port]
  48. if changed_device.connectionState == ConnectionState.connected:
  49. self.getOutputDeviceManager().addOutputDevice(changed_device)
  50. else:
  51. self.getOutputDeviceManager().removeOutputDevice(serial_port)
  52. def _updateThread(self):
  53. while self._check_updates:
  54. container_stack = Application.getInstance().getGlobalContainerStack()
  55. if container_stack is None:
  56. time.sleep(5)
  57. continue
  58. if container_stack.getMetaDataEntry("supports_usb_connection"):
  59. port_list = self.getSerialPortList(only_list_usb=True)
  60. else:
  61. port_list = [] # Just use an empty list; all USB devices will be removed.
  62. self._addRemovePorts(port_list)
  63. time.sleep(5)
  64. ## Return the singleton instance of the USBPrinterManager
  65. @classmethod
  66. def getInstance(cls, engine = None, script_engine = None):
  67. # Note: Explicit use of class name to prevent issues with inheritance.
  68. if USBPrinterOutputDeviceManager._instance is None:
  69. USBPrinterOutputDeviceManager._instance = cls()
  70. return USBPrinterOutputDeviceManager._instance
  71. @pyqtSlot(result = str)
  72. def getDefaultFirmwareName(self):
  73. # Check if there is a valid global container stack
  74. global_container_stack = Application.getInstance().getGlobalContainerStack()
  75. if not global_container_stack:
  76. Logger.log("e", "There is no global container stack. Can not update firmware.")
  77. self._firmware_view.close()
  78. return ""
  79. # The bottom of the containerstack is the machine definition
  80. machine_id = global_container_stack.getBottom().id
  81. machine_has_heated_bed = global_container_stack.getProperty("machine_heated_bed", "value")
  82. if platform.system() == "Linux":
  83. baudrate = 115200
  84. else:
  85. baudrate = 250000
  86. # NOTE: The keyword used here is the id of the machine. You can find the id of your machine in the *.json file, eg.
  87. # https://github.com/Ultimaker/Cura/blob/master/resources/machines/ultimaker_original.json#L2
  88. # The *.hex files are stored at a seperate repository:
  89. # https://github.com/Ultimaker/cura-binary-data/tree/master/cura/resources/firmware
  90. machine_without_extras = {"bq_witbox" : "MarlinWitbox.hex",
  91. "bq_hephestos_2" : "MarlinHephestos2.hex",
  92. "ultimaker_original" : "MarlinUltimaker-{baudrate}.hex",
  93. "ultimaker_original_plus" : "MarlinUltimaker-UMOP-{baudrate}.hex",
  94. "ultimaker_original_dual" : "MarlinUltimaker-{baudrate}-dual.hex",
  95. "ultimaker2" : "MarlinUltimaker2.hex",
  96. "ultimaker2_go" : "MarlinUltimaker2go.hex",
  97. "ultimaker2_plus" : "MarlinUltimaker2plus.hex",
  98. "ultimaker2_extended" : "MarlinUltimaker2extended.hex",
  99. "ultimaker2_extended_plus" : "MarlinUltimaker2extended-plus.hex",
  100. }
  101. machine_with_heated_bed = {"ultimaker_original" : "MarlinUltimaker-HBK-{baudrate}.hex",
  102. "ultimaker_original_dual" : "MarlinUltimaker-HBK-{baudrate}-dual.hex",
  103. }
  104. ##TODO: Add check for multiple extruders
  105. hex_file = None
  106. if machine_id in machine_without_extras.keys(): # The machine needs to be defined here!
  107. if machine_id in machine_with_heated_bed.keys() and machine_has_heated_bed:
  108. Logger.log("d", "Choosing firmware with heated bed enabled for machine %s.", machine_id)
  109. hex_file = machine_with_heated_bed[machine_id] # Return firmware with heated bed enabled
  110. else:
  111. Logger.log("d", "Choosing basic firmware for machine %s.", machine_id)
  112. hex_file = machine_without_extras[machine_id] # Return "basic" firmware
  113. else:
  114. Logger.log("w", "There is no firmware for machine %s.", machine_id)
  115. if hex_file:
  116. return Resources.getPath(CuraApplication.ResourceTypes.Firmware, hex_file.format(baudrate=baudrate))
  117. else:
  118. Logger.log("w", "Could not find any firmware for machine %s.", machine_id)
  119. return ""
  120. ## Helper to identify serial ports (and scan for them)
  121. def _addRemovePorts(self, serial_ports):
  122. # First, find and add all new or changed keys
  123. for serial_port in list(serial_ports):
  124. if serial_port not in self._serial_port_list:
  125. self.addUSBOutputDeviceSignal.emit(serial_port) # Hack to ensure its created in main thread
  126. continue
  127. self._serial_port_list = list(serial_ports)
  128. for port, device in self._usb_output_devices.items():
  129. if port not in self._serial_port_list:
  130. device.close()
  131. ## Because the model needs to be created in the same thread as the QMLEngine, we use a signal.
  132. def addOutputDevice(self, serial_port):
  133. device = USBPrinterOutputDevice.USBPrinterOutputDevice(serial_port)
  134. device.connectionStateChanged.connect(self._onConnectionStateChanged)
  135. self._usb_output_devices[serial_port] = device
  136. device.connect()
  137. ## Create a list of serial ports on the system.
  138. # \param only_list_usb If true, only usb ports are listed
  139. def getSerialPortList(self, only_list_usb = False):
  140. base_list = []
  141. for port in serial.tools.list_ports.comports():
  142. if not isinstance(port, tuple):
  143. port = (port.device, port.description, port.hwid)
  144. if only_list_usb and not port[2].startswith("USB"):
  145. continue
  146. base_list += [port[0]]
  147. return list(base_list)
  148. _instance = None # type: "USBPrinterOutputDeviceManager"