Merge branch 'improve/port_detection_refactoring' into maintenance

This commit is contained in:
Gina Häußge committed 2020-06-05 12:34:34 +02:00
commit 72ebf6f4c4
20 files changed
+546 -718

No files matched your search

-168
View File
@@ -293,174 +293,6 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# enable or disable the loading animation
showLoadingAnimation: true
# Settings for the virtual printer
virtualPrinter:
# Whether to enable the virtual printer and include it in the list of available serial connections.
# Defaults to false.
enabled: true
# Whether to send an additional "ok" after a resend request (like Repetier)
okAfterResend: false
# Whether to force checksums and line number in the communication (like Repetier), if set to true
# printer will only accept commands that come with linenumber and checksum and throw an error for
# lines that don't. Defaults to false
forceChecksum: false
# Whether to send "ok" responses with the line number that gets acknowledged by the "ok". Defaults
# to false.
okWithLinenumber: false
# Number of extruders to simulate on the virtual printer. Map from tool id (0, 1, ...) to temperature
# in °C
numExtruders: 1
# Allows pinning certain hotends to a fixed temperature
pinnedExtruders: null
# Whether to include the current tool temperature in the M105 output as separate T segment or not.
#
# True: > M105
# < ok T:23.5/0.0 T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
# False: > M105
# < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
includeCurrentToolInTemps: true
# Whether to include the selected filename in the M23 File opened response.
#
# True: > M23 filename.gcode
# < File opened: filename.gcode Size: 27
# False: > M23 filename.gcode
# > File opened
includeFilenameInOpened: true
# Whether the simulated printer should also simulate a heated bed or not
hasBed: true
# Whether the simulated printer should also simulate a heated chamber or not
hasChamber: false
# If enabled, reports the set target temperatures as separate messages from the firmware
#
# True: > M109 S220.0
# < TargetExtr0:220.0
# < ok
# > M105
# < ok T0:34.3 T1:23.5 B:43.2
# False: > M109 S220.0
# < ok
# > M105
# < ok T0:34.3/220.0 T1:23.5/0.0 B:43.2/0.0
repetierStyleTargetTemperature: false
# If enabled, uses repetier style resends, sending multiple resends for the same line
# to make sure nothing gets lost on the line
repetierStyleResends: false
# If enabled, ok will be sent before a commands output, otherwise after or inline (M105)
#
# True: > M20
# < ok
# < Begin file list
# < End file list
# False: > M20
# < Begin file list
# < End file list
# < ok
okBeforeCommandOutput: false
# If enabled, reports the first extruder in M105 responses as T instead of T0
#
# True: > M105
# < ok T:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
# False: > M105
# < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
smoothieTemperatureReporting: false
# Whether M20 responses will include filesize or not
#
# True: <filename> <filesize in bytes>
# False: <filename>
extendedSdFileList: false
# Forced pause for retrieving from the outgoing buffer
throttle: 0.01
# Whether to send "wait" responses every "waitInterval" seconds when serial rx buffer is empty
sendWait: false
# Interval in which to send "wait" lines when rx buffer is empty
waitInterval: 1
# Size of the simulated RX buffer in bytes, when it's full a send from OctoPrint's
# side will block
rxBuffer: 64
# Size of simulated command buffer, number of commands. If full, buffered commands will block
# until a slot frees up
commandBuffer: 4
# Whether to support the M112 command with simulated kill
supportM112: true
# Whether to send messages received via M117 back as "echo:" lines
echoOnM117: true
# Whether to simulate broken M29 behaviour (missing ok after response)
brokenM29: true
# Whether F is supported as individual command
supportF: false
# Firmware name to report (useful for testing firmware detection)
firmwareName: Virtual Marlin 1.0
# Simulate a shared nozzle
sharedNozzle: false
# Send "busy" messages if busy processing something
sendBusy: false
# Simulate a reset on connect
simulateReset: true
# Lines to send on simulated reset
resetLines:
- start
- "Marlin: Virtual Marlin!"
- "SD card ok"
# Initial set of prepared oks to use instead of regular ok (e.g. to simulate
# mis-sent oks). Can also be filled at runtime via the debug command prepare_ok
preparedOks: []
# Format string for ok response.
#
# Placeholders:
# - lastN: last acknowledged line number
# - buffer: empty slots in internal command buffer
#
# Example format string for "extended" ok format:
# ok N{lastN} P{buffer}
okFormatString: ok
# Format string for M115 output.
#
# Placeholders:
# - firmare_name: The firmware name as defined in firmwareName
m115FormatString: "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0"
# Whether to include capability report in M115 output
m115ReportCapabilites: false
# Capabilities to report if capability report is enabled
capabilities:
AUTOREPORT_TEMP: true
# Simulated ambient temperature in °C
ambientTemperature: 21.3
.. _sec-configuration-config_yaml-estimation:
Estimation
+173 -18
View File
@@ -12,24 +12,7 @@ that may be hard to reproduce with a real printer.
Enabling the virtual printer
----------------------------
The virtual printer is enabled by editing OctoPrint's config.yaml file. Details on the configuration file can
be found in the full :ref:`config.yaml documentation <sec-configuration-config_yaml>`.
The steps to take are as follows:
* Find config.yaml in the OctoPrint settings folder. Usually in ``~/.octoprint`` on Linux, in ``%APPDATA%/OctoPrint`` on Windows and in ``~/Library/Application Support/OctoPrint`` on macOS.
* Add or extend the ``devel`` section with:
.. code-block:: yaml
devel:
virtualPrinter:
enabled: true
* Restart OctoPrint.
* In the connection panel, a new option will appear in the Serial Port dropdown labeled ``VIRTUAL``.
* Select this option and click ``connect``.
* The virtual printer is now active.
The virtual printer can be enabled through its Settings pane.
.. _sec-development-virtual-printer-config:
@@ -40,6 +23,178 @@ The config.yaml file has many configuration options for the virtual printer that
Please see the relevant :ref:`config.yaml section <sec-configuration-config_yaml-devel>` for the full details.
.. code-block:: yaml
plugins:
# Settings for the virtual printer
virtual_printer:
# Whether to enable the virtual printer and include it in the list of available serial connections.
# Defaults to false.
enabled: true
# Whether to send an additional "ok" after a resend request (like Repetier)
okAfterResend: false
# Whether to force checksums and line number in the communication (like Repetier), if set to true
# printer will only accept commands that come with linenumber and checksum and throw an error for
# lines that don't. Defaults to false
forceChecksum: false
# Whether to send "ok" responses with the line number that gets acknowledged by the "ok". Defaults
# to false.
okWithLinenumber: false
# Number of extruders to simulate on the virtual printer. Map from tool id (0, 1, ...) to temperature
# in °C
numExtruders: 1
# Allows pinning certain hotends to a fixed temperature
pinnedExtruders: null
# Whether to include the current tool temperature in the M105 output as separate T segment or not.
#
# True: > M105
# < ok T:23.5/0.0 T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
# False: > M105
# < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
includeCurrentToolInTemps: true
# Whether to include the selected filename in the M23 File opened response.
#
# True: > M23 filename.gcode
# < File opened: filename.gcode Size: 27
# False: > M23 filename.gcode
# > File opened
includeFilenameInOpened: true
# Whether the simulated printer should also simulate a heated bed or not
hasBed: true
# Whether the simulated printer should also simulate a heated chamber or not
hasChamber: false
# If enabled, reports the set target temperatures as separate messages from the firmware
#
# True: > M109 S220.0
# < TargetExtr0:220.0
# < ok
# > M105
# < ok T0:34.3 T1:23.5 B:43.2
# False: > M109 S220.0
# < ok
# > M105
# < ok T0:34.3/220.0 T1:23.5/0.0 B:43.2/0.0
repetierStyleTargetTemperature: false
# If enabled, uses repetier style resends, sending multiple resends for the same line
# to make sure nothing gets lost on the line
repetierStyleResends: false
# If enabled, ok will be sent before a commands output, otherwise after or inline (M105)
#
# True: > M20
# < ok
# < Begin file list
# < End file list
# False: > M20
# < Begin file list
# < End file list
# < ok
okBeforeCommandOutput: false
# If enabled, reports the first extruder in M105 responses as T instead of T0
#
# True: > M105
# < ok T:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
# False: > M105
# < ok T0:34.3/0.0 T1:23.5/0.0 B:43.2/0.0
smoothieTemperatureReporting: false
# Whether M20 responses will include filesize or not
#
# True: <filename> <filesize in bytes>
# False: <filename>
extendedSdFileList: false
# Forced pause for retrieving from the outgoing buffer
throttle: 0.01
# Whether to send "wait" responses every "waitInterval" seconds when serial rx buffer is empty
sendWait: false
# Interval in which to send "wait" lines when rx buffer is empty
waitInterval: 1
# Size of the simulated RX buffer in bytes, when it's full a send from OctoPrint's
# side will block
rxBuffer: 64
# Size of simulated command buffer, number of commands. If full, buffered commands will block
# until a slot frees up
commandBuffer: 4
# Whether to support the M112 command with simulated kill
supportM112: true
# Whether to send messages received via M117 back as "echo:" lines
echoOnM117: true
# Whether to simulate broken M29 behaviour (missing ok after response)
brokenM29: true
# Whether F is supported as individual command
supportF: false
# Firmware name to report (useful for testing firmware detection)
firmwareName: Virtual Marlin 1.0
# Simulate a shared nozzle
sharedNozzle: false
# Send "busy" messages if busy processing something
sendBusy: false
# Simulate a reset on connect
simulateReset: true
# Lines to send on simulated reset
resetLines:
- start
- "Marlin: Virtual Marlin!"
- "SD card ok"
# Initial set of prepared oks to use instead of regular ok (e.g. to simulate
# mis-sent oks). Can also be filled at runtime via the debug command prepare_ok
preparedOks: []
# Format string for ok response.
#
# Placeholders:
# - lastN: last acknowledged line number
# - buffer: empty slots in internal command buffer
#
# Example format string for "extended" ok format:
# ok N{lastN} P{buffer}
okFormatString: ok
# Format string for M115 output.
#
# Placeholders:
# - firmare_name: The firmware name as defined in firmwareName
m115FormatString: "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0"
# Whether to include capability report in M115 output
m115ReportCapabilites: false
# Capabilities to report if capability report is enabled
capabilities:
AUTOREPORT_TEMP: true
# Simulated ambient temperature in °C
ambientTemperature: 21.3
.. _sec-development-virtual-printer-log:
Log file
+19
View File
@@ -890,6 +890,25 @@ octoprint.comm.protocol.temperatures.received
:tab-width: 4
:caption: `sanitize_temperatures.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/sanitize_temperatures.py>`_
.. _sec-plugins-hook-comm-transport-serial-additonal-port-names:
octoprint.comm.transport.serial.additional_port_names
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: additional_port_names_hook(candidates, *args, **kwargs)
Return additional port names (not glob patterns!) to use as a serial connection to the printer. Expected to be
``list`` of ``string``s.
Useful in combination with :ref:`octoprint.comm.transport.serial.factory <sec-plugins-hook-comm-transport-serial-factory>`
to implement custom serial-like ports through plugins.
For an example of use see the bundled ``virtual_printer`` plugin.
:param list candidates: The port names already found on the system available for connection.
:return: Additional port names to offer up for connection.
:rtype: list
.. _sec-plugins-hook-comm-transport-serial-factory:
octoprint.comm.transport.serial.factory
@@ -25,16 +25,12 @@ SETTINGS_DEFAULTS = dict(enabled=False,
import serial
import requests.exceptions
import errno
import octoprint.util.avr_isp.ispBase
import tornado.websocket
IGNORED_EXCEPTIONS = [
# serial exceptions in octoprint.util.comm
(serial.SerialException, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"),
# isp errors during port auto detection in octoprint.util.comm
(octoprint.util.avr_isp.ispBase.IspError, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"),
# IOErrors of any kind due to a full file system
(IOError, lambda exc, logger, plugin, cb: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)),
@@ -7,15 +7,84 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import octoprint.plugin
class VirtualPrinterPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.TemplatePlugin):
def get_template_configs(self):
return [
dict(type="settings", custom_bindings=False)
]
def get_settings_defaults(self):
return {
"enabled": False,
"okAfterResend": False,
"forceChecksum": False,
"numExtruders": 1,
"pinnedExtruders": None,
"includeCurrentToolInTemps": True,
"includeFilenameInOpened": True,
"hasBed": True,
"hasChamber": False,
"repetierStyleTargetTemperature": False,
"okBeforeCommandOutput": False,
"smoothieTemperatureReporting": False,
"reprapfwM114": False,
"extendedSdFileList": False,
"throttle": 0.01,
"sendWait": True,
"waitInterval": 1.0,
"rxBuffer": 64,
"commandBuffer": 4,
"supportM112": True,
"echoOnM117": True,
"brokenM29": True,
"brokenResend": False,
"supportF": False,
"firmwareName": "Virtual Marlin 1.0",
"sharedNozzle": False,
"sendBusy": False,
"busyInterval": 2.0,
"simulateReset": True,
"resetLines": ['start', 'Marlin: Virtual Marlin!', '\x80', 'SD card ok'],
"preparedOks": [],
"okFormatString": "ok",
"m115FormatString": "FIRMWARE_NAME:{firmware_name} PROTOCOL_VERSION:1.0",
"m115ReportCapabilities": True,
"capabilities": {
"AUTOREPORT_TEMP": True,
"AUTOREPORT_SD_STATUS": True,
"EMERGENCY_PARSER": True
},
"m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}",
"ambientTemperature": 21.3,
"errors": {
"checksum_mismatch": "Checksum mismatch",
"checksum_missing": "Missing checksum",
"lineno_mismatch": "expected line {} got {}",
"lineno_missing": "No Line Number with checksum, Last Line: {}",
"maxtemp": "MAXTEMP triggered!",
"mintemp": "MINTEMP triggered!",
"command_unknown": "Unknown command {}"
}
}
def get_settings_version(self):
return 1
def on_settings_migrate(self, target, current):
if current is None:
config = self._settings.global_get(["devel", "virtualPrinter"])
if config:
self._logger.info("Migrating settings from devel.virtualPrinter to plugins.virtual_printer...")
self._settings.global_set(["plugins", "virtual_printer"], config, force=True)
self._settings.global_remove(["devel", "virtualPrinter"])
class VirtualPrinterPlugin(octoprint.plugin.SettingsPlugin):
def virtual_printer_factory(self, comm_instance, port, baudrate,
read_timeout):
if not port == "VIRTUAL":
return None
if not self._settings.global_get_boolean(
["devel", "virtualPrinter", "enabled"]):
if not self._settings.get_boolean(["enabled"]):
return None
import logging.handlers
@@ -29,10 +98,17 @@ class VirtualPrinterPlugin(octoprint.plugin.SettingsPlugin):
from . import virtual
serial_obj = virtual.VirtualPrinter(seriallog_handler=seriallog_handler,
read_timeout=float(read_timeout))
serial_obj = virtual.VirtualPrinter(self._settings,
seriallog_handler=seriallog_handler,
read_timeout=float(read_timeout),
faked_baudrate=baudrate)
return serial_obj
def get_additional_port_names(self, *args, **kwargs):
if self._settings.get_boolean(["enabled"]):
return ["VIRTUAL"]
else:
return []
__plugin_name__ = "Virtual Printer"
__plugin_author__ = "Gina Häußge, based on work by Daid Braam"
@@ -49,5 +125,6 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.comm.transport.serial.factory": plugin.virtual_printer_factory
"octoprint.comm.transport.serial.factory": plugin.virtual_printer_factory,
"octoprint.comm.transport.serial.additional_port_names": plugin.get_additional_port_names
}
@@ -0,0 +1,12 @@
<h3>Virtual Printer</h3>
<form class="form-horizontal">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.virtual_printer.enabled"> {{ _('Enable the virtual printer') }}
<span class="help-block">{{ _('If enabled, an additional serial port <code>VIRTUAL</code> will be available for connecting, backed by a fake printer implementation. Useful for development.') }}</span>
</label>
</div>
</div>
</form>
@@ -21,7 +21,6 @@ from past.builtins import basestring
from serial import SerialTimeoutException
from octoprint.settings import settings
from octoprint.plugin import plugin_manager
from octoprint.util import RepeatedTimer, monotonic_time, to_bytes, to_unicode
@@ -41,10 +40,13 @@ class VirtualPrinter(object):
start_sd_regex = re.compile(r"start_sd (.*)")
select_sd_regex = re.compile(r"select_sd (.*)")
def __init__(self, seriallog_handler=None, read_timeout=5.0, write_timeout=10.0):
def __init__(self, settings, seriallog_handler=None, read_timeout=5.0, write_timeout=10.0, faked_baudrate=115200):
import logging
self._logger = logging.getLogger("octoprint.plugins.virtual_printer.VirtualPrinter")
self._settings = settings
self._faked_baudrate = faked_baudrate
self._seriallog = logging.getLogger("octoprint.plugin.virtual_printer.VirtualPrinter.serial")
self._seriallog.setLevel(logging.CRITICAL)
self._seriallog.propagate = False
@@ -59,35 +61,35 @@ class VirtualPrinter(object):
self._read_timeout = read_timeout
self._write_timeout = write_timeout
self._rx_buffer_size = settings().getInt(["devel", "virtualPrinter", "rxBuffer"])
self._rx_buffer_size = self._settings.get_int(["rxBuffer"])
self.incoming = CharCountingQueue(self._rx_buffer_size, name="RxBuffer")
self.outgoing = queue.Queue()
self.buffered = queue.Queue(maxsize=settings().getInt(["devel", "virtualPrinter", "commandBuffer"]))
self.buffered = queue.Queue(maxsize=self._settings.get_int(["commandBuffer"]))
if settings().getBoolean(["devel", "virtualPrinter", "simulateReset"]):
for item in settings().get(["devel", "virtualPrinter", "resetLines"]):
if self._settings.get_boolean(["simulateReset"]):
for item in self._settings.get(["resetLines"]):
self._send(item + "\n")
self._prepared_oks = []
prepared = settings().get(["devel", "virtualPrinter", "preparedOks"])
prepared = self._settings.get(["preparedOks"])
if prepared and isinstance(prepared, list):
for prep in prepared:
self._prepared_oks.append(prep)
self._prepared_errors = []
self._errors = settings().get(["devel", "virtualPrinter", "errors"], merged=True)
self._errors = self._settings.get(["errors"], merged=True)
self.currentExtruder = 0
self.extruderCount = settings().getInt(["devel", "virtualPrinter", "numExtruders"])
self.pinnedExtruders = settings().get(["devel", "virtualPrinter", "pinnedExtruders"])
self.extruderCount = self._settings.get_int(["numExtruders"])
self.pinnedExtruders = self._settings.get(["pinnedExtruders"])
if self.pinnedExtruders is None:
self.pinnedExtruders = dict()
self.sharedNozzle = settings().getBoolean(["devel", "virtualPrinter", "sharedNozzle"])
self.sharedNozzle = self._settings.get_boolean(["sharedNozzle"])
self.temperatureCount = (1 if self.sharedNozzle else self.extruderCount)
self._ambient_temperature = settings().getFloat(["devel", "virtualPrinter", "ambientTemperature"])
self._ambient_temperature = self._settings.get_float(["ambientTemperature"])
self.temp = [self._ambient_temperature] * self.temperatureCount
self.targetTemp = [0.0] * self.temperatureCount
@@ -108,7 +110,7 @@ class VirtualPrinter(object):
self._feedrate_multiplier = 100
self._flowrate_multiplier = 100
self._virtualSd = settings().getBaseFolder("virtualSd")
self._virtualSd = self._settings.global_get_basefolder("virtualSd")
self._sdCardReady = True
self._sdPrinter = None
self._sdPrintingSemaphore = threading.Event()
@@ -122,26 +124,26 @@ class VirtualPrinter(object):
self._heatingUp = False
self._okBeforeCommandOutput = settings().getBoolean(["devel", "virtualPrinter", "okBeforeCommandOutput"])
self._supportM112 = settings().getBoolean(["devel", "virtualPrinter", "supportM112"])
self._supportF = settings().getBoolean(["devel", "virtualPrinter", "supportF"])
self._okBeforeCommandOutput = self._settings.get_boolean(["okBeforeCommandOutput"])
self._supportM112 = self._settings.get_boolean(["supportM112"])
self._supportF = self._settings.get_boolean(["supportF"])
self._sendWait = settings().getBoolean(["devel", "virtualPrinter", "sendWait"])
self._sendBusy = settings().getBoolean(["devel", "virtualPrinter", "sendBusy"])
self._waitInterval = settings().getFloat(["devel", "virtualPrinter", "waitInterval"])
self._busyInterval = settings().getFloat(["devel", "virtualPrinter", "busyInterval"])
self._sendWait = self._settings.get_boolean(["sendWait"])
self._sendBusy = self._settings.get_boolean(["sendBusy"])
self._waitInterval = self._settings.get_float(["waitInterval"])
self._busyInterval = self._settings.get_float(["busyInterval"])
self._echoOnM117 = settings().getBoolean(["devel", "virtualPrinter", "echoOnM117"])
self._echoOnM117 = self._settings.get_boolean(["echoOnM117"])
self._brokenM29 = settings().getBoolean(["devel", "virtualPrinter", "brokenM29"])
self._brokenResend = settings().getBoolean(["devel", "virtualPrinter", "brokenResend"])
self._brokenM29 = self._settings.get_boolean(["brokenM29"])
self._brokenResend = self._settings.get_boolean(["brokenResend"])
self._m115FormatString = settings().get(["devel", "virtualPrinter", "m115FormatString"])
self._firmwareName = settings().get(["devel", "virtualPrinter", "firmwareName"])
self._m115FormatString = self._settings.get(["m115FormatString"])
self._firmwareName = self._settings.get(["firmwareName"])
self._okFormatString = settings().get(["devel", "virtualPrinter", "okFormatString"])
self._okFormatString = self._settings.get(["okFormatString"])
self._capabilities = settings().get(["devel", "virtualPrinter", "capabilities"], merged=True)
self._capabilities = self._settings.get(["capabilities"], merged=True)
self._temperature_reporter = None
self._sdstatus_reporter = None
@@ -178,7 +180,7 @@ class VirtualPrinter(object):
def __str__(self):
return "VIRTUAL(read_timeout={read_timeout},write_timeout={write_timeout},options={options})"\
.format(read_timeout=self._read_timeout, write_timeout=self._write_timeout, options=settings().get(["devel", "virtualPrinter"]))
.format(read_timeout=self._read_timeout, write_timeout=self._write_timeout, options=self._settings.get([]))
def _reset(self):
with self._incoming_lock:
@@ -245,8 +247,8 @@ class VirtualPrinter(object):
self._clearQueue(self.outgoing)
self._clearQueue(self.buffered)
if settings().getBoolean(["devel", "virtualPrinter", "simulateReset"]):
for item in settings().get(["devel", "virtualPrinter", "resetLines"]):
if self._settings.get_boolean(["simulateReset"]):
for item in self._settings.get(["resetLines"]):
self._send(item + "\n")
@property
@@ -267,6 +269,14 @@ class VirtualPrinter(object):
self._logger.debug("Setting write timeout to {}s".format(value))
self._write_timeout = value
@property
def port(self):
return "VIRTUAL"
@property
def baudrate(self):
return self._faked_baudrate
# noinspection PyMethodMayBeStatic
def _clearQueue(self, q):
try:
@@ -327,7 +337,7 @@ class VirtualPrinter(object):
continue
self.current_line += 1
elif settings().getBoolean(["devel", "virtualPrinter", "forceChecksum"]):
elif self._settings.get_boolean(["forceChecksum"]):
self._send(self._error("checksum_missing"))
continue
@@ -593,7 +603,7 @@ class VirtualPrinter(object):
# noinspection PyUnusedLocal
def _gcode_M114(self, data):
# type: (str) -> bool
m114FormatString = settings().get(["devel", "virtualPrinter", "m114FormatString"])
m114FormatString = self._settings.get(["m114FormatString"])
e = dict((index, value) for index, value in enumerate(self._lastE))
e["current"] = self._lastE[self.currentExtruder]
e["all"] = " ".join(["E{}:{}".format(num, self._lastE[self.currentExtruder]) for num in range(self.extruderCount)])
@@ -619,7 +629,7 @@ class VirtualPrinter(object):
output = self._m115FormatString.format(firmware_name=self._firmwareName)
self._send(output)
if settings().getBoolean(["devel", "virtualPrinter", "m115ReportCapabilities"]):
if self._settings.get_boolean(["m115ReportCapabilities"]):
for cap, enabled in self._capabilities.items():
self._send("Cap:{}:{}".format(cap.upper(), "1" if enabled else "0"))
@@ -959,7 +969,7 @@ class VirtualPrinter(object):
def _listSd(self):
self._send("Begin file list")
if settings().getBoolean(["devel", "virtualPrinter", "extendedSdFileList"]):
if self._settings.get_boolean(["extendedSdFileList"]):
items = map(
lambda x: "%s %d" % (x.upper(), os.stat(os.path.join(self._virtualSd, x)).st_size),
os.listdir(self._virtualSd)
@@ -987,7 +997,7 @@ class VirtualPrinter(object):
else:
self._selectedSdFile = file
self._selectedSdFileSize = os.stat(file).st_size
if settings().getBoolean(["devel", "virtualPrinter", "includeFilenameInOpened"]):
if self._settings.get_boolean(["includeFilenameInOpened"]):
self._send("File opened: %s Size: %d" % (filename, self._selectedSdFileSize))
else:
self._send("File opened")
@@ -1015,7 +1025,7 @@ class VirtualPrinter(object):
def _generateTemperatureOutput(self):
# type: () -> str
includeTarget = not settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"])
includeTarget = not self._settings.get_boolean(["repetierStyleTargetTemperature"])
# send simulated temperature data
if self.temperatureCount > 1:
@@ -1024,22 +1034,22 @@ class VirtualPrinter(object):
allTemps.append((i, self.temp[i], self.targetTemp[i]))
allTempsString = " ".join(map(lambda x: "T%d:%.2f /%.2f" % x if includeTarget else "T%d:%.2f" % (x[0], x[1]), allTemps))
if settings().getBoolean(["devel", "virtualPrinter", "smoothieTemperatureReporting"]):
if self._settings.get_boolean(["smoothieTemperatureReporting"]):
allTempsString = allTempsString.replace("T0:", "T:")
if settings().getBoolean(["devel", "virtualPrinter", "hasBed"]):
if self._settings.get_boolean(["hasBed"]):
if includeTarget:
allTempsString = "B:%.2f /%.2f %s" % (self.bedTemp, self.bedTargetTemp, allTempsString)
else:
allTempsString = "B:%.2f %s" % (self.bedTemp, allTempsString)
if settings().getBoolean(["devel", "virtualPrinter", "hasChamber"]):
if self._settings.get_boolean(["hasChamber"]):
if includeTarget:
allTempsString = "C:%.2f /%.2f %s" % (self.chamberTemp, self.chamberTargetTemp, allTempsString)
else:
allTempsString = "C:%.2f %s" % (self.chamberTemp, allTempsString)
if settings().getBoolean(["devel", "virtualPrinter", "includeCurrentToolInTemps"]):
if self._settings.get_boolean(["includeCurrentToolInTemps"]):
if includeTarget:
output = "T:%.2f /%.2f %s" % (self.temp[self.currentExtruder], self.targetTemp[self.currentExtruder], allTempsString)
else:
@@ -1052,7 +1062,7 @@ class VirtualPrinter(object):
else:
t = "T:%.2f" % self.temp[0]
if settings().getBoolean(["devel", "virtualPrinter", "hasBed"]):
if self._settings.get_boolean(["hasBed"]):
if includeTarget:
b = "B:%.2f /%.2f" % (self.bedTemp, self.bedTargetTemp)
else:
@@ -1060,7 +1070,7 @@ class VirtualPrinter(object):
else:
b = ""
if settings().getBoolean(["devel", "virtualPrinter", "hasChamber"]):
if self._settings.get_boolean(["hasChamber"]):
if includeTarget:
c = "C:%.2f /%.2f" % (self.chamberTemp, self.chamberTargetTemp)
else:
@@ -1107,12 +1117,12 @@ class VirtualPrinter(object):
if wait:
self._waitForHeatup("tool%d" % tool, only_wait_if_higher)
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]):
if self._settings.get_boolean(["repetierStyleTargetTemperature"]):
self._send("TargetExtr%d:%d" % (tool, self.targetTemp[tool]))
def _parseBedCommand(self, line, wait=False, support_r=False):
# type: (str, bool, bool) -> None
if not settings().getBoolean(["devel", "virtualPrinter", "hasBed"]):
if not self._settings.get_boolean(["hasBed"]):
return
only_wait_if_higher = True
@@ -1128,11 +1138,11 @@ class VirtualPrinter(object):
if wait:
self._waitForHeatup("bed", only_wait_if_higher)
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]):
if self._settings.get_boolean(["repetierStyleTargetTemperature"]):
self._send("TargetBed:%d" % self.bedTargetTemp)
def _parseChamberCommand(self, line, wait=False, support_r=False):
if not settings().getBoolean(["devel", "virtualPrinter", "hasChamber"]):
if not self._settings.get_boolean(["hasChamber"]):
return
only_wait_if_higher = True
+4
View File
@@ -161,6 +161,8 @@ def getSettings():
"log": s.getBoolean(["serial", "log"]),
"additionalPorts": s.get(["serial", "additionalPorts"]),
"additionalBaudrates": s.get(["serial", "additionalBaudrates"]),
"blacklistedPorts": s.get(["serial", "blacklistedPorts"]),
"blacklistedBaudrates": s.get(["serial", "blacklistedBaudrates"]),
"longRunningCommands": s.get(["serial", "longRunningCommands"]),
"checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]),
"blockedCommands": s.get(["serial", "blockedCommands"]),
@@ -458,6 +460,8 @@ def _saveSettings(data):
if "timeoutPositionLogWait" in data["serial"]: s.setFloat(["serial", "timeout", "positionLogWait"], data["serial"]["timeoutPositionLogWait"], min=1.0)
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"])
if "blacklistedPorts" in data["serial"] and isinstance(data["serial"]["blacklistedPorts"], (list, tuple)): s.set(["serial", "blacklistedPorts"], data["serial"]["blacklistedPorts"])
if "blacklistedBaudrates" in data["serial"] and isinstance(data["serial"]["blacklistedBaudrates"], (list, tuple)): s.set(["serial", "blacklistedBaudrates"], data["serial"]["blacklistedBaudrates"])
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
if "checksumRequiringCommands" in data["serial"] and isinstance(data["serial"]["checksumRequiringCommands"], (list, tuple)): s.set(["serial", "checksumRequiringCommands"], data["serial"]["checksumRequiringCommands"])
if "blockedCommands" in data["serial"] and isinstance(data["serial"]["blockedCommands"], (list, tuple)): s.set(["serial", "blockedCommands"], data["serial"]["blockedCommands"])
+3 -53
View File
@@ -119,6 +119,8 @@ default_settings = {
"maxWritePasses": 5,
"additionalPorts": [],
"additionalBaudrates": [],
"blacklistedPorts": [],
"blacklistedBaudrates": [],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226", "M600"],
"blockedCommands": ["M0", "M1"],
"pausingCommands": ["M0", "M1", "M25"],
@@ -421,59 +423,7 @@ default_settings = {
},
"useFrozenDictForPrinterState": True,
"showLoadingAnimation": True,
"sockJsConnectTimeout": 10,
"virtualPrinter": {
"enabled": False,
"okAfterResend": False,
"forceChecksum": False,
"numExtruders": 1,
"pinnedExtruders": None,
"includeCurrentToolInTemps": True,
"includeFilenameInOpened": True,
"hasBed": True,
"hasChamber": False,
"repetierStyleTargetTemperature": False,
"okBeforeCommandOutput": False,
"smoothieTemperatureReporting": False,
"reprapfwM114": False,
"extendedSdFileList": False,
"throttle": 0.01,
"sendWait": True,
"waitInterval": 1.0,
"rxBuffer": 64,
"commandBuffer": 4,
"supportM112": True,
"echoOnM117": True,
"brokenM29": True,
"brokenResend": False,
"supportF": False,
"firmwareName": "Virtual Marlin 1.0",
"sharedNozzle": False,
"sendBusy": False,
"busyInterval": 2.0,
"simulateReset": True,
"resetLines": ['start', 'Marlin: Virtual Marlin!', '\x80', 'SD card ok'],
"preparedOks": [],
"okFormatString": "ok",
"m115FormatString": "FIRMWARE_NAME:{firmware_name} PROTOCOL_VERSION:1.0",
"m115ReportCapabilities": True,
"capabilities": {
"AUTOREPORT_TEMP": True,
"AUTOREPORT_SD_STATUS": True,
"EMERGENCY_PARSER": True
},
"m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}",
"ambientTemperature": 21.3,
"errors": {
"checksum_mismatch": "Checksum mismatch",
"checksum_missing": "Missing checksum",
"lineno_mismatch": "expected line {} got {}",
"lineno_missing": "No Line Number with checksum, Last Line: {}",
"maxtemp": "MAXTEMP triggered!",
"mintemp": "MINTEMP triggered!",
"command_unknown": "Unknown command {}"
}
}
"sockJsConnectTimeout": 10
}
}
"""The default settings of the core application."""
+1 -2
View File
@@ -303,8 +303,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
text = _.sprintf(gettext("There was an error while trying to start a print job. Error: %(error)s"), {error: _.escape(payload.error)});
break;
}
case "autodetect_port":
case "autodetect_baudrate": {
case "autodetect": {
// ignore
break;
}
+2 -3
View File
@@ -203,9 +203,8 @@ $(function() {
[
// printer states
gettext("Offline"),
gettext("Opening serial port"),
gettext("Detecting serial port"),
gettext("Detecting baudrate"),
gettext("Opening serial connection"),
gettext("Detecting serial connection"),
gettext("Connecting"),
gettext("Operational"),
gettext("Starting"),
@@ -176,6 +176,8 @@ $(function() {
self.serial_log = ko.observable(undefined);
self.serial_additionalPorts = ko.observable(undefined);
self.serial_additionalBaudrates = ko.observable(undefined);
self.serial_blacklistedPorts = ko.observable(undefined);
self.serial_blacklistedBaudrates = ko.observable(undefined);
self.serial_longRunningCommands = ko.observable(undefined);
self.serial_checksumRequiringCommands = ko.observable(undefined);
self.serial_blockedCommands = ko.observable(undefined);
@@ -826,6 +828,8 @@ $(function() {
serial: {
additionalPorts : function() { return commentableLinesToArray(self.serial_additionalPorts()) },
additionalBaudrates: function() { return _.map(splitTextToArray(self.serial_additionalBaudrates(), ",", true, function(item) { return !isNaN(parseInt(item)); }), function(item) { return parseInt(item); }) },
blacklistedPorts : function() { return commentableLinesToArray(self.serial_blacklistedPorts()) },
blacklistedBaudrates: function() { return _.map(splitTextToArray(self.serial_blacklistedBaudrates(), ",", true, function(item) { return !isNaN(parseInt(item)); }), function(item) { return parseInt(item); }) },
longRunningCommands: function() { return splitTextToArray(self.serial_longRunningCommands(), ",", true) },
checksumRequiringCommands: function() { return splitTextToArray(self.serial_checksumRequiringCommands(), ",", true) },
blockedCommands: function() { return splitTextToArray(self.serial_blockedCommands(), ",", true) },
@@ -966,6 +970,8 @@ $(function() {
serial: {
additionalPorts : function(value) { self.serial_additionalPorts(value.join("\n"))},
additionalBaudrates: function(value) { self.serial_additionalBaudrates(value.join(", "))},
blacklistedPorts : function(value) { self.serial_blacklistedPorts(value.join("\n"))},
blacklistedBaudrates: function(value) { self.serial_blacklistedBaudrates(value.join(", "))},
longRunningCommands: function(value) { self.serial_longRunningCommands(value.join(", "))},
checksumRequiringCommands: function(value) { self.serial_checksumRequiringCommands(value.join(", "))},
blockedCommands: function(value) { self.serial_blockedCommands(value.join(", "))},
@@ -43,6 +43,20 @@
<span class="help-inline">{{ _('Use this to define additional serial port baud rates to list for connecting with, e.g. <code>123456</code>. Comma separated.') }}</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-serialBlacklistedPorts">{{ _('Blacklisted serial ports') }}</label>
<div class="controls">
<textarea rows="4" class="block" id="settings-serialBlacklistedPorts" data-bind="value: serial_blacklistedPorts"></textarea>
<span class="help-inline">{{ _('Use this to define <a href="%%(glob_url)s">glob patterns</a> matching serial ports to blacklist for connecting against, e.g. <code>/dev/ttyS*</code>. One entry per line.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-serialBlacklistedBaudrates">{{ _('Blacklisted baud rates') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-serialBlacklistedBaudrates" data-bind="value: serial_blacklistedBaudrates">
<span class="help-inline">{{ _('Use this to define serial port baud rates to blacklist for connecting with, e.g. <code>123456</code>. Comma separated.') }}</span>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
-6
View File
@@ -1,6 +0,0 @@
The code in this sub package mostly originates from the Cura project (https://github.com/daid/Cura). It has been
slightly reorganized and adapted. The mapping to the original Cura source is the following:
* avr_isp.* => Cura.avr_isp.*
* comm => Cura.util.machineCom (highly modified now)
* gcodeInterpreter => Cura.util.gcodeInterpreter
-2
View File
@@ -1,2 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
-22
View File
@@ -1,22 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
avrChipDB = {
'ATMega1280': {
'signature': [0x1E, 0x97, 0x03],
'pageSize': 128,
'pageCount': 512,
},
'ATMega2560': {
'signature': [0x1E, 0x98, 0x01],
'pageSize': 128,
'pageCount': 1024,
},
}
def getChipFromDB(sig):
for chip in avrChipDB.values():
if chip['signature'] == sig:
return chip
return None
-39
View File
@@ -1,39 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import io
from builtins import range
def readHex(filename):
data = []
extraAddr = 0
f = io.open(filename, 'rt', encoding='utf-8')
for line in f:
line = line.strip()
if line[0] != ':':
raise Exception("Hex file has a line not starting with ':'")
recLen = int(line[1:3], 16)
addr = int(line[3:7], 16) + extraAddr
recType = int(line[7:9], 16)
if len(line) != recLen * 2 + 11:
raise Exception("Error in hex file: " + line)
checkSum = 0
for i in range(0, recLen + 5):
checkSum += int(line[i*2+1:i*2+3], 16)
checkSum &= 0xFF
if checkSum != 0:
raise Exception("Checksum error in hex file: " + line)
if recType == 0:#Data record
while len(data) < addr + recLen:
data.append(0)
for i in range(0, recLen):
data[addr + i] = int(line[i*2+9:i*2+11], 16)
elif recType == 1: #End Of File record
pass
elif recType == 2: #Extended Segment Address Record
extraAddr = int(line[9:13], 16) * 16
else:
print(recType, recLen, addr, checkSum, line)
f.close()
return data
-38
View File
@@ -1,38 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import os, struct, sys, time
from serial import Serial
from . import chipDB
class IspBase():
def programChip(self, flashData):
self.curExtAddr = -1
self.chip = chipDB.getChipFromDB(self.getSignature())
if not self.chip:
raise IspError("Chip with signature: " + str(self.getSignature()) + "not found")
self.chipErase()
print("Flashing %i bytes" % len(flashData))
self.writeFlash(flashData)
print("Verifying %i bytes" % len(flashData))
self.verifyFlash(flashData)
#low level ISP commands
def getSignature(self):
sig = []
sig.append(self.sendISP([0x30, 0x00, 0x00, 0x00])[3])
sig.append(self.sendISP([0x30, 0x00, 0x01, 0x00])[3])
sig.append(self.sendISP([0x30, 0x00, 0x02, 0x00])[3])
return sig
def chipErase(self):
self.sendISP([0xAC, 0x80, 0x00, 0x00])
class IspError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
-161
View File
@@ -1,161 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import os, struct, sys, time
from serial import Serial
from serial import SerialException, SerialTimeoutException
from builtins import range
from . import ispBase, intelHex
class Stk500v2(ispBase.IspBase):
def __init__(self):
self.serial = None
self.seq = 1
self.lastAddr = -1
self.progressCallback = None
def connect(self, port = 'COM22', speed = 115200):
if self.serial is not None:
self.close()
try:
self.serial = Serial(str(port), speed, timeout=1, writeTimeout=10000)
except SerialException:
raise ispBase.IspError("Failed to open serial port")
except Exception:
raise ispBase.IspError("Unexpected error while connecting to serial port:" + port + ":" + str(sys.exc_info()[0]))
self.seq = 1
#Reset the controller
self.serial.setDTR(1)
time.sleep(0.1)
self.serial.setDTR(0)
time.sleep(0.2)
self.sendMessage([1])
if self.sendMessage([0x10, 0xc8, 0x64, 0x19, 0x20, 0x00, 0x53, 0x03, 0xac, 0x53, 0x00, 0x00]) != [0x10, 0x00]:
self.close()
raise ispBase.IspError("Failed to enter programming mode")
def close(self):
if self.serial is not None:
self.serial.close()
self.serial = None
#Leave ISP does not reset the serial port, only resets the device, and returns the serial port after disconnecting it from the programming interface.
# This allows you to use the serial port without opening it again.
def leaveISP(self):
if self.serial is not None:
if self.sendMessage([0x11]) != [0x11, 0x00]:
raise ispBase.IspError("Failed to leave programming mode")
ret = self.serial
self.serial = None
return ret
return None
def isConnected(self):
return self.serial is not None
def sendISP(self, data):
recv = self.sendMessage([0x1D, 4, 4, 0, data[0], data[1], data[2], data[3]])
return recv[2:6]
def writeFlash(self, flashData):
#Set load addr to 0, in case we have more then 64k flash we need to enable the address extension
pageSize = self.chip['pageSize'] * 2
flashSize = pageSize * self.chip['pageCount']
if flashSize > 0xFFFF:
self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00])
else:
self.sendMessage([0x06, 0x00, 0x00, 0x00, 0x00])
loadCount = (len(flashData) + pageSize - 1) // pageSize
for i in range(0, loadCount):
self.sendMessage([0x13, pageSize >> 8, pageSize & 0xFF, 0xc1, 0x0a, 0x40, 0x4c, 0x20, 0x00, 0x00] + flashData[(i * pageSize):(i * pageSize + pageSize)])
if self.progressCallback is not None:
self.progressCallback(i + 1, loadCount*2)
def verifyFlash(self, flashData):
#Set load addr to 0, in case we have more then 64k flash we need to enable the address extension
flashSize = self.chip['pageSize'] * 2 * self.chip['pageCount']
if flashSize > 0xFFFF:
self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00])
else:
self.sendMessage([0x06, 0x00, 0x00, 0x00, 0x00])
loadCount = (len(flashData) + 0xFF) // 0x100
for i in range(0, loadCount):
recv = self.sendMessage([0x14, 0x01, 0x00, 0x20])[2:0x102]
if self.progressCallback is not None:
self.progressCallback(loadCount + i + 1, loadCount*2)
for j in range(0, 0x100):
if i * 0x100 + j < len(flashData) and flashData[i * 0x100 + j] != recv[j]:
raise ispBase.IspError('Verify error at: 0x%x' % (i * 0x100 + j))
def sendMessage(self, data):
message = struct.pack(">BBHB", 0x1B, self.seq, len(data), 0x0E)
for c in data:
message += struct.pack(">B", c)
checksum = 0
for c in bytearray(message):
checksum ^= c
message += struct.pack(">B", checksum)
try:
self.serial.write(message)
self.serial.flush()
except SerialTimeoutException:
raise ispBase.IspError('Serial send timeout')
self.seq = (self.seq + 1) & 0xFF
return self.recvMessage()
def recvMessage(self):
state = 'Start'
checksum = 0
while True:
for _ in range(0, 5):
s = self.serial.read()
if len(s) > 0:
break
else:
raise ispBase.IspError("Timeout")
b = struct.unpack(">B", s)[0]
checksum ^= b
#print(hex(b))
if state == 'Start':
if b == 0x1B:
state = 'GetSeq'
checksum = 0x1B
elif state == 'GetSeq':
state = 'MsgSize1'
elif state == 'MsgSize1':
msgSize = b << 8
state = 'MsgSize2'
elif state == 'MsgSize2':
msgSize |= b
state = 'Token'
elif state == 'Token':
if b != 0x0E:
state = 'Start'
else:
state = 'Data'
data = []
elif state == 'Data':
data.append(b)
if len(data) == msgSize:
state = 'Checksum'
elif state == 'Checksum':
if checksum != 0:
state = 'Start'
else:
return data
def main():
programmer = Stk500v2()
programmer.connect(port = sys.argv[1])
programmer.programChip(intelHex.readHex(sys.argv[2]))
sys.exit(1)
if __name__ == '__main__':
main()
+173 -150
View File
@@ -3,11 +3,16 @@ from __future__ import absolute_import, division, print_function, unicode_litera
__author__ = "Gina Häußge <osd@foosel.net> based on work by David Braam"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
__copyright__ = "Copyright (C) 2013 David Braam, Gina Häußge & others - Released under terms of the AGPLv3 License"
"""
The code in this file is based on Cura.util.machineCom from the Cura project from late 2012
(https://github.com/daid/Cura).
"""
import os
import glob
import fnmatch
import time
import re
import threading
@@ -30,9 +35,6 @@ import octoprint.plugin
from collections import deque
from octoprint.util.avr_isp import stk500v2
from octoprint.util.avr_isp import ispBase
from octoprint.settings import settings, default_settings
from octoprint.events import eventManager, Events
from octoprint.filemanager import valid_file_type
@@ -160,41 +162,58 @@ regex_resend_linenumber = re.compile(r"(N|N:)?(?P<n>%s)" % regex_int_pattern)
"""Regex to use for request line numbers in resend requests"""
def serialList():
baselist=[]
if os.name=="nt":
candidates = []
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM")
i=0
while(1):
baselist+=[winreg.EnumValue(key,i)[1]]
i+=1
i = 0
while True:
candidates += [winreg.EnumValue(key,i)[1]]
i += 1
except Exception:
pass
baselist = baselist \
+ glob.glob("/dev/ttyUSB*") \
+ glob.glob("/dev/ttyACM*") \
+ glob.glob("/dev/tty.usb*") \
+ glob.glob("/dev/cu.*") \
+ glob.glob("/dev/cuaU*") \
+ glob.glob("/dev/ttyS*") \
+ glob.glob("/dev/rfcomm*")
else:
candidates = glob.glob("/dev/ttyUSB*") \
+ glob.glob("/dev/ttyACM*") \
+ glob.glob("/dev/tty.usb*") \
+ glob.glob("/dev/cu.*") \
+ glob.glob("/dev/cuaU*") \
+ glob.glob("/dev/ttyS*") \
+ glob.glob("/dev/rfcomm*")
# additional ports
additionalPorts = settings().get(["serial", "additionalPorts"])
if additionalPorts:
for additional in additionalPorts:
baselist += glob.glob(additional)
candidates += glob.glob(additional)
hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.comm.transport.serial.additional_port_names")
for name, hook in hooks.items():
try:
candidates += hook(candidates)
except Exception:
logging.getLogger(__name__).exception("Error while retrieving additional "
"serial port names from hook {}".format(name))
# blacklisted ports
blacklistedPorts = settings().get(["serial", "blacklistedPorts"])
if blacklistedPorts:
for pattern in settings().get(["serial", "blacklistedPorts"]):
candidates = list(filter(lambda x: not fnmatch.fnmatch(x, pattern), candidates))
# last used port = first to try, move to start
prev = settings().get(["serial", "port"])
if prev in baselist:
baselist.remove(prev)
baselist.insert(0, prev)
if settings().getBoolean(["devel", "virtualPrinter", "enabled"]):
baselist.append("VIRTUAL")
return baselist
if prev in candidates:
candidates.remove(prev)
candidates.insert(0, prev)
def baudrateList():
# sorted by likelihood
candidates = [115200, 250000, 230400, 57600, 38400, 19200, 9600]
return candidates
def baudrateList(candidates=None):
if candidates is None:
# sorted by likelihood
candidates = [115200, 250000, 230400, 57600, 38400, 19200, 9600]
# additional baudrates prepended, sorted descending
additionalBaudrates = settings().get(["serial", "additionalBaudrates"])
@@ -204,6 +223,12 @@ def baudrateList():
except Exception:
_logger.warning("{} is not a valid additional baudrate, ignoring it".format(additional))
# blacklisted baudrates
blacklistedBaudrates = settings().get(["serial", "blacklistedBaudrates"])
if blacklistedBaudrates:
for baudrate in blacklistedBaudrates:
candidates.remove(baudrate)
# last used baudrate = first to try, move to start
prev = settings().getInt(["serial", "baudrate"])
if prev in candidates:
@@ -369,20 +394,19 @@ class MachineCom(object):
STATE_NONE = 0
STATE_OPEN_SERIAL = 1
STATE_DETECT_SERIAL = 2
STATE_DETECT_BAUDRATE = 3
STATE_CONNECTING = 4
STATE_OPERATIONAL = 5
STATE_STARTING = 6
STATE_PRINTING = 7
STATE_PAUSED = 8
STATE_PAUSING = 9
STATE_RESUMING = 10
STATE_FINISHING = 11
STATE_CLOSED = 12
STATE_ERROR = 13
STATE_CLOSED_WITH_ERROR = 14
STATE_TRANSFERING_FILE = 15
STATE_CANCELLING = 16
STATE_CONNECTING = 3
STATE_OPERATIONAL = 4
STATE_STARTING = 5
STATE_PRINTING = 6
STATE_PAUSED = 7
STATE_PAUSING = 8
STATE_RESUMING = 9
STATE_FINISHING = 10
STATE_CLOSED = 11
STATE_ERROR = 12
STATE_CLOSED_WITH_ERROR = 13
STATE_TRANSFERING_FILE = 14
STATE_CANCELLING = 15
# be sure to add anything here that signifies an operational state
OPERATIONAL_STATES = (STATE_PRINTING, STATE_STARTING, STATE_OPERATIONAL, STATE_PAUSED, STATE_CANCELLING,
@@ -401,6 +425,8 @@ class MachineCom(object):
CAPABILITY_SUPPORT_DETECTED = "detected"
CAPABILITY_SUPPORT_DISABLED = "disabled"
DETECTION_RETRIES = 3
def __init__(self, port=None, baudrate=None, callbackObject=None, printerProfileManager=None):
self._logger = logging.getLogger(__name__)
self._serialLogger = logging.getLogger("SERIAL")
@@ -423,8 +449,10 @@ class MachineCom(object):
self._printerProfileManager = printerProfileManager
self._state = self.STATE_NONE
self._serial = None
self._baudrateDetectList = []
self._baudrateDetectRetry = 0
self._detection_candidates = []
self._detection_retry = self.DETECTION_RETRIES
self._temperatureTargetSetThreshold = 25
self._tempOffsets = dict()
self._command_queue = CommandQueue()
@@ -706,11 +734,9 @@ class MachineCom(object):
if state == self.STATE_NONE:
return "Offline"
elif state == self.STATE_OPEN_SERIAL:
return "Opening serial port"
return "Opening serial connection"
elif state == self.STATE_DETECT_SERIAL:
return "Detecting serial port"
elif state == self.STATE_DETECT_BAUDRATE:
return "Detecting baudrate"
return "Detecting serial connection"
elif state == self.STATE_CONNECTING:
return "Connecting"
elif state == self.STATE_OPERATIONAL:
@@ -1635,25 +1661,21 @@ class MachineCom(object):
self._consecutive_timeouts = 0
#Open the serial port.
if not self._openSerial():
return
# Open the serial port
needs_detection = not (self._port and self._port != 'AUTO' and self._baudrate)
try_hello = False
try_hello = not settings().getBoolean(["serial", "waitForStartOnConnect"])
if not needs_detection:
self._changeState(self.STATE_OPEN_SERIAL)
if not self._open_serial(self._port, self._baudrate):
return
try_hello = not settings().getBoolean(["serial", "waitForStartOnConnect"])
self._changeState(self.STATE_CONNECTING)
else:
self._changeState(self.STATE_DETECT_SERIAL)
self._perform_detection_step(init=True)
self._log("Connected to: %s, starting monitor" % self._serial)
if self._baudrate == 0:
try_hello = False
self._log("Starting baud rate detection...")
self._changeState(self.STATE_DETECT_BAUDRATE)
# Some controllers (e.g. Original Prusa) don't appear to like too fast serial interaction after
# open, so let's wait a bit before the first baudrate detection step
time.sleep(settings().getFloat(["serial", "timeout", "baudrateDetectionPause"]))
self._perform_baudrate_detection_step(init=True)
else:
self._changeState(self.STATE_CONNECTING)
#Start monitoring the serial port.
self._timeout = self._ok_timeout = self._get_new_communication_timeout()
@@ -1715,7 +1737,7 @@ class MachineCom(object):
self._set_busy_protocol_interval(interval=busy_interval, callback=busyIntervalSet)
if self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_BAUDRATE):
if self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_SERIAL):
continue
##~~ debugging output handling
@@ -1752,7 +1774,7 @@ class MachineCom(object):
extra=dict(plugin=name))
continue
if self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_BAUDRATE):
if self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_SERIAL):
continue
def convert_line(line):
@@ -1836,7 +1858,7 @@ class MachineCom(object):
handled = self.isPrinting() and line == ""
# we don't have to process the rest if the line has already been handled fully
if handled and self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_BAUDRATE):
if handled and self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_SERIAL):
continue
##~~ position report processing
@@ -2193,10 +2215,10 @@ class MachineCom(object):
elif "toggle" in pause_triggers and pause_triggers["toggle"].search(line) is not None:
self.setPause(not self.isPaused())
### Baudrate detection
if self._state == self.STATE_DETECT_BAUDRATE:
### Serial detection
if self._state == self.STATE_DETECT_SERIAL:
if line == '' or monotonic_time() > self._timeout:
self._perform_baudrate_detection_step()
self._perform_detection_step()
elif 'start' in line or line.startswith('ok'):
self._onConnected()
if 'start' in line:
@@ -2348,42 +2370,77 @@ class MachineCom(object):
self._log(message + " " + general_message)
self._clear_to_send.set()
def _perform_baudrate_detection_step(self, init=False):
def _perform_detection_step(self, init=False):
def log(message):
self._log(message)
self._logger.info("Serial detection: {}".format(message))
if init:
timeout = settings().getFloat(["serial", "timeout", "connection"])
self._baudrateDetectList = baudrateList()
port = self._port
baudrate = self._baudrate
if port and port != "AUTO":
port_candidates = [port]
else:
port_candidates = serialList()
if baudrate:
baudrate_candidates = [baudrate]
elif len(port_candidates) == 1:
baudrate_candidates = baudrateList()
else:
# if we have no baudrate and more than one port we limit tested baudrates to
# the two most common plus any additionally configured ones
baudrate_candidates = baudrateList([115200, 250000])
self._detection_candidates = [(p, b) for p in port_candidates for b in baudrate_candidates]
log("Performing autodetection with {} " \
"port/baudrate candidates: {}".format(len(self._detection_candidates),
", ".join(map(lambda x: "{}@{}".format(x[0], x[1]),
self._detection_candidates))))
else:
timeout = settings().getFloat(["serial", "timeout", "detection"])
if self._baudrateDetectRetry > 0:
if self._serial.timeout != timeout:
self._serial.timeout = timeout
self._timeout = monotonic_time() + timeout
self._log("Baudrate test retry #{}".format(5 - self._baudrateDetectRetry))
self._baudrateDetectRetry -= 1
self._do_send_without_checksum(b"", log=False) # new line to reset things
self.sayHello(tags={"trigger:baudrate_detection", })
elif len(self._baudrateDetectList) > 0:
baudrate = self._baudrateDetectList.pop(0)
try:
self._serial.baudrate = baudrate
while len(self._detection_candidates) > 0:
if self._detection_retry < self.DETECTION_RETRIES:
if self._serial.timeout != timeout:
self._serial.timeout = timeout
self._timeout = monotonic_time() + timeout
self._log("Trying baudrate: {}".format(baudrate))
self._baudrateDetectRetry = 4
self._do_send_without_checksum(b"", log=False) # new line to reset things
self.sayHello(tags={"trigger:baudrate_detection", })
except Exception:
self._log("Unexpected error while setting baudrate {}: {}".format(baudrate, get_exception_string()))
self._logger.exception("Unexpected error while setting baudrate {}".format(baudrate))
log("Handshake attempt #{}".format(self._detection_retry + 1))
else:
error_text = "No more baudrates to test, and no suitable baudrate found."
self._trigger_error(error_text, "autodetect_baudrate")
self._detection_retry += 1
self._do_send_without_checksum(b"", log=False) # new line to reset things
self.sayHello(tags={"trigger:detection", })
return
else:
(p, b) = self._detection_candidates.pop(0)
try:
if self._serial is None or self._serial.port != p:
if not self._open_serial(p, b, trigger_errors=False):
log("Could not open port {}, baudrate {}, skipping".format(p, b))
continue
else:
self._serial.baudrate = b
if self._serial.timeout != timeout:
self._serial.timeout = timeout
self._timeout = monotonic_time() + timeout
log("Trying port {}, baudrate {}".format(p, b))
self._detection_retry = 0
except Exception:
self._log("Unexpected error while setting baudrate {}: {}".format(b, get_exception_string()))
self._logger.exception("Unexpected error while setting baudrate {}".format(b))
error_text = "No more candidates to test, and no working port/baudrate combination detected."
self._trigger_error(error_text, "autodetect")
def _finish_heatup(self):
if self._heating:
@@ -2444,7 +2501,9 @@ class MachineCom(object):
except KeyError:
output = template.format(**match.groupdict())
except Exception:
self._logger.debug("Could not proces template %s: %s", template_key, template, exc_info=1)
self._logger.debug("Could not process template {}: {}".format(template_key,
template),
exc_info=1)
output = None
if output is not None:
@@ -2645,54 +2704,14 @@ class MachineCom(object):
finally:
self._command_queue.task_done()
def _detect_port(self):
potentials = serialList()
self._log("Serial port list: %s" % (str(potentials)))
if len(potentials) == 1:
# short cut: only one port, let's try that
return potentials[0]
elif len(potentials) > 1:
programmer = stk500v2.Stk500v2()
for p in potentials:
serial_obj = None
try:
self._log("Trying {}".format(p))
programmer.connect(p)
serial_obj = programmer.leaveISP()
except Exception as e:
self._log("Could not connect to or enter programming mode on {}, might not be a printer or just not allow programming mode".format(p))
self._logger.info("Could not enter programming mode on {}: {}".format(p, e))
found = serial_obj is not None
programmer.close()
if found:
return p
return None
def _openSerial(self):
def default(_, port, baudrate, read_timeout):
if port is None or port == 'AUTO':
# no known port, try auto detection
self._changeState(self.STATE_DETECT_SERIAL)
port = self._detect_port()
if port is None:
error_text = "Failed to autodetect serial port, please set it manually."
self._trigger_error(error_text, "autodetect_port")
self._log(error_text)
return None
def _open_serial(self, port, baudrate, trigger_errors=True):
def default(_, p, b, timeout):
# connect to regular serial port
self._log("Connecting to: %s" % port)
self._dual_log("Connecting to port {}, baudrate {}".format(port, baudrate), level=logging.INFO)
serial_port_args = {
"baudrate": baudrateList()[0] if baudrate == 0 else baudrate,
"timeout": read_timeout,
"baudrate": baudrate,
"timeout": timeout,
"write_timeout": 0,
}
@@ -2700,7 +2719,7 @@ class MachineCom(object):
serial_port_args["exclusive"] = True
serial_obj = serial.Serial(**serial_port_args)
serial_obj.port = str(port)
serial_obj.port = str(p)
use_parity_workaround = settings().get(["serial", "useParityWorkaround"])
needs_parity_workaround = get_os() == "linux" and os.path.exists("/etc/debian_version") # See #673
@@ -2727,23 +2746,27 @@ class MachineCom(object):
serial_factories = list(self._serial_factory_hooks.items()) + [("default", default)]
for name, factory in serial_factories:
try:
serial_obj = factory(self, self._port, self._baudrate, settings().getFloat(["serial", "timeout", "connection"]))
serial_obj = factory(self,
port,
baudrate,
settings().getFloat(["serial", "timeout", "connection"]))
except Exception:
exception_string = get_exception_string()
self._trigger_error("Connection error, see Terminal tab", "connection")
error_message = "Unexpected error while connecting to serial port: %s %s (hook %s)" % (self._port, exception_string, name)
if trigger_errors:
self._trigger_error("Connection error, see Terminal tab", "connection")
error_message = "Unexpected error while connecting to " \
"serial port {}, baudrate {} from hook {}: {}".format(port,
baudrate,
name,
exception_string)
self._log(error_message)
self._logger.exception(error_message)
if "failed to set custom baud rate" in exception_string.lower():
self._log("Your installation does not support custom baudrates (e.g. 250000) for connecting to your printer. This is a problem of the pyserial library that OctoPrint depends on. Please update to a pyserial version that supports your baudrate or switch your printer's firmware to a standard baudrate (e.g. 115200). See https://github.com/OctoPrint/OctoPrint/wiki/OctoPrint-support-for-250000-baud-rate-on-Raspbian")
return False
if serial_obj is not None:
# first hook to succeed wins, but any can pass on to the next
self._changeState(self.STATE_OPEN_SERIAL)
self._serial = serial_obj
self._clear_to_send.reset()
return True