FirmwareUpdater.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt5.QtCore import QObject, QUrl, pyqtSignal, pyqtProperty
  4. from enum import IntEnum
  5. from threading import Thread
  6. from typing import Union
  7. MYPY = False
  8. if MYPY:
  9. from cura.PrinterOutput.PrinterOutputDevice import PrinterOutputDevice
  10. class FirmwareUpdater(QObject):
  11. firmwareProgressChanged = pyqtSignal()
  12. firmwareUpdateStateChanged = pyqtSignal()
  13. def __init__(self, output_device: "PrinterOutputDevice") -> None:
  14. super().__init__()
  15. self._output_device = output_device
  16. self._update_firmware_thread = Thread(target=self._updateFirmware, daemon=True)
  17. self._firmware_file = ""
  18. self._firmware_progress = 0
  19. self._firmware_update_state = FirmwareUpdateState.idle
  20. def updateFirmware(self, firmware_file: Union[str, QUrl]) -> None:
  21. # the file path could be url-encoded.
  22. if firmware_file.startswith("file://"):
  23. self._firmware_file = QUrl(firmware_file).toLocalFile()
  24. else:
  25. self._firmware_file = firmware_file
  26. self._setFirmwareUpdateState(FirmwareUpdateState.updating)
  27. self._update_firmware_thread.start()
  28. def _updateFirmware(self) -> None:
  29. raise NotImplementedError("_updateFirmware needs to be implemented")
  30. ## Cleanup after a succesful update
  31. def _cleanupAfterUpdate(self) -> None:
  32. # Clean up for next attempt.
  33. self._update_firmware_thread = Thread(target=self._updateFirmware, daemon=True)
  34. self._firmware_file = ""
  35. self._onFirmwareProgress(100)
  36. self._setFirmwareUpdateState(FirmwareUpdateState.completed)
  37. @pyqtProperty(int, notify = firmwareProgressChanged)
  38. def firmwareProgress(self) -> int:
  39. return self._firmware_progress
  40. @pyqtProperty(int, notify=firmwareUpdateStateChanged)
  41. def firmwareUpdateState(self) -> "FirmwareUpdateState":
  42. return self._firmware_update_state
  43. def _setFirmwareUpdateState(self, state: "FirmwareUpdateState") -> None:
  44. if self._firmware_update_state != state:
  45. self._firmware_update_state = state
  46. self.firmwareUpdateStateChanged.emit()
  47. # Callback function for firmware update progress.
  48. def _onFirmwareProgress(self, progress: int, max_progress: int = 100) -> None:
  49. self._firmware_progress = int(progress * 100 / max_progress) # Convert to scale of 0-100
  50. self.firmwareProgressChanged.emit()
  51. class FirmwareUpdateState(IntEnum):
  52. idle = 0
  53. updating = 1
  54. completed = 2
  55. unknown_error = 3
  56. communication_error = 4
  57. io_error = 5
  58. firmware_not_found_error = 6