✨ M20 T support (timestamps for files on sd card) (#4610)
- Use "M20 L T" (if CAPABILITY_EXTENDED_M20 is available) which gives us long file names but also file timestamps. - Wire up that timestamp into "date" field which gives us "Uploaded: ... ago" for files on SD card. Sorting by upload date also works. - Implementing this also fixes parsing of response to (for example manually sent) "M20 T" command. Octoprint assumed that third entry in response is always long file name while with M20 T it is timestamp. - Add conversion routines between M20 T timestamp and unix timestamp. Wire up that conversion in virtual printer. See also https://reprap.org/wiki/G-code#M20:_List_SD_card
This commit is contained in:
1 parent
82c892ba40
commit
65e222da1e
9 files changed
+282
-37
No files matched your search
@@ -170,6 +170,7 @@ date of first contribution):
|
||||
* [Kestin Goforth](https://github.com/kforth)
|
||||
* [Dawid Pieper](https://github.com/dawidpieper)
|
||||
* ["arrdem"](https://github.com/arrdem)
|
||||
* [Arkadiusz Miśkiewicz](https://github.com/arekm)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
|
||||
@@ -118,6 +118,12 @@ There many configuration options via ``config.yaml`` for the virtual printer tha
|
||||
# False: <filename>
|
||||
size: true
|
||||
|
||||
# Whether M20 responses will include timestamp or not (only if size = true as well)
|
||||
#
|
||||
# True: <filename> <filesize in bytes> <timestamp as hex>
|
||||
# False: <filename> <filesize in bytes>
|
||||
timestamp: false
|
||||
|
||||
# Whether M20 responses will include longname or not (only if size = true as well)
|
||||
#
|
||||
# True: <filename> <filesize in bytes> <longname>
|
||||
|
||||
@@ -15,6 +15,7 @@ from serial import SerialTimeoutException
|
||||
|
||||
from octoprint.plugin import plugin_manager
|
||||
from octoprint.util import RepeatedTimer, get_dos_filename, to_bytes, to_unicode
|
||||
from octoprint.util.files import unix_timestamp_to_m20_timestamp
|
||||
|
||||
|
||||
# noinspection PyBroadException
|
||||
@@ -126,6 +127,7 @@ class VirtualPrinter:
|
||||
|
||||
self._writingToSd = False
|
||||
self._writingToSdHandle = None
|
||||
self._writingToSdFile = None
|
||||
self._newSdFilePos = None
|
||||
|
||||
self._heatingUp = False
|
||||
@@ -256,6 +258,7 @@ class VirtualPrinter:
|
||||
pass
|
||||
self._writingToSd = False
|
||||
self._writingToSdHandle = None
|
||||
self._writingToSdFile = None
|
||||
self._newSdFilePos = None
|
||||
|
||||
self._heatingUp = False
|
||||
@@ -592,7 +595,7 @@ class VirtualPrinter:
|
||||
# noinspection PyUnusedLocal
|
||||
def _gcode_M20(self, data: str) -> None:
|
||||
if self._sdCardReady:
|
||||
self._listSd(incl_long="L" in data)
|
||||
self._listSd(incl_long="L" in data, incl_timestamp="T" in data)
|
||||
|
||||
# noinspection PyUnusedLocal
|
||||
def _gcode_M21(self, data: str) -> None:
|
||||
@@ -1379,17 +1382,17 @@ class VirtualPrinter:
|
||||
except Exception:
|
||||
self._logger.exception("While handling %r", data)
|
||||
|
||||
def _listSd(self, incl_long=False):
|
||||
def _listSd(self, incl_long=False, incl_timestamp=False):
|
||||
line = "{dosname}"
|
||||
if self._settings.get_boolean(["sdFiles", "size"]):
|
||||
line += " {size}"
|
||||
if self._settings.get_boolean(["sdFiles", "timestamp"]) or incl_timestamp:
|
||||
line += " {timestamp}"
|
||||
if self._settings.get_boolean(["sdFiles", "longname"]) or incl_long:
|
||||
if self._settings.get_boolean(["sdFiles", "longname_quoted"]):
|
||||
line = '{dosname} {size} "{name}"'
|
||||
line += ' "{name}"'
|
||||
else:
|
||||
line = "{dosname} {size} {name}"
|
||||
else:
|
||||
line = "{dosname} {size}"
|
||||
else:
|
||||
line = "{dosname}"
|
||||
line += " {name}"
|
||||
|
||||
files = self._mappedSdList()
|
||||
items = map(lambda x: line.format(**x), files.values())
|
||||
@@ -1414,6 +1417,7 @@ class VirtualPrinter:
|
||||
"path": entry.path,
|
||||
"dosname": dosname,
|
||||
"size": entry.stat().st_size,
|
||||
"timestamp": unix_timestamp_to_m20_timestamp(entry.stat().st_mtime),
|
||||
}
|
||||
return result
|
||||
|
||||
@@ -1791,6 +1795,7 @@ class VirtualPrinter:
|
||||
except Exception:
|
||||
self._send("error writing to file")
|
||||
self._writingToSdHandle = handle
|
||||
self._writingToSdFile = file
|
||||
self._writingToSd = True
|
||||
self._selectedSdFile = file
|
||||
self._send("Writing to file: %s" % filename)
|
||||
@@ -1804,6 +1809,12 @@ class VirtualPrinter:
|
||||
self._writingToSdHandle = None
|
||||
self._writingToSd = False
|
||||
self._selectedSdFile = None
|
||||
# Most printers don't have RTC and set some ancient date
|
||||
# by default. Emulate that using 2000-01-01 01:00:00
|
||||
# (taken from prusa firmware behaviour)
|
||||
st = os.stat(self._writingToSdFile)
|
||||
os.utime(self._writingToSdFile, (st.st_atime, 946684800))
|
||||
self._writingToSdFile = None
|
||||
self._send("Done saving file")
|
||||
|
||||
def _sdPrintingWorker(self):
|
||||
|
||||
@@ -910,7 +910,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
return list(
|
||||
map(
|
||||
lambda x: {"name": x[0][1:], "size": x[1], "display": x[2]},
|
||||
lambda x: {"name": x[0][1:], "size": x[1], "display": x[2], "date": x[3]},
|
||||
self._comm.getSdFiles(),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -331,6 +331,8 @@ def _getFileList(
|
||||
}
|
||||
if f["size"] is not None:
|
||||
file.update({"size": f["size"]})
|
||||
if f["date"] is not None:
|
||||
file.update({"date": f["date"]})
|
||||
files.append(file)
|
||||
else:
|
||||
filter_func = None
|
||||
|
||||
+65
-28
@@ -43,6 +43,7 @@ from octoprint.util import (
|
||||
sanitize_ascii,
|
||||
to_unicode,
|
||||
)
|
||||
from octoprint.util.files import m20_timestamp_to_unix_timestamp
|
||||
from octoprint.util.platform import get_os, set_close_exec
|
||||
|
||||
try:
|
||||
@@ -1969,7 +1970,7 @@ class MachineCom:
|
||||
|
||||
def getSdFiles(self):
|
||||
return list(
|
||||
map(lambda x: (x[0], x[1], self._sdFilesMap.get(x[0])), self._sdFiles)
|
||||
map(lambda x: (x[0], x[1], self._sdFilesMap.get(x[0]), x[2]), self._sdFiles)
|
||||
)
|
||||
|
||||
def deleteSdFile(self, filename, tags=None):
|
||||
@@ -2007,7 +2008,7 @@ class MachineCom:
|
||||
tags = set()
|
||||
|
||||
if self._capability_supported(self.CAPABILITY_EXTENDED_M20):
|
||||
command = "M20 L"
|
||||
command = "M20 L T"
|
||||
else:
|
||||
command = "M20"
|
||||
|
||||
@@ -2443,28 +2444,7 @@ class MachineCom:
|
||||
##~~ 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._sdEnabled and self._sdFileList and "End file list" not in line:
|
||||
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
|
||||
(filename, size, timestamp, longname) = parse_file_list_line(line)
|
||||
|
||||
if valid_file_type(filename, "machinecode"):
|
||||
if filter_non_ascii(filename):
|
||||
@@ -2487,11 +2467,8 @@ class MachineCom:
|
||||
filename = "/" + filename
|
||||
if self._sdLowerCase:
|
||||
filename = filename.lower()
|
||||
self._sdFiles.append((filename, size))
|
||||
self._sdFiles.append((filename, size, timestamp))
|
||||
if longname is not None:
|
||||
if longname[0] == '"' and longname[-1] == '"':
|
||||
# apparently some firmwares enclose the long name in quotes...
|
||||
longname = longname[1:-1]
|
||||
self._sdFilesMap[filename] = longname
|
||||
continue
|
||||
|
||||
@@ -6275,6 +6252,66 @@ def canonicalize_temperatures(parsed, current):
|
||||
return result
|
||||
|
||||
|
||||
def _validate_m20_timestamp(timestamp):
|
||||
try:
|
||||
m20_timestamp_to_unix_timestamp(timestamp)
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def parse_file_list_line(line):
|
||||
longname = None
|
||||
size = None
|
||||
timestamp = None
|
||||
fileinfo = line.split(None, 3)
|
||||
if len(fileinfo) == 4:
|
||||
# name, size, timestamp, long name or name, size, long name with spaces
|
||||
filename, size, timestamp, longname = fileinfo
|
||||
if not _validate_m20_timestamp(timestamp):
|
||||
# longname with spaces. Split line again with twice split limit to get longname right in case
|
||||
# of multiple whitespace characters in it.
|
||||
filename, size, longname = line.split(None, 2)
|
||||
timestamp = None
|
||||
elif len(fileinfo) == 3:
|
||||
# name, size, long name or name, size, timestamp
|
||||
filename, size, third = fileinfo
|
||||
if _validate_m20_timestamp(third):
|
||||
timestamp = third
|
||||
else:
|
||||
longname = third
|
||||
elif len(fileinfo) == 2:
|
||||
# name, size
|
||||
filename, size = fileinfo
|
||||
else:
|
||||
# name
|
||||
filename = line
|
||||
|
||||
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/timestamp/longname to None
|
||||
filename = line
|
||||
size = None
|
||||
timestamp = None
|
||||
longname = None
|
||||
else:
|
||||
if timestamp is not None:
|
||||
# size was valid and we have timestamp, so try to use it
|
||||
try:
|
||||
timestamp = m20_timestamp_to_unix_timestamp(timestamp)
|
||||
except ValueError:
|
||||
timestamp = None
|
||||
|
||||
if longname is not None:
|
||||
if longname[0] == '"' and longname[-1] == '"':
|
||||
# apparently some firmwares enclose the long name in quotes...
|
||||
longname = longname[1:-1]
|
||||
|
||||
return (filename, size, timestamp, longname)
|
||||
|
||||
|
||||
def parse_temperature_line(line, current):
|
||||
"""
|
||||
Parses the provided temperature line.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import datetime
|
||||
import itertools
|
||||
import logging
|
||||
import os.path
|
||||
@@ -315,3 +316,65 @@ def search_through_file_python(path, term, compiled):
|
||||
if term in line or compiled.match(term):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def unix_timestamp_to_m20_timestamp(unix_timestamp):
|
||||
"""
|
||||
Converts unix timestamp to "M20 T" format
|
||||
which embeds date and time into 32bit int.
|
||||
Upper 16 bit contain date, lower 16 bit contain time.
|
||||
|
||||
https://reprap.org/wiki/G-code#M20:_List_SD_card
|
||||
|
||||
Format derived from FAT filesystem timestamps:
|
||||
https://wiki.osdev.org/FAT
|
||||
|
||||
Arguments:
|
||||
unix_timestamp (int): Unix timestamp in seconds
|
||||
Returns:
|
||||
string: M20 T timestamp as hex string
|
||||
"""
|
||||
|
||||
dt = datetime.datetime.fromtimestamp(unix_timestamp)
|
||||
m20_date = dt.year - 1980 << 9 | dt.month << 5 | dt.day
|
||||
m20_time = dt.hour << 11 | dt.minute << 5
|
||||
m20_time |= (dt.second - (dt.second % 2)) // 2
|
||||
return hex(m20_date << 16 | m20_time)
|
||||
|
||||
|
||||
def m20_timestamp_to_unix_timestamp(timestamp):
|
||||
"""
|
||||
Converts "M20 T" timestamp to unix timestamp.
|
||||
Upper 16 bit contain date, lower 16 bit contain time.
|
||||
|
||||
https://reprap.org/wiki/G-code#M20:_List_SD_card
|
||||
|
||||
Format derived from FAT filesystem timestamps:
|
||||
https://wiki.osdev.org/FAT
|
||||
|
||||
Arguments:
|
||||
timestamp (string): M20 T timestamp as hex string
|
||||
Returns:
|
||||
int: Unix timestamp in seconds
|
||||
"""
|
||||
|
||||
# Only hex in 0xABC format is valid while int() accepts
|
||||
# hex without 0x prefix, too.
|
||||
if not timestamp.startswith("0x"):
|
||||
raise ValueError("Invalid M20 T timestamp format")
|
||||
|
||||
timestamp = int(timestamp, 16)
|
||||
dt = timestamp >> 16
|
||||
day = dt & (1 << 5) - 1
|
||||
month = (dt >> 5) & ((1 << 4) - 1)
|
||||
year = ((dt >> 9) & (1 << 7) - 1) + 1980
|
||||
d = datetime.date(year, month, day)
|
||||
|
||||
tm = timestamp & (2**16 - 1)
|
||||
second = (tm & (1 << 5) - 1) * 2
|
||||
minute = (tm >> 5) & ((1 << 6) - 1)
|
||||
hour = (tm >> 11) & ((1 << 5) - 1)
|
||||
t = datetime.time(hour, minute, second)
|
||||
|
||||
combined_dt = datetime.datetime.combine(d, t)
|
||||
return int(combined_dt.timestamp())
|
||||
@@ -2,8 +2,10 @@ import unittest
|
||||
from unittest import mock
|
||||
|
||||
import ddt
|
||||
import pytest
|
||||
|
||||
import octoprint.util.comm
|
||||
from octoprint.util.files import m20_timestamp_to_unix_timestamp
|
||||
|
||||
|
||||
@ddt.ddt
|
||||
@@ -286,3 +288,102 @@ class TestCommErrorHandling(unittest.TestCase):
|
||||
self.assert_not_disconnected()
|
||||
self.assert_not_print_cancelled()
|
||||
self.assert_not_cleared_to_send()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"val,expected",
|
||||
[
|
||||
("aaa", False),
|
||||
("1234", False),
|
||||
("0x21bf7d", True),
|
||||
("0xghijk", False),
|
||||
("0x28210800", True),
|
||||
],
|
||||
)
|
||||
def test__validate_m20_timestamp(val, expected):
|
||||
assert octoprint.util.comm._validate_m20_timestamp(val) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"val,expected",
|
||||
[
|
||||
(
|
||||
"line that makes little sense",
|
||||
("line that makes little sense", None, None, None),
|
||||
),
|
||||
("name.gco", ("name.gco", None, None, None)),
|
||||
("name.gco invalid-size", ("name.gco invalid-size", None, None, None)),
|
||||
(
|
||||
"name.gco 3424324",
|
||||
("name.gco", 3424324, None, None),
|
||||
),
|
||||
(
|
||||
"name.gco 3424324 longname.gcode",
|
||||
("name.gco", 3424324, None, "longname.gcode"),
|
||||
),
|
||||
(
|
||||
"name.gco 3424324 0x21bf7d",
|
||||
(
|
||||
"name.gco",
|
||||
3424324,
|
||||
m20_timestamp_to_unix_timestamp("0x21bf7d"),
|
||||
None,
|
||||
),
|
||||
),
|
||||
(
|
||||
"name.gco 3424324 0xinvalid_timestamp_as_longname",
|
||||
("name.gco", 3424324, None, "0xinvalid_timestamp_as_longname"),
|
||||
),
|
||||
(
|
||||
"longname.gcode 3424324 0x21bf7d",
|
||||
(
|
||||
"longname.gcode",
|
||||
3424324,
|
||||
m20_timestamp_to_unix_timestamp("0x21bf7d"),
|
||||
None,
|
||||
),
|
||||
),
|
||||
(
|
||||
"longname.gcode 3424324 longname.gcode",
|
||||
("longname.gcode", 3424324, None, "longname.gcode"),
|
||||
),
|
||||
(
|
||||
"name.gco 32424 0x21bf7d long name without quoting",
|
||||
(
|
||||
"name.gco",
|
||||
32424,
|
||||
m20_timestamp_to_unix_timestamp("0x21bf7d"),
|
||||
"long name without quoting",
|
||||
),
|
||||
),
|
||||
(
|
||||
"name.gco 32424 0x21bf7d long name without quoting",
|
||||
(
|
||||
"name.gco",
|
||||
32424,
|
||||
m20_timestamp_to_unix_timestamp("0x21bf7d"),
|
||||
"long name without quoting",
|
||||
),
|
||||
),
|
||||
(
|
||||
'name.gco 32424 0x21bf7d "long name with quoting"',
|
||||
(
|
||||
"name.gco",
|
||||
32424,
|
||||
m20_timestamp_to_unix_timestamp("0x21bf7d"),
|
||||
"long name with quoting",
|
||||
),
|
||||
),
|
||||
(
|
||||
'name.gco 32424 0x21bf7d "long name with quoting"',
|
||||
(
|
||||
"name.gco",
|
||||
32424,
|
||||
m20_timestamp_to_unix_timestamp("0x21bf7d"),
|
||||
"long name with quoting",
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_parse_file_list_line(val, expected):
|
||||
assert octoprint.util.comm.parse_file_list_line(val) == expected
|
||||
@@ -1,16 +1,20 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import datetime
|
||||
import os
|
||||
import re
|
||||
import unittest
|
||||
|
||||
import pytest
|
||||
from ddt import data, ddt, unpack
|
||||
|
||||
from octoprint.util.files import (
|
||||
m20_timestamp_to_unix_timestamp,
|
||||
sanitize_filename,
|
||||
search_through_file,
|
||||
search_through_file_python,
|
||||
unix_timestamp_to_m20_timestamp,
|
||||
)
|
||||
|
||||
|
||||
@@ -66,3 +70,23 @@ class FilesUtilTest(unittest.TestCase):
|
||||
)
|
||||
actual = search_through_file_python(path, term, compiled)
|
||||
self.assertEqual(actual, expected)
|
||||
|
||||
|
||||
# based on https://github.com/nathanhi/pyfatfs/blob/master/tests/test_DosDateTime.py
|
||||
m20_timestamp_tests = [
|
||||
("0x210000", datetime.datetime(1980, 1, 1).timestamp()),
|
||||
("0xff9f0000", datetime.datetime(2107, 12, 31).timestamp()),
|
||||
("0x21bf7d", datetime.datetime(1980, 1, 1, 23, 59, 58).timestamp()),
|
||||
("0x549088aa", datetime.datetime(2022, 4, 16, 17, 5, 20).timestamp()),
|
||||
("0x28210800", datetime.datetime(2000, 1, 1, 1, 0).timestamp()),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("val,expected", m20_timestamp_tests)
|
||||
def test_m20_timestamp_to_unix_timestamp(val, expected):
|
||||
assert m20_timestamp_to_unix_timestamp(val) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("expected,val", m20_timestamp_tests)
|
||||
def test_unix_timestamp_to_m20_timestamp(expected, val):
|
||||
assert unix_timestamp_to_m20_timestamp(val) == expected
|
||||
Reference in new issue
Block a user