Add firmware & capability reporting, temp autoreports

Also refactored flavors to make adding additional ones (e.g. from
plugins) even easier.
This commit is contained in:
Gina Häußge committed 2018-05-31 10:19:15 +02:00
1 parent ba00b4d675
commit eab0ce8aee
9 files changed
+810 -553

No files matched your search

+108 -9
View File
@@ -14,6 +14,8 @@ from octoprint.comm.protocol.reprap.commands import Command, to_command
from octoprint.comm.protocol.reprap.commands.atcommand import AtCommand
from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
from octoprint.comm.protocol.reprap.flavors import GenericFlavor, all_flavors
from octoprint.comm.protocol.reprap.util import normalize_command_handler_result, SendQueue, LineHistory
from octoprint.util import TypedQueue, TypeAlreadyInQueue
@@ -36,7 +38,7 @@ import threading
import time
gcode_to_event = {
GCODE_TO_EVENT = {
# pause for user input
"M226": Events.WAITING,
"M0": Events.WAITING,
@@ -67,6 +69,9 @@ gcode_to_event = {
"M81": Events.POWER_OFF,
}
CAPABILITY_AUTOREPORT_TEMP = "AUTOREPORT_TEMP"
CAPABILITY_AUTOREPORT_SD_STATUS = "AUTOREPORT_SD_STATUS"
CAPABILITY_BUSY_PROTOCOL = "BUSY_PROTOCOL"
class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProtocolMixin,
FanControlProtocolMixin, FileStreamingProtocolMixin,
@@ -84,20 +89,27 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
def get_attributes_starting_with(cls, prefix):
return dict((x, getattr(cls, x)) for x in dir(cls) if x.startswith(prefix))
def __init__(self, flavor, connection_timeout=30.0, communication_timeout=5.0,
temperature_interval_idle=5.0, temperature_interval_printing=5.0):
def __init__(self, flavor=None,
connection_timeout=30.0,
communication_timeout=10.0,
temperature_interval_idle=5.0,
temperature_interval_printing=5.0,
temperature_interval_autoreport=2.0,
sd_status_interval_autoreport=1.0):
super(ReprapGcodeProtocol, self).__init__()
self._phase_logger = logging.getLogger(__name__ + ".command_phases")
self.flavor = flavor
self.flavor = flavor if flavor is not None else GenericFlavor
self.timeouts = dict(
connection=connection_timeout,
communication=communication_timeout
)
self.interval = dict(
temperature_idle=temperature_interval_idle,
temperature_printing=temperature_interval_printing
temperature_printing=temperature_interval_printing,
temperature_autoreport=temperature_interval_autoreport,
sd_status_autoreport=sd_status_interval_autoreport
)
flavor_comm_attrs = self.get_flavor_attributes_starting_with(self.flavor, "comm_")
@@ -111,6 +123,9 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._handlers_atcommand = self.get_attributes_starting_with("_atcommand_")
self._handlers_command_phase = self.get_attributes_starting_with("_command_phase_")
self._capability_support = dict()
self._capability_support[CAPABILITY_AUTOREPORT_TEMP] = True
self._transport = None
self._internal_state = dict(
@@ -119,6 +134,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
heating_start=None,
heating_lost=0,
heating=False,
temperature_autoreporting=False,
# current stuff
current_tool=0,
@@ -129,6 +145,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
sd_available=False,
sd_files=[],
sd_files_temp=None,
sd_status_autoreporting=False,
# resend status
resend_requested=None,
@@ -146,6 +163,12 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
# timeout
timeout = None,
timeout_consecutive=0,
# firmware info
firmware_identified=False,
firmware_name=None,
firmware_info=dict(),
firmware_capabilities=dict()
)
self._protected_state = protectedkeydict(self._internal_state)
@@ -358,7 +381,10 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
return self.interval["temperature_printing"] if self.state == ProtocolState.PROCESSING else self.interval["temperature_idle"]
def poll_temperature():
if self._is_operational() and not self._internal_state["only_from_job"] and self.can_send():
if self._is_operational() \
and not self._internal_state["temperature_autoreporting"] \
and not self._internal_state["only_from_job"] \
and self.can_send():
self._send_command(self.flavor.command_get_temp(), command_type="temperature_poll")
from octoprint.util import RepeatedTimer
@@ -690,6 +716,33 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self.notify_listeners("on_protocol_temperature", self, self._internal_state["temperatures"])
def _on_message_firmware_info(self, firmware_name, data):
# TODO
#self._event_bus.fire(Events.FIRMWARE_DATA, dict(name=firmware_name, data=copy.copy(data)))
if not self._internal_state["firmware_identified"] and firmware_name:
self._logger.info("Printer reports firmware name \"{}\"".format(firmware_name))
for flavor in all_flavors():
if flavor.identifier and callable(flavor.identifier) and flavor.identifier(firmware_name, data):
self._logger.info("Detected firmware flavor \"{}\", switching...".format(flavor.key))
self._switch_flavor(flavor)
self._internal_state["firmware_identified"] = True
self._internal_state["firmware_name"] = firmware_name
self._internal_state["firmware_info"] = data
def _on_message_firmware_capability(self, cap, enabled):
self._internal_state["firmware_capabilities"][cap] = enabled
if self._capability_support.get(cap, False):
if cap == CAPABILITY_AUTOREPORT_TEMP and enabled:
self._logger.info("Firmware states that it supports temperature autoreporting")
self._set_autoreport_temperature_interval()
elif cap == CAPABILITY_AUTOREPORT_SD_STATUS and enabled:
self._logger.info("Firmware states that it supports sd status autoreporting")
self._set_autoreport_sdstatus_interval()
def _on_message_sd_init_ok(self):
self._internal_state["sd_available"] = True
self.list_files()
@@ -891,7 +944,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
# trigger the "queued" phase only if we are not streaming to sd right now
self._process_command_phase("queued", command)
if self._internal_state["trigger_events"] and isinstance(command, GcodeCommand) and command.code in gcode_to_event:
if self._internal_state["trigger_events"] and isinstance(command, GcodeCommand) and command.code in GCODE_TO_EVENT:
# TODO inject eventbus
#self._eventbus.fire(gcode_to_event[command.code])
pass
@@ -1228,6 +1281,24 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
pass
_gcode_M190_queuing = _gcode_M140_queuing
def _gcode_M155_sending(self, command):
try:
interval = int(command.s)
self._internal_state["temperature_autoreporting"] = self._internal_state["firmware_capabilities"].get(CAPABILITY_AUTOREPORT_TEMP,
False) \
and (interval > 0)
except:
pass
def _gcode_M27_sending(self, command):
try:
interval = int(command.s)
self._internal_state["sd_status_autoreporting"] = self._internal_state["firmware_capabilities"].get(CAPABILITY_AUTOREPORT_SD_STATUS,
False) \
and (interval > 0)
except:
pass
def _gcode_M104_sent(self, command, wait=False, support_r=False):
tool_num = self._internal_state["current_tool"]
if command.t:
@@ -1370,6 +1441,24 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
if gcode is not None and gcode.code in self.flavor.long_running_commands:
self._internal_state["long_running_command"] = True
##~~ autoreporting
def _set_autoreport_temperature_interval(self, interval=None):
if interval is None:
try:
interval = int(self.interval.get("temperature_autoreport", 2))
except:
interval = 2
self.send_commands(self.flavor.command_autoreport_temperature(interval=interval))
def _set_autoreport_sdstatus_interval(self, interval=None):
if interval is None:
try:
interval = int(self.interval.get("sd_status_autoreport", 1))
except:
interval = 1
self.send_commands(self.flavor.command_autoreport_sd_status(interval=interval))
##~~ helpers
def _set_temperature(self, tool, actual, target):
@@ -1392,11 +1481,21 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
log = message + u"\n| " + log
self._logger.log(level, log)
def _switch_flavor(self, new_flavor):
self.flavor = new_flavor
flavor_comm_attrs = self.get_flavor_attributes_starting_with(self.flavor, "comm_")
flavor_message_attrs = self.get_flavor_attributes_starting_with(self.flavor, "message_")
flavor_error_attrs = self.get_flavor_attributes_starting_with(self.flavor, "error_")
self._registered_messages = flavor_comm_attrs + flavor_message_attrs
self._error_messages = flavor_error_attrs
if __name__ == "__main__":
from octoprint.comm.transport.serialtransport import VirtualSerialTransport
from octoprint.comm.protocol.reprap.virtual import VirtualPrinter
from octoprint.comm.protocol.reprap.flavors import ReprapGcodeFlavor
from octoprint.comm.protocol.reprap.flavors import GenericFlavor
from octoprint.comm.protocol import ProtocolListener, FileAwareProtocolListener
from octoprint.job import PrintjobListener
@@ -1466,7 +1565,7 @@ if __name__ == "__main__":
self.start_next_job()
transport = VirtualSerialTransport(virtual_serial_factory=virtual_serial_factory)
protocol = ReprapGcodeProtocol(ReprapGcodeFlavor)
protocol = ReprapGcodeProtocol()
protocol_listener = CustomProtocolListener(protocol)
protocol_listener.add_job(LocalGcodeFilePrintjob(os.path.join(virtual_sd, filename)))
@@ -1,532 +1,13 @@
# coding=utf-8
from __future__ import absolute_import, unicode_literals, print_function, \
division
from __future__ import absolute_import, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import re
import logging
import time
from .generic import *
from .marlin import *
from .repetier import *
from .reprapfirmware import *
from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
from octoprint.comm.protocol.reprap.util import regex_float_pattern, regex_positive_float_pattern, regex_int_pattern
# TODO needed? move?
from octoprint.util import chunks
class ReprapGcodeFlavor(object):
key = "generic"
logger = logging.getLogger(__name__)
unknown_requires_ack = False
unknown_with_checksum = False
always_send_checksum = False
never_send_checksum = False
checksum_requiring_commands = ["M110"]
long_running_commands = ["G4", "G28", "G29", "G30", "G32", "M190", "M109", "M400", "M226"]
asynchronous_commands = ["G0", "G1", "G2", "G3"]
regex_resend_linenumber = re.compile("(N|N:)?(?P<n>%s)" % regex_int_pattern)
"""Regex to use for request line numbers in resend requests"""
regex_temp = re.compile("(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?" % (regex_positive_float_pattern, regex_positive_float_pattern))
"""Regex matching temperature entries in line.
Groups will be as follows:
* ``tool``: whole tool designator, incl. optional ``toolnum`` (str)
* ``toolnum``: tool number, if provided (int)
* ``actual``: actual temperature (float)
* ``target``: target temperature, if provided (float)
"""
regex_position = re.compile("(?P<axis>X|Y|Z|E):(?P<pos>{float})\s*".format(float=regex_float_pattern))
"""Regex for matching position entries in line.
Groups will be as follows:
* ``axis``: axis designator, either ``X``, ``Y``, ``Z`` or ``E`` (str)
* ``pos``: axis position (float)
"""
regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):")
"""Regex to use for splitting M115 responses."""
regex_sd_file_opened = re.compile("file opened:\s*(?P<name>.*?)(\s+size:\s*(?P<size>[0-9]+)|$)")
regex_sd_printing_byte = re.compile("sd printing byte (?P<current>[0-9]*)/(?P<total>[0-9]*)")
"""Regex matching SD printing status reports.
Groups will be as follows:
* ``current``: current byte position in file being printed
* ``total``: total size of file being printed
"""
##~~ Message matchers
@classmethod
def comm_timeout(cls, line, lower_line, state):
return line == "" and time.time() > state["timeout"]
@classmethod
def comm_ok(cls, line, lower_line, state):
return lower_line.startswith("ok"), cls.message_temperature(line, lower_line, state) \
or cls.message_position(line, lower_line, state) \
or cls.message_firmware_info(line, lower_line, state)
@classmethod
def comm_start(cls, line, lower_line, state):
return lower_line.startswith("start")
@classmethod
def comm_wait(cls, line, lower_line, state):
return lower_line.startswith("wait")
@classmethod
def comm_resend(cls, line, lower_line, state):
return lower_line.startswith("resend") or lower_line.startswith("rs")
@classmethod
def comm_debug(cls, line, lower_line, state):
return line.startswith("//")
@classmethod
def comm_error(cls, line, lower_line, state):
return line.startswith("Error:") or line.startswith("!!")
@classmethod
def comm_ignore_ok(cls, line, lower_line, state):
return False
@classmethod
def error_multiline(cls, line, lower_line, state):
return False
@classmethod
def error_communication(cls, line, lower_line, state):
return "line number" in lower_line or "checksum" in lower_line or "format error" in lower_line or "expected line" in lower_line
@classmethod
def message_temperature(cls, line, lower_line, state):
return "T:" in line or "T0:" in line or "B:" in line
@classmethod
def message_position(cls, line, lower_line, state):
return "C:" in line or "X:" in line
@classmethod
def message_firmware_info(cls, line, lower_line, state):
return "NAME:" in line
@classmethod
def message_sd_init_ok(cls, line, lower_line, state):
return "sd card ok" in lower_line
@classmethod
def message_sd_init_fail(cls, line, lower_line, state):
return "sd init fail" in lower_line or "volume.init failed" in lower_line or "openroot failed" in lower_line
@classmethod
def message_sd_file_opened(cls, line, lower_line, state):
return lower_line.startswith("file opened")
@classmethod
def message_sd_file_selected(cls, line, lower_line, state):
return lower_line.startswith("file selected")
@classmethod
def message_sd_begin_file_list(cls, line, lower_line, state):
return lower_line.startswith("begin file list")
@classmethod
def message_sd_end_file_list(cls, line, lower_line, state):
return lower_line.startswith("end file list")
@classmethod
def message_sd_printing_byte(cls, line, lower_line, state):
return "sd printing byte" in lower_line
@classmethod
def message_sd_not_printing(cls, line, lower_line, state):
return "not sd printing" in lower_line
@classmethod
def message_sd_done_printing(cls, line, lower_line, state):
return "done printing file" in lower_line
@classmethod
def message_sd_begin_writing(cls, line, lower_line, state):
return "writing to file" in lower_line
@classmethod
def message_sd_end_writing(cls, line, lower_line, state):
return "done saving file" in lower_line
@classmethod
def message_sd_entry(cls, line, lower_line, state):
return state["sd_files_temp"] is not None
##~~ Message parsers
@classmethod
def parse_comm_error(cls, line, lower_line, state):
return dict(line=line, lower_line=lower_line)
@classmethod
def parse_error_communication(cls, line, lower_line, state):
if "line number" in lower_line or "expected line" in lower_line:
error_type = "linenumber"
elif "checksum" in lower_line:
error_type = "checksum"
else:
error_type = "other"
state["last_communication_error"] = error_type
return dict(error_type=error_type)
@classmethod
def parse_comm_resend(cls, line, lower_line, state):
line_to_resend = None
match = cls.regex_resend_linenumber.search(line)
if match is not None:
line_to_resend = int(match.group(b"n"))
return dict(linenumber=line_to_resend)
@classmethod
def parse_message_temperature(cls, line, lower_line, state):
"""
Parses the provided temperature line.
The result will be a dictionary mapping from the extruder or bed key to
a tuple with current and target temperature. The result will be canonicalized
with :func:`canonicalize_temperatures` before returning.
Returns:
tuple: a 2-tuple with the maximum tool number and a dict mapping from
key to (actual, target) tuples, with key either matching ``Tn`` for ``n >= 0`` or ``B``
"""
current_tool = state["current_tool"]
result = {}
max_tool_num = 0
for match in re.finditer(cls.regex_temp, line):
values = match.groupdict()
tool = values["tool"]
if tool == "T" and "toolnum" in values and values["toolnum"]:
tool_num = int(values["toolnum"])
if tool_num > max_tool_num:
max_tool_num = tool_num
try:
actual = float(values.get("actual", None)) if values.get("actual", None) is not None else None
target = float(values.get("target", None)) if values.get("target", None) is not None else None
result[tool] = actual, target
except ValueError:
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
pass
heatup_detected = not lower_line.startswith("ok") and not state["heating"]
return dict(max_tool_num=max(max_tool_num, current_tool),
temperatures=cls._canonicalize_temperatures(result, current_tool),
heatup_detected=heatup_detected)
@classmethod
def parse_message_position(cls, line, lower_line, state):
position = dict(x=None, y=None, z=None, e=None)
for match in re.finditer(cls.regex_position, line):
position[match.group(b"axis").lower()] = float(match.group(b"pos"))
return position
@classmethod
def parse_message_firmware_info(cls, line, lower_line, state):
data = cls._parse_firmware_line(line)
firmware_name = data.get("FIRMWARE_NAME")
if firmware_name is None:
# Malyan's "Marlin compatible firmware" isn't actually Marlin compatible and doesn't even
# report its firmware name properly in response to M115. Wonderful - why stick to established
# protocol when you can do your own thing, right?
#
# Example: NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02
#
# We do a bit of manual fiddling around here to circumvent that issue and get ourselves a
# reliable firmware name (NAME + VER) out of the Malyan M115 response.
name = data.get("NAME")
ver = data.get("VER")
if "malyan" in name.lower() and ver:
firmware_name = name.strip() + " " + ver.strip()
return dict(firmware_name=firmware_name,
data=data)
@classmethod
def parse_message_sd_file_opened(cls, line, lower_line, state):
match = cls.regex_sd_file_opened.match(lower_line)
if not match:
return
return dict(name=match.group(b"name"), size=int(match.group(b"size")))
@classmethod
def parse_message_sd_entry(cls, line, lower_line, state):
fileinfo = lower_line.rsplit(None, 1)
if len(fileinfo) > 1:
# we might have extended file information here, so let's split filename and size and try to make them a bit nicer
filename, size = fileinfo
try:
size = int(size)
except ValueError:
# whatever that was, it was not an integer, so we'll just use the whole line as filename and set size to None
filename = lower_line
size = None
else:
# no extended file information, so only the filename is there and we set size to None
filename = lower_line
size = None
from octoprint.util import filter_non_ascii
if filter_non_ascii(filename):
return None
else:
if not filename.startswith("/"):
# file from the root of the sd -- we'll prepend a /
filename = "/" + filename
return dict(name=filename, size=int(size) if size is not None else None)
@classmethod
def parse_message_sd_printing_byte(cls, line, lower_line, state):
match = cls.regex_sd_printing_byte.match(lower_line)
if not match:
return None
return dict(current=int(match.group(b"current")), total=int(match.group(b"total")))
##~~ Commands
@classmethod
def command_hello(cls):
return cls.command_set_line(0)
@classmethod
def command_get_temp(cls):
return GcodeCommand("M105")
@classmethod
def command_set_line(cls, n):
return GcodeCommand("M110", n=n)
@classmethod
def command_emergency_stop(cls):
return GcodeCommand("M112")
@classmethod
def command_set_extruder_temp(cls, s, t, wait):
return GcodeCommand("M109" if wait else "M104", s=s, t=t)
@classmethod
def command_set_bed_temp(cls, s, wait):
return GcodeCommand("M190" if wait else "M140", s=s)
@classmethod
def command_set_relative_positioning(cls):
return GcodeCommand("G91")
@classmethod
def command_set_absolute_positioning(cls):
return GcodeCommand("G90")
@classmethod
def command_move(cls, x=None, y=None, z=None, e=None, f=None):
return GcodeCommand("G1", x=x, y=y, z=z, e=e, f=f)
@classmethod
def command_extrude(cls, e=None, f=None):
return cls.command_move(e=e, f=f)
@classmethod
def command_home(cls, x=False, y=False, z=False):
return GcodeCommand("G28", x=0 if x else None, y=0 if y else None, z=0 if z else None)
@classmethod
def command_set_tool(cls, tool):
return GcodeCommand("T{}".format(tool))
@classmethod
def command_set_feedrate_multiplier(cls, multiplier):
return GcodeCommand("M220", s=multiplier)
@classmethod
def command_set_extrusion_multiplier(cls, multiplier):
return GcodeCommand("M221", s=multiplier)
@classmethod
def command_set_fan_speed(cls, speed):
return GcodeCommand("M106", s=speed)
@classmethod
def command_set_motors(cls, enable):
return GcodeCommand("M17") if enable else GcodeCommand("M18")
@classmethod
def command_sd_refresh(cls):
return GcodeCommand("M20")
@classmethod
def command_sd_init(cls):
return GcodeCommand("M21")
@classmethod
def command_sd_release(cls):
return GcodeCommand("M22")
@classmethod
def command_sd_select_file(cls, name):
return GcodeCommand("M23", param=name)
@classmethod
def command_sd_start(cls):
return GcodeCommand("M24")
@classmethod
def command_sd_pause(cls):
return GcodeCommand("M25")
@classmethod
def command_sd_set_pos(cls, pos):
return GcodeCommand("M26", s=pos)
@classmethod
def command_sd_status(cls):
return GcodeCommand("M27")
@classmethod
def command_sd_begin_write(cls, name):
return GcodeCommand("M28", param=name)
@classmethod
def command_sd_end_write(cls):
return GcodeCommand("M29")
@classmethod
def command_sd_delete(cls, name):
return GcodeCommand("M30", param=name)
##~~ Helpers
@classmethod
def _canonicalize_temperatures(cls, parsed, current):
"""
Canonicalizes the temperatures provided in parsed.
Will make sure that returned result only contains extruder keys
like Tn, so always qualified with a tool number.
The algorithm for cleaning up the parsed keys is the following:
* If ``T`` is not included with the reported extruders, return
* If more than just ``T`` is reported:
* If both ``T`` and ``T0`` are reported set ``Tc`` to ``T``, remove
``T`` from the result.
* Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra).
* If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T``
* return
Arguments:
parsed (dict): the parsed temperatures (mapping tool => (actual, target))
to canonicalize
current (int): the current active extruder
Returns:
dict: the canonicalized version of ``parsed``
"""
reported_extruders = filter(lambda x: x.startswith("T"), parsed.keys())
if not "T" in reported_extruders:
# Our reported_extruders are either empty or consist purely
# of Tn keys, no need for any action
return parsed
current_tool_key = "T%d" % current
result = dict(parsed)
if len(reported_extruders) > 1:
if "T0" in reported_extruders:
# Both T and T0 are present, so T contains the current
# extruder's temperature, e.g. for current_tool == 1:
#
# T:<T1> T0:<T0> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T1> T1:<T1> T2:<T2> ... B:<B>
#
# Same goes if Tc is already present, it will be overwritten:
#
# T:<T1> T0:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result[current_tool_key] = result["T"]
del result["T"]
else:
# So T is there, but T0 isn't. That looks like Smoothieware which
# always reports the first extruder T0 as T:
#
# T:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result["T0"] = result["T"]
del result["T"]
else:
# We only have T. That can mean two things:
#
# * we only have one extruder at all, or
# * we are currently parsing a response to M109/M190, which on
# some firmwares doesn't report the full M105 output while
# waiting for the target temperature to be reached but only
# reports the current tool and bed
#
# In both cases it is however safe to just move our T over
# to T<current> in the parsed data, current should always stay
# 0 for single extruder printers. E.g. for current_tool == 1:
#
# T:<T1>
#
# becomes
#
# T1:<T1>
result[current_tool_key] = result["T"]
del result["T"]
return result
@classmethod
def _parse_firmware_line(cls, line):
"""
Parses the provided firmware info line.
The result will be a dictionary mapping from the contained keys to the contained
values.
Arguments:
line (str): the line to parse
Returns:
dict: a dictionary with the parsed data
"""
result = dict()
split_line = cls.regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string
for key, value in chunks(split_line, 2):
result[key] = value
return result
from .anet import *
from .malyan import *
@@ -0,0 +1,11 @@
from .repetier import RepetierFlavor
class AnetA8RepetierFlavor(RepetierFlavor):
key = "aneta8repetier"
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "anet_a8" in firmware_name.lower()
@@ -0,0 +1,635 @@
# coding=utf-8
from __future__ import absolute_import, unicode_literals, print_function, \
division
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import re
import logging
import time
from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
from octoprint.comm.protocol.reprap.util import regex_float_pattern, regex_positive_float_pattern, regex_int_pattern
# TODO needed? move?
from octoprint.util import chunks
_flavor_registry = dict()
def _register_flavor(cls):
key = getattr(cls, b"key", None)
if key and not key in _flavor_registry:
_flavor_registry[key] = cls
def all_flavors():
return _flavor_registry.values()
def flavor(key):
return _flavor_registry.get(key)
class FlavorMeta(type):
def __new__(mcs, name, bases, class_dict):
cls = type.__new__(mcs, name, bases, class_dict)
_register_flavor(cls)
return cls
class GenericFlavor(object):
__metaclass__ = FlavorMeta
key = "generic"
logger = logging.getLogger(__name__)
unknown_requires_ack = False
unknown_with_checksum = False
always_send_checksum = False
never_send_checksum = False
detect_external_heatups = True
sd_relative_path = False
checksum_requiring_commands = ["M110"]
long_running_commands = ["G4", "G28", "G29", "G30", "G32", "M190", "M109", "M400", "M226"]
asynchronous_commands = ["G0", "G1", "G2", "G3"]
regex_resend_linenumber = re.compile("(N|N:)?(?P<n>%s)" % regex_int_pattern)
"""Regex to use for request line numbers in resend requests"""
regex_temp = re.compile("(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?" % (
regex_positive_float_pattern, regex_positive_float_pattern))
"""Regex matching temperature entries in line.
Groups will be as follows:
* ``tool``: whole tool designator, incl. optional ``toolnum`` (str)
* ``toolnum``: tool number, if provided (int)
* ``actual``: actual temperature (float)
* ``target``: target temperature, if provided (float)
"""
regex_position = re.compile("(?P<axis>X|Y|Z|E):(?P<pos>{float})\s*".format(float=regex_float_pattern))
"""Regex for matching position entries in line.
Groups will be as follows:
* ``axis``: axis designator, either ``X``, ``Y``, ``Z`` or ``E`` (str)
* ``pos``: axis position (float)
"""
regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):")
"""Regex to use for splitting M115 responses."""
regex_sd_file_opened = re.compile("file opened:\s*(?P<name>.*?)(\s+size:\s*(?P<size>[0-9]+)|$)")
regex_sd_printing_byte = re.compile("sd printing byte (?P<current>[0-9]*)/(?P<total>[0-9]*)")
"""Regex matching SD printing status reports.
Groups will be as follows:
* ``current``: current byte position in file being printed
* ``total``: total size of file being printed
"""
##~~ Identifier
@classmethod
def identifier(cls, firmware_name, firmware_info):
return False
##~~ Message matchers
@classmethod
def comm_timeout(cls, line, lower_line, state):
return line == "" and time.time() > state["timeout"]
@classmethod
def comm_ok(cls, line, lower_line, state):
return lower_line.startswith("ok"), cls.message_temperature(line, lower_line, state) \
or cls.message_position(line, lower_line, state) \
or cls.message_firmware_info(line, lower_line, state)
@classmethod
def comm_start(cls, line, lower_line, state):
return lower_line.startswith("start")
@classmethod
def comm_wait(cls, line, lower_line, state):
return lower_line.startswith("wait")
@classmethod
def comm_resend(cls, line, lower_line, state):
return lower_line.startswith("resend") or lower_line.startswith("rs")
@classmethod
def comm_debug(cls, line, lower_line, state):
return line.startswith("//")
@classmethod
def comm_error(cls, line, lower_line, state):
return line.startswith("Error:") or line.startswith("!!")
@classmethod
def comm_ignore_ok(cls, line, lower_line, state):
return False
@classmethod
def error_multiline(cls, line, lower_line, state):
return False
@classmethod
def error_communication(cls, line, lower_line, state):
return "line number" in lower_line or "checksum" in lower_line or "format error" in lower_line or "expected line" in lower_line
@classmethod
def message_temperature(cls, line, lower_line, state):
return "T:" in line or "T0:" in line or "B:" in line
@classmethod
def message_position(cls, line, lower_line, state):
return "C:" in line or "X:" in line
@classmethod
def message_firmware_info(cls, line, lower_line, state):
return "NAME:" in line
@classmethod
def message_firmware_capability(cls, line, lower_line, state):
return lower_line.startswith("cap:")
@classmethod
def message_sd_init_ok(cls, line, lower_line, state):
return "sd card ok" in lower_line
@classmethod
def message_sd_init_fail(cls, line, lower_line, state):
return "sd init fail" in lower_line or "volume.init failed" in lower_line or "openroot failed" in lower_line
@classmethod
def message_sd_file_opened(cls, line, lower_line, state):
return lower_line.startswith("file opened")
@classmethod
def message_sd_file_selected(cls, line, lower_line, state):
return lower_line.startswith("file selected")
@classmethod
def message_sd_begin_file_list(cls, line, lower_line, state):
return lower_line.startswith("begin file list")
@classmethod
def message_sd_end_file_list(cls, line, lower_line, state):
return lower_line.startswith("end file list")
@classmethod
def message_sd_printing_byte(cls, line, lower_line, state):
return "sd printing byte" in lower_line
@classmethod
def message_sd_not_printing(cls, line, lower_line, state):
return "not sd printing" in lower_line
@classmethod
def message_sd_done_printing(cls, line, lower_line, state):
return "done printing file" in lower_line
@classmethod
def message_sd_begin_writing(cls, line, lower_line, state):
return "writing to file" in lower_line
@classmethod
def message_sd_end_writing(cls, line, lower_line, state):
return "done saving file" in lower_line
@classmethod
def message_sd_entry(cls, line, lower_line, state):
return state["sd_files_temp"] is not None
##~~ Message parsers
@classmethod
def parse_comm_error(cls, line, lower_line, state):
return dict(line=line, lower_line=lower_line)
@classmethod
def parse_error_communication(cls, line, lower_line, state):
if "line number" in lower_line or "expected line" in lower_line:
error_type = "linenumber"
elif "checksum" in lower_line:
error_type = "checksum"
else:
error_type = "other"
state["last_communication_error"] = error_type
return dict(error_type=error_type)
@classmethod
def parse_comm_resend(cls, line, lower_line, state):
line_to_resend = None
match = cls.regex_resend_linenumber.search(line)
if match is not None:
line_to_resend = int(match.group(b"n"))
return dict(linenumber=line_to_resend)
@classmethod
def parse_message_temperature(cls, line, lower_line, state):
"""
Parses the provided temperature line.
The result will be a dictionary mapping from the extruder or bed key to
a tuple with current and target temperature. The result will be canonicalized
with :func:`canonicalize_temperatures` before returning.
Returns:
tuple: a 2-tuple with the maximum tool number and a dict mapping from
key to (actual, target) tuples, with key either matching ``Tn`` for ``n >= 0`` or ``B``
"""
current_tool = state["current_tool"]
result = {}
max_tool_num = 0
for match in re.finditer(cls.regex_temp, line):
values = match.groupdict()
tool = values["tool"]
if tool == "T" and "toolnum" in values and values["toolnum"]:
tool_num = int(values["toolnum"])
if tool_num > max_tool_num:
max_tool_num = tool_num
try:
actual = float(values.get("actual", None)) if values.get("actual", None) is not None else None
target = float(values.get("target", None)) if values.get("target", None) is not None else None
result[tool] = actual, target
except ValueError:
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
pass
heatup_detected = not lower_line.startswith("ok") and not state["heating"]
return dict(max_tool_num=max(max_tool_num, current_tool),
temperatures=cls._canonicalize_temperatures(result, current_tool),
heatup_detected=heatup_detected)
@classmethod
def parse_message_position(cls, line, lower_line, state):
position = dict(x=None, y=None, z=None, e=None)
for match in re.finditer(cls.regex_position, line):
position[match.group(b"axis").lower()] = float(match.group(b"pos"))
return position
@classmethod
def parse_message_firmware_info(cls, line, lower_line, state):
data = cls._parse_firmware_line(line)
firmware_name = data.get("FIRMWARE_NAME")
if firmware_name is None:
# Malyan's "Marlin compatible firmware" isn't actually Marlin compatible and doesn't even
# report its firmware name properly in response to M115. Wonderful - why stick to established
# protocol when you can do your own thing, right?
#
# Example: NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02
#
# We do a bit of manual fiddling around here to circumvent that issue and get ourselves a
# reliable firmware name (NAME + VER) out of the Malyan M115 response.
name = data.get("NAME")
ver = data.get("VER")
if "malyan" in name.lower() and ver:
firmware_name = name.strip() + " " + ver.strip()
if firmware_name is not None:
firmware_name = firmware_name.strip()
return dict(firmware_name=firmware_name,
data=data)
@classmethod
def parse_message_firmware_capability(cls, line, lower_line, state):
result = cls._parse_capability_line(line)
if not result:
return
cap, enabled = result
return dict(cap=cap, enabled=enabled)
@classmethod
def parse_message_sd_file_opened(cls, line, lower_line, state):
match = cls.regex_sd_file_opened.match(lower_line)
if not match:
return
return dict(name=match.group(b"name"), size=int(match.group(b"size")))
@classmethod
def parse_message_sd_entry(cls, line, lower_line, state):
fileinfo = lower_line.rsplit(None, 1)
if len(fileinfo) > 1:
# we might have extended file information here, so let's split filename and size and try to make them a bit nicer
filename, size = fileinfo
try:
size = int(size)
except ValueError:
# whatever that was, it was not an integer, so we'll just use the whole line as filename and set size to None
filename = lower_line
size = None
else:
# no extended file information, so only the filename is there and we set size to None
filename = lower_line
size = None
from octoprint.util import filter_non_ascii
if filter_non_ascii(filename):
return None
else:
if not filename.startswith("/"):
# file from the root of the sd -- we'll prepend a /
filename = "/" + filename
return dict(name=filename, size=int(size) if size is not None else None)
@classmethod
def parse_message_sd_printing_byte(cls, line, lower_line, state):
match = cls.regex_sd_printing_byte.match(lower_line)
if not match:
return None
return dict(current=int(match.group(b"current")), total=int(match.group(b"total")))
##~~ Commands
@classmethod
def command_hello(cls):
return cls.command_set_line(0)
@classmethod
def command_get_temp(cls):
return GcodeCommand("M105")
@classmethod
def command_set_line(cls, n):
return GcodeCommand("M110", n=n)
@classmethod
def command_emergency_stop(cls):
return GcodeCommand("M112")
@classmethod
def command_set_extruder_temp(cls, s, t, wait):
return GcodeCommand("M109" if wait else "M104", s=s, t=t)
@classmethod
def command_set_bed_temp(cls, s, wait):
return GcodeCommand("M190" if wait else "M140", s=s)
@classmethod
def command_set_relative_positioning(cls):
return GcodeCommand("G91")
@classmethod
def command_set_absolute_positioning(cls):
return GcodeCommand("G90")
@classmethod
def command_move(cls, x=None, y=None, z=None, e=None, f=None):
return GcodeCommand("G1", x=x, y=y, z=z, e=e, f=f)
@classmethod
def command_extrude(cls, e=None, f=None):
return cls.command_move(e=e, f=f)
@classmethod
def command_home(cls, x=False, y=False, z=False):
return GcodeCommand("G28", x=0 if x else None, y=0 if y else None, z=0 if z else None)
@classmethod
def command_set_tool(cls, tool):
return GcodeCommand("T{}".format(tool))
@classmethod
def command_set_feedrate_multiplier(cls, multiplier):
return GcodeCommand("M220", s=multiplier)
@classmethod
def command_set_extrusion_multiplier(cls, multiplier):
return GcodeCommand("M221", s=multiplier)
@classmethod
def command_set_fan_speed(cls, speed):
return GcodeCommand("M106", s=speed)
@classmethod
def command_set_motors(cls, enable):
return GcodeCommand("M17") if enable else GcodeCommand("M18")
@classmethod
def command_sd_refresh(cls):
return GcodeCommand("M20")
@classmethod
def command_sd_init(cls):
return GcodeCommand("M21")
@classmethod
def command_sd_release(cls):
return GcodeCommand("M22")
@classmethod
def command_sd_select_file(cls, name):
return GcodeCommand("M23", param=name)
@classmethod
def command_sd_start(cls):
return GcodeCommand("M24")
@classmethod
def command_sd_pause(cls):
return GcodeCommand("M25")
@classmethod
def command_sd_set_pos(cls, pos):
return GcodeCommand("M26", s=pos)
@classmethod
def command_sd_status(cls):
return GcodeCommand("M27")
@classmethod
def command_sd_begin_write(cls, name):
return GcodeCommand("M28", param=name)
@classmethod
def command_sd_end_write(cls):
return GcodeCommand("M29")
@classmethod
def command_sd_delete(cls, name):
return GcodeCommand("M30", param=name)
@classmethod
def command_autoreport_temperature(cls, interval):
return GcodeCommand("M155", s=interval)
@classmethod
def command_autoreport_sd_status(cls, interval):
return GcodeCommand("M27", s=interval)
@classmethod
def command_busy_protocol_interval(cls, interval):
return GcodeCommand("M113", s=interval)
##~~ Helpers
@classmethod
def _canonicalize_temperatures(cls, parsed, current):
"""
Canonicalizes the temperatures provided in parsed.
Will make sure that returned result only contains extruder keys
like Tn, so always qualified with a tool number.
The algorithm for cleaning up the parsed keys is the following:
* If ``T`` is not included with the reported extruders, return
* If more than just ``T`` is reported:
* If both ``T`` and ``T0`` are reported set ``Tc`` to ``T``, remove
``T`` from the result.
* Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra).
* If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T``
* return
Arguments:
parsed (dict): the parsed temperatures (mapping tool => (actual, target))
to canonicalize
current (int): the current active extruder
Returns:
dict: the canonicalized version of ``parsed``
"""
reported_extruders = filter(lambda x: x.startswith("T"), parsed.keys())
if not "T" in reported_extruders:
# Our reported_extruders are either empty or consist purely
# of Tn keys, no need for any action
return parsed
current_tool_key = "T%d" % current
result = dict(parsed)
if len(reported_extruders) > 1:
if "T0" in reported_extruders:
# Both T and T0 are present, so T contains the current
# extruder's temperature, e.g. for current_tool == 1:
#
# T:<T1> T0:<T0> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T1> T1:<T1> T2:<T2> ... B:<B>
#
# Same goes if Tc is already present, it will be overwritten:
#
# T:<T1> T0:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result[current_tool_key] = result["T"]
del result["T"]
else:
# So T is there, but T0 isn't. That looks like Smoothieware which
# always reports the first extruder T0 as T:
#
# T:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result["T0"] = result["T"]
del result["T"]
else:
# We only have T. That can mean two things:
#
# * we only have one extruder at all, or
# * we are currently parsing a response to M109/M190, which on
# some firmwares doesn't report the full M105 output while
# waiting for the target temperature to be reached but only
# reports the current tool and bed
#
# In both cases it is however safe to just move our T over
# to T<current> in the parsed data, current should always stay
# 0 for single extruder printers. E.g. for current_tool == 1:
#
# T:<T1>
#
# becomes
#
# T1:<T1>
result[current_tool_key] = result["T"]
del result["T"]
return result
@classmethod
def _parse_firmware_line(cls, line):
"""
Parses the provided firmware info line.
The result will be a dictionary mapping from the contained keys to the contained
values.
Arguments:
line (unicode): the line to parse
Returns:
dict: a dictionary with the parsed data
"""
result = dict()
split_line = cls.regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string
for key, value in chunks(split_line, 2):
result[key] = value
return result
@classmethod
def _parse_capability_line(cls, line):
"""
Parses the provided firmware capability line.
Lines are expected to be of the format
Cap:<capability name in caps>:<0 or 1>
e.g.
Cap:AUTOREPORT_TEMP:1
Cap:TOGGLE_LIGHTS:0
Args:
line (unicode): the line to parse
Returns:
tuple: a 2-tuple of the parsed capability name and whether it's on (true) or off (false), or None if the line
could not be parsed
"""
line = line.lower()
if line.startswith("cap:"):
line = line[len("cap:"):]
parts = line.split(":")
if len(parts) != 2:
# wrong format, can't parse this
return None
capability, flag = parts
if not flag in ("0", "1"):
# wrong format, can't parse this
return None
return capability.upper(), flag == "1"
@@ -0,0 +1,15 @@
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class MalyanFlavor(GenericFlavor):
key = "malyan"
always_send_checksum = False
block_while_dwelling = True
sd_always_available = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "malyan" in firmware_name.lower()
@@ -7,9 +7,9 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors import ReprapGcodeFlavor
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class MarlinFlavor(ReprapGcodeFlavor):
class MarlinFlavor(GenericFlavor):
key = "marlin"
@@ -7,19 +7,20 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors import ReprapGcodeFlavor
from octoprint.comm.protocol.reprap.flavors import GenericFlavor
from octoprint.comm.protocol.gcode.util import regex_positive_float_pattern
from octoprint.comm.protocol.reprap.util import regex_positive_float_pattern
import re
class RepetierFlavor(ReprapGcodeFlavor):
class RepetierFlavor(GenericFlavor):
key = "repetier"
always_send_checksum = True
identical_resends_countdown = 5
block_while_dwelling = True
detect_external_heatups = False
regex_tempextr = re.compile("targetextr(?P<toolnum>\d+):(?P<target>%s)" % regex_positive_float_pattern)
"""Regex for matching target temp reporting from Repetier.
@@ -39,36 +40,40 @@ class RepetierFlavor(ReprapGcodeFlavor):
* ``target``: new target temperature (float)
"""
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "repetier" in firmware_name.lower()
@classmethod
def message_temperature(cls, line, lower_line, state):
return ReprapGcodeFlavor.message_temperature(line, lower_line, state) or "targetextr" in lower_line or "targetbed" in lower_line
return GenericFlavor.message_temperature(line, lower_line, state) or "targetextr" in lower_line or "targetbed" in lower_line
@classmethod
def parse_message_temperature(cls, line, lower_line, state):
if "targetextr" in lower_line:
match = cls.regex_tempextr.match(lower_line)
if match is not None:
tool_num = int(match.group("toolnum"))
target = float(match.group("target"))
tool_num = int(match.group(b"toolnum"))
target = float(match.group(b"target"))
tool = "T{}".format(tool_num)
temperatures = dict()
temperatures[tool] = (None, target)
return dict(max_tool_num=max(tool_num, state.get("current_tool", 0)),
temperatures=temperatures,
detected_heatup=False)
heatup_detected=False)
elif "targetbed" in lower_line:
match = cls.regex_tempbed.match(lower_line)
if match is not None:
target = float(match.group("target"))
target = float(match.group(b"target"))
temperatures = dict(bed=(None, target))
return dict(max_tool_num=state.get("current_tool", 0),
temperatures=temperatures,
detected_heatup=False)
heatup_detected=False)
else:
# Repetier sends temperature output on it's own line, so we can't use the
# "no ok in temperature output" metric to detected external heatups
result = ReprapGcodeFlavor.parse_message_temperature(line, lower_line, state)
result["heating"] = False
result = GenericFlavor.parse_message_temperature(line, lower_line, state)
result[b"heatup_detected"] = False
return result
@@ -89,4 +94,3 @@ class RepetierFlavor(ReprapGcodeFlavor):
state["resend_swallow_repetitions_counter"] = cls.identical_resends_countdown
@@ -0,0 +1,13 @@
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class ReprapFirmwareFlavor(GenericFlavor):
key = "reprapfirmware"
sd_relative_path = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "reprapfirmware" in firmware_name.lower()
+1 -2
View File
@@ -293,8 +293,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
# TODO make this depend on the printer profile
from octoprint.comm.protocol.reprap import ReprapGcodeProtocol
from octoprint.comm.protocol.reprap.flavors.marlin import BqMarlinFlavor
protocol = ReprapGcodeProtocol(BqMarlinFlavor)
protocol = ReprapGcodeProtocol()
protocol.register_listener(self)
self._transport = transport