octoprint.printer¶
This module defines the interface for communicating with a connected printer.
The communication is in fact divided into two components, the PrinterInterface
, the
printer communication specific ConnectedPrinter
, and possibly deeper lying
communication components. However, plugins should only ever need to use the PrinterMixin
as the
abstracted version of the actual printer communication.
- class octoprint.printer.CommonPrinterMixin¶
The
PrinterInterface
represents the developer interface to thePrinter
instance.-
cancel_print(tags=
None
, *args, **kwargs)¶ Cancels the current print job.
- Parameters:¶
An optional set of tags to attach to the command(s) throughout their lifecycle
-
change_tool(tool, tags=
None
, *args, **kwargs)¶ Switch the currently active
tool
(for which extrude commands will apply).
- connect(*args, **kwargs)¶
Connects to the printer, using the specified connection parameters. If a connection is already established, that connection will be closed prior to connecting anew with the provided parameters.
- disconnect(*args, **kwargs)¶
Disconnects from the printer. Does nothing if no connection is currently established.
-
extrude(amount, speed=
None
, tags=None
, *args, **kwargs)¶ Extrude
amount
millimeters of material from the tool.- Parameters:¶
- get_current_connection(*args, **kwargs)¶
- Returns:¶
- (tuple) The current connection information as a 4-tuple
(connection_string, port, baudrate, printer_profile)
. If the printer is currently not connected, the tuple will be
("Closed", None, None, None)
.
- (tuple) The current connection information as a 4-tuple
- get_state_id(*args, **kwargs) str ¶
Identifier of the current communication state.
For possible values see
ConnectedPrinterState
.- Returns:¶
(str) A unique identifier corresponding to the current communication state.
- get_state_string(*args, **kwargs)¶
- Returns:¶
(str) A human readable string corresponding to the current communication state.
- is_cancelling(*args, **kwargs)¶
- Returns:¶
(boolean) Whether the printer is currently cancelling a print.
- is_closed_or_error(*args, **kwargs)¶
- Returns:¶
(boolean) Whether the printer is currently disconnected and/or in an error state.
- is_finishing(*args, **kwargs)¶
- Returns:¶
(boolean) Whether the printer is currently finishing a print.
- is_operational(*args, **kwargs)¶
- Returns:¶
(boolean) Whether the printer is currently connected and available.
- is_ready(*args, **kwargs)¶
- Returns:¶
(boolean) Whether the printer is currently operational and ready for new print jobs (not printing).
- is_resuming(*args, **kwargs)¶
- Returns:¶
(boolean) Whether the printer is currently resuming a print.
-
job_on_hold(blocking=
True
, *args, **kwargs)¶ Contextmanager that allows executing code while printing while making sure that no commands from the file being printed are continued to be sent to the printer. Note that this will only work for local files, NOT SD files.
Example:
with printer.job_on_hold(): park_printhead() take_snapshot() send_printhead_back()
It should be used sparingly and only for very specific situations (such as parking the print head somewhere, taking a snapshot from the webcam, then continuing). If you abuse this, you WILL cause print quality issues!
A lock is in place that ensures that the context can only actually be held by one thread at a time. If you don’t want to block on acquire, be sure to set
blocking
toFalse
and catch theRuntimeException
thrown if the lock can’t be acquired.
-
jog(axes, relative=
True
, speed=None
, tags=None
, *args, **kwargs)¶ Jogs the specified printer
axis
by the specifiedamount
in mm.- Parameters:¶
- axes : dict¶
Axes and distances to jog, keys are axes (“x”, “y”, “z”), values are distances in mm
- relative : bool¶
Whether to interpret the distance values as relative (true, default) or absolute (false) coordinates
- speed : int, bool or None¶
Speed at which to jog (F parameter). If set to
False
no speed will be set specifically. If set toNone
(or left out) the minimum of all involved axes speeds from the printer profile will be used.An optional set of tags to attach to the command(s) throughout their lifecycle
- log_lines(*lines)¶
Logs the provided lines to the printer log and serial.log :param *lines: the lines to log
-
pause_print(tags=
None
, *args, **kwargs)¶ Pauses the current print job if it is currently running, does nothing otherwise.
- Parameters:¶
An optional set of tags to attach to the command(s) throughout their lifecycle
- repair_communication(*args, **kwargs)¶
Fakes an acknowledgment for the communication layer. If the communication between OctoPrint and the printer gets stuck due to lost “ok” responses from the server due to communication issues, this can be used to get things going again.
-
resume_print(tags=
None
, *args, **kwargs)¶ Resumes the current print job if it is currently paused, does nothing otherwise.
- Parameters:¶
An optional set of tags to attach to the command(s) throughout their lifecycle
-
script(name, context=
None
, tags=None
, must_be_set=True
, part_of_job=False
, *args, **kwargs)¶ Sends the script
name
to the printer.The script will be run through the template engine, the rendering context can be extended by providing a
context
with additional template variables to use.If the script is unknown, an
UnknownScriptException
will be raised.
-
set_job_on_hold(value, blocking=
True
, *args, **kwargs)¶ Setter for finer control over putting jobs on hold. Set to
True
to ensure that no commands from the file being printed are continued to be sent to the printer. Set toFalse
to resume. Note that this will only work for local files, NOT SD files.Make absolutely sure that if you set this flag, you will always also unset it again. If you don’t, the job will be stuck forever.
Example:
if printer.set_job_on_hold(True): try: park_printhead() take_snapshot() send_printhead_back() finally: printer.set_job_on_hold(False)
Just like
job_on_hold()
this should be used sparingly and only for very specific situations. If you abuse this, you WILL cause print quality issues!
-
set_temperature(heater, value, tags=
None
, *args, **kwargs)¶ Sets the target temperature on the specified
heater
to the givenvalue
in celsius.- Parameters:¶
- heater : str¶
The heater for which to set the target temperature. Either “bed” for setting the bed temperature, “chamber” for setting the temperature of the heated enclosure or something matching the regular expression “tool[0-9]+” (e.g. “tool0”, “tool1”, …) for the hotends of the printer. However, addressing components that are disabled or unconfigured in the printer profile will result in a “Suppressed command” error popup message.
- value : int, float¶
The temperature in celsius to set the target temperature to.
An optional set of tags to attach to the command(s) throughout their lifecycle.
-
set_temperature_offset(offsets: dict =
None
, tags: set =None
, *args, **kwargs)¶ Sets the temperature
offsets
to apply to target temperatures read from a GCODE file while printing.- Parameters:¶
- offsets : dict¶
A dictionary specifying the offsets to apply. Keys must match the format for the
heater
parameter toset_temperature()
, so “bed” for the offset for the bed target temperature and “tool[0-9]+” for the offsets to the hotend target temperatures.An optional set of tags to attach to the command(s) throughout their lifecycle
-
start_print(tags=
None
, *args, **kwargs)¶ Starts printing the currently selected file. If no file is currently selected, does nothing.
- Parameters:¶
An optional set of tags to attach to the command(s) throughout their lifecycle
-
toggle_pause_print(tags=
None
, *args, **kwargs)¶ Pauses the current print job if it is currently running or resumes it if it is currently paused.
- Parameters:¶
An optional set of tags to attach to the command(s) throughout their lifecycle
-
valid_axes =
('x', 'y', 'z', 'e')
¶ Valid axes identifiers.
-
valid_heater_regex =
re.compile('^(tool\\d*|bed|chamber)$')
¶ Regex for valid heater identifiers.
-
valid_heater_regex_no_current =
re.compile('^(tool\\d+|bed|chamber)$')
¶ Regex for valid heater identifiers without the current heater.
-
valid_tool_regex =
re.compile('^(tool\\d+)$')
¶ Regex for valid tool identifiers.
-
cancel_print(tags=
- class octoprint.printer.ConnectedPrinterMixin¶
- connect(*args, **kwargs)¶
Connects to the printer, using the specified connection parameters. If a connection is already established, that connection will be closed prior to connecting anew with the provided parameters.
- disconnect(*args, **kwargs)¶
Disconnects from the printer. Does nothing if no connection is currently established.
-
job_on_hold(blocking=
True
, *args, **kwargs)¶ Contextmanager that allows executing code while printing while making sure that no commands from the file being printed are continued to be sent to the printer. Note that this will only work for local files, NOT SD files.
Example:
with printer.job_on_hold(): park_printhead() take_snapshot() send_printhead_back()
It should be used sparingly and only for very specific situations (such as parking the print head somewhere, taking a snapshot from the webcam, then continuing). If you abuse this, you WILL cause print quality issues!
A lock is in place that ensures that the context can only actually be held by one thread at a time. If you don’t want to block on acquire, be sure to set
blocking
toFalse
and catch theRuntimeException
thrown if the lock can’t be acquired.
-
set_job_on_hold(value, blocking=
True
, *args, **kwargs)¶ Setter for finer control over putting jobs on hold. Set to
True
to ensure that no commands from the file being printed are continued to be sent to the printer. Set toFalse
to resume. Note that this will only work for local files, NOT SD files.Make absolutely sure that if you set this flag, you will always also unset it again. If you don’t, the job will be stuck forever.
Example:
if printer.set_job_on_hold(True): try: park_printhead() take_snapshot() send_printhead_back() finally: printer.set_job_on_hold(False)
Just like
job_on_hold()
this should be used sparingly and only for very specific situations. If you abuse this, you WILL cause print quality issues!
- class octoprint.printer.PrinterFilesMixin¶
- class octoprint.printer.PrinterCallback¶
- on_printer_add_log(data)¶
Called when the
PrinterInterface
receives a new communication log entry from the communication layer.
- on_printer_add_message(data)¶
Called when the
PrinterInterface
receives a new message from the communication layer.
- on_printer_add_temperature(data)¶
Called when the
PrinterInterface
receives a new temperature data set from the communication layer.data
is adict
of the following structure:tool0: actual: <temperature of the first hotend, in degC> target: <target temperature of the first hotend, in degC> ... bed: actual: <temperature of the bed, in degC> target: <target temperature of the bed, in degC> chamber: actual: <temperature of the chamber, in degC> target: <target temperature of the chamber, in degC>
- on_printer_received_registered_message(name, output)¶
Called when the
PrinterInterface
received a registered message, e.g. from a feedback command.
- on_printer_send_current_data(data)¶
Called when the internal state of the
PrinterInterface
changes, due to changes in the printer state, temperatures, log lines, job progress etc. Updates via this method are guaranteed to be throttled to a maximum of 2 calls per second.data
is adict
of the following structure:state: text: <current state string> flags: operational: <whether the printer is currently connected and responding> printing: <whether the printer is currently printing> closedOrError: <whether the printer is currently disconnected and/or in an error state> error: <whether the printer is currently in an error state> paused: <whether the printer is currently paused> ready: <whether the printer is operational and ready for jobs> sdReady: <whether an SD card is present> job: file: name: <name of the file>, size: <size of the file in bytes>, origin: <origin of the file, "local" or "printer">, date: <last modification date of the file> estimatedPrintTime: <estimated print time of the file in seconds> lastPrintTime: <last print time of the file in seconds> filament: length: <estimated length of filament needed for this file, in mm> volume: <estimated volume of filament needed for this file, in ccm> progress: completion: <progress of the print job in percent (0-100)> filepos: <current position in the file in bytes> printTime: <current time elapsed for printing, in seconds> printTimeLeft: <estimated time left to finish printing, in seconds> currentZ: <current position of the z axis, in mm> offsets: <current configured temperature offsets, keys are "bed" or "tool[0-9]+", values the offset in degC>
- on_printer_send_initial_data(data)¶
Called when registering as a callback with the
PrinterInterface
to receive the initial data (state, log and temperature history etc) from the printer.data
is adict
of the following structure:temps: - time: <timestamp of the temperature data point> tool0: actual: <temperature of the first hotend, in degC> target: <target temperature of the first hotend, in degC> ... bed: actual: <temperature of the bed, in degC> target: <target temperature of the bed, in degC> - ... logs: <list of current communication log lines> messages: <list of current messages from the firmware>
octoprint.printer.connection¶
This module defines the interface for implementing a printer connector.
-
class octoprint.printer.connection.ConnectedPrinter(owner: PrinterMixin, listener: ConnectedPrinterListenerMixin =
None
, profile=None
, *args, **kwargs)¶ - classmethod connection_preconditions_met(params: dict[str, Any]) bool ¶
Returns True if a connection with the provided parameters might be possible.
Note that an actual connection attempt might still fail even if this returns True, connectors will only check if the parameters meet any basic preconditions that can easily be checked.
-
get_state_string(state: ConnectedPrinterState =
None
)¶ - Returns:¶
(str) A human readable string corresponding to the current communication state.
- is_cancelling(*args, **kwargs)¶
- Returns:¶
(boolean) Whether the printer is currently cancelling a print.
- is_closed_or_error(*args, **kwargs)¶
- Returns:¶
(boolean) Whether the printer is currently disconnected and/or in an error state.
- is_finishing(*args, **kwargs)¶
- Returns:¶
(boolean) Whether the printer is currently finishing a print.
- is_operational(*args, **kwargs)¶
- Returns:¶
(boolean) Whether the printer is currently connected and available.
- is_ready(*args, **kwargs)¶
- Returns:¶
(boolean) Whether the printer is currently operational and ready for new print jobs (not printing).
- class octoprint.printer.connection.ConnectedPrinterRegistration(name: str, bases: tuple[type, ...], args: dict[str, Any])¶
Meta class acting as registration for custom
ConnectedPrinter
implementationsBy subclassing type:ConnectedPrinter (and importing the subclass), it will register itself on this meta class under it’s
connector
id.This also works from plugins, and thus allows adding custom connectors easily from plugins just by importing them, e.g.
# __init__.py class CustomConnectorPlugin( octoprint.plugin.OctoPrintPlugin, ): def initialize(self): # this not only imports but also registers # the connector with the system! from .connector import MyCustomConnectedPrinter # connector.py from octoprint.printer.connection import ConnectedPrinter class MyCustomConnectedPrinter(ConnectedPrinter): # ...
- all() Iterable[ConnectedPrinter] ¶
Returns all registered connectors
-
connectors : dict[str, ConnectedPrinter] =
{}
¶ Collection of all currently registered connectors
- find(connector: str) ConnectedPrinter | None ¶
Returns the requested connector, if registered
- class octoprint.printer.connection.ConnectedPrinterState(*values)¶
Possible states of the connected printer
-
CANCELLING =
'Cancelling'
¶
-
CLOSED =
'Offline'
¶
-
CLOSED_WITH_ERROR =
'Offline after error'
¶
-
CONNECTING =
'Connecting'
¶
-
DETECTING =
'Detecting'
¶
-
ERROR =
'Error'
¶
-
FINISHING =
'Finishing'
¶
-
OPERATIONAL =
'Operational'
¶
-
PAUSED =
'Paused'
¶
-
PAUSING =
'Pausing'
¶
-
PRINTING =
'Printing'
¶
-
RESUMING =
'Resuming'
¶
-
STARTING =
'Starting'
¶
-
TRANSFERRING_FILE =
'Transferring file to printer'
¶
-
CANCELLING =
-
octoprint.printer.connection.ERROR_STATES =
{ConnectedPrinterState.CLOSED_WITH_ERROR, ConnectedPrinterState.ERROR}
¶ ConnectedPrinterStates that are considered error states
-
octoprint.printer.connection.CLOSED_STATES =
{ConnectedPrinterState.CLOSED, ConnectedPrinterState.CLOSED_WITH_ERROR}
¶ ConnectedPrinterStates that are considered closed states
-
octoprint.printer.connection.OPERATIONAL_STATES =
{ConnectedPrinterState.CANCELLING, ConnectedPrinterState.FINISHING, ConnectedPrinterState.OPERATIONAL, ConnectedPrinterState.PAUSED, ConnectedPrinterState.PAUSING, ConnectedPrinterState.PRINTING, ConnectedPrinterState.RESUMING, ConnectedPrinterState.STARTING, ConnectedPrinterState.TRANSFERRING_FILE}
¶ ConnectedPrinterStates that are considered operational states
-
octoprint.printer.connection.PRINTING_STATES =
{ConnectedPrinterState.CANCELLING, ConnectedPrinterState.FINISHING, ConnectedPrinterState.PAUSED, ConnectedPrinterState.PAUSING, ConnectedPrinterState.PRINTING, ConnectedPrinterState.RESUMING, ConnectedPrinterState.STARTING}
¶ ConnectedPrinterStats that are considered printing states
octoprint.printer.estimation¶
- class octoprint.printer.estimation.PrintTimeEstimator(job_type)¶
Estimator implementation.
Subclass this and register via the octoprint.printer.estimation.factory hook to provide your own implementation.
- estimate(progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType)¶
Tries to estimate the print time left for the print job
This is somewhat horrible since accurate print time estimation is pretty much impossible to achieve, considering that we basically have only two data points (current progress in file and time needed for that so far - former prints or a file analysis might not have happened or simply be completely impossible e.g. if the file is stored on the printer’s SD card) and hence can only do a linear estimation of a completely non-linear process. That’s a recipe for inaccurate predictions right there. Yay.
Anyhow, here’s how this implementation works. This method gets the current progress in the printed file (percentage based on bytes read vs total bytes), the print time that elapsed, the same print time with the heat up times subtracted (if possible) and if available also some statistical total print time (former prints or a result from the GCODE analysis).
First get an “intelligent” estimate based on the
TimeEstimationHelper
. That thing tries to detect if the estimation based on our progress and time needed for that becomes stable over time through a rolling window and only returns a result once that appears to be the case.If we have any statistical data (former prints or a result from the GCODE analysis) but no intelligent estimate yet, we’ll use that for the next step. Otherwise, up to a certain percentage in the print we do a percentage based weighing of the statistical data and the intelligent estimate - the closer to the beginning of the print, the more precedence for the statistical data, the closer to the cut off point, the more precedence for the intelligent estimate. This is our preliminary total print time.
If the total print time is set, we do a sanity check for it. Based on the total print time estimate and the time we already spent printing, we calculate at what percentage we SHOULD be and compare that to the percentage at which we actually ARE. If it’s too far off, our total can’t be trusted and we fall back on the dumb estimate. Same if the time we spent printing is already higher than our total estimate.
If we do NOT have a total print time estimate yet but we’ve been printing for longer than a configured amount of minutes or are further in the file than a configured percentage, we also use the dumb estimate for now.
Yes, all this still produces horribly inaccurate results. But we have to do this live during the print and hence can’t produce to much computational overhead, we do not have any insight into the firmware implementation with regards to planner setup and acceleration settings, we might not even have access to the printed file’s contents and such we need to find something that works “mostly” all of the time without costing too many resources. Feel free to propose a better solution within the above limitations (and I mean that, this solution here makes me unhappy).
- Parameters:¶
- progress : float or None¶
Current percentage in the printed file
- printTime : float or None¶
Print time elapsed so far
- cleanedPrintTime : float or None¶
Print time elapsed minus the time needed for getting up to temperature (if detectable).
- statisticalTotalPrintTime : float or None¶
Total print time of past prints against same printer profile, or estimated total print time from GCODE analysis.
- statisticalTotalPrintTimeType : str or None¶
Type of statistical print time, either “average” (total time of former prints) or “analysis”
- Returns:¶
(2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation
-
class octoprint.printer.estimation.TimeEstimationHelper(rolling_window=
None
, countdown=None
, threshold=None
)¶ -
STABLE_COUNTDOWN =
250
¶
-
STABLE_ROLLING_WINDOW =
250
¶
-
STABLE_THRESHOLD =
0.1
¶
- property average_distance¶
- property average_total¶
- property average_total_rolling¶
- is_stable()¶
- update(new_estimate)¶
-
STABLE_COUNTDOWN =
octoprint.printer.job¶
- pydantic model octoprint.printer.job.DurationEstimate¶
- Config:¶
use_enum_values: bool = True
validate_default: bool = True
- pydantic model octoprint.printer.job.FilamentEstimate¶
- Config:¶
use_enum_values: bool = True
validate_default: bool = True
- pydantic model octoprint.printer.job.JobProgress¶
- Config:¶
use_enum_values: bool = True
validate_default: bool = True
- pydantic model octoprint.printer.job.PrintJob¶
- Config:¶
use_enum_values: bool = True
validate_default: bool = True
-
field duration_estimate : DurationEstimate | None =
None
¶
-
field filament_estimate : dict[str, FilamentEstimate] =
{}
¶
- pydantic model octoprint.printer.job.UploadJob¶
- Config:¶
use_enum_values: bool = True
validate_default: bool = True
octoprint.printer.profile¶
This module contains printer profile related code.
A printer profile is a dict
of the following structure:
Name |
Type |
Description |
---|---|---|
|
|
Internal id of the printer profile |
|
|
Human readable name of the printer profile |
|
|
Printer model |
|
|
Color to associate with the printer profile |
|
|
Information about the print volume |
|
|
Width of the print volume (X axis) |
|
|
Depth of the print volume (Y axis) |
|
|
Height of the print volume (Z axis) |
|
|
Form factor of the print bed, either |
|
|
Location of gcode origin in the print volume, either |
|
|
Custom boundary box overriding the default bounding box based on the provided width, depth, height and origin.
If |
|
|
Minimum valid X coordinate |
|
|
Minimum valid Y coordinate |
|
|
Minimum valid Z coordinate |
|
|
Maximum valid X coordinate |
|
|
Maximum valid Y coordinate |
|
|
Maximum valid Z coordinate |
|
|
Whether the printer has a heated bed ( |
|
|
Whether the printer has a heated chamber ( |
|
|
Information about the printer’s extruders |
|
|
How many extruders the printer has (default 1) |
|
|
Extruder offsets relative to first extruder, list of (x, y) tuples, first is always (0,0) |
|
|
Diameter of the printer nozzle(s) |
|
|
Whether there’s only one nozzle shared among all extruders (true) or one nozzle per extruder (false). |
|
|
Default extrusion length used in Control tab on initial page load in mm. |
|
|
Information about the printer axes |
|
|
Information about the printer’s X axis |
|
|
Speed of the X axis in mm/min |
|
|
Whether a positive value change moves the nozzle away from the print bed’s origin (False, default) or towards it (True) |
|
|
Information about the printer’s Y axis |
|
|
Speed of the Y axis in mm/min |
|
|
Whether a positive value change moves the nozzle away from the print bed’s origin (False, default) or towards it (True) |
|
|
Information about the printer’s Z axis |
|
|
Speed of the Z axis in mm/min |
|
|
Whether a positive value change moves the nozzle away from the print bed (False, default) or towards it (True) |
|
|
Information about the printer’s E axis |
|
|
Speed of the E axis in mm/min |
|
|
Whether a positive value change extrudes (False, default) or retracts (True) filament |
- class octoprint.printer.profile.PrinterProfileManager¶
Manager for printer profiles. Offers methods to select the globally used printer profile and to list, add, remove, load and save printer profiles.
- class octoprint.printer.profile.BedFormFactor¶
Valid values for bed form factor
-
CIRCULAR =
'circular'
¶ Circular bed
-
RECTANGULAR =
'rectangular'
¶ Rectangular bed
-
CIRCULAR =
- class octoprint.printer.profile.BedOrigin¶
Valid values for bed origin
-
CENTER =
'center'
¶ Origin at the center of the bed when looking from top
-
LOWERLEFT =
'lowerleft'
¶ Origin at lower left corner of the bed when looking from the top
-
CENTER =
- class octoprint.printer.profile.SaveError¶
Saving a profile failed
- class octoprint.printer.profile.CouldNotOverwriteError¶
Overwriting of a profile not allowed
- class octoprint.printer.profile.InvalidProfileError¶
Profile invalid