WIP first throw at scripts

Currently broken:
  * temperature and position logging in context
  * pausing and cancelling
This commit is contained in:
Gina Häußge committed 2018-06-07 17:49:35 +02:00
1 parent 02252d1254
commit 701208484a
6 files changed
+260 -64

No files matched your search

+3
View File
@@ -114,6 +114,9 @@ class Protocol(ListenerAware, TransportListener):
def send_commands(self, command_type=None, *commands):
pass
def send_script(self, script, context=None):
pass
def repair(self):
pass
+67 -28
View File
@@ -16,7 +16,7 @@ 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, SendToken, LineHistory, QueueMarker, SendQueueMarker, PositionRecord
from octoprint.comm.protocol.reprap.util import normalize_command_handler_result, SendQueue, SendToken, LineHistory, QueueMarker, SendQueueMarker, PositionRecord, TemperatureRecord
from octoprint.comm.job import LocalGcodeFilePrintjob, SDFilePrintjob, \
LocalGcodeStreamjob
@@ -135,7 +135,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._internal_flags = dict(
# temperature and heating related
temperatures=dict(),
temperatures=TemperatureRecord(),
heating_start=None,
heating_lost=0,
heating=False,
@@ -193,6 +193,10 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._last_lines = LineHistory(maxlen = 50)
self._last_communication_error = None
# last known temperatures
self.pause_temperature = TemperatureRecord()
self.cancel_temperature = TemperatureRecord()
# last known positions
self.last_position = PositionRecord()
self.pause_position = PositionRecord()
@@ -341,8 +345,8 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
# cancel the job
self.state = ProtocolState.CANCELLING
self.notify_listeners("on_protocol_job_cancelling", self, self._job)
self._job.cancel(error=error)
self.notify_listeners("on_protocol_job_cancelling", self, self._job)
if log_position:
self.send_commands(self.flavor.command_finish_moving(),
@@ -394,8 +398,8 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
tags = set()
self.state = ProtocolState.PAUSING
self.notify_listeners("on_protocol_job_pausing", self, self._job)
self._job.pause()
self.notify_listeners("on_protocol_job_pausing", self, self._job)
if suppress_scripts_and_commands:
with self._suppress_scripts_mutex:
@@ -536,6 +540,28 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
elif self._is_operational() or force:
self._send_commands(*commands, on_sent=on_sent, command_type=command_type, tags=tags)
def send_script(self, script, context=None):
if context is None:
context = dict()
# TODO printer profile
context.update(dict(last_position=self.last_position))
if script.name == "afterPrintPaused" or script.name == "beforePrintResumed":
context.update(dict(pause_position=self.pause_position,
pause_temperature=self.pause_temperature.as_script_dict()))
elif script.name == "afterPrintCancelled":
context.update(dict(cancel_position=self.cancel_position,
cancel_temperature=self.cancel_temperature.as_script_dict()))
lines = script.render(context=context)
self.send_commands(tags={"trigger:protocol.send_script",
"source:script",
"script:{}".format(script.name)}, *lines)
def repair(self):
self._on_comm_ok()
##~~ State handling
def _is_operational(self):
@@ -564,7 +590,23 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._clear_to_send.set()
def poll_temperature_interval():
return self.interval["temperature_printing"] if self.state == ProtocolState.PROCESSING else self.interval["temperature_idle"]
printing_default = 4.0
target_default = 2.0
threshold = 25
if self.state in ProtocolState.PROCESSING_STATES:
return self.interval.get("temperature_printing", printing_default)
tools = self._internal_flags["temperatures"].tools
for temp in [tools[k][1] for k in tools]:
if temp > threshold:
return self.interval.get("temperature_target_set", target_default)
bed = self.last_temperatur.bed
if bed and len(bed) > 0 and bed[1] > threshold:
return self.interval.get("temperature_target_set", target_default)
return self.interval.get("temperature_idle")
def poll_temperature():
if self._is_operational() \
@@ -604,11 +646,13 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self.state = ProtocolState.FINISHING
self.notify_listeners("on_protocol_job_finishing", self, job)
self._job_processed(job)
def finalize():
self.state = ProtocolState.CONNECTED
self.notify_listeners("on_protocol_job_done", self, job)
self.send_commands(SendQueueMarker(finalize))
self._continue_sending()
def _job_processed(self, job):
self._internal_flags["expect_continous_comms"] = False
@@ -968,16 +1012,20 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
self._internal_flags["heating"] = True
self._internal_flags["heatup_start"] = monotonic_time()
potential_tools = dict(("T{}".format(x), "tool{}".format(x)) for x in range(max_tool_num + 1))
potential_tools.update(dict(B="bed"))
for tool_rep, tool in potential_tools.items():
if not tool_rep in temperatures:
for x in range(max_tool_num + 1):
tool = "T{}".format(x)
if not tool in temperatures:
# TODO shared nozzle
continue
actual, target = temperatures[tool_rep]
self._set_temperature(tool, actual, target)
else:
actual, target = temperatures[tool]
self._internal_flags["temperatures"].set_tool(x, actual=actual, target=target)
self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"])
if "B" in temperatures:
actual, target = temperatures["B"]
self._internal_flags["temperatures"].set_bed(actual=actual, target=target)
self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"].as_dict())
def _on_message_position(self, position):
self.last_position.valid = True
@@ -1006,14 +1054,14 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
reason = "pause"
self._record_pause_data = False
self.pause_position.copy_from(self.last_position)
#self.pause_temperature.copy_from(self.last_temperature) # TODO pause temperature
self.pause_temperature.copy_from(self._internal_flags["temperatures"])
self._pause_preparation_done()
if self._record_cancel_data:
reason = "cancel"
self._record_cancel_data = False
self.cancel_position.copy_from(self.last_position)
#self.cancel_temperature.copy_from(self.last_temperature) # TODO cancel temperature
self.cancel_temperature.copy_from(self._internal_flags["temperatures"])
self._cancel_preparation_done()
self.notify_listeners("on_protocol_position_all_update", self, position, reason=reason)
@@ -1659,9 +1707,8 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
target = float(command.r)
if target:
tool = "tool{}".format(tool_num)
self._set_temperature(tool, None, target)
self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"])
self._internal_flags["temperatures"].set_tool(tool_num, target=target)
self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"].as_dict())
def _gcode_M140_sent(self, command, wait=False, support_r=False):
target = None
@@ -1671,8 +1718,8 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
target = float(command.r)
if target:
self._set_temperature("bed", None, target)
self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"])
self._internal_flags["temperatures"].set_bed(target=target)
self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"].as_dict())
def _gcode_M109_sent(self, command):
self._internal_flags["heatup_start"] = monotonic_time()
@@ -1825,14 +1872,6 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
##~~ helpers
def _set_temperature(self, tool, actual, target):
temperatures = self._internal_flags["temperatures"]
if actual is None and tool in temperatures:
actual, _ = temperatures[tool]
if target is None and tool in temperatures:
_, target = temperatures[tool]
temperatures[tool] = (actual, target)
def _get_timeout(self, timeout_type):
if timeout_type in self.timeouts:
return monotonic_time() + self.timeouts[timeout_type]
@@ -0,0 +1,17 @@
# coding=utf-8
from __future__ import absolute_import, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.scripts import Script
from octoprint.comm.protocol.reprap.util import process_gcode_line
class GcodeScript(Script):
def render(self, context=None):
script = super(GcodeScript, self).render(context)
return filter(lambda x: x is not None and x.strip() != "",
map(lambda x: process_gcode_line(x),
script))
@@ -418,3 +418,73 @@ class PositionRecord(object):
attrs = self._standard_attrs | set([key for key in dir(self) if self.valid_e(key)])
return dict((attr, getattr(self, attr)) for attr in attrs)
class TemperatureRecord(object):
def __init__(self):
self._tools = dict()
self._bed = (None, None)
def copy_from(self, other):
self._tools = other.tools
self._bed = other.bed
def set_tool(self, tool, actual=None, target=None):
current = self._tools.get(tool, (None, None))
self._tools[tool] = self._to_new_tuple(current, actual, target)
def set_bed(self, actual=None, target=None):
current = self._bed
self._bed = self._to_new_tuple(current, actual, target)
@property
def tools(self):
return dict(self._tools)
@property
def bed(self):
return self._bed
def as_dict(self):
result = dict()
tools = self.tools
for tool, data in tools.items():
result["tool{}".format(tool)] = dict(actual=data[0],
target=data[1])
bed = self.bed
result["bed"] = dict(actual=bed[0],
target=bed[1])
return result
def as_script_dict(self):
result = self.as_dict()
# backwards compatibility
tools = self.tools
for tool, data in tools.items():
result[tool] = dict(actual=data[0],
target=data[1])
bed = self.bed
result["b"] = dict(actual=bed[0],
target=bed[1])
return result
@classmethod
def _to_new_tuple(cls, current, actual, target):
if current is None or not isinstance(current, tuple) or len(current) != 2:
current = (None, None)
if actual is None and target is None:
return current
old_actual, old_target = current
if actual is None:
return old_actual, target
elif target is None:
return actual, old_target
else:
return actual, target
+25
View File
@@ -0,0 +1,25 @@
# coding=utf-8
from __future__ import absolute_import, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
class Script(object):
def __init__(self, name, renderer, context=None):
if context is None:
context = dict()
self.name = name
self.renderer = renderer
self.context = context
def render(self, context=None):
if context is None:
context = dict()
render_context = dict(self.context)
render_context.update(context)
return self.renderer(render_context).split("\n")
+78 -36
View File
@@ -12,6 +12,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import copy
import logging
import os
import string
import threading
import time
@@ -31,8 +32,8 @@ from octoprint.util import InvariantContainer
from octoprint.util import to_unicode
from octoprint.comm.protocol import ProtocolListener, FileAwareProtocolListener, PositionAwareProtocolListener, ProtocolState
from octoprint.comm.job import StoragePrintjob, LocalGcodeFilePrintjob, LocalGcodeStreamjob, SDFilePrintjob
from octoprint.comm.protocol.reprap.scripts import GcodeScript
from collections import namedtuple
@@ -368,14 +369,16 @@ class Printer(PrinterInterface,
if name is None or not name:
raise ValueError("name must be set")
# TODO
#result = self._comm.sendGcodeScript(name,
# replacements=context,
# tags=kwargs.get("tags", set()) | {"trigger:printer.script"})
#if not result:
# if must_be_set:
# raise UnknownScript(name)
# return
if context is None:
context = dict()
def render(context):
lines = settings().loadScript("gcode", name, context=context)
if lines is None and must_be_set:
raise UnknownScript(name)
return lines
script = GcodeScript(name, render, context=context)
self._protocol.send_script(script)
def jog(self, axes, relative=True, speed=None, *args, **kwargs):
if isinstance(axes, basestring):
@@ -388,12 +391,23 @@ class Printer(PrinterInterface,
if not isinstance(amount, (int, long, float)):
raise ValueError("amount must be a valid number: {amount}".format(amount=amount))
printer_profile = self._printer_profile_manager.get_current_or_default()
movement_speed = printer_profile["axes"][axis]["speed"]
axes = dict()
axes[axis] = amount
kwargs = dict(feedrate=movement_speed,
relative=True)
kwargs[axis] = amount
if not axes:
raise ValueError("At least one axis to jog must be provided")
for axis in axes:
if not axis in PrinterInterface.valid_axes:
raise ValueError("Invalid axis {}, valid axes are {}".format(axis, ", ".join(PrinterInterface.valid_axes)))
if speed is None:
printer_profile = self._printer_profile_manager.get_current_or_default()
speed = max(*map(lambda x: printer_profile["axes"][x]["speed"], axes))
kwargs = dict(feedrate=speed,
relative=relative)
kwargs.update(axes)
self._protocol.move(**kwargs)
def home(self, axes, *args, **kwargs):
@@ -913,9 +927,9 @@ class Printer(PrinterInterface,
temperatures = dict()
entry = dict(time=int(time.time()))
for tool in temperatures.keys():
entry[tool] = dict(actual=temperatures[tool][0],
target=temperatures[tool][1])
for tool in temperatures:
entry[tool] = dict(actual=temperatures[tool]["actual"],
target=temperatures[tool]["target"])
self._temperature_history.append(entry)
self._state_monitor.add_temperature(entry)
@@ -1041,13 +1055,13 @@ class Printer(PrinterInterface,
#~~ octoprint.comm.protocol.ProtocolListener implementation
def on_protocol_log(self, protocol, message):
def on_protocol_log(self, protocol, message, *args, **kwargs):
if protocol != self._protocol:
return
self._add_log(message)
def on_protocol_state(self, protocol, old_state, new_state):
def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs):
if protocol != self._protocol:
return
@@ -1080,7 +1094,7 @@ class Printer(PrinterInterface,
self._set_state(new_state)
def on_protocol_temperature(self, protocol, temperatures):
def on_protocol_temperature(self, protocol, temperatures, *args, **kwargs):
if protocol != self._protocol:
return
@@ -1088,14 +1102,14 @@ class Printer(PrinterInterface,
#~~ octoprint.comm.protocol.FileAwareProtocolListener implementation
def on_protocol_file_storage_available(self, protocol, available):
def on_protocol_file_storage_available(self, protocol, available, *args, **kwargs):
if protocol != self._protocol:
return
self._sd_ready = available
self._state_monitor.set_state({"text": self.get_state_string(), "flags": self._get_state_flags()})
def on_protocol_file_list(self, protocol, files):
def on_protocol_file_list(self, protocol, files, *args, **kwargs):
if protocol != self._protocol:
return
@@ -1105,7 +1119,7 @@ class Printer(PrinterInterface,
#~~ octoprint.comm.protocol.PositionAwareProtocolListener implementation
def on_protocol_position_z_update(self, protocol, z):
def on_protocol_position_z_update(self, protocol, z, *args, **kwargs):
if protocol != self._protocol:
return
@@ -1132,7 +1146,7 @@ class Printer(PrinterInterface,
context=dict(event=payload),
must_be_set=False)
def on_protocol_job_done(self, protocol, job, suppress_script=False):
def on_protocol_job_finishing(self, protocol, job, suppress_script=False, *args, **kwargs):
if protocol != self._protocol:
return
@@ -1202,13 +1216,22 @@ class Printer(PrinterInterface,
return
firmware_error = kwargs.get("error", None)
cancel_position = kwargs.get("position", None)
suppress_scripts = kwargs.get("suppress_scripts", None)
payload = job.event_payload()
if payload:
if firmware_error:
payload["firmwareError"] = firmware_error
if cancel_position:
payload["position"] = cancel_position
eventManager().fire(Events.PRINT_CANCELLING, payload)
if not suppress_scripts:
self.script("afterPrintCancelled",
context=dict(event=payload),
must_be_set=False)
def on_protocol_job_cancelled(self, protocol, job, *args, **kwargs):
if protocol != self._protocol:
return
@@ -1219,7 +1242,6 @@ class Printer(PrinterInterface,
self._update_progress_data()
cancel_position = kwargs.get("position", None)
suppress_scripts = kwargs.get("suppress_scripts", None)
payload = job.event_payload()
if payload:
@@ -1228,10 +1250,6 @@ class Printer(PrinterInterface,
payload["position"] = cancel_position
eventManager().fire(Events.PRINT_CANCELLED, payload)
if not suppress_scripts:
self.script("afterPrintCancelled",
context=dict(event=payload),
must_be_set=False)
def finalize():
self._file_manager.log_print(job.storage,
@@ -1246,7 +1264,7 @@ class Printer(PrinterInterface,
thread.daemon = True
thread.start()
def on_protocol_job_paused(self, protocol, job, *args, **kwargs):
def on_protocol_job_pausing(self, protocol, job, *args, **kwargs):
if protocol != self._protocol:
return
@@ -1260,13 +1278,28 @@ class Printer(PrinterInterface,
if payload:
if pause_position:
payload["position"] = pause_position
eventManager().fire(Events.PRINT_PAUSED, payload)
#eventManager().fire(Events.PRINT_PAUSED, payload)
if not suppress_scripts:
self.script("afterPrintPaused",
context=dict(event=payload),
must_be_set=False)
def on_protocol_job_resumed(self, protocol, job, *args, **kwargs):
def on_protocol_job_paused(self, protocol, job, *args, **kwargs):
if protocol != self._protocol:
return
if self._job is None or job != self._job.job:
return
pause_position = kwargs.get("position", None)
payload = job.event_payload()
if payload:
if pause_position:
payload["position"] = pause_position
eventManager().fire(Events.PRINT_PAUSED, payload)
def on_protocol_job_resuming(self, protocol, job, *args, **kwargs):
if protocol != self._protocol:
return
@@ -1275,13 +1308,22 @@ class Printer(PrinterInterface,
suppress_scripts = kwargs.get("suppress_scripts", False)
payload = job.event_payload()
if payload and not suppress_scripts:
self.script("beforePrintResumed",
context=dict(event=payload),
must_be_set=False)
def on_protocol_job_resumed(self, protocol, job, *args, **kwargs):
if protocol != self._protocol:
return
if self._job is None or job != self._job.job:
return
payload = job.event_payload()
if payload:
eventManager().fire(Events.PRINT_RESUMED, payload)
if not suppress_scripts:
self.script("beforePrintResumed",
context=dict(event=payload),
must_be_set=False)
# ~~ octoprint.comm.job.PrintjobListener implementation