Compare commits

...
Author SHA1 Message Date
Gina Häußge cf69c4500d Merge branch 'commRefactoring' into commRefactoring-commandTracking 2014-12-31 15:56:02 +01:00
Gina Häußge c7c6a08748 Merge branch 'devel' into commRefactoring 2014-12-31 15:55:37 +01:00
Gina Häußge c9c4066331 Fixed a bunch of doc issues, updated /api/printer/command to have more meaningful error messages 2014-12-31 15:47:12 +01:00
Gina Häußge 835b973bdc Merge branch 'patch-1' of https://github.com/bortek/OctoPrint into devel
Conflicts:
	docs/api/printer.rst
2014-12-31 15:19:18 +01:00
Gina Häußge bf6a32907c Ported possibility to set external host via headers from reverse proxy to the devel branch 2014-12-31 15:09:31 +01:00
bortek 2b7885c3f8 Update printer.rst 2014-12-30 12:18:39 +01:00
Gina Häußge 749af60796 Merge branch 'master' into devel
Conflicts:
	src/octoprint/server/util.py
	src/octoprint/settings.py
	src/octoprint/templates/index.jinja2
2014-12-30 10:49:03 +01:00
Gina Häußge 87ddcac2fc Don't user server.host but server.forwardedHost as fallback for generated external URLs
Closes #698
2014-12-30 10:20:50 +01:00
Gina Häußge e3383fe4c1 Generated URLs now take X-Forwarded-Host header sent by proxies into account for included host and port 2014-12-29 20:48:33 +01:00
Gina Häußge 292856e1bd Fixed relative URL to sockjs endpoint, wasn't yet using the proper base url 2014-12-29 20:45:54 +01:00
Gina Häußge 3dacaaf03a Merge branch 'master' into devel 2014-12-28 00:20:11 +01:00
Gina Häußge 6307b765e3 Only decrement the image counter if it is set and larger than 0
Backported from devel
2014-12-28 00:19:55 +01:00
Gina Häußge eb2561175d Merge branch 'master' into devel
Conflicts:
	setup.py
	src/octoprint/timelapse.py
2014-12-28 00:18:49 +01:00
Gina Häußge a30e41f0b4 Timelapses: Do not try to use image counter if still set to None and synchronize decrementing of image counter via mutex as well
Possible fixes for #693, the latter maybe also for #690
2014-12-28 00:12:19 +01:00
Gina Häußge 51341f6722 Added removal of pyc files (and their parent folders if they are empty after that) to the python setup.py clean command
(cherry picked from commit 9e014eb)
2014-12-28 00:00:57 +01:00
Gina Häußge fb15751703 Decrease image counter if an image could not be captured from webcam
Should keep rendering of timelapse from breaking if only a couple of images couldn't be captured due to whatever reason. Suggested by @midopple in #344
(cherry picked from commit bf9d5ef)
2014-12-27 23:55:23 +01:00
Gina Häußge a0105bcb2f Better error handling for capture issues during timelapsing
Should help debugging issue #425 and any future problems in that area.
(cherry picked from commit 1a7a468)
2014-12-27 23:52:38 +01:00
Gina Häußge 103e0796b7 Request available slicers and slicing profiles from backend asynchronously when opening the slicing dialog
Should make sure that slicers and new profiles are detected correctly even without reload.

Could maybe help with #689
2014-12-21 15:57:23 +01:00
Gina Häußge 363b23d6e3 Better handling of errors while sending to (disconnected) clients on the websocket 2014-12-21 15:47:24 +01:00
Gina Häußge 52ad02a08a Updated the changelog with a lot of stuff that gone done the past weeks 2014-12-21 15:32:30 +01:00
Gina Häußge 977cf3c383 Added handler for uncaught exceptions to make sure those get logged 2014-12-21 15:32:07 +01:00
Gina Häußge 827ea36d72 Merge remote-tracking branch 'origin/devel' into devel 2014-12-21 15:16:34 +01:00
Gina Häußge 46b0367335 Log a message to octoprint.log if Cura is not fully configured and hence not available for slicing yet.
As suggested in #689
2014-12-21 15:15:59 +01:00
Gina Häußge 596afddfb6 Merge pull request #685 from Bevaz/bug_video_output_filename
Enframed output video filename with quotes.
2014-12-20 18:05:50 +01:00
Gina Häußge 68e4fca347 Merge branch 'devel' into commRefactoring 2014-12-20 10:15:06 +01:00
Gina Häußge 256c2dfdbe More error resilient handling of .metadata.yaml writes in local storage
Writes updated metadata to a backup file first and then copies it atomically (at least under anything that is not windows where the operation is a bit more complicated and hence not atomic)
2014-12-20 01:06:40 +01:00
Gina Häußge 0737ee65bd Support action: commands sent from printer, for now only pause, resume and disconnect are supported, plus a new hook "octoprint.comm.protocol.action" to add handlers of custom actions via plugins.
Added "!!DEBUG:" command to virtual printer to be able to trigger such commands to be sent by it.
2014-12-20 00:31:46 +01:00
Gina Häußge 05ac02770b WIP of command tracking and more intelligent pausing 2014-12-19 23:29:49 +01:00
Bevaz 699ed1da4d Enframed output filename with quotes. 2014-12-17 22:08:47 +03:00
19 changed files with 374 additions and 43 deletions

No files matched your search

+49 -4
View File
@@ -19,6 +19,12 @@
* OctoPrint now has a [plugin system](http://docs.octoprint.org/en/devel/plugins/index.html) which allows extending its
core functionality.
* New type of API key: [App Session Keys](http://docs.octoprint.org/en/devel/api/apps.html) for trusted applications
* Printer Profiles: Printer properties like print volume, extruder offsets etc are now managed via Printer Profiles. A
connection to a printer will always have a printer profile associated.
* OctoPrint now supports `action:...` commands received via debug messages (`// action:...`) from the printer. Currently supported are
- `action:pause`: Pauses the current job in OctoPrint
- `action:resume`: Resumes the current job in OctoPrint
- `action:disconnect`: Disconnects OctoPrint from the printer
### Improvements
@@ -33,13 +39,17 @@
([#532](https://github.com/foosel/OctoPrint/issues/532) and [#590](https://github.com/foosel/OctoPrint/pull/590))
* Slicing has been greatly improved:
* It now allows for a definition of slicing profiles to use for slicing plus overrides which can be defined per slicing
job (defining overrides is not yet part of the UI but it's on the roadmap).
job (defining overrides is not yet part of the UI but it's on the roadmap).
* A new slicing dialog has been added which allows (re-)slicing uploaded STL files (which are now displayed in the file list
as well). This dialog also allows specifying which action to take after slicing has been completed (none, selecting the
sliced GCODE for printing or starting to print it directly)
* Slicers themselves are integrated into the system via ``SlicingPlugins``.
* The [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the
[CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See
[the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to
accommodate the new integration.
* The "Slicing done" notification is now colored green ([#558](https://github.com/foosel/OctoPrint/issues/558)).
* The slicing API allows positioning the model to slice on the print bed (Note: this is not yet available in the UI).
* File management now supports STL files as first class citizens (including UI adjustments to allow management of
uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI)
* Also interpret lines starting with "!!" as errors
@@ -51,8 +61,17 @@
long as they are in use
* Settings in UI get refreshed when opening settings dialog
* New event "SettingsUpdated"
* Print time estimation is now not displayed until it becomes somewhat stable. Display in web interface now also happens
in a fuzzy way instead of the format hh:mm:ss, to not suggest a high accuracy anymore where the can't be one
* "Print time left" is now not displayed until it becomes somewhat stable. Display in web interface now also happens
in a fuzzy way instead of the format hh:mm:ss, to not suggest a high accuracy anymore where the can't be one. Additionally
OctoPrint will use data from prior prints to enhance the initial print time estimation.
* Added handler for uncaught exceptions to make sure those get logged, should make the logs even more useful for analysing
bug reports
* The server now tracks the modification date of the configuration file and reloads it prior to saving the config if
it has been changed during runtime by external editing, hence no config settings added manually while the server
was running should be overwritten anymore.
* Automatically hard-reload the UI if upon reconnecting to the server a new version is detected.
* Better handling of errors on the websocket - no more logging of the full stack trace to the log, only a warning
message for now.
### Bug Fixes
@@ -62,20 +81,44 @@
setups under Smoothieware
* [#556](https://github.com/foosel/OctoPrint/issues/556) - Allow login of the same user from multiple browsers without
side effects
* [#680](https://github.com/foosel/OctoPrint/issues/680) - Don't accidentally include a newline from the MIME headers
in the parsed multipart data from file uploads
* Various fixes of bugs in newly introduced features and improvements:
* [#625](https://github.com/foosel/OctoPrint/pull/625) - Newly added GCODE files were not being added to the analysis
queue
* [#664](https://github.com/foosel/OctoPrint/issues/664) - Fixed jog controls again
* [#677](https://github.com/foosel/OctoPrint/issues/677) - Fixed extruder offsets not being properly editable in
printer profiles
* [#683](https://github.com/foosel/OctoPrint/issues/683) - Fixed heated bed option not being properly displayed in
printer profiles
* Various fixes without tickets:
* GCODE viewer now doesn't stumble over completely extrusionless GCODE files
* Do not deliver the API key on settings API unless user has admin rights
* Don't hiccup on slic3r filament_diameter comments in GCODE generated for multi extruder setups
## 1.1.2 (Unreleased)
### Improvements
* Added deletion of `*.pyc` files to `python setup.py clean` command, should help tremendously when switching branches (backported
from [9e014eb](https://github.com/foosel/OctoPrint/commit/9e014eba1feffde11ed0601d9c911b8cac9f3fb0))
### Bug Fixes
* [#634](https://github.com/foosel/OctoPrint/pull/634) - Fixed missing `branch` fields in version dicts generated
by versioneer
* [IRC] Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups
* [IRC] - Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups
* [ML] - Fixed relative URL to sockjs endpoint, wasn't yet using the proper base url
* [unreported] & [#698](https://github.com/foosel/OctoPrint/issues/698) - Generated URLs now take X-Forwarded-Host header
sent by proxies into account for included host and port, also fixed [#698](https://github.com/foosel/OctoPrint/issues/698)
introduced by this
* Small fixes for timelapse creation:
- [#344](https://github.com/foosel/OctoPrint/issues/344) - Made timelapses capable of coping with missing captures in between by decrementing the image counter again if there
was an error fetching the latest image from the snapshot URL (backport of [1a7a468](https://github.com/foosel/OctoPrint/commit/1a7a468eb65fdf2a13b4c7a7723280e822c9c34b)
and [bf9d5ef](https://github.com/foosel/OctoPrint/commit/bf9d5efe43a1e57aacd8512125082ddca06b4efc))
- [#693](https://github.com/foosel/OctoPrint/issues/693) - Try not to capture an image if image counter is still unset
- [unreported] Synchronize image counter decrementing as well as incrementing to prevent rare race conditions when generating the
image file names
## 1.1.1 (2014-10-27)
@@ -93,6 +136,8 @@
* [#604](https://github.com/foosel/OctoPrint/issues/604) - Properly initialize settings basedir on server startup
* [IRC] Also allow downloading .g files via Tornado
([Commits](https://github.com/foosel/OctoPrint/compare/1.1.0...1.1.1))
## 1.1.0 (2014-09-03)
### New Features
+76
View File
@@ -755,6 +755,61 @@ Retrieve the current SD state
:statuscode 200: No error
:statuscode 404: If SD support has been disabled in OctoPrint's config.
.. _sec-api-printer-arbcommand:
Send an arbitrary command to the printer
========================================
.. http:post:: /api/printer/command
Sends any command to the printer via the serial interface. Should be used with some care as some commands can interfere with
or even stop a running print job.
Expects a :ref:`Arbitrary Command Request <sec-api-printer-datamodel-arbcommand>` as the request's body.
If successful returns a :http:statuscode:`204` and an empty body.
**Example for sending a single command**
.. sourcecode:: http
POST /api/printer/command HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "M106"
}
.. sourcecode:: http
HTTP/1.1 204 No Content
**Example for sending multiple commands**
.. sourcecode:: http
POST /api/printer/command HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"commands": [
"M18",
"M106 S0"
]
}
.. sourcecode:: http
HTTP/1.1 204 No Content
:json string command: Single command to send to the printer, mutually exclusive with ``commands``.
:json string commands: List of commands to send to the printer, mutually exclusive with ``command``.
:statuscode 204: No error
.. _sec-api-printer-datamodel:
Datamodel
@@ -831,3 +886,24 @@ SD State
- Boolean
- Whether the SD card has been initialized (``true``) or not (``false``).
.. _sec-api-printer-datamodel-arbcommand:
Arbitrary Command Request
-------------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``command``
- 0..1
- String
- Single command to send to the printer, mutually exclusive with ``commands``.
* - ``commands``
- 0..*
- Array of String
- Multiple commands to send to the printer (in the given order), mutually exclusive with ``command``.
+4
View File
@@ -96,6 +96,10 @@ ClientOpened
ClientClosed
A client has disconnected from the webserver
Payload:
* ``remoteAddress``: the remote address (IP) of the client that disconnected
Printer communication
---------------------
+20
View File
@@ -96,6 +96,26 @@ class CleanCommand(Command):
file_handler=delete_file
)
# pyc files
def delete_folder_if_empty(path, applied_handler):
if not applied_handler:
return
if len(os.listdir(path)) == 0:
shutil.rmtree(path)
print "Deleted %s since it was empty" % path
def delete_file(path):
os.remove(path)
print "Deleted %s" % path
import fnmatch
_recursively_handle_files(
os.path.abspath("src"),
lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"),
folder_handler=delete_folder_if_empty,
file_handler=delete_file
)
class NewTranslation(Command):
description = "create a new translation"
+98 -2
View File
@@ -67,10 +67,15 @@ class RepRapProtocol(Protocol):
COMMAND_SET_BED_TEMP = staticmethod(lambda s, w: GcodeCommand("M190", s=s) if w else GcodeCommand("M140", s=s))
COMMAND_SET_RELATIVE_POSITIONING = staticmethod(lambda: GcodeCommand("G91"))
COMMAND_SET_ABSOLUTE_POSITIONING = staticmethod(lambda: GcodeCommand("G90"))
COMMAND_SET_RELATIVE_EXTRUDER = staticmethod(lambda: GcodeCommand("M83"))
COMMAND_SET_ABSOLUTE_EXTRUDER = staticmethod(lambda: GcodeCommand("M82"))
COMMAND_MOVE_AXIS = staticmethod(lambda axis, amount, speed: GcodeCommand("G1", x=amount if axis=='x' else None, y=amount if axis=='y' else None, z=amount if axis=='z' else None, f=speed))
COMMAND_MOVE = staticmethod(lambda x, y, z, speed: GcodeCommand("G1", x=x if x is not None else None, y=y if y is not None else None, z=z if z is not None else None, f=speed))
COMMAND_EXTRUDE = staticmethod(lambda amount, speed: GcodeCommand("G1", e=amount, f=speed))
COMMAND_HOME_AXIS = staticmethod(lambda x, y, z: GcodeCommand("G28", x=0 if x else None, y=0 if y else None, z=0 if z else None))
COMMAND_SET_TOOL = staticmethod(lambda t: GcodeCommand("T%d" % t))
COMMAND_SET_POSITION = staticmethod(lambda x, y, z, e: GcodeCommand("G92", x=x if x is not None else None, y=y if y is not None else None, z=z if z is not None else None, e=e if e is not None else None))
COMMAND_GET_POSITION = staticmethod(lambda: GcodeCommand("M114"))
COMMAND_SD_REFRESH = staticmethod(lambda: GcodeCommand("M20"))
COMMAND_SD_INIT = staticmethod(lambda: GcodeCommand("M21"))
COMMAND_SD_RELEASE = staticmethod(lambda: GcodeCommand("M22"))
@@ -116,6 +121,13 @@ class RepRapProtocol(Protocol):
# to be fetched from the transport layer in order to fully handle the error at hand.
REGEX_ERROR_MULTILINE = re.compile("Error:[0-9]\n")
# Regex matching M114 output: "X:<x>Y:<y>Z:<z>E:<e> ..."
# - 1: current X
# - 2: current Y
# - 3: current Z
# - 4: current E
REGEX_POSITION = re.compile("X:([-+]?\d*\.?\d+)\s*Y:([-+]?\d*\.?\d+)\s*Z:([-+]?\d*\.?\d+)\s*E:([-+]?\d*\.?\d+)")
BLOCKING_COMMANDS = (
"M109", "M190", # set and wait for temperature (hotend & bed)
"G28", # home
@@ -159,6 +171,11 @@ class RepRapProtocol(Protocol):
self._thread.daemon = True
self._thread.start()
self._last_queried_position = None
self._last_seen_f = None
self._output = []
self._fill_queue_semaphore = threading.BoundedSemaphore(10)
self._fill_queue_state_signal = threading.Event()
self._fill_queue_mutex = threading.Lock()
@@ -231,6 +248,10 @@ class RepRapProtocol(Protocol):
self._current_resend_count = 0
self._sent_before_resend = 0
self._output = []
self._last_queried_position = None
self._last_seen_f = None
def connect(self, protocol_options, transport_options):
self._wait_for_start = protocol_options["waitForStart"] if "waitForStart" in protocol_options else False
self._force_checksum = protocol_options["checksum"] if "checksum" in protocol_options else True
@@ -285,6 +306,67 @@ class RepRapProtocol(Protocol):
cleared = self._send_queue.clear(matcher=lambda entry: entry is not None and entry.command is not None and hasattr(entry.command, "progress") and entry.command.progress is not None and (not hasattr(entry, "prepared") or entry.prepared is None))
self._logger.debug("Cleared %d job entries from the send queue: %r" % (len(cleared), cleared))
def pause_print(self, only_pause=None, only_resume=None):
wasPaused = self._state == State.PAUSED
Protocol.pause_print(self, only_pause=only_pause, only_resume=only_resume)
isPaused = self._state == State.PAUSED
if wasPaused == isPaused:
# nothing changed, either we are still printing or we are still paused
return
if not wasPaused:
# printer was printing, now paused
def positionCallback(command):
print("### command: %s" % command.command)
print("### output: %r" % command.output)
if command.output is None:
return
for line in command.output:
match = self.__class__.REGEX_POSITION.search(line)
if match is None:
continue
try:
x = float(match.group(1))
y = float(match.group(2))
z = float(match.group(3))
e = float(match.group(4))
self._last_queried_position = (x, y, z, e)
print("### set last_queried_position: %r" % (self._last_queried_position,))
except ValueError:
self._last_queried_position = None
print("### set last_queried_position: %r" % (self._last_queried_position,))
else:
self._send(self.__class__.COMMAND_SET_RELATIVE_EXTRUDER()) # relative extruder
self._send(self.__class__.COMMAND_EXTRUDE(-4.5, 6000)) # retract
self._send(self.__class__.COMMAND_SET_RELATIVE_POSITIONING()) # relative positioning
self._send(self.__class__.COMMAND_MOVE_AXIS("z", 15, 7800)) # move z up a bit
self._send(self.__class__.COMMAND_HOME_AXIS(True, True, False)) # home x/y
self._send(self.__class__.COMMAND_SET_ABSOLUTE_POSITIONING()) # absolute positioning
self._send(self.__class__.COMMAND_SET_ABSOLUTE_EXTRUDER()) # absolute extruder
# fetch the current position, once we have that we can continue
positionCommand = self.__class__.COMMAND_GET_POSITION()
positionCommand.callback = positionCallback
self._send(positionCommand)
else:
# printer was paused, now resuming
print("### get last_queried_position: %r" % (self._last_queried_position,))
if self._last_queried_position is not None:
x, y, z, e = self._last_queried_position
f = self._last_seen_f if self._last_seen_f else 7800
self._send(self.__class__.COMMAND_SET_RELATIVE_EXTRUDER()) # relative extruder
self._send(self.__class__.COMMAND_EXTRUDE(4.5, 6000)) # prime the nozzle
self._send(self.__class__.COMMAND_EXTRUDE(-4.5, 6000)) # prime the nozzle
self._send(self.__class__.COMMAND_MOVE(x, y, z, f)) # move back to former x, y, z
self._send(self.__class__.COMMAND_EXTRUDE(4.5, 300)) # extrude a bit of material
self._send(self.__class__.COMMAND_SET_ABSOLUTE_EXTRUDER()) # absolute extruder
self._send(self.__class__.COMMAND_SET_POSITION(None, None, None, e)) # define current as old e
self._send(self.__class__.COMMAND_MOVE(None, None, None, f)) # set speed
def init_sd(self):
Protocol.init_sd(self)
self._send(self.__class__.COMMAND_SD_INIT())
@@ -406,6 +488,10 @@ class RepRapProtocol(Protocol):
message = self._handle_errors(message.strip())
if message:
self._output.append(message)
print("--- output: %r" % self._output)
##~~ Control message processing: ok, resend, start, wait
if self.__class__.MESSAGE_OK(message):
@@ -535,10 +621,17 @@ class RepRapProtocol(Protocol):
##~~ private
def _process_acknowledgement(self):
output = self._output
self._output = []
with self._send_lock:
if len(self._sent_lines) > 0:
entry = self._sent_lines.popleft()
if entry.command is not None:
entry.command.output = output
print("!!! Adding output to command %s: %r (entry: %r)" % (entry.command.command, entry.command.output, entry))
# process command as acknowledged
self._process_command(entry.command, "acknowledged", with_line_number=entry.line_number)
@@ -804,6 +897,7 @@ class RepRapProtocol(Protocol):
if self._fill_queue_semaphore.acquire(0.5):
self._send_next()
print("/// sent next line from file: %r" % self._fill_queue_semaphore._Semaphore__value)
##~~ the actual send queue handling starts here
@@ -872,6 +966,7 @@ class RepRapProtocol(Protocol):
# add the queue item into the deque of commands not yet acknowledged
self._sent_lines.append(item)
print("+++ sent: %r" % item)
self._process_command(item.command, "sent", with_line_number=item.line_number)
else:
@@ -945,8 +1040,9 @@ class RepRapProtocol(Protocol):
def _gcode_G0_acknowledged(self, command, with_line_number):
if command.z is not None:
z = command.z
self._reportZChange(z)
self._reportZChange(command.z)
if command.f is not None:
self._last_seen_f = command.f
return command, with_line_number
_gcode_G1_acknowledged = _gcode_G0_acknowledged
+13 -6
View File
@@ -9,9 +9,12 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
import os
import pylru
import tempfile
import octoprint.filemanager
from octoprint.util import safeRename
class StorageInterface(object):
@@ -867,12 +870,16 @@ class LocalFileStorage(StorageInterface):
def _save_metadata(self, path, metadata):
metadata_path = os.path.join(path, ".metadata.yaml")
fh, metadata_temporary_path = tempfile.mkstemp()
os.close(fh)
with self._metadata_lock:
with open(metadata_path, "w") as f:
try:
try:
with open(metadata_temporary_path, "w") as f:
import yaml
yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
except:
self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals()))
else:
self._metadata_cache[path] = metadata
safeRename(metadata_temporary_path, metadata_path, throw_error=True)
except:
self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals()))
else:
self._metadata_cache[path] = metadata
+4 -1
View File
@@ -188,7 +188,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
def is_slicer_configured(self):
cura_engine = s.get(["cura_engine"])
return cura_engine is not None and os.path.exists(cura_engine)
if cura_engine is not None and os.path.exists(cura_engine):
return True
else:
self._logger.info("Path to CuraEngine has not been configured yet or does not exist (currently set to %r), Cura will not be selectable for slicing" % cura_engine)
def get_slicer_properties(self):
return dict(
+3
View File
@@ -705,6 +705,9 @@ class Printer():
def mcReceivedRegisteredMessage(self, command, output):
self._sendFeedbackCommandOutput(command, output)
def mcForceDisconnect(self):
self.disconnect()
#~~ sd file handling
def getSdFiles(self):
+8 -1
View File
@@ -216,6 +216,8 @@ class Server():
from tornado.ioloop import IOLoop
from tornado.web import Application
import sys
debug = self._debug
# first initialize the settings singleton and make sure it uses given configfile and basedir if available
@@ -224,6 +226,9 @@ class Server():
# then initialize logging
self._initLogging(self._debug, self._logConf)
logger = logging.getLogger(__name__)
def exception_logger(exc_type, exc_value, exc_tb):
logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
sys.excepthook = exception_logger
logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)
# then initialize the plugin manager
@@ -275,8 +280,10 @@ class Server():
app.wsgi_app,
settings().get(["server", "reverseProxy", "prefixHeader"]),
settings().get(["server", "reverseProxy", "schemeHeader"]),
settings().get(["server", "reverseProxy", "hostHeader"]),
settings().get(["server", "reverseProxy", "prefixFallback"]),
settings().get(["server", "reverseProxy", "prefixScheme"])
settings().get(["server", "reverseProxy", "schemeFallback"]),
settings().get(["server", "reverseProxy", "hostFallback"])
)
secret_key = settings().get(["server", "secretKey"])
+8 -7
View File
@@ -300,7 +300,6 @@ def printerSdState():
@api.route("/printer/command", methods=["POST"])
@restricted_access
def printerCommand():
# TODO: document me
if not printer.isOperational():
return make_response("Printer is not operational", 409)
@@ -309,15 +308,17 @@ def printerCommand():
data = request.json
parameters = {}
if "parameters" in data.keys():
parameters = data["parameters"]
parameters = dict()
if "parameters" in data.keys(): parameters = data["parameters"]
commands = []
if "command" in data.keys():
if "command" in data and "commands" in data:
return make_response("'command' and 'commands' are mutually exclusive", 400)
elif "command" in data:
commands = [data["command"]]
elif "commands" in data.keys():
elif "commands" in data and isinstance(data["commands"], (list, tuple)):
commands = data["commands"]
else:
return make_response("Need either single 'command' or list of 'commands'", 400)
commandsToSend = []
for command in commands:
+17 -3
View File
@@ -147,20 +147,25 @@ class ReverseProxied(object):
:param app: the WSGI application
:param header_script_name: the HTTP header in the wsgi environment from which to determine the prefix
:param header_scheme: the HTTP header in the wsgi environment from which to determine the scheme
:param header_host: the HTTP header in the wsgi environment from which to determine the host for which to generate external URLs
:param base_url: the prefix to use as fallback if headers are not set
:param scheme: the scheme to use as fallback if headers are not set
:param host: the host to use as fallback if headers are not set
"""
def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", base_url="", scheme=""):
def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", header_host="x-forwarded-host", base_url="", scheme="", host=""):
self.app = app
# headers for prefix & scheme, converted to conform to WSGI format
# headers for prefix & scheme & host, converted to conform to WSGI format
to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_")
self._header_prefix = to_wsgi_format(header_prefix)
self._header_scheme = to_wsgi_format(header_scheme)
self._header_host = to_wsgi_format(header_host)
# fallback prefix & scheme from config
# fallback prefix & scheme & host from config
self._fallback_prefix = base_url
self._fallback_scheme = scheme
self._fallback_host = host
def __call__(self, environ, start_response):
# determine prefix
@@ -184,6 +189,15 @@ class ReverseProxied(object):
if scheme:
environ["wsgi.url_scheme"] = scheme
# determine host
host = environ.get(self._header_host, "")
if not host:
host = self._fallback_host
# rewrite host header based on host
if host:
environ["HTTP_HOST"] = host
# call wrapped app with rewritten environment
return self.app(environ, start_response)
+11 -6
View File
@@ -34,6 +34,8 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
self._eventManager = eventManager
self._pluginManager = pluginManager
self._remoteAddress = None
def _getRemoteAddress(self, info):
forwardedFor = info.headers.get("X-Forwarded-For")
if forwardedFor is not None:
@@ -41,8 +43,8 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
return info.ip
def on_open(self, info):
remoteAddress = self._getRemoteAddress(info)
self._logger.info("New connection from client: %s" % remoteAddress)
self._remoteAddress = self._getRemoteAddress(info)
self._logger.info("New connection from client: %s" % self._remoteAddress)
# connected => update the API key, might be necessary if the client was left open while the server restarted
self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "display_version": octoprint.server.DISPLAY_VERSION})
@@ -52,20 +54,20 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
octoprint.timelapse.registerCallback(self)
self._pluginManager.register_client(self)
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress})
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
for event in octoprint.events.all_events():
self._eventManager.subscribe(event, self._onEvent)
octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current)
def on_close(self):
self._logger.info("Client connection closed")
self._logger.info("Client connection closed: %s" % self._remoteAddress)
self._printer.unregisterCallback(self)
self._fileManager.unregister_slicingprogress_callback(self)
octoprint.timelapse.unregisterCallback(self)
self._pluginManager.unregister_client(self)
self._eventManager.fire(Events.CLIENT_CLOSED)
self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress})
for event in octoprint.events.all_events():
self._eventManager.unsubscribe(event, self._onEvent)
@@ -137,4 +139,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
self.sendEvent(event, payload)
def _emit(self, type, payload):
self.send({type: payload})
try:
self.send({type: payload})
except Exception as e:
self._logger.warn("Could not send message to client %s: %s" % (self._remoteAddress, e.message))
+3 -1
View File
@@ -69,8 +69,10 @@ default_settings = {
"reverseProxy": {
"prefixHeader": "X-Script-Name",
"schemeHeader": "X-Scheme",
"hostHeader": "X-Forwarded-Host",
"prefixFallback": "",
"schemeFallback": ""
"schemeFallback": "",
"hostFallback": ""
},
"uploads": {
"maxSize": 1 * 1024 * 1024 * 1024, # 1GB
@@ -28,6 +28,7 @@ function SlicingViewModel(loginStateViewModel, printerProfilesViewModel) {
self.afterSlicing = ko.observable("none");
self.show = function(target, file) {
self.requestData();
self.target = target;
self.file = file;
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: self.file}));
@@ -48,13 +49,18 @@ function SlicingViewModel(loginStateViewModel, printerProfilesViewModel) {
&& self.profile() != undefined;
});
self.requestData = function() {
self.requestData = function(callback) {
$.ajax({
url: API_BASEURL + "slicing",
type: "GET",
dataType: "json",
success: self.fromResponse
})
success: function(data) {
self.fromResponse(data);
if (callback !== undefined) {
callback();
}
}
});
};
self.fromResponse = function(data) {
+1 -1
View File
@@ -59,7 +59,7 @@
var CONFIG_GCODE_SIZE_THRESHOLD = {{ gcodeThreshold }};
var CONFIG_GCODE_MOBILE_SIZE_THRESHOLD = {{ gcodeMobileThreshold }};
var SOCKJS_URI = window.location.protocol.slice(0, -1) + "://" + (window.document ? window.document.domain : window.location.hostname) + ":" + window.location.port + BASEURL + "sockjs";
var SOCKJS_URI = "{{ url_for('index') }}" + "sockjs";
var SOCKJS_DEBUG = {% if debug -%} true; {% else %} false; {%- endif %}
var UI_API_KEY = "{{ uiApiKey }}";
+9 -4
View File
@@ -227,8 +227,12 @@ class Timelapse(object):
self._logger.warn("Cannot capture image, capture directory is unset")
return
if self._imageNumber is None:
self._logger.warn("Cannot capture image, image number is unset")
return
with self._captureMutex:
filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % (self._imageNumber))
filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % self._imageNumber)
self._imageNumber += 1
self._logger.debug("Capturing image to %s" % filename)
captureThread = threading.Thread(target=self._captureWorker, kwargs={"filename": filename})
@@ -243,8 +247,9 @@ class Timelapse(object):
self._logger.debug("Image %s captured from %s" % (filename, self._snapshotUrl))
except:
self._logger.exception("Could not capture image %s from %s, decreasing image counter again" % (filename, self._snapshotUrl))
if self._imageNumber is not None and self._imageNumber > 0:
self._imageNumber -= 1
with self._captureMutex:
if self._imageNumber is not None and self._imageNumber > 0:
self._imageNumber -= 1
eventManager().fire(Events.CAPTURE_DONE, {"file": filename})
def _createMovie(self, success=True):
@@ -299,7 +304,7 @@ class Timelapse(object):
# finalize command with output file
self._logger.debug("Rendering movie to %s" % output)
command.append(output)
command.append("\"" + output + "\"")
eventManager().fire(Events.MOVIE_RENDERING, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)})
command_str = " ".join(command)
+6 -4
View File
@@ -148,7 +148,7 @@ def findCollisionfreeName(input, extension, existingFilenames):
raise ValueError("Can't create a collision free filename")
def safeRename(old, new):
def safeRename(old, new, throw_error=False):
"""
Safely renames a file.
@@ -173,12 +173,14 @@ def safeRename(old, new):
os.rename(new, backup)
os.rename(old, new)
os.remove(backup)
except OSError:
except OSError as e:
# if anything went wrong, try to rename the backup file to its original name
logger.error("Could not perform safe rename, trying to revert")
if os.path.exists(backup):
os.remove(new)
os.rename(backup, new)
silentRemove(new)
os.rename(backup, new)
if throw_error:
raise e
else:
# on anything else than windows it's ooooh so much easier...
os.rename(old, new)
+25
View File
@@ -161,6 +161,7 @@ class MachineCom(object):
# hooks
self._pluginManager = octoprint.plugin.plugin_manager()
self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.gcode")
self._printer_action_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.action")
# SD status data
self._sdAvailable = False
@@ -655,6 +656,27 @@ class MachineCom(object):
if line.strip() is not "":
self._timeout = getNewTimeout("communication")
##~~ debugging output handling
if line.startswith("//"):
debugging_output = line[2:].strip()
if debugging_output.startswith("action:"):
action_command = debugging_output[len("action:"):].strip()
if action_command == "pause":
self._log("Pausing on request of the printer...")
self.setPause(True)
elif action_command == "resume":
self._log("Resuming on request of the printer...")
self.setPause(False)
elif action_command == "disconnect":
self._log("Disconnecting on request of the printer...")
self._callback.mcForceDisconnect()
else:
for hook in self._printer_action_hooks:
self._printer_action_hooks[hook](self, line, action_command)
else:
continue
##~~ Error handling
line = self._handleErrors(line)
@@ -1296,6 +1318,9 @@ class MachineComPrintCallback(object):
def mcReceivedRegisteredMessage(self, command, message):
pass
def mcForceDisconnect(self):
pass
### Printing file information classes ##################################################################################
class PrintingFileInformation(object):
+10
View File
@@ -227,6 +227,8 @@ class VirtualPrinter():
self._relative = True
elif "G92" in data:
self._setPosition(data)
elif data.startswith("!!DEBUG:"):
self._debugTrigger(data[len("!!DEBUG:"):].strip())
elif data.startswith("G0") or data.startswith("G1") or data.startswith("G2") or data.startswith("G3") \
or data.startswith("G28") or data.startswith("G29") or data.startswith("G30") \
@@ -237,6 +239,14 @@ class VirtualPrinter():
if len(data.strip()) > 0:
self._sendOk()
def _debugTrigger(self, data):
if data == "action_pause":
self.outgoing.put("// action:pause")
elif data == "action_resume":
self.outgoing.put("// action:resume")
elif data == "action_disconnect":
self.outgoing.put("// action:disconnect")
def _listSd(self):
self.outgoing.put("Begin file list")
if settings().getBoolean(["devel", "virtualPrinter", "extendedSdFileList"]):