Refactored some things and added more docs
There was still some redundancy due to how SD upload so far was implemented. Things are now better reusable from hooks. Also fixed the problem that OctoPrint would *always* use the first hook, whether it actually handled the upload or not.
This commit is contained in:
1 parent
37f3396be3
commit
07934d26eb
4 files changed
+176
-131
No files matched your search
+85
-72
@@ -1089,6 +1089,91 @@ octoprint.printer.estimation.factory
|
||||
:return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method
|
||||
:rtype: class or function
|
||||
|
||||
.. _sec-plugins-hook-octoprint-printer-sdcardupload:
|
||||
|
||||
octoprint.printer.sdcardupload
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: sd_card_upload_hook(printer, filename, path, start_callback, success_callback, failure_callback, *args, **kwargs)
|
||||
|
||||
Via this hook plugins can change the way files are being uploaded to the sd card of the printer.
|
||||
|
||||
Implementations **must** call the provided ``start_callback`` on start of the file transfer and either the ``success_callback``
|
||||
or ``failure_callback`` on the end of the file transfer, depending on whether it was successful or not.
|
||||
|
||||
The ``start_callback`` has the following signature:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def start_callback(local_filename, remote_filename):
|
||||
# ...
|
||||
|
||||
``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file
|
||||
to be created on the ``sdcard`` storage.
|
||||
|
||||
``success_callback`` and ``failure_callback`` both have the following signature:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def success_or_failure_callback(local_filename, remote_filename, elapsed):
|
||||
# ...
|
||||
|
||||
``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file
|
||||
to be created on the ``sdcard`` storage. ``elapsed`` is the elapsed time in seconds.
|
||||
|
||||
If the hook is going to handle the upload, it must return the (future) remote filename of the file on the ``sdcard``
|
||||
storage. If it returns ``None`` (or an otherwise falsy value), OctoPrint will interpret this as the hook not going to
|
||||
handle the file upload, in which case the next hook or - if no other hook is registered - the default implementation
|
||||
will be called.
|
||||
|
||||
**Example**
|
||||
|
||||
The following example creates a dummy SD card uploader that does nothing but sleep for ten seconds when a file
|
||||
is supposed to be uploaded. Note that the long running process of sleeping for ten seconds is extracted into its
|
||||
own thread, which is important in order to not block the main application!
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import threading
|
||||
import logging
|
||||
import time
|
||||
|
||||
def nop_upload_to_sd(printer, filename, path, sd_upload_started, sd_upload_succeeded, sd_upload_failed, *args, **kwargs):
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
remote_name = printer._get_free_remote_name(filename)
|
||||
logger.info("Starting dummy SDCard upload from {} to {}".format(filename, remote_name))
|
||||
|
||||
sd_upload_started(filename, remote_name)
|
||||
|
||||
def process():
|
||||
logger.info("Sleeping 10s...")
|
||||
time.sleep(10)
|
||||
logger.info("And done!")
|
||||
sd_upload_succeeded(filename, remote_name, 10)
|
||||
|
||||
thread = threading.Thread(target=process)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
return remote_name
|
||||
|
||||
__plugin_name__ = "No-op SDCard Upload Test"
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.printer.sdcardupload": nop_upload_to_sd
|
||||
}
|
||||
|
||||
.. versionadded:: 1.3.11
|
||||
|
||||
:param object printer: the :py:class:`~octoprint.printer.PrinterInterface` instance the hook was called from
|
||||
:param str filename: filename on the ``local`` storage
|
||||
:param str path: path of the file in the local file system
|
||||
:param function sd_upload_started: callback for when the upload started
|
||||
:param function sd_upload_success: callback for successful finish of upload
|
||||
:param function sd_upload_failure: callback for failure of upload
|
||||
:return: the name of the file on the ``sdcard`` storage or ``None``
|
||||
:rtype: string or ``None``
|
||||
|
||||
.. _sec-plugins-hook-server-http-after_request:
|
||||
|
||||
octoprint.server.api.after_request
|
||||
@@ -1137,78 +1222,6 @@ octoprint.server.http.access_validator
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
.. _sec-plugins-hook-octoprint-printer-sdcardupload:
|
||||
|
||||
octoprint.printer.sdcardupload
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: sd_card_upload_hook(printer, filename, absolutePath, remoteName, *args, **kwargs)
|
||||
|
||||
via hook, you can change the upload system on the sd card of the printer.
|
||||
|
||||
when your copy is finished, you must call the callback (success_hook_sdcopy or error_hook_sdcopy) for notify the status (it's important)
|
||||
|
||||
these callback take into parameter a specific payload :
|
||||
.. code-block:: python
|
||||
payload = {
|
||||
"local": filename,
|
||||
"remote": remoteName,
|
||||
"time": time.time() - timestart
|
||||
}
|
||||
|
||||
``
|
||||
|
||||
**Example:**
|
||||
.. code-block:: python
|
||||
|
||||
# coding=utf-8
|
||||
|
||||
class CustomSdCardUploadPlugin(octoprint.plugin.OctoPrintPlugin):
|
||||
|
||||
def sdcard(self, printer, filename, remoteName, absolutePath, success_hook_sdcopy, error_hook_sdcopy, *args, **kwargs):
|
||||
self._logger.info("custom sd card upload")
|
||||
timestart = time.time()
|
||||
# you can use the printer methode...
|
||||
# for exemple :
|
||||
# printer.release_sd_card(self)
|
||||
# printer.init_sd_card(self)
|
||||
# printer.refresh_sd_files()
|
||||
# do something
|
||||
payload = {
|
||||
"local": filename,
|
||||
"remote": remoteName,
|
||||
"time": time.time() - timestart
|
||||
}
|
||||
success_hook_sdcopy(payload);
|
||||
|
||||
__plugin_name__ = "Custom sd card upload plugin"
|
||||
|
||||
def __plugin_load__():
|
||||
plugin = CustomSdCardUploadPlugin()
|
||||
|
||||
global __plugin_implementation__
|
||||
__plugin_implementation__ = plugin
|
||||
|
||||
global __plugin_hooks__
|
||||
__plugin_hooks__ = {"octoprint.printer.sdcardupload": plugin.custom_sd_card_upload_plugin}
|
||||
|
||||
global __plugin_name__
|
||||
__plugin_name__ = "custom sd card upload plugin"
|
||||
|
||||
|
||||
``
|
||||
|
||||
.. versionadded:: 1.3.11
|
||||
|
||||
:param object printer: access to printer methode
|
||||
:param str filename: filename inside octoprint
|
||||
:param str remoteName: name inside sd card printer
|
||||
:param str absolutePath: absolutePath inside octoprint
|
||||
:param callback : absolutePath inside octoprint
|
||||
:param str absolutePath: absolutePath inside octoprint
|
||||
:return success_hook_sdcopy: for notify success (important), this callback take payload parameter
|
||||
:return error_hook_sdcopy: for notify error (important), this callback take payload parameter
|
||||
|
||||
.. _sec-plugins-hook-server-http-bodysize:
|
||||
|
||||
octoprint.server.http.bodysize
|
||||
|
||||
@@ -653,49 +653,75 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
return []
|
||||
return map(lambda x: (x[0][1:], x[1]), self._comm.getSdFiles())
|
||||
|
||||
def success_hook_sdcopy(self, payload, *args, **kwargs):
|
||||
self.on_comm_file_transfer_done(payload["remote"])
|
||||
eventManager().fire(Events.TRANSFER_DONE, payload)
|
||||
|
||||
def error_hook_sdcopy(self, payload, *args, **kwargs):
|
||||
eventManager().fire(Events.TRANSFER_FAILED, payload)
|
||||
|
||||
def add_sd_file(self, filename, absolutePath, on_success=None, on_failure=None, *args, **kwargs):
|
||||
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():
|
||||
self._logger.error("No connection to printer or printer is busy")
|
||||
return
|
||||
|
||||
def default_add_sd_file(printer, filename, remoteName, absolutePath, on_success, on_failure):
|
||||
self._create_estimator("stream")
|
||||
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName,
|
||||
special=not valid_file_type(filename, "gcode"),
|
||||
tags=kwargs.get("tags", set()) | {"trigger:printer.add_sd_file"})
|
||||
|
||||
self._streamingFinishedCallback = on_success
|
||||
self._streamingFailedCallback = on_failure
|
||||
|
||||
def sd_upload_started(local_filename, remote_filename):
|
||||
eventManager().fire(Events.TRANSFER_STARTED, dict(local=local_filename,
|
||||
remote=remote_filename))
|
||||
|
||||
def sd_upload_succeeded(local_filename, remote_filename, elapsed):
|
||||
payload = dict(local=local_filename,
|
||||
remote=remote_filename,
|
||||
time=elapsed)
|
||||
eventManager().fire(Events.TRANSFER_DONE, payload)
|
||||
if callable(self._streamingFailedCallback):
|
||||
self._streamingFinishedCallback(remote_filename, remote_filename, FileDestinations.SDCARD)
|
||||
|
||||
def sd_upload_failed(local_filename, remote_filename, elapsed):
|
||||
payload = dict(local=local_filename,
|
||||
remote=remote_filename,
|
||||
time=elapsed)
|
||||
eventManager().fire(Events.TRANSFER_FAILED, payload)
|
||||
if callable(self._streamingFailedCallback):
|
||||
self._streamingFailedCallback(remote_filename, remote_filename, FileDestinations.SDCARD)
|
||||
|
||||
for name, hook in self.sd_card_upload_hooks.items():
|
||||
# first sd card upload plugin that feels responsible gets the job
|
||||
try:
|
||||
result = hook(self, filename, path, sd_upload_started, sd_upload_succeeded, sd_upload_failed,
|
||||
*args, **kwargs)
|
||||
if result is not None:
|
||||
return result
|
||||
except:
|
||||
self._logger.exception("There was an error running the sd upload hook provided by plugin {}".format(name))
|
||||
|
||||
else:
|
||||
# no plugin feels responsible, use the default implementation
|
||||
return self._add_sd_file(filename, path, tags=kwargs.get("tags"))
|
||||
|
||||
def _get_free_remote_name(self, filename):
|
||||
self.refresh_sd_files(blocking=True)
|
||||
existingSdFiles = map(lambda x: x[0], self._comm.getSdFiles())
|
||||
|
||||
if valid_file_type(filename, "gcode"):
|
||||
remoteName = util.get_dos_filename(filename,
|
||||
existing_filenames=existingSdFiles,
|
||||
extension="gco",
|
||||
whitelisted_extensions=["gco", "g"])
|
||||
# figure out remote filename
|
||||
remote_name = util.get_dos_filename(filename,
|
||||
existing_filenames=existingSdFiles,
|
||||
extension="gco",
|
||||
whitelisted_extensions=["gco", "g"])
|
||||
else:
|
||||
# probably something else added through a plugin, use it's basename as-is
|
||||
remoteName = os.path.basename(filename)
|
||||
sd_card_uploads = self.sd_card_upload_hooks.items() + [("default", default_add_sd_file)]
|
||||
for name, hook in sd_card_uploads:
|
||||
try:
|
||||
self._logger.info("run sd card upload with {}".format(name))
|
||||
hook(self, filename, remoteName, absolutePath, self.success_hook_sdcopy, self.error_hook_sdcopy)
|
||||
#only one impl authorize
|
||||
break
|
||||
except:
|
||||
self._logger.exception("Error while processing copy to sd from {}".format(name))
|
||||
|
||||
return remoteName
|
||||
remote_name = os.path.basename(filename)
|
||||
|
||||
return remote_name
|
||||
|
||||
def _add_sd_file(self, filename, path, tags=None):
|
||||
if tags is None:
|
||||
tags = set()
|
||||
|
||||
remote_name = self._get_free_remote_name(filename)
|
||||
self._create_estimator("stream")
|
||||
self._comm.startFileTransfer(path, filename, "/" + remote_name,
|
||||
special=not valid_file_type(filename, "gcode"),
|
||||
tags=tags | {"trigger:printer.add_sd_file"})
|
||||
|
||||
return remote_name
|
||||
|
||||
def delete_sd_file(self, filename, *args, **kwargs):
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
@@ -1174,32 +1200,39 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
part_of_job=True,
|
||||
must_be_set=False)
|
||||
|
||||
def on_comm_file_transfer_started(self, filename, filesize, user=None):
|
||||
def on_comm_file_transfer_started(self, local_filename, remote_filename, filesize, user=None):
|
||||
eventManager().fire(Events.TRANSFER_STARTED, dict(local=local_filename,
|
||||
remote=remote_filename))
|
||||
|
||||
self._sdStreaming = True
|
||||
|
||||
self._setJobData(filename, filesize, True, user=user)
|
||||
self._setJobData(remote_filename, filesize, True, user=user)
|
||||
self._updateProgressData(completion=0.0, filepos=0, printTime=0)
|
||||
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
|
||||
|
||||
def on_comm_file_transfer_done(self, filename, failed=False):
|
||||
def on_comm_file_transfer_done(self, local_filename, remote_filename, elapsed, failed=False):
|
||||
self._sdStreaming = False
|
||||
|
||||
# in case of SD files, both filename and absolutePath are the same, so we set the (remote) filename for
|
||||
# both parameters
|
||||
payload = dict(local=local_filename,
|
||||
remote=remote_filename,
|
||||
time=elapsed)
|
||||
|
||||
if failed:
|
||||
if self._streamingFailedCallback is not None:
|
||||
self._streamingFailedCallback(filename, filename, FileDestinations.SDCARD)
|
||||
eventManager().fire(Events.TRANSFER_FAILED, payload)
|
||||
if callable(self._streamingFailedCallback):
|
||||
self._streamingFailedCallback(remote_filename, remote_filename, FileDestinations.SDCARD)
|
||||
else:
|
||||
if self._streamingFinishedCallback is not None:
|
||||
self._streamingFinishedCallback(filename, filename, FileDestinations.SDCARD)
|
||||
eventManager().fire(Events.TRANSFER_DONE, payload)
|
||||
if callable(self._streamingFinishedCallback):
|
||||
self._streamingFinishedCallback(remote_filename, remote_filename, FileDestinations.SDCARD)
|
||||
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._updateProgressData()
|
||||
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
|
||||
|
||||
def on_comm_file_transfer_failed(self, filename):
|
||||
self.on_comm_file_transfer_done(filename, failed=True)
|
||||
def on_comm_file_transfer_failed(self, local_filename, remote_filename, elapsed):
|
||||
self.on_comm_file_transfer_done(local_filename, remote_filename, elapsed, failed=True)
|
||||
|
||||
def on_comm_force_disconnect(self):
|
||||
self.disconnect()
|
||||
|
||||
@@ -336,7 +336,9 @@ def uploadGcodeFile(target):
|
||||
"""
|
||||
|
||||
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "machinecode"):
|
||||
return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint, tags={"source:api", "api:files.sd"})
|
||||
return filename, printer.add_sd_file(filename, absFilename,
|
||||
on_success=selectAndOrPrint,
|
||||
tags={"source:api", "api:files.sd"})
|
||||
else:
|
||||
selectAndOrPrint(filename, absFilename, destination)
|
||||
return filename
|
||||
|
||||
+14
-17
@@ -1053,7 +1053,7 @@ class MachineCom(object):
|
||||
self._logger.exception("Error while trying to start printing")
|
||||
self._trigger_error(get_exception_string(), "start_print")
|
||||
|
||||
def startFileTransfer(self, filename, localFilename, remoteFilename, special=False, tags=None):
|
||||
def startFileTransfer(self, path, localFilename, remoteFilename, special=False, tags=None):
|
||||
if not self.isOperational() or self.isBusy():
|
||||
self._logger.info("Printer is not operational or busy")
|
||||
return
|
||||
@@ -1065,14 +1065,16 @@ class MachineCom(object):
|
||||
self.resetLineNumbers(tags={"trigger:comm.start_file_transfer"})
|
||||
|
||||
if special:
|
||||
self._currentFile = SpecialStreamingGcodeFileInformation(filename, localFilename, remoteFilename)
|
||||
self._currentFile = SpecialStreamingGcodeFileInformation(path, localFilename, remoteFilename)
|
||||
else:
|
||||
self._currentFile = StreamingGcodeFileInformation(filename, localFilename, remoteFilename)
|
||||
self._currentFile = StreamingGcodeFileInformation(path, localFilename, remoteFilename)
|
||||
self._currentFile.start()
|
||||
|
||||
self.sendCommand("M28 %s" % remoteFilename, tags=tags | {"trigger:comm.start_file_transfer",})
|
||||
eventManager().fire(Events.TRANSFER_STARTED, {"local": localFilename, "remote": remoteFilename})
|
||||
self._callback.on_comm_file_transfer_started(remoteFilename, self._currentFile.getFilesize(), user=self._currentFile.getUser())
|
||||
self._callback.on_comm_file_transfer_started(localFilename,
|
||||
remoteFilename,
|
||||
self._currentFile.getFilesize(),
|
||||
user=self._currentFile.getUser())
|
||||
|
||||
def cancelFileTransfer(self, tags=None):
|
||||
if not self.isOperational() or not self.isStreaming():
|
||||
@@ -1092,22 +1094,17 @@ class MachineCom(object):
|
||||
if failed:
|
||||
self.deleteSdFile(remote)
|
||||
|
||||
payload = {
|
||||
"local": self._currentFile.getLocalFilename(),
|
||||
"remote": remote,
|
||||
"time": self.getPrintTime()
|
||||
}
|
||||
local = self._currentFile.getLocalFilename()
|
||||
elapsed = self.getPrintTime()
|
||||
|
||||
def finalize():
|
||||
self._currentFile = None
|
||||
self._changeState(self.STATE_OPERATIONAL)
|
||||
|
||||
if failed:
|
||||
self._callback.on_comm_file_transfer_failed(remote)
|
||||
eventManager().fire(Events.TRANSFER_FAILED, payload)
|
||||
self._callback.on_comm_file_transfer_failed(local, remote, elapsed)
|
||||
else:
|
||||
self._callback.on_comm_file_transfer_done(remote)
|
||||
eventManager().fire(Events.TRANSFER_DONE, payload)
|
||||
self._callback.on_comm_file_transfer_done(local, remote, elapsed)
|
||||
|
||||
self.refreshSdFiles(tags={"trigger:comm.finish_file_transfer",})
|
||||
self._sendCommand(SendQueueMarker(finalize))
|
||||
@@ -3625,13 +3622,13 @@ class MachineComPrintCallback(object):
|
||||
def on_comm_sd_files(self, files):
|
||||
pass
|
||||
|
||||
def on_comm_file_transfer_started(self, filename, filesize, user=None):
|
||||
def on_comm_file_transfer_started(self, local_filename, remote_filename, filesize, user=None):
|
||||
pass
|
||||
|
||||
def on_comm_file_transfer_done(self, filename):
|
||||
def on_comm_file_transfer_done(self, local_filename, remote_filename, elapsed):
|
||||
pass
|
||||
|
||||
def on_comm_file_transfer_failed(self, filename):
|
||||
def on_comm_file_transfer_failed(self, local_filename, remote_filename, elapsed):
|
||||
pass
|
||||
|
||||
def on_comm_force_disconnect(self):
|
||||
|
||||
Reference in new issue
Block a user