Merge branch 'devel' of github:foosel/OctoPrint into dev/permission
This commit is contained in:
commit
fbd8a97ffd
16 files changed
+361
-162
No files matched your search
@@ -198,6 +198,13 @@ Version checks
|
||||
* ``branch``: Branch of the Bitbucket repository to check, defaults to
|
||||
``master`` if not set.
|
||||
* ``current``: Current commit hash. Will be updated automatically.
|
||||
* ``api_user``: (mandatory only for private repositories) Bitbucket user name (not email address).
|
||||
Requires ``api_password`` to be set. Hint: This is used for the check only. For the actual
|
||||
download you might register your public SSH key as access key for the according repo and
|
||||
configure this as pip URL in ``config.yaml``: ``git+ssh://git@bitbucket.org/my_user/my_repo.git@{target_version}``
|
||||
* ``api_password``: (mandatory only for private repositories) App password. Requires
|
||||
``api_user`` to be set. **Important**: Never use your actual Bitbucket login password. Generate
|
||||
a new app password. App passwords are user specific on Bitbucket.
|
||||
|
||||
* ``git_commit``: Checks a local git repository for new commits on its
|
||||
configured remote. Additional config parameters:
|
||||
|
||||
@@ -389,7 +389,7 @@ This describes actually four hooks:
|
||||
* ``octoprint.comm.protocol.gcode.sending``
|
||||
* ``octoprint.comm.protocol.gcode.sent``
|
||||
|
||||
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs)
|
||||
.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, *args, **kwargs)
|
||||
|
||||
Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases
|
||||
are the following:
|
||||
@@ -488,6 +488,8 @@ This describes actually four hooks:
|
||||
:param str cmd_type: Type of command, e.g. ``temperature_poll`` for temperature polling or ``sd_status_poll`` for SD
|
||||
printing status polling.
|
||||
:param str gcode: Parsed GCODE command, e.g. ``G0`` or ``M110``, may also be None if no known command could be parsed
|
||||
:param str subcode: Parsed subcode of the GCODE command, e.g. ``1`` for ``M80.1``. Will be None if no subcode was provided
|
||||
or no command could be parsed.
|
||||
:return: None, 1-tuple, 2-tuple or string, see the description above for details.
|
||||
|
||||
.. _sec-plugins-hook-comm-protocol-gcode-received:
|
||||
|
||||
@@ -53,10 +53,10 @@ class Events(object):
|
||||
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
|
||||
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
|
||||
|
||||
FILE_ADDED = "FileAdded",
|
||||
FILE_REMOVED = "FileRemoved",
|
||||
FOLDER_ADDED = "FolderAdded",
|
||||
FOLDER_REMOVED = "FolderRemoved",
|
||||
FILE_ADDED = "FileAdded"
|
||||
FILE_REMOVED = "FileRemoved"
|
||||
FOLDER_ADDED = "FolderAdded"
|
||||
FOLDER_REMOVED = "FolderRemoved"
|
||||
|
||||
# SD Upload
|
||||
TRANSFER_STARTED = "TransferStarted"
|
||||
|
||||
@@ -253,6 +253,26 @@ class FileManager(object):
|
||||
def default_slicer(self):
|
||||
return self._slicing_manager.default_slicer
|
||||
|
||||
def analyse(self, destination, path, printer_profile_id=None):
|
||||
if not self.file_exists(destination, path):
|
||||
return
|
||||
|
||||
if printer_profile_id is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
else:
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
queue_entry = self._analysis_queue_entry(destination, path)
|
||||
self._analysis_queue.dequeue(queue_entry)
|
||||
|
||||
queue_entry = self._analysis_queue_entry(destination, path, printer_profile=printer_profile)
|
||||
if queue_entry:
|
||||
return self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
|
||||
return False
|
||||
|
||||
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path,
|
||||
position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None):
|
||||
absolute_source_path = self.path_on_disk(source_location, source_path)
|
||||
|
||||
@@ -6,15 +6,20 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms
|
||||
|
||||
import requests
|
||||
import logging
|
||||
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
import base64
|
||||
|
||||
BRANCH_HEAD_URL = "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}"
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.bitbucket_commit")
|
||||
|
||||
def _get_latest_commit(user, repo, branch):
|
||||
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch))
|
||||
|
||||
def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
|
||||
url = BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch)
|
||||
headers = {}
|
||||
if api_user is not None and api_password is not None:
|
||||
auth_value = base64.b64encode(b"{user}:{pw}".format(user=api_user, pw=api_password))
|
||||
headers["authorization"] = "Basic {}".format(auth_value)
|
||||
r = requests.get(url, headers=headers)
|
||||
|
||||
if not r.status_code == requests.codes.ok:
|
||||
return None
|
||||
@@ -27,18 +32,21 @@ def _get_latest_commit(user, repo, branch):
|
||||
|
||||
|
||||
def get_latest(target, check):
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
if "user" not in check or "repo" not in check:
|
||||
raise ConfigurationInvalid("Update configuration for %s of type bitbucket_commit needs all of user and repo" % target)
|
||||
|
||||
branch = "master"
|
||||
if "branch" in check:
|
||||
if "branch" in check and check["branch"] is not None:
|
||||
branch = check["branch"]
|
||||
|
||||
current = None
|
||||
if "current" in check:
|
||||
current = check["current"]
|
||||
api_user = check.get("api_user")
|
||||
api_password = check.get("api_password")
|
||||
|
||||
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
|
||||
current = check.get("current")
|
||||
|
||||
remote_commit = _get_latest_commit(check["user"], check["repo"], branch, api_user, api_password)
|
||||
|
||||
information = dict(
|
||||
local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current),
|
||||
|
||||
@@ -8,8 +8,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import requests
|
||||
import logging
|
||||
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
BRANCH_HEAD_URL = "https://api.github.com/repos/{user}/{repo}/git/refs/heads/{branch}"
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit")
|
||||
@@ -31,6 +29,8 @@ def _get_latest_commit(user, repo, branch):
|
||||
|
||||
|
||||
def get_latest(target, check):
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
user = check.get("user")
|
||||
repo = check.get("repo")
|
||||
|
||||
@@ -41,9 +41,7 @@ def get_latest(target, check):
|
||||
if "branch" in check and check["branch"] is not None:
|
||||
branch = check["branch"]
|
||||
|
||||
current = None
|
||||
if "current" in check:
|
||||
current = check["current"]
|
||||
current = check.get("current")
|
||||
|
||||
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
|
||||
|
||||
|
||||
@@ -65,6 +65,9 @@ class VirtualPrinter(object):
|
||||
|
||||
self.currentExtruder = 0
|
||||
self.extruderCount = settings().getInt(["devel", "virtualPrinter", "numExtruders"])
|
||||
self.pinnedExtruders = settings().get(["devel", "virtualPrinter", "pinnedExtruders"])
|
||||
if self.pinnedExtruders is None:
|
||||
self.pinnedExtruders = dict()
|
||||
self.sharedNozzle = settings().getBoolean(["devel", "virtualPrinter", "sharedNozzle"])
|
||||
self.temperatureCount = (1 if self.sharedNozzle else self.extruderCount)
|
||||
|
||||
@@ -1001,6 +1004,10 @@ class VirtualPrinter(object):
|
||||
timeDiff = self.lastTempAt - time.time()
|
||||
self.lastTempAt = time.time()
|
||||
for i in range(len(self.temp)):
|
||||
if i in self.pinnedExtruders:
|
||||
self.temp[i] = self.pinnedExtruders[i]
|
||||
continue
|
||||
|
||||
if abs(self.temp[i] - self.targetTemp[i]) > delta:
|
||||
oldVal = self.temp[i]
|
||||
self.temp[i] += math.copysign(timeDiff * 10, self.targetTemp[i] - self.temp[i])
|
||||
|
||||
@@ -763,7 +763,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
(2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation
|
||||
"""
|
||||
|
||||
if progress is None or printTime is None or cleanedPrintTime is None:
|
||||
if progress is None or progress == 0 or printTime is None or cleanedPrintTime is None:
|
||||
return None, None
|
||||
|
||||
dumbTotalPrintTime = printTime / progress
|
||||
@@ -1000,7 +1000,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
with self._selectedFileMutex:
|
||||
if self._selectedFile is not None:
|
||||
if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_ERROR or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
|
||||
def log_print():
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL,
|
||||
self._selectedFile["filename"],
|
||||
time.time(),
|
||||
self._comm.getPrintTime(),
|
||||
False,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
|
||||
thread = threading.Thread(target=log_print)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
|
||||
elif state == comm.MachineCom.STATE_PRINTING:
|
||||
self._analysisQueue.pause() # do not analyse files while printing
|
||||
@@ -1091,12 +1101,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
context=dict(event=payload),
|
||||
must_be_set=False)
|
||||
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
True,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
def log_print():
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
True,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
|
||||
thread = threading.Thread(target=log_print)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
else:
|
||||
self._updateProgressData()
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
@@ -1119,13 +1135,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
context=dict(event=payload),
|
||||
must_be_set=False)
|
||||
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
False,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
def finalize():
|
||||
self._fileManager.log_print(payload["origin"],
|
||||
payload["path"],
|
||||
time.time(),
|
||||
payload["time"],
|
||||
False,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
thread = threading.Thread(target=finalize)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def on_comm_print_job_paused(self):
|
||||
payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None)
|
||||
|
||||
@@ -471,6 +471,7 @@ def gcodeFileCommand(filename, target):
|
||||
valid_commands = {
|
||||
"select": [],
|
||||
"slice": [],
|
||||
"analyse": [],
|
||||
"copy": ["destination"],
|
||||
"move": ["destination"]
|
||||
}
|
||||
@@ -626,6 +627,17 @@ def gcodeFileCommand(filename, target):
|
||||
r.headers["Location"] = location
|
||||
return r
|
||||
|
||||
elif command == "analyse":
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
|
||||
printer_profile = None
|
||||
if "printerProfile" in data and data["printerProfile"]:
|
||||
printer_profile = data["printerProfile"]
|
||||
|
||||
if not fileManager.analyse(target, filename, printer_profile_id=printer_profile):
|
||||
return make_response("No analysis possible for {} on {}".format(filename, target), 400)
|
||||
|
||||
elif command == "copy" or command == "move":
|
||||
with Permissions.UPLOAD.require(403):
|
||||
# Copy and move are only possible on local storage
|
||||
|
||||
@@ -345,6 +345,7 @@ default_settings = {
|
||||
"okAfterResend": False,
|
||||
"forceChecksum": False,
|
||||
"numExtruders": 1,
|
||||
"pinnedExtruders": None,
|
||||
"includeCurrentToolInTemps": True,
|
||||
"includeFilenameInOpened": True,
|
||||
"hasBed": True,
|
||||
|
||||
@@ -89,6 +89,10 @@
|
||||
return this.issueEntryCommand(location, path, "select", data, opts);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.analyse = function (location, path, parameters, opts) {
|
||||
return this.issueEntryCommand(location, path, "analyse", parameters || {}, opts);
|
||||
};
|
||||
|
||||
OctoPrintFilesClient.prototype.slice = function (location, path, parameters, opts) {
|
||||
return this.issueEntryCommand(location, path, "slice",
|
||||
parameters || {}, opts);
|
||||
|
||||
@@ -592,7 +592,7 @@ $(function() {
|
||||
|
||||
var additionalInfo = $(".additionalInfo", entryElement);
|
||||
additionalInfo.slideToggle("fast", function() {
|
||||
$(".toggleAdditionalData i", entryElement).toggleClass("icon-chevron-down icon-chevron-up");
|
||||
$(".toggleAdditionalData i", entryElement).toggleClass("fa-chevron-down fa-chevron-up");
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -1111,7 +1111,7 @@ class InvariantContainer(object):
|
||||
return self._data.__iter__()
|
||||
|
||||
|
||||
class PrependQueue(queue.Queue):
|
||||
class PrependableQueue(queue.Queue):
|
||||
|
||||
def __init__(self, maxsize=0):
|
||||
queue.Queue.__init__(self, maxsize=maxsize)
|
||||
@@ -1147,21 +1147,21 @@ class PrependQueue(queue.Queue):
|
||||
self.queue.appendleft(item)
|
||||
|
||||
|
||||
class TypedQueue(PrependQueue):
|
||||
class TypedQueue(PrependableQueue):
|
||||
|
||||
def __init__(self, maxsize=0):
|
||||
PrependQueue.__init__(self, maxsize=maxsize)
|
||||
PrependableQueue.__init__(self, maxsize=maxsize)
|
||||
self._lookup = set()
|
||||
|
||||
def put(self, item, item_type=None, *args, **kwargs):
|
||||
PrependQueue.put(self, (item, item_type), *args, **kwargs)
|
||||
PrependableQueue.put(self, (item, item_type), *args, **kwargs)
|
||||
|
||||
def get(self, *args, **kwargs):
|
||||
item, _ = PrependQueue.get(self, *args, **kwargs)
|
||||
item, _ = PrependableQueue.get(self, *args, **kwargs)
|
||||
return item
|
||||
|
||||
def prepend(self, item, item_type=None, *args, **kwargs):
|
||||
PrependQueue.prepend(self, (item, item_type), *args, **kwargs)
|
||||
PrependableQueue.prepend(self, (item, item_type), *args, **kwargs)
|
||||
|
||||
def _put(self, item):
|
||||
_, item_type = item
|
||||
@@ -1171,10 +1171,10 @@ class TypedQueue(PrependQueue):
|
||||
else:
|
||||
self._lookup.add(item_type)
|
||||
|
||||
queue.Queue._put(self, item)
|
||||
PrependableQueue._put(self, item)
|
||||
|
||||
def _get(self):
|
||||
item = PrependQueue._get(self)
|
||||
item = PrependableQueue._get(self)
|
||||
_, item_type = item
|
||||
|
||||
if item_type is not None:
|
||||
@@ -1190,7 +1190,7 @@ class TypedQueue(PrependQueue):
|
||||
else:
|
||||
self._lookup.add(item_type)
|
||||
|
||||
PrependQueue._prepend(self, item)
|
||||
PrependableQueue._prepend(self, item)
|
||||
|
||||
class TypeAlreadyInQueue(Exception):
|
||||
def __init__(self, t, *args, **kwargs):
|
||||
|
||||
+206
-108
@@ -32,7 +32,7 @@ from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager import valid_file_type
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, \
|
||||
to_unicode, bom_aware_open, TypedQueue, TypeAlreadyInQueue, chunks
|
||||
to_unicode, bom_aware_open, TypedQueue, PrependableQueue, TypeAlreadyInQueue, chunks
|
||||
|
||||
try:
|
||||
import _winreg
|
||||
@@ -47,7 +47,7 @@ regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
|
||||
regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
|
||||
regex_int_pattern = "\d+"
|
||||
|
||||
regex_command = re.compile("^\s*((?P<commandGM>[GM]\d+)|(?P<commandT>T)\d+|(?P<commandF>F)\d+)")
|
||||
regex_command = re.compile("^\s*((?P<codeGM>[GM]\d+)(\\.(?P<subcode>\d+))?|(?P<codeT>T)\d+|(?P<codeF>F)\d+)")
|
||||
"""Regex for a GCODE command."""
|
||||
|
||||
regex_float = re.compile(regex_float_pattern)
|
||||
@@ -89,7 +89,7 @@ Groups will be as follows:
|
||||
* ``size``: size of the file in bytes (int)
|
||||
"""
|
||||
|
||||
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_temp = re.compile("(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?" % (regex_float_pattern, regex_float_pattern))
|
||||
"""Regex matching temperature entries in line.
|
||||
|
||||
Groups will be as follows:
|
||||
@@ -100,7 +100,7 @@ Groups will be as follows:
|
||||
* ``target``: target temperature, if provided (float)
|
||||
"""
|
||||
|
||||
regex_repetierTempExtr = re.compile("TargetExtr(?P<toolnum>\d+):(?P<target>%s)" % regex_positive_float_pattern)
|
||||
regex_repetierTempExtr = re.compile("TargetExtr(?P<toolnum>\d+):(?P<target>%s)" % regex_float_pattern)
|
||||
"""Regex for matching target temp reporting from Repetier.
|
||||
|
||||
Groups will be as follows:
|
||||
@@ -110,7 +110,7 @@ Groups will be as follows:
|
||||
* ``target``: new target temperature (float)
|
||||
"""
|
||||
|
||||
regex_repetierTempBed = re.compile("TargetBed:(?P<target>%s)" % regex_positive_float_pattern)
|
||||
regex_repetierTempBed = re.compile("TargetBed:(?P<target>%s)" % regex_float_pattern)
|
||||
"""Regex for matching target temp reporting from Repetier for beds.
|
||||
|
||||
Groups will be as follows:
|
||||
@@ -423,7 +423,7 @@ class MachineCom(object):
|
||||
self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"])
|
||||
|
||||
self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send")
|
||||
self._send_queue = TypedQueue()
|
||||
self._send_queue = SendQueue()
|
||||
self._temperature_timer = None
|
||||
self._sd_status_timer = None
|
||||
|
||||
@@ -2069,6 +2069,7 @@ class MachineCom(object):
|
||||
self._to_logfile_with_terminal("Got a resend request from the printer: requested line = {}, current line = {}".format(lineToResend, self._currentLine))
|
||||
self._log_resends_rate_count += 1
|
||||
|
||||
self._send_queue.resend_active = True
|
||||
return True
|
||||
finally:
|
||||
if self._supportResendsWithoutOk:
|
||||
@@ -2097,7 +2098,7 @@ class MachineCom(object):
|
||||
cmd = self._lastLines[-self._resendDelta]
|
||||
lineNumber = self._currentLine - self._resendDelta
|
||||
|
||||
result = self._enqueue_for_sending(cmd, linenumber=lineNumber)
|
||||
result = self._enqueue_for_sending(cmd, linenumber=lineNumber, resend=True)
|
||||
|
||||
self._resendDelta -= 1
|
||||
if self._resendDelta <= 0:
|
||||
@@ -2105,6 +2106,8 @@ class MachineCom(object):
|
||||
self._lastResendNumber = None
|
||||
self._currentResendCount = 0
|
||||
|
||||
self._send_queue.resend_active = False
|
||||
|
||||
return result
|
||||
|
||||
def _sendCommand(self, cmd, cmd_type=None, on_sent=None):
|
||||
@@ -2113,20 +2116,20 @@ class MachineCom(object):
|
||||
if self._serial is None:
|
||||
return False
|
||||
|
||||
gcode = None
|
||||
gcode, subcode = gcode_and_subcode_for_cmd(cmd)
|
||||
|
||||
if not self.isStreaming():
|
||||
# trigger the "queuing" phase only if we are not streaming to sd right now
|
||||
results = self._process_command_phase("queuing", cmd, cmd_type, gcode=gcode)
|
||||
results = self._process_command_phase("queuing", cmd, command_type=cmd_type, gcode=gcode, subcode=subcode)
|
||||
|
||||
if not results:
|
||||
# command is no more, return
|
||||
return False
|
||||
else:
|
||||
results = [(cmd, cmd_type, gcode)]
|
||||
results = [(cmd, cmd_type, gcode, subcode)]
|
||||
|
||||
# process helper
|
||||
def process(cmd, cmd_type, gcode, on_sent=None):
|
||||
def process(cmd, cmd_type, gcode, subcode, on_sent=None):
|
||||
if cmd is None:
|
||||
# no command, next entry
|
||||
return False
|
||||
@@ -2139,7 +2142,7 @@ class MachineCom(object):
|
||||
if self._enqueue_for_sending(cmd, command_type=cmd_type, on_sent=on_sent):
|
||||
if not self.isStreaming():
|
||||
# trigger the "queued" phase only if we are not streaming to sd right now
|
||||
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode)
|
||||
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode, subcode=subcode)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
@@ -2156,18 +2159,18 @@ class MachineCom(object):
|
||||
enqueued_something = False
|
||||
|
||||
# process all but the last ...
|
||||
for (cmd, cmd_type, gcode) in results:
|
||||
enqueued_something = process(cmd, cmd_type, gcode) or enqueued_something
|
||||
for (cmd, cmd_type, gcode, subcode) in results:
|
||||
enqueued_something = process(cmd, cmd_type, gcode, subcode) or enqueued_something
|
||||
|
||||
# ... and then process the last one with the on_sent callback attached
|
||||
cmd, cmd_type, gcode = last_command
|
||||
enqueued_something = process(cmd, cmd_type, gcode, on_sent=on_sent) or enqueued_something
|
||||
cmd, cmd_type, gcode, subcode = last_command
|
||||
enqueued_something = process(cmd, cmd_type, gcode, subcode, on_sent=on_sent) or enqueued_something
|
||||
|
||||
return enqueued_something
|
||||
|
||||
##~~ send loop handling
|
||||
|
||||
def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None):
|
||||
def _enqueue_for_sending(self, command, linenumber=None, command_type=None, on_sent=None, resend=False):
|
||||
"""
|
||||
Enqueues a command and optional linenumber to use for it in the send queue.
|
||||
|
||||
@@ -2181,7 +2184,11 @@ class MachineCom(object):
|
||||
"""
|
||||
|
||||
try:
|
||||
self._send_queue.put((command, linenumber, command_type, on_sent, False), item_type=command_type)
|
||||
target = "send"
|
||||
if resend:
|
||||
target = "resend"
|
||||
|
||||
self._send_queue.put((command, linenumber, command_type, on_sent, False), item_type=command_type, target=target)
|
||||
return True
|
||||
except TypeAlreadyInQueue as e:
|
||||
self._logger.debug("Type already in send queue: " + e.type)
|
||||
@@ -2189,7 +2196,7 @@ class MachineCom(object):
|
||||
|
||||
def _send_loop(self):
|
||||
"""
|
||||
The send loop is reponsible of sending commands in ``self._send_queue`` over the line, if it is cleared for
|
||||
The send loop is responsible of sending commands in ``self._send_queue`` over the line, if it is cleared for
|
||||
sending (through received ``ok`` responses from the printer's firmware.
|
||||
"""
|
||||
|
||||
@@ -2217,7 +2224,7 @@ class MachineCom(object):
|
||||
# some firmwares (e.g. Smoothie) might support additional in-band communication that will not
|
||||
# stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
|
||||
# at hand here and only clear our clear_to_send flag later if that's the case
|
||||
gcode = gcode_command_for_cmd(command)
|
||||
gcode, subcode = gcode_and_subcode_for_cmd(command)
|
||||
|
||||
if linenumber is not None:
|
||||
# line number predetermined - this only happens for resends, so we'll use the number and
|
||||
@@ -2227,7 +2234,7 @@ class MachineCom(object):
|
||||
else:
|
||||
if not processed:
|
||||
# trigger "sending" phase if we didn't so far
|
||||
results = self._process_command_phase("sending", command, command_type, gcode=gcode)
|
||||
results = self._process_command_phase("sending", command, command_type, gcode=gcode, subcode=subcode)
|
||||
|
||||
if not results:
|
||||
# No, we are not going to send this, that was a last-minute bail.
|
||||
@@ -2241,19 +2248,18 @@ class MachineCom(object):
|
||||
continue
|
||||
|
||||
if len(results) > 1:
|
||||
# last command gets on_sent attached
|
||||
last = results[-1]
|
||||
self._send_queue.prepend((last[0], None, None, on_sent, True))
|
||||
on_sent = None
|
||||
|
||||
# middle gets prepended reversed (so order gets restored)
|
||||
if len(results) > 2:
|
||||
with self._sendingLock:
|
||||
# prepend reversed (so order gets restored)
|
||||
to_prepend = reversed(results[1:-1])
|
||||
for m in to_prepend:
|
||||
self._send_queue.prepend((m[0], None, None, None, True))
|
||||
try:
|
||||
self._send_queue.prepend((m[0], None, m[1], on_sent, True), item_type=m[1])
|
||||
on_sent = None
|
||||
except TypeAlreadyInQueue:
|
||||
pass
|
||||
|
||||
# we only actually send the first entry here
|
||||
command, _, gcode = results[0]
|
||||
command, _, gcode, subcode = results[0]
|
||||
|
||||
if command.strip() == "":
|
||||
self._logger.info("Refusing to send an empty line to the printer")
|
||||
@@ -2281,7 +2287,7 @@ class MachineCom(object):
|
||||
if on_sent is not None and callable(on_sent):
|
||||
# we have a sent callback for this specific command, let's execute it now
|
||||
on_sent()
|
||||
self._process_command_phase("sent", command, command_type, gcode=gcode)
|
||||
self._process_command_phase("sent", command, command_type, gcode=gcode, subcode=subcode)
|
||||
|
||||
# we only need to use up a clear if the command we just sent was either a gcode command or if we also
|
||||
# require ack's for unknown commands
|
||||
@@ -2309,10 +2315,10 @@ class MachineCom(object):
|
||||
self._logger.exception("Caught an exception in the send loop")
|
||||
self._log("Closing down send loop")
|
||||
|
||||
def _process_command_phase(self, phase, command, command_type=None, gcode=None):
|
||||
def _process_command_phase(self, phase, command, command_type=None, gcode=None, subcode=None):
|
||||
if gcode is None:
|
||||
gcode = gcode_command_for_cmd(command)
|
||||
results = [(command, command_type, gcode)]
|
||||
gcode, subcode = gcode_and_subcode_for_cmd(command)
|
||||
results = [(command, command_type, gcode, subcode)]
|
||||
|
||||
if (self.isStreaming() and self.isPrinting()) or phase not in ("queuing", "queued", "sending", "sent"):
|
||||
return results
|
||||
@@ -2320,13 +2326,13 @@ class MachineCom(object):
|
||||
# send it through the phase specific handlers provided by plugins
|
||||
for name, hook in self._gcode_hooks[phase].items():
|
||||
new_results = []
|
||||
for command, command_type, gcode in results:
|
||||
for command, command_type, gcode, subcode in results:
|
||||
try:
|
||||
hook_results = hook(self, phase, command, command_type, gcode)
|
||||
hook_results = hook(self, phase, command, command_type, gcode, subcode=subcode)
|
||||
except:
|
||||
self._logger.exception("Error while processing hook {name} for phase {phase} and command {command}:".format(**locals()))
|
||||
else:
|
||||
normalized = _normalize_command_handler_result(command, command_type, gcode, hook_results)
|
||||
normalized = _normalize_command_handler_result(command, command_type, gcode, subcode, hook_results)
|
||||
new_results += normalized
|
||||
if not new_results:
|
||||
# hook handler returned None or empty list for all commands, so we'll stop here and return a full out empty result
|
||||
@@ -2336,15 +2342,15 @@ class MachineCom(object):
|
||||
# if it's a gcode command send it through the specific handler if it exists
|
||||
new_results = []
|
||||
modified = False
|
||||
for command, command_type, gcode in results:
|
||||
for command, command_type, gcode, subcode in results:
|
||||
if gcode is not None:
|
||||
gcode_handler = "_gcode_" + gcode + "_" + phase
|
||||
if hasattr(self, gcode_handler):
|
||||
handler_results = getattr(self, gcode_handler)(command, cmd_type=command_type)
|
||||
new_results += _normalize_command_handler_result(command, command_type, gcode, handler_results)
|
||||
handler_results = getattr(self, gcode_handler)(command, cmd_type=command_type, subcode=subcode)
|
||||
new_results += _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results)
|
||||
modified = True
|
||||
else:
|
||||
new_results.append((command, command_type, gcode))
|
||||
new_results.append((command, command_type, gcode, subcode))
|
||||
modified = True
|
||||
if modified:
|
||||
if not new_results:
|
||||
@@ -2357,9 +2363,9 @@ class MachineCom(object):
|
||||
command_phase_handler = "_command_phase_" + phase
|
||||
if hasattr(self, command_phase_handler):
|
||||
new_results = []
|
||||
for command, command_type, gcode in results:
|
||||
handler_results = getattr(self, command_phase_handler)(command, cmd_type=command_type, gcode=gcode)
|
||||
new_results += _normalize_command_handler_result(command, command_type, gcode, handler_results)
|
||||
for command, command_type, gcode, subcode in results:
|
||||
handler_results = getattr(self, command_phase_handler)(command, cmd_type=command_type, gcode=gcode, subcode=subcode)
|
||||
new_results += _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results)
|
||||
results = new_results
|
||||
|
||||
# finally return whatever we resulted on
|
||||
@@ -2445,7 +2451,7 @@ class MachineCom(object):
|
||||
|
||||
##~~ command handlers
|
||||
|
||||
def _gcode_T_queuing(self, cmd, cmd_type=None):
|
||||
def _gcode_T_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
toolMatch = regexes_parameters["intT"].search(cmd)
|
||||
if toolMatch:
|
||||
current_tool = self._currentTool
|
||||
@@ -2456,14 +2462,14 @@ class MachineCom(object):
|
||||
|
||||
return before + [cmd] + after
|
||||
|
||||
def _gcode_T_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_T_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
toolMatch = regexes_parameters["intT"].search(cmd)
|
||||
if toolMatch:
|
||||
old = self._currentTool
|
||||
self._currentTool = int(toolMatch.group("value"))
|
||||
eventManager().fire(Events.TOOL_CHANGE, dict(old=old, new=self._currentTool))
|
||||
|
||||
def _gcode_G0_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_G0_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
if "Z" in cmd or "F" in cmd:
|
||||
# track Z
|
||||
match = regexes_parameters["floatZ"].search(cmd)
|
||||
@@ -2486,7 +2492,7 @@ class MachineCom(object):
|
||||
pass
|
||||
_gcode_G1_sent = _gcode_G0_sent
|
||||
|
||||
def _gcode_G28_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_G28_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
if "F" in cmd:
|
||||
match = regexes_parameters["floatF"].search(cmd)
|
||||
if match:
|
||||
@@ -2496,34 +2502,34 @@ class MachineCom(object):
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def _gcode_M0_queuing(self, cmd, cmd_type=None):
|
||||
def _gcode_M0_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
self.setPause(True)
|
||||
return None, # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
|
||||
_gcode_M1_queuing = _gcode_M0_queuing
|
||||
|
||||
def _gcode_M25_queuing(self, cmd, cmd_type=None):
|
||||
def _gcode_M25_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
# M25 while not printing from SD will be handled as pause. This way it can be used as another marker
|
||||
# for GCODE induced pausing. Send it to the printer anyway though.
|
||||
if self.isPrinting() and not self.isSdPrinting():
|
||||
self.setPause(True)
|
||||
|
||||
def _gcode_M28_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_M28_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
if not self.isStreaming():
|
||||
self._log("Detected manual streaming. Disabling temperature polling. Finish writing with M29. Do NOT attempt to print while manually streaming!")
|
||||
self._manualStreaming = True
|
||||
|
||||
def _gcode_M29_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_M29_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
if self._manualStreaming:
|
||||
self._log("Manual streaming done. Re-enabling temperature polling. All is well.")
|
||||
self._manualStreaming = False
|
||||
|
||||
def _gcode_M140_queuing(self, cmd, cmd_type=None):
|
||||
def _gcode_M140_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
if not self._printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
self._log("Warn: Not sending \"{}\", printer profile has no heated bed".format(cmd))
|
||||
return None, # Don't send bed commands if we don't have a heated bed
|
||||
_gcode_M190_queuing = _gcode_M140_queuing
|
||||
|
||||
def _gcode_M104_sent(self, cmd, cmd_type=None, wait=False, support_r=False):
|
||||
def _gcode_M104_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, wait=False, support_r=False, *args, **kwargs):
|
||||
toolNum = self._currentTool
|
||||
toolMatch = regexes_parameters["intT"].search(cmd)
|
||||
|
||||
@@ -2546,7 +2552,7 @@ class MachineCom(object):
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def _gcode_M140_sent(self, cmd, cmd_type=None, wait=False, support_r=False):
|
||||
def _gcode_M140_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, wait=False, support_r=False, *args, **kwargs):
|
||||
match = regexes_parameters["floatS"].search(cmd)
|
||||
if not match and support_r:
|
||||
match = regexes_parameters["floatR"].search(cmd)
|
||||
@@ -2559,24 +2565,24 @@ class MachineCom(object):
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def _gcode_M109_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_M109_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
self._heatupWaitStartTime = time.time()
|
||||
self._long_running_command = True
|
||||
self._heating = True
|
||||
self._gcode_M104_sent(cmd, cmd_type, wait=True, support_r=True)
|
||||
|
||||
def _gcode_M190_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_M190_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
self._heatupWaitStartTime = time.time()
|
||||
self._long_running_command = True
|
||||
self._heating = True
|
||||
self._gcode_M140_sent(cmd, cmd_type, wait=True, support_r=True)
|
||||
|
||||
def _gcode_M116_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_M116_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
self._heatupWaitStartTime = time.time()
|
||||
self._long_running_command = True
|
||||
self._heating = True
|
||||
|
||||
def _gcode_M155_sending(self, cmd, cmd_type=None):
|
||||
def _gcode_M155_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
match = regexes_parameters["intS"].search(cmd)
|
||||
if match:
|
||||
try:
|
||||
@@ -2586,7 +2592,7 @@ class MachineCom(object):
|
||||
except:
|
||||
pass
|
||||
|
||||
def _gcode_M110_sending(self, cmd, cmd_type=None):
|
||||
def _gcode_M110_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
newLineNumber = 0
|
||||
match = regexes_parameters["intN"].search(cmd)
|
||||
if match:
|
||||
@@ -2605,7 +2611,7 @@ class MachineCom(object):
|
||||
self._lastLines.clear()
|
||||
self._resendDelta = None
|
||||
|
||||
def _gcode_M112_queuing(self, cmd, cmd_type=None):
|
||||
def _gcode_M112_queuing(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
# emergency stop, jump the queue with the M112
|
||||
self._do_send_without_checksum("M112")
|
||||
self._do_increment_and_send_with_checksum("M112")
|
||||
@@ -2634,7 +2640,7 @@ class MachineCom(object):
|
||||
# I hope it got it the first time because as far as I can tell, there is no way to know
|
||||
return None,
|
||||
|
||||
def _gcode_G4_sent(self, cmd, cmd_type=None):
|
||||
def _gcode_G4_sent(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
# we are intending to dwell for a period of time, increase the timeout to match
|
||||
p_match = regexes_parameters["floatP"].search(cmd)
|
||||
s_match = regexes_parameters["floatS"].search(cmd)
|
||||
@@ -2650,7 +2656,7 @@ class MachineCom(object):
|
||||
|
||||
##~~ command phase handlers
|
||||
|
||||
def _command_phase_sending(self, cmd, cmd_type=None, gcode=None):
|
||||
def _command_phase_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
if gcode is not None and gcode in self._long_running_commands:
|
||||
self._long_running_command = True
|
||||
|
||||
@@ -2926,6 +2932,88 @@ class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
|
||||
duration=duration)
|
||||
self._logger.info("Finished in {duration:.3f} s. Approx. transfer rate of {rate:.3f} lines/s or {time_per_line:.3f} ms per line".format(**stats))
|
||||
|
||||
|
||||
class SendQueue(PrependableQueue):
|
||||
|
||||
def __init__(self, maxsize=0):
|
||||
PrependableQueue.__init__(self, maxsize=maxsize)
|
||||
|
||||
self._resend_queue = PrependableQueue()
|
||||
self._send_queue = PrependableQueue()
|
||||
self._lookup = set()
|
||||
|
||||
self._resend_active = False
|
||||
|
||||
@property
|
||||
def resend_active(self):
|
||||
return self._resend_active
|
||||
|
||||
@resend_active.setter
|
||||
def resend_active(self, resend_active):
|
||||
with self.mutex:
|
||||
self._resend_active = resend_active
|
||||
|
||||
def prepend(self, item, item_type=None, target=None, block=True, timeout=None):
|
||||
PrependableQueue.prepend(self, (item, item_type, target), block=block, timeout=timeout)
|
||||
|
||||
def put(self, item, item_type=None, target=None, block=True, timeout=None):
|
||||
PrependableQueue.put(self, (item, item_type, target), block=block, timeout=timeout)
|
||||
|
||||
def get(self, block=True, timeout=None):
|
||||
item, _, _ = PrependableQueue.get(self, block=block, timeout=timeout)
|
||||
return item
|
||||
|
||||
def _put(self, item):
|
||||
_, item_type, target = item
|
||||
if item_type is not None:
|
||||
if item_type in self._lookup:
|
||||
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
|
||||
else:
|
||||
self._lookup.add(item_type)
|
||||
|
||||
if target == "resend":
|
||||
self._resend_queue.put(item)
|
||||
else:
|
||||
self._send_queue.put(item)
|
||||
|
||||
pass
|
||||
|
||||
def _prepend(self, item):
|
||||
_, item_type, target = item
|
||||
if item_type is not None:
|
||||
if item_type in self._lookup:
|
||||
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
|
||||
else:
|
||||
self._lookup.add(item_type)
|
||||
|
||||
if target == "resend":
|
||||
self._resend_queue.prepend(item)
|
||||
else:
|
||||
self._send_queue.prepend(item)
|
||||
|
||||
def _get(self):
|
||||
if self.resend_active:
|
||||
item = self._resend_queue.get(block=False)
|
||||
else:
|
||||
try:
|
||||
item = self._resend_queue.get(block=False)
|
||||
except queue.Empty:
|
||||
item = self._send_queue.get(block=False)
|
||||
|
||||
_, item_type, _ = item
|
||||
if item_type is not None:
|
||||
if item_type in self._lookup:
|
||||
self._lookup.remove(item_type)
|
||||
|
||||
return item
|
||||
|
||||
def _qsize(self):
|
||||
if self.resend_active:
|
||||
return self._resend_queue.qsize()
|
||||
else:
|
||||
return self._resend_queue.qsize() + self._send_queue.qsize()
|
||||
|
||||
|
||||
def get_new_timeout(type, intervals):
|
||||
now = time.time()
|
||||
return now + intervals.get(type, 0.0)
|
||||
@@ -3278,35 +3366,43 @@ def gcode_command_for_cmd(cmd):
|
||||
Returns:
|
||||
str or None: The GCODE command identifier if it could be parsed, or None if not.
|
||||
"""
|
||||
|
||||
gcode, _ = gcode_and_subcode_for_cmd(cmd)
|
||||
return gcode
|
||||
|
||||
|
||||
def gcode_and_subcode_for_cmd(cmd):
|
||||
if not cmd:
|
||||
return None
|
||||
return None, None
|
||||
|
||||
gcode = regex_command.search(cmd)
|
||||
if not gcode:
|
||||
return None
|
||||
match = regex_command.search(cmd)
|
||||
if not match:
|
||||
return None, None
|
||||
|
||||
values = gcode.groupdict()
|
||||
if "commandGM" in values and values["commandGM"]:
|
||||
return values["commandGM"]
|
||||
elif "commandT" in values and values["commandT"]:
|
||||
return values["commandT"]
|
||||
elif settings().getBoolean(["feature", "supportFAsCommand"]) and "commandF" in values and values["commandF"]:
|
||||
return values["commandF"]
|
||||
values = match.groupdict()
|
||||
if "codeGM" in values and values["codeGM"]:
|
||||
gcode = values["codeGM"]
|
||||
elif "codeT" in values and values["codeT"]:
|
||||
gcode = values["codeT"]
|
||||
elif settings().getBoolean(["feature", "supportFAsCommand"]) and "codeF" in values and values["codeF"]:
|
||||
gcode = values["codeF"]
|
||||
else:
|
||||
# this should never happen
|
||||
return None
|
||||
return None, None
|
||||
|
||||
return gcode, values.get("subcode", None)
|
||||
|
||||
|
||||
def _normalize_command_handler_result(command, command_type, gcode, handler_results):
|
||||
def _normalize_command_handler_result(command, command_type, gcode, subcode, handler_results):
|
||||
"""
|
||||
Normalizes a command handler result.
|
||||
|
||||
Handler results can be either ``None``, a single result entry or a list of result
|
||||
entries.
|
||||
|
||||
``None`` results are ignored, the provided ``command``, ``command_type``
|
||||
and ``gcode`` are returned in that case (as single-entry list with one
|
||||
3-tuple as entry).
|
||||
``None`` results are ignored, the provided ``command``, ``command_type``,
|
||||
``gcode`` and ``subcode`` are returned in that case (as single-entry list with
|
||||
one 4-tuple as entry).
|
||||
|
||||
Single result entries are either:
|
||||
|
||||
@@ -3318,31 +3414,31 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu
|
||||
the normalized result.
|
||||
|
||||
The method returns a list of normalized result entries. Normalized result
|
||||
entries always are a 3-tuple consisting of ``command``, ``command_type``
|
||||
and ``gcode``, the latter two being allowed to be ``None``. The list may
|
||||
entries always are a 4-tuple consisting of ``command``, ``command_type``,
|
||||
``gcode`` and ``subcode``, the latter three being allowed to be ``None``. The list may
|
||||
be empty in which case the command is to be suppressed.
|
||||
|
||||
Examples:
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None)
|
||||
[('M105', None, 'M105')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", "M110")
|
||||
[('M110', None, 'M110')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", ["M110"])
|
||||
[('M110', None, 'M110')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", ["M110", "M117 Foobar"])
|
||||
[('M110', None, 'M110'), ('M117 Foobar', None, 'M117')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", [("M110",), "M117 Foobar"])
|
||||
[('M110', None, 'M110'), ('M117 Foobar', None, 'M117')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", [("M110", "lineno_reset"), "M117 Foobar"])
|
||||
[('M110', 'lineno_reset', 'M110'), ('M117 Foobar', None, 'M117')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", [])
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None)
|
||||
[('M105', None, 'M105', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, "M110")
|
||||
[('M110', None, 'M110', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, ["M110"])
|
||||
[('M110', None, 'M110', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, ["M110", "M117 Foobar"])
|
||||
[('M110', None, 'M110', None), ('M117 Foobar', None, 'M117', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), "M117 Foobar"])
|
||||
[('M110', None, 'M110', None), ('M117 Foobar', None, 'M117', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, [("M110", "lineno_reset"), "M117 Foobar"])
|
||||
[('M110', 'lineno_reset', 'M110', None), ('M117 Foobar', None, 'M117', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, [])
|
||||
[]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", ["M110", None])
|
||||
[('M110', None, 'M110')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", [("M110",), (None, "ignored")])
|
||||
[('M110', None, 'M110')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of unexpected", "length"), ("M110", "lineno_reset")])
|
||||
[('M110', None, 'M110'), ('M117 Foobar', 'display_message', 'M117'), ('M110', 'lineno_reset', 'M110')]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, ["M110", None])
|
||||
[('M110', None, 'M110', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), (None, "ignored")])
|
||||
[('M110', None, 'M110', None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of unexpected", "length"), ("M110", "lineno_reset")])
|
||||
[('M110', None, 'M110', None), ('M117 Foobar', 'display_message', 'M117', None), ('M110', 'lineno_reset', 'M110', None)]
|
||||
|
||||
Arguments:
|
||||
command (str or None): The command for which the handler result was
|
||||
@@ -3351,16 +3447,18 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu
|
||||
result was generated
|
||||
gcode (str or None): The GCODE for which the handler result was
|
||||
generated
|
||||
subcode (str or None): The GCODE subcode for which the handler result
|
||||
was generated
|
||||
handler_results: The handler result(s) to normalized. Can be either
|
||||
a single result entry or a list of result entries.
|
||||
|
||||
Returns:
|
||||
(list) - A list of normalized handler result entries, which are
|
||||
3-tuples consisting of ``command``, ``command_type`` and
|
||||
``gcode``, the latter two of which may be ``None``.
|
||||
4-tuples consisting of ``command``, ``command_type``, ``gcode``
|
||||
and ``subcode``, the latter three of which may be ``None``.
|
||||
"""
|
||||
|
||||
original = (command, command_type, gcode)
|
||||
original = (command, command_type, gcode, subcode)
|
||||
|
||||
if handler_results is None:
|
||||
# handler didn't return anything, we'll just continue
|
||||
@@ -3381,8 +3479,8 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu
|
||||
if isinstance(handler_result, basestring):
|
||||
# entry is just a string, replace command with it
|
||||
command = handler_result
|
||||
gcode = gcode_command_for_cmd(command)
|
||||
result.append((command, command_type, gcode))
|
||||
gcode, subcode = gcode_and_subcode_for_cmd(command)
|
||||
result.append((command, command_type, gcode, subcode))
|
||||
|
||||
elif isinstance(handler_result, tuple):
|
||||
# entry is a tuple, extract command and command_type
|
||||
@@ -3402,11 +3500,11 @@ def _normalize_command_handler_result(command, command_type, gcode, handler_resu
|
||||
# command is None, ignore it and continue
|
||||
continue
|
||||
|
||||
gcode = gcode_command_for_cmd(command)
|
||||
result.append((command, command_type, gcode))
|
||||
gcode, subcode = gcode_and_subcode_for_cmd(command)
|
||||
result.append((command, command_type, gcode, subcode))
|
||||
|
||||
# reset to original
|
||||
command, command_type, gcode = original
|
||||
command, command_type, gcode, subcode = original
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@@ -222,7 +222,6 @@ class gcode(object):
|
||||
lineNo = 0
|
||||
readBytes = 0
|
||||
pos = Vector3D(0.0, 0.0, 0.0)
|
||||
toolOffset = Vector3D(0.0, 0.0, 0.0)
|
||||
currentE = [0.0]
|
||||
totalExtrusion = [0.0]
|
||||
maxExtrusion = [0.0]
|
||||
@@ -320,16 +319,16 @@ class gcode(object):
|
||||
|
||||
# Use new coordinates if provided. If not provided, use prior coordinates (minus tool offset)
|
||||
# in absolute and 0.0 in relative mode.
|
||||
newPos = Vector3D(x if x is not None else (0.0 if relativeMode else pos.x - toolOffset.x),
|
||||
y if y is not None else (0.0 if relativeMode else pos.y - toolOffset.y),
|
||||
z if z is not None else (0.0 if relativeMode else pos.z - toolOffset.z))
|
||||
newPos = Vector3D(x if x is not None else (0.0 if relativeMode else pos.x),
|
||||
y if y is not None else (0.0 if relativeMode else pos.y),
|
||||
z if z is not None else (0.0 if relativeMode else pos.z))
|
||||
|
||||
if relativeMode:
|
||||
# Relative mode: scale and add to current position
|
||||
pos += newPos * scale
|
||||
else:
|
||||
# Absolute mode: scale coordinates and apply tool offsets
|
||||
pos = newPos * scale + toolOffset
|
||||
pos = newPos * scale
|
||||
|
||||
if f is not None and f != 0:
|
||||
feedrate = f
|
||||
@@ -442,14 +441,16 @@ class gcode(object):
|
||||
elif T is not None:
|
||||
if T > max_extruders:
|
||||
self._logger.warn("GCODE tried to select tool %d, that looks wrong, ignoring for GCODE analysis" % T)
|
||||
elif T == currentExtruder:
|
||||
pass
|
||||
else:
|
||||
toolOffset.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
|
||||
toolOffset.y -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
|
||||
pos.x -= offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
|
||||
pos.y -= offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
|
||||
|
||||
currentExtruder = T
|
||||
|
||||
toolOffset.x += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
|
||||
toolOffset.y += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
|
||||
pos.x += offsets[currentExtruder][0] if currentExtruder < len(offsets) else 0
|
||||
pos.y += offsets[currentExtruder][1] if currentExtruder < len(offsets) else 0
|
||||
|
||||
if len(currentE) <= currentExtruder:
|
||||
for i in range(len(currentE), currentExtruder + 1):
|
||||
|
||||
@@ -198,12 +198,32 @@ class TestCommHelpers(unittest.TestCase):
|
||||
result = gcode_command_for_cmd(cmd)
|
||||
self.assertEqual(expected, result)
|
||||
|
||||
@data(
|
||||
("G0 X0", "G0", None),
|
||||
("M105", "M105", None),
|
||||
("T2", "T", None),
|
||||
("M80.1", "M80", "1"),
|
||||
("G28.2", "G28", "2"),
|
||||
("T0.3", "T", None),
|
||||
("M80.nosubcode", "M80", None),
|
||||
(None, None, None),
|
||||
("No match", None, None)
|
||||
)
|
||||
@unpack
|
||||
def test_gcode_and_subcode_for_cmd(self, cmd, expected_gcode, expected_subcode):
|
||||
from octoprint.util.comm import gcode_and_subcode_for_cmd
|
||||
actual_gcode, actual_subcode = gcode_and_subcode_for_cmd(cmd)
|
||||
self.assertEqual(expected_gcode, actual_gcode)
|
||||
self.assertEqual(expected_subcode, actual_subcode)
|
||||
|
||||
@data(
|
||||
("T:23.0 B:60.0", 0, dict(T0=(23.0, None), B=(60.0, None)), 0),
|
||||
("T:23.0 B:60.0", 1, dict(T1=(23.0, None), B=(60.0, None)), 1),
|
||||
("T:23.0/220.0 B:60.0/70.0", 0, dict(T0=(23.0, 220.0), B=(60.0, 70.0)), 0),
|
||||
("ok T:23.0/220.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 0, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2),
|
||||
("ok T:50.2/210.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 1, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2)
|
||||
("ok T:50.2/210.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 1, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2),
|
||||
("ok T:-55.7/0 T0:-55.7/0 T1:150.0/210.0", 0, dict(T0=(-55.7, 0), T1=(150.0, 210.0)), 1),
|
||||
("ok T:150.0/210.0 T0:-55.7/0 T1:150.0/210.0", 1, dict(T0=(-55.7, 0), T1=(150.0, 210.0)), 1)
|
||||
)
|
||||
@unpack
|
||||
def test_process_temperature_line(self, line, current, expected_result, expected_max):
|
||||
|
||||
Reference in new issue
Block a user