USBPrinterOutputDeviceManager.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # Copyright (c) 2020 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import threading
  4. import time
  5. from typing import Optional
  6. import serial.tools.list_ports
  7. from os import environ
  8. from re import search
  9. from PyQt5.QtCore import QObject, pyqtSignal
  10. from UM.Signal import Signal, signalemitter
  11. from UM.OutputDevice.OutputDevicePlugin import OutputDevicePlugin
  12. from UM.i18n import i18nCatalog
  13. from cura.PrinterOutput.PrinterOutputDevice import ConnectionState
  14. from . import USBPrinterOutputDevice
  15. i18n_catalog = i18nCatalog("cura")
  16. @signalemitter
  17. class USBPrinterOutputDeviceManager(QObject, OutputDevicePlugin):
  18. """Manager class that ensures that an USBPrinterOutput device is created for every connected USB printer."""
  19. addUSBOutputDeviceSignal = Signal()
  20. progressChanged = pyqtSignal()
  21. def __init__(self, application):
  22. if USBPrinterOutputDeviceManager.__instance is not None:
  23. raise RuntimeError("Try to create singleton '%s' more than once" % self.__class__.__name__)
  24. USBPrinterOutputDeviceManager.__instance = self
  25. super(USBPrinterOutputDeviceManager, self).__init__(parent = application)
  26. self._application = application
  27. self._serial_port_list = []
  28. self._usb_output_devices = {}
  29. self._usb_output_devices_model = None
  30. self._update_thread = threading.Thread(target = self._updateThread)
  31. self._update_thread.setDaemon(True)
  32. self._check_updates = True
  33. self._application.applicationShuttingDown.connect(self.stop)
  34. # Because the model needs to be created in the same thread as the QMLEngine, we use a signal.
  35. self.addUSBOutputDeviceSignal.connect(self.addOutputDevice)
  36. self._application.globalContainerStackChanged.connect(self.updateUSBPrinterOutputDevices)
  37. # The method updates/reset the USB settings for all connected USB devices
  38. def updateUSBPrinterOutputDevices(self):
  39. for device in self._usb_output_devices.values():
  40. if isinstance(device, USBPrinterOutputDevice.USBPrinterOutputDevice):
  41. device.resetDeviceSettings()
  42. def start(self):
  43. self._check_updates = True
  44. self._update_thread.start()
  45. def stop(self, store_data: bool = True):
  46. self._check_updates = False
  47. def _onConnectionStateChanged(self, serial_port):
  48. if serial_port not in self._usb_output_devices:
  49. return
  50. changed_device = self._usb_output_devices[serial_port]
  51. if changed_device.connectionState == ConnectionState.Connected:
  52. self.getOutputDeviceManager().addOutputDevice(changed_device)
  53. else:
  54. self.getOutputDeviceManager().removeOutputDevice(serial_port)
  55. def _updateThread(self):
  56. while self._check_updates:
  57. container_stack = self._application.getGlobalContainerStack()
  58. if container_stack is None:
  59. time.sleep(5)
  60. continue
  61. port_list = [] # Just an empty list; all USB devices will be removed.
  62. if container_stack.getMetaDataEntry("supports_usb_connection"):
  63. machine_file_formats = [file_type.strip() for file_type in container_stack.getMetaDataEntry("file_formats").split(";")]
  64. if "text/x-gcode" in machine_file_formats:
  65. port_list = self.getSerialPortList(only_list_usb=True)
  66. self._addRemovePorts(port_list)
  67. time.sleep(5)
  68. def _addRemovePorts(self, serial_ports):
  69. """Helper to identify serial ports (and scan for them)"""
  70. # First, find and add all new or changed keys
  71. for serial_port in list(serial_ports):
  72. if serial_port not in self._serial_port_list:
  73. self.addUSBOutputDeviceSignal.emit(serial_port) # Hack to ensure its created in main thread
  74. continue
  75. self._serial_port_list = list(serial_ports)
  76. for port, device in self._usb_output_devices.items():
  77. if port not in self._serial_port_list:
  78. device.close()
  79. def addOutputDevice(self, serial_port):
  80. """Because the model needs to be created in the same thread as the QMLEngine, we use a signal."""
  81. device = USBPrinterOutputDevice.USBPrinterOutputDevice(serial_port, parent = self)
  82. device.connectionStateChanged.connect(self._onConnectionStateChanged)
  83. self._usb_output_devices[serial_port] = device
  84. device.connect()
  85. def getSerialPortList(self, only_list_usb = False):
  86. """Create a list of serial ports on the system.
  87. :param only_list_usb: If true, only usb ports are listed
  88. """
  89. base_list = []
  90. try:
  91. port_list = serial.tools.list_ports.comports()
  92. except TypeError: # Bug in PySerial causes a TypeError if port gets disconnected while processing.
  93. port_list = []
  94. for port in port_list:
  95. if not isinstance(port, tuple):
  96. port = (port.device, port.description, port.hwid)
  97. if not port[2]: # HWID may be None if the device is not USB or the system doesn't report the type.
  98. continue
  99. if only_list_usb and not port[2].startswith("USB"):
  100. continue
  101. # To prevent cura from messing with serial ports of other devices,
  102. # filter by regular expressions passed in as environment variables.
  103. # Get possible patterns with python3 -m serial.tools.list_ports -v
  104. # set CURA_DEVICENAMES=USB[1-9] -> e.g. not matching /dev/ttyUSB0
  105. pattern = environ.get('CURA_DEVICENAMES')
  106. if pattern and not search(pattern, port[0]):
  107. continue
  108. # set CURA_DEVICETYPES=CP2102 -> match a type of serial converter
  109. pattern = environ.get('CURA_DEVICETYPES')
  110. if pattern and not search(pattern, port[1]):
  111. continue
  112. # set CURA_DEVICEINFOS=LOCATION=2-1.4 -> match a physical port
  113. # set CURA_DEVICEINFOS=VID:PID=10C4:EA60 -> match a vendor:product
  114. pattern = environ.get('CURA_DEVICEINFOS')
  115. if pattern and not search(pattern, port[2]):
  116. continue
  117. base_list += [port[0]]
  118. return list(base_list)
  119. __instance = None # type: USBPrinterOutputDeviceManager
  120. @classmethod
  121. def getInstance(cls, *args, **kwargs) -> "USBPrinterOutputDeviceManager":
  122. return cls.__instance