✨ Support parsing of M33 and M20 w/ long names
As to my knowledge no firmware currently implements M20 with long file names like this: Begin file list UGLYNA~1.GCO 2342 Uglyname with some_longer-name.gcode End file list However, as proposed by myself back in 2016 that would make the most sense (contrary to M33, which requires n+1 requests to get all metadata from the printer), so OctoPrint now supports it and firmwares are welcome to implement it accordingly to finally implement a *usable* way to retrieve long filenames that doesn't saturate the serial connection for an undeterminable amount of time just to retrieve a list of file names. Compare MarlinFirmware/Marlin#4733. Also add parsing of the (not really parser friendly) output of M33. Note that OctoPrint will not send M33 on its own even though it now supports parsing its response. There's no capability flag for this as far as documented, and there appears to exist a GCODE clash according to https://reprap.org/wiki/G-code, so just blindly sending M33 to the printer from core might cause severe issues. Users may instead add active querying for the long name (if not included in the M20 response) through a plugin, as demonstrated in https://gist.github.com/foosel/cadc38123687a46816a1d3e1d160d48a Closes #1600
This commit is contained in:
1 parent
df66dd9abf
commit
003b80689e
4 files changed
+84
-27
No files matched your search
@@ -700,8 +700,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
def get_sd_files(self, *args, **kwargs):
|
||||
if self._comm is None or not self._comm.isSdReady():
|
||||
return []
|
||||
return list(map(lambda x: (x[0][1:], x[1]), self._comm.getSdFiles()))
|
||||
result = []
|
||||
else:
|
||||
result = list(map(lambda x: dict(name=x[0][1:], size=x[1], display=x[2]), self._comm.getSdFiles()))
|
||||
return result
|
||||
|
||||
def add_sd_file(self, filename, path, on_success=None, on_failure=None, *args, **kwargs):
|
||||
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
|
||||
|
||||
@@ -97,7 +97,7 @@ def _create_etag(path, filter, recursive, lm=None):
|
||||
|
||||
if path == "" or storage == FileDestinations.SDCARD:
|
||||
# include sd data in etag
|
||||
hash_update(repr(sorted(printer.get_sd_files(), key=lambda x: sv(x[0]))))
|
||||
hash_update(repr(sorted(printer.get_sd_files(), key=lambda x: sv(x["name"]))))
|
||||
|
||||
hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format
|
||||
|
||||
@@ -192,8 +192,8 @@ def _getFileList(origin, path=None, filter=None, recursive=False, allow_from_cac
|
||||
|
||||
files = []
|
||||
if sdFileList is not None:
|
||||
for sdFile, sdSize in sdFileList:
|
||||
type_path = octoprint.filemanager.get_file_type(sdFile)
|
||||
for f in sdFileList:
|
||||
type_path = octoprint.filemanager.get_file_type(f["name"])
|
||||
if not type_path:
|
||||
# only supported extensions
|
||||
continue
|
||||
@@ -203,16 +203,19 @@ def _getFileList(origin, path=None, filter=None, recursive=False, allow_from_cac
|
||||
file = {
|
||||
"type": file_type,
|
||||
"typePath": type_path,
|
||||
"name": sdFile,
|
||||
"display": sdFile,
|
||||
"path": sdFile,
|
||||
"name": f["name"],
|
||||
"display": f["display"] if f["display"] else f["name"],
|
||||
"path": f["name"],
|
||||
"origin": FileDestinations.SDCARD,
|
||||
"refs": {
|
||||
"resource": url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFile, _external=True)
|
||||
"resource": url_for(".readGcodeFile",
|
||||
target=FileDestinations.SDCARD,
|
||||
filename=f["name"],
|
||||
_external=True)
|
||||
}
|
||||
}
|
||||
if sdSize is not None:
|
||||
file.update({"size": sdSize})
|
||||
if f["size"] is not None:
|
||||
file.update({"size": f["size"]})
|
||||
files.append(file)
|
||||
else:
|
||||
filter_func = None
|
||||
@@ -288,7 +291,7 @@ def _getFileList(origin, path=None, filter=None, recursive=False, allow_from_cac
|
||||
|
||||
def _verifyFileExists(origin, filename):
|
||||
if origin == FileDestinations.SDCARD:
|
||||
return filename in (x[0] for x in printer.get_sd_files())
|
||||
return filename in (x["name"] for x in printer.get_sd_files())
|
||||
else:
|
||||
return fileManager.file_exists(origin, filename)
|
||||
|
||||
|
||||
@@ -645,6 +645,14 @@ def filter_non_ascii(line):
|
||||
return True
|
||||
|
||||
|
||||
def filter_non_utf8(line):
|
||||
try:
|
||||
to_bytes(to_unicode(line, encoding="utf-8"), encoding="utf-8")
|
||||
return False
|
||||
except ValueError:
|
||||
return True
|
||||
|
||||
|
||||
def chunks(l, n):
|
||||
"""
|
||||
Yield successive n-sized chunks from l.
|
||||
|
||||
+59
-15
@@ -41,7 +41,7 @@ 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, PrependableQueue, TypeAlreadyInQueue, chunks, ResettableTimer, \
|
||||
monotonic_time
|
||||
monotonic_time, filter_non_utf8
|
||||
from octoprint.util.platform import get_os, set_close_exec
|
||||
|
||||
try:
|
||||
@@ -604,7 +604,9 @@ class MachineCom(object):
|
||||
self._sdEnabled = settings().getBoolean(["feature", "sdSupport"])
|
||||
self._sdAvailable = False
|
||||
self._sdFileList = False
|
||||
self._sdFileLongName = False
|
||||
self._sdFiles = []
|
||||
self._sdFilesMap = dict()
|
||||
self._sdFileToSelect = None
|
||||
self._sdFileToSelectUser = None
|
||||
self._ignore_select = False
|
||||
@@ -676,6 +678,7 @@ class MachineCom(object):
|
||||
if settings().getBoolean(["feature", "sdSupport"]):
|
||||
self._sdFileList = False
|
||||
self._sdFiles = []
|
||||
self._sdFilesMap = dict()
|
||||
self._callback.on_comm_sd_files([])
|
||||
|
||||
if self._currentFile is not None:
|
||||
@@ -1497,7 +1500,8 @@ class MachineCom(object):
|
||||
user=user)
|
||||
|
||||
def getSdFiles(self):
|
||||
return self._sdFiles
|
||||
return list(map(lambda x: (x[0], x[1], self._sdFilesMap.get(x[0])),
|
||||
self._sdFiles))
|
||||
|
||||
def deleteSdFile(self, filename, tags=None):
|
||||
if not self._sdEnabled:
|
||||
@@ -1557,9 +1561,10 @@ class MachineCom(object):
|
||||
self.sendCommand("M22", tags=tags | {"trigger:comm.release_sd_card",})
|
||||
self._sdAvailable = False
|
||||
self._sdFiles = []
|
||||
self._sdFilesMap = dict()
|
||||
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
self._callback.on_comm_sd_files(self._sdFiles)
|
||||
self._callback.on_comm_sd_files(self.getSdFiles())
|
||||
|
||||
def sayHello(self, tags=None):
|
||||
if tags is None:
|
||||
@@ -1791,32 +1796,61 @@ class MachineCom(object):
|
||||
##~~ SD file list
|
||||
# if we are currently receiving an sd file list, each line is just a filename, so just read it and abort processing
|
||||
if self._sdFileList and not "End file list" in line:
|
||||
preprocessed_line = lower_line
|
||||
fileinfo = preprocessed_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
|
||||
preprocessed_line = line
|
||||
fileinfo = preprocessed_line.split(None, 2)
|
||||
if len(fileinfo) == 3:
|
||||
# name, size, long name
|
||||
filename, size, longname = fileinfo
|
||||
elif len(fileinfo) == 2:
|
||||
# name, size
|
||||
filename, size = fileinfo
|
||||
longname = None
|
||||
else:
|
||||
# name
|
||||
filename = preprocessed_line
|
||||
size = None
|
||||
longname = None
|
||||
|
||||
if size is not None:
|
||||
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 = preprocessed_line
|
||||
size = None
|
||||
else:
|
||||
# no extended file information, so only the filename is there and we set size to None
|
||||
filename = preprocessed_line
|
||||
size = None
|
||||
|
||||
if valid_file_type(filename, "machinecode"):
|
||||
if filter_non_ascii(filename):
|
||||
self._logger.warning("Got a file from printer's SD that has a non-ascii filename (%s), that shouldn't happen according to the protocol" % filename)
|
||||
self._logger.warning("Got a file from printer's SD that has a non-ascii filename ({!r}), "
|
||||
"that shouldn't happen according to the protocol".format(filename))
|
||||
elif longname and filter_non_utf8(longname):
|
||||
self._logger.warning("Got a file from printer's SD that has a non-utf8 longname ({!r}), "
|
||||
"that shouldn't happen according to the protocol".format(longname))
|
||||
else:
|
||||
if not filename.startswith("/"):
|
||||
# file from the root of the sd -- we'll prepend a /
|
||||
filename = "/" + filename
|
||||
self._sdFiles.append((filename, size))
|
||||
self._sdFiles.append((filename.lower(), size))
|
||||
if longname is not None:
|
||||
self._sdFilesMap[filename] = longname
|
||||
continue
|
||||
|
||||
elif self._sdFileLongName:
|
||||
# Response to M33: just one line with the long name. Yay.
|
||||
#
|
||||
# As we have NO way to parse the request short name from that, and also no indicator
|
||||
# on the line that this is in fact a reply to M33 and not just some arbitrary line injected
|
||||
# by the firmware belonging to some other command and/or an out of band message/autoreport, we have
|
||||
# to hope for the best here, set our requested filename as a flag and only use the potential mapping
|
||||
# if it has a valid file extension.
|
||||
#
|
||||
# It would have been so much easier if M33's output was something sensible like
|
||||
# "<short name>: <long name>" or such, but why make things easy...
|
||||
_, ext = os.path.splitext(lower_line)
|
||||
if ext and valid_file_type(lower_line, "machinecode"):
|
||||
self._sdFilesMap[self._sdFileLongName] = line
|
||||
self._sdFileLongName = False
|
||||
|
||||
handled = False
|
||||
|
||||
# process oks
|
||||
@@ -1824,6 +1858,7 @@ class MachineCom(object):
|
||||
# ok only considered handled if it's alone on the line, might be
|
||||
# a response to an M105 or an M114
|
||||
self._handle_ok()
|
||||
self._sdFileLongName = False # reset looking for M33 response
|
||||
needs_further_handling = "T:" in line or "T0:" in line or "B:" in line or "C:" in line or \
|
||||
"X:" in line or "NAME:" in line
|
||||
handled = (line == "wait" or line == "ok" or not needs_further_handling)
|
||||
@@ -2096,7 +2131,7 @@ class MachineCom(object):
|
||||
self._sdFileList = True
|
||||
elif 'End file list' in line:
|
||||
self._sdFileList = False
|
||||
self._callback.on_comm_sd_files(self._sdFiles)
|
||||
self._callback.on_comm_sd_files(self.getSdFiles())
|
||||
elif 'SD printing byte' in line:
|
||||
# answer to M27, at least on Marlin, Repetier and Sprinter: "SD printing byte %d/%d"
|
||||
match = regex_sdPrintingByte.search(line)
|
||||
@@ -3696,7 +3731,8 @@ class MachineCom(object):
|
||||
|
||||
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._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, gcode=None, subcode=None, *args, **kwargs):
|
||||
@@ -3802,6 +3838,14 @@ class MachineCom(object):
|
||||
self._sdstatus_autoreporting = self._firmware_capabilities.get(self.CAPABILITY_AUTOREPORT_SD_STATUS, False) \
|
||||
and (interval > 0)
|
||||
|
||||
def _gcode_M33_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
parts = cmd.split(None, 1)
|
||||
if len(parts) > 1:
|
||||
filename = parts[1].strip().lower()
|
||||
if not filename.startswith("/"):
|
||||
filename = "/" + filename
|
||||
self._sdFileLongName = filename
|
||||
|
||||
def _gcode_M110_sending(self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs):
|
||||
newLineNumber = 0
|
||||
match = regexes_parameters["intN"].search(cmd)
|
||||
|
||||
Reference in new issue
Block a user