AvrFirmwareUpdater.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.Logger import Logger
  4. from cura.CuraApplication import CuraApplication
  5. from cura.PrinterOutput.FirmwareUpdater import FirmwareUpdater, FirmwareUpdateState
  6. from .avr_isp import stk500v2, intelHex
  7. from serial import SerialException
  8. from time import sleep
  9. MYPY = False
  10. if MYPY:
  11. from cura.PrinterOutput.PrinterOutputDevice import PrinterOutputDevice
  12. class AvrFirmwareUpdater(FirmwareUpdater):
  13. def __init__(self, output_device: "PrinterOutputDevice") -> None:
  14. super().__init__(output_device)
  15. def _updateFirmware(self) -> None:
  16. try:
  17. hex_file = intelHex.readHex(self._firmware_file)
  18. assert len(hex_file) > 0
  19. except (FileNotFoundError, AssertionError):
  20. Logger.log("e", "Unable to read provided hex file. Could not update firmware.")
  21. self._setFirmwareUpdateState(FirmwareUpdateState.firmware_not_found_error)
  22. return
  23. programmer = stk500v2.Stk500v2()
  24. programmer.progress_callback = self._onFirmwareProgress
  25. # Ensure that other connections are closed.
  26. if self._output_device.isConnected():
  27. self._output_device.close()
  28. try:
  29. programmer.connect(self._output_device._serial_port)
  30. except:
  31. programmer.close()
  32. Logger.logException("e", "Failed to update firmware")
  33. self._setFirmwareUpdateState(FirmwareUpdateState.communication_error)
  34. return
  35. # Give programmer some time to connect. Might need more in some cases, but this worked in all tested cases.
  36. sleep(1)
  37. if not programmer.isConnected():
  38. Logger.log("e", "Unable to connect with serial. Could not update firmware")
  39. self._setFirmwareUpdateState(FirmwareUpdateState.communication_error)
  40. try:
  41. programmer.programChip(hex_file)
  42. except SerialException as e:
  43. Logger.log("e", "A serial port exception occurred during firmware update: %s" % e)
  44. self._setFirmwareUpdateState(FirmwareUpdateState.io_error)
  45. return
  46. except Exception as e:
  47. Logger.log("e", "An unknown exception occurred during firmware update: %s" % e)
  48. self._setFirmwareUpdateState(FirmwareUpdateState.unknown_error)
  49. return
  50. programmer.close()
  51. # Try to re-connect with the machine again, which must be done on the Qt thread, so we use call later.
  52. CuraApplication.getInstance().callLater(self._output_device.connect)
  53. self._cleanupAfterUpdate()