✨ Support writing long names to SD
If LFN_WRITE capability is reported as supported, OctoPrint by default now will upload SD files to the printer under their full name instead of shortening it to DOS conventions. The primary name as reported by the firmware (first entry in the M20 output) is still considered the main name and used for any file operations like selecting or deleting. So, if the firmware supports a DOS name here, that's also what OctoPrint will (continue to) use for any such operations. Implements #4494
This commit is contained in:
1 parent
b7bd1d9359
commit
4af7bbea5f
6 files changed
+126
-43
No files matched your search
@@ -78,7 +78,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
# sd handling
|
||||
self._sdPrinting = False
|
||||
self._sdStreaming = False
|
||||
self._sdFilelistAvailable = threading.Event()
|
||||
self._streamingFinishedCallback = None
|
||||
self._streamingFailedCallback = None
|
||||
|
||||
@@ -1007,12 +1006,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
remote_name = self._get_free_remote_name(filename)
|
||||
self._create_estimator("stream")
|
||||
self._comm.startFileTransfer(
|
||||
remote_name = self._comm.startFileTransfer(
|
||||
path,
|
||||
filename,
|
||||
"/" + remote_name,
|
||||
special=not valid_file_type(filename, "gcode"),
|
||||
tags=tags | {"trigger:printer.add_sd_file"},
|
||||
)
|
||||
@@ -1049,12 +1046,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
"""
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._sdFilelistAvailable.clear()
|
||||
self._comm.refreshSdFiles(
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.refresh_sd_files"}
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.refresh_sd_files"},
|
||||
blocking=blocking,
|
||||
timeout=kwargs.get("timeout", 10),
|
||||
)
|
||||
if blocking and not self.is_printing():
|
||||
self._sdFilelistAvailable.wait(kwargs.get("timeout", 10))
|
||||
|
||||
# ~~ state monitoring
|
||||
|
||||
@@ -1225,7 +1221,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
)
|
||||
)
|
||||
|
||||
def _setJobData(self, filename, filesize, sd, user=None):
|
||||
def _setJobData(self, filename, filesize, sd, user=None, data=None):
|
||||
with self._selectedFileMutex:
|
||||
if filename is not None:
|
||||
if sd:
|
||||
@@ -1278,11 +1274,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
date = None
|
||||
filament = None
|
||||
display_name = name_in_storage
|
||||
|
||||
if path_on_disk:
|
||||
# Use a string for mtime because it could be float and the
|
||||
# Use an int for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
date = int(os.stat(path_on_disk).st_mtime)
|
||||
date = int(os.stat(path_on_disk).st_mtime)
|
||||
|
||||
try:
|
||||
fileData = self._fileManager.get_metadata(
|
||||
@@ -1329,6 +1325,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
|
||||
self._selectedFile["estimatedPrintTimeType"] = "analysis"
|
||||
|
||||
elif data:
|
||||
display_name = data.longname
|
||||
date = data.timestamp
|
||||
|
||||
self._stateMonitor.set_job_data(
|
||||
self._dict(
|
||||
file=self._dict(
|
||||
@@ -1539,9 +1539,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
def on_comm_sd_files(self, files):
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
|
||||
self._sdFilelistAvailable.set()
|
||||
|
||||
def on_comm_file_selected(self, full_path, size, sd, user=None):
|
||||
def on_comm_file_selected(self, full_path, size, sd, user=None, data=None):
|
||||
if full_path is not None:
|
||||
payload = self._payload_for_print_job_event(
|
||||
location=FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
|
||||
@@ -1564,7 +1563,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
"Print job deselected - user: {}".format(user if user else "n/a")
|
||||
)
|
||||
|
||||
self._setJobData(full_path, size, sd, user=user)
|
||||
self._setJobData(full_path, size, sd, user=user, data=data)
|
||||
self._stateMonitor.set_state(
|
||||
self._dict(
|
||||
text=self.get_state_string(),
|
||||
|
||||
@@ -70,13 +70,22 @@ class SerialCapabilities(BaseModel):
|
||||
"""Whether to enable temperature autoreport in the firmware if its support is detected"""
|
||||
|
||||
autoreport_sdstatus: bool = True
|
||||
"""Whether to enable SD printing autoreport in the firmware if its support is detected"""
|
||||
|
||||
autoreport_pos: bool = True
|
||||
"""Whether to enable position autoreport in the firmware if its support is detected"""
|
||||
|
||||
busy_protocol: bool = True
|
||||
"""Whether to shorten the communication timeout if the firmware seems to support the busy protocol"""
|
||||
|
||||
emergency_parser: bool = True
|
||||
"""Whether to send emergency commands out of band if the firmware seems to support the emergency parser"""
|
||||
|
||||
extended_m20: bool = True
|
||||
"""Whether to request extended M20 (file list) output from the firmware if its support is detected"""
|
||||
|
||||
lfn_write: bool = True
|
||||
"""Whether to enable long filename support for SD card writes if the firmware reports support for it"""
|
||||
|
||||
|
||||
@with_attrs_docs
|
||||
|
||||
@@ -258,6 +258,7 @@ def getSettings():
|
||||
["serial", "capabilities", "emergency_parser"]
|
||||
),
|
||||
"capExtendedM20": s.getBoolean(["serial", "capabilities", "extended_m20"]),
|
||||
"capLfnWrite": s.getBoolean(["serial", "capabilities", "lfn_write"]),
|
||||
"resendRatioThreshold": s.getInt(["serial", "resendRatioThreshold"]),
|
||||
"resendRatioStart": s.getInt(["serial", "resendRatioStart"]),
|
||||
"ignoreEmptyPorts": s.getBoolean(["serial", "ignoreEmptyPorts"]),
|
||||
@@ -957,6 +958,11 @@ def _saveSettings(data):
|
||||
["serial", "capabilities", "extended_m20"],
|
||||
data["serial"]["capExtendedM20"],
|
||||
),
|
||||
if "capLfnWrite" in data["serial"]:
|
||||
s.setBoolean(
|
||||
["serial", "capabilities", "lfn_write"],
|
||||
data["serial"]["capLfnWrite"],
|
||||
)
|
||||
if "resendRatioThreshold" in data["serial"]:
|
||||
s.setInt(
|
||||
["serial", "resendRatioThreshold"], data["serial"]["resendRatioThreshold"]
|
||||
|
||||
@@ -238,6 +238,7 @@ $(function () {
|
||||
self.serial_capBusyProtocol = ko.observable(undefined);
|
||||
self.serial_capEmergencyParser = ko.observable(undefined);
|
||||
self.serial_capExtendedM20 = ko.observable(undefined);
|
||||
self.serial_capLfnWrite = ko.observable(undefined);
|
||||
self.serial_sendM112OnError = ko.observable(undefined);
|
||||
self.serial_disableSdPrintingDetection = ko.observable(undefined);
|
||||
self.serial_ackMax = ko.observable(undefined);
|
||||
|
||||
@@ -411,6 +411,13 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_capLfnWrite" id="settings-serialCapLfnWrite"> {{ _('Send long names for writing files to the printer\'s SD card via <code>M28</code>, if detected as supported by the firmware') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
|
||||
+89
-28
@@ -17,7 +17,7 @@ import queue
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from collections import deque, namedtuple
|
||||
|
||||
import serial
|
||||
import wrapt
|
||||
@@ -39,6 +39,7 @@ from octoprint.util import (
|
||||
filter_non_ascii,
|
||||
filter_non_utf8,
|
||||
get_bom,
|
||||
get_dos_filename,
|
||||
get_exception_string,
|
||||
sanitize_ascii,
|
||||
to_unicode,
|
||||
@@ -183,6 +184,13 @@ regex_serial_devices = re.compile(r"^(?:ttyUSB|ttyACM|tty\.usb|cu\.|cuaU|ttyS|rf
|
||||
"""Regex used to filter out valid tty devices"""
|
||||
|
||||
|
||||
MINIMAL_SD_TIMESTAMP = 1212012000
|
||||
# May 29th 2008 = RepRap 1.0 "Darwin" achieves self-replication
|
||||
|
||||
|
||||
SDFileData = namedtuple("SDFileData", ["name", "size", "timestamp", "longname"])
|
||||
|
||||
|
||||
def serialList():
|
||||
if os.name == "nt":
|
||||
candidates = []
|
||||
@@ -478,6 +486,7 @@ class MachineCom:
|
||||
CAPABILITY_EMERGENCY_PARSER = "EMERGENCY_PARSER"
|
||||
CAPABILITY_CHAMBER_TEMP = "CHAMBER_TEMPERATURE"
|
||||
CAPABILITY_EXTENDED_M20 = "EXTENDED_M20"
|
||||
CAPABILITY_LFN_WRITE = "LFN_WRITE"
|
||||
|
||||
CAPABILITY_SUPPORT_ENABLED = "enabled"
|
||||
CAPABILITY_SUPPORT_DETECTED = "detected"
|
||||
@@ -604,6 +613,9 @@ class MachineCom:
|
||||
self.CAPABILITY_EXTENDED_M20: settings().getBoolean(
|
||||
["serial", "capabilities", "extended_m20"]
|
||||
),
|
||||
self.CAPABILITY_LFN_WRITE: settings().getBoolean(
|
||||
["serial", "capabilities", "lfn_write"]
|
||||
),
|
||||
}
|
||||
|
||||
last_line_count = settings().getInt(["serial", "lastLineBufferSize"])
|
||||
@@ -752,8 +764,8 @@ class MachineCom:
|
||||
self._sdAvailable = False
|
||||
self._sdFileList = False
|
||||
self._sdFileLongName = False
|
||||
self._sdFiles = []
|
||||
self._sdFilesMap = {}
|
||||
self._sdFiles = {}
|
||||
self._sdFilesAvailable = threading.Event()
|
||||
self._sdFileToSelect = None
|
||||
self._sdFileToSelectUser = None
|
||||
self._ignore_select = False
|
||||
@@ -886,8 +898,7 @@ class MachineCom:
|
||||
if newState == self.STATE_CLOSED or newState == self.STATE_CLOSED_WITH_ERROR:
|
||||
if settings().getBoolean(["feature", "sdSupport"]):
|
||||
self._sdFileList = False
|
||||
self._sdFiles = []
|
||||
self._sdFilesMap = {}
|
||||
self._sdFiles = {}
|
||||
self._callback.on_comm_sd_files([])
|
||||
|
||||
if self._currentFile is not None:
|
||||
@@ -1249,7 +1260,7 @@ class MachineCom:
|
||||
self._changeState(self.STATE_CLOSED)
|
||||
|
||||
if settings().getBoolean(["feature", "sdSupport"]):
|
||||
self._sdFileList = []
|
||||
self._sdFiles = {}
|
||||
|
||||
def setTemperatureOffset(self, offsets):
|
||||
self._tempOffsets.update(offsets)
|
||||
@@ -1518,9 +1529,26 @@ class MachineCom:
|
||||
self._logger.exception("Error while trying to start printing")
|
||||
self._trigger_error(get_exception_string(), "start_print")
|
||||
|
||||
def startFileTransfer(
|
||||
self, path, localFilename, remoteFilename, special=False, tags=None
|
||||
):
|
||||
def _get_free_remote_name(self, filename: str) -> str:
|
||||
if not self._capability_supported(self.CAPABILITY_LFN_WRITE) and valid_file_type(
|
||||
filename, "gcode"
|
||||
):
|
||||
# figure out remote filename
|
||||
self.refreshSdFiles(blocking=True)
|
||||
existingSdFiles = list(map(lambda x: x[0], self.getSdFiles()))
|
||||
remote_name = get_dos_filename(
|
||||
filename,
|
||||
existing_filenames=existingSdFiles,
|
||||
extension="gco",
|
||||
whitelisted_extensions=["gco", "g"],
|
||||
)
|
||||
else:
|
||||
# either LFN_WRITE is supported, or this is not a gcode file
|
||||
remote_name = os.path.basename(filename)
|
||||
|
||||
return remote_name
|
||||
|
||||
def startFileTransfer(self, path, filename, remote=None, special=False, tags=None):
|
||||
if not self.isOperational() or self.isBusy():
|
||||
self._logger.info("Printer is not operational or busy")
|
||||
return
|
||||
@@ -1528,33 +1556,36 @@ class MachineCom:
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
if remote is None:
|
||||
remote = "/" + self._get_free_remote_name(filename)
|
||||
|
||||
with self._jobLock:
|
||||
self.resetLineNumbers(tags={"trigger:comm.start_file_transfer"})
|
||||
|
||||
if special:
|
||||
self._currentFile = SpecialStreamingGcodeFileInformation(
|
||||
path, localFilename, remoteFilename
|
||||
path, filename, remote
|
||||
)
|
||||
else:
|
||||
self._currentFile = StreamingGcodeFileInformation(
|
||||
path, localFilename, remoteFilename
|
||||
)
|
||||
self._currentFile = StreamingGcodeFileInformation(path, filename, remote)
|
||||
self._currentFile.start()
|
||||
|
||||
self.sendCommand(
|
||||
"M28 %s" % remoteFilename,
|
||||
"M28 %s" % remote,
|
||||
tags=tags
|
||||
| {
|
||||
"trigger:comm.start_file_transfer",
|
||||
},
|
||||
)
|
||||
self._callback.on_comm_file_transfer_started(
|
||||
localFilename,
|
||||
remoteFilename,
|
||||
filename,
|
||||
remote,
|
||||
self._currentFile.getFilesize(),
|
||||
user=self._currentFile.getUser(),
|
||||
)
|
||||
|
||||
return remote
|
||||
|
||||
def cancelFileTransfer(self, tags=None):
|
||||
if not self.isOperational() or not self.isStreaming():
|
||||
self._logger.info("Printer is not operational or not streaming")
|
||||
@@ -1976,7 +2007,15 @@ class MachineCom:
|
||||
|
||||
def getSdFiles(self):
|
||||
return list(
|
||||
map(lambda x: (x[0], x[1], self._sdFilesMap.get(x[0]), x[2]), self._sdFiles)
|
||||
map(
|
||||
lambda x: (
|
||||
x.name,
|
||||
x.size,
|
||||
x.longname if x.longname else x.name,
|
||||
x.timestamp,
|
||||
),
|
||||
self._sdFiles.values(),
|
||||
)
|
||||
)
|
||||
|
||||
def deleteSdFile(self, filename, tags=None):
|
||||
@@ -2003,7 +2042,7 @@ class MachineCom:
|
||||
)
|
||||
self.refreshSdFiles()
|
||||
|
||||
def refreshSdFiles(self, tags=None):
|
||||
def refreshSdFiles(self, tags=None, blocking=False, timeout=10):
|
||||
if not self._sdEnabled:
|
||||
return
|
||||
|
||||
@@ -2024,6 +2063,7 @@ class MachineCom:
|
||||
else:
|
||||
command = "M20"
|
||||
|
||||
self._sdFilesAvailable.clear()
|
||||
self.sendCommand(
|
||||
command,
|
||||
tags=tags
|
||||
@@ -2031,6 +2071,8 @@ class MachineCom:
|
||||
"trigger:comm.refresh_sd_files",
|
||||
},
|
||||
)
|
||||
if blocking:
|
||||
self._sdFilesAvailable.wait(timeout=timeout)
|
||||
|
||||
def initSdCard(self, tags=None):
|
||||
if not self._sdEnabled:
|
||||
@@ -2067,8 +2109,7 @@ class MachineCom:
|
||||
},
|
||||
)
|
||||
self._sdAvailable = False
|
||||
self._sdFiles = []
|
||||
self._sdFilesMap = {}
|
||||
self._sdFiles = {}
|
||||
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
self._callback.on_comm_sd_files(self.getSdFiles())
|
||||
@@ -2409,7 +2450,7 @@ class MachineCom:
|
||||
"Printer reported SD card as ejected", level=logging.INFO
|
||||
)
|
||||
self._sdAvailable = False
|
||||
self._sdFiles = []
|
||||
self._sdFiles = {}
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
elif self._sdEnabled and action_name == "sd_updated":
|
||||
self._dual_log(
|
||||
@@ -2479,9 +2520,16 @@ class MachineCom:
|
||||
filename = "/" + filename
|
||||
if self._sdLowerCase:
|
||||
filename = filename.lower()
|
||||
self._sdFiles.append((filename, size, timestamp))
|
||||
if longname is not None:
|
||||
self._sdFilesMap[filename] = longname
|
||||
if timestamp is not None and timestamp < MINIMAL_SD_TIMESTAMP:
|
||||
# sanitize timestamp, when creating a file through serial the firmware usually doesn't know the date
|
||||
# and sets something ridiculously low (e.g. 2000-01-01), so let's ignore timestamps like that here
|
||||
timestamp = None
|
||||
self._sdFiles[filename] = SDFileData(
|
||||
name=filename,
|
||||
size=size,
|
||||
timestamp=timestamp,
|
||||
longname=longname,
|
||||
)
|
||||
continue
|
||||
|
||||
elif self._sdFileLongName:
|
||||
@@ -2497,7 +2545,14 @@ class MachineCom:
|
||||
# "<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
|
||||
data = self._sdFiles.get(self._sdFileLongName)
|
||||
if data is not None:
|
||||
self._sdFiles[self._sdFileLongName] = SDFileData(
|
||||
name=data.name,
|
||||
size=data.size,
|
||||
timestamp=data.timestamp,
|
||||
longname=line,
|
||||
)
|
||||
self._sdFileLongName = False
|
||||
|
||||
handled = False
|
||||
@@ -2750,6 +2805,10 @@ class MachineCom:
|
||||
self._logger.info(
|
||||
"Firmware states that it supports long filenames"
|
||||
)
|
||||
elif capability == self.CAPABILITY_LFN_WRITE and enabled:
|
||||
self._logger.info(
|
||||
"Firmware states that it supports writing long filenames"
|
||||
)
|
||||
|
||||
# notify plugins
|
||||
for name, hook in self._firmware_info_hooks[
|
||||
@@ -2948,7 +3007,7 @@ class MachineCom:
|
||||
or "SD card released" in line
|
||||
):
|
||||
self._sdAvailable = False
|
||||
self._sdFiles = []
|
||||
self._sdFiles = {}
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
elif (
|
||||
"SD card ok" in line or "Card successfully initialized" in line
|
||||
@@ -2957,10 +3016,11 @@ class MachineCom:
|
||||
self.refreshSdFiles()
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
elif "Begin file list" in line:
|
||||
self._sdFiles = []
|
||||
self._sdFiles = {}
|
||||
self._sdFileList = True
|
||||
elif "End file list" in line:
|
||||
self._sdFileList = False
|
||||
self._sdFilesAvailable.set()
|
||||
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"
|
||||
@@ -3055,6 +3115,7 @@ class MachineCom:
|
||||
self._currentFile.getFilesize(),
|
||||
True,
|
||||
user=self._currentFile.getUser(),
|
||||
data=self._sdFiles.get(self._currentFile.getFilename()),
|
||||
)
|
||||
elif "Writing to file" in line and self.isStreaming():
|
||||
self._changeState(self.STATE_PRINTING)
|
||||
@@ -5579,7 +5640,7 @@ class MachineComPrintCallback:
|
||||
def on_comm_z_change(self, newZ):
|
||||
pass
|
||||
|
||||
def on_comm_file_selected(self, filename, filesize, sd, user=None):
|
||||
def on_comm_file_selected(self, filename, filesize, sd, user=None, data=None):
|
||||
pass
|
||||
|
||||
def on_comm_sd_state_change(self, sdReady):
|
||||
|
||||
Reference in new issue
Block a user