Compare commits

...
Author SHA1 Message Date
Gina Häußge 25dc81a5d2 Couple more compatibility fixes to bring this up to par with devel 2014-12-19 23:20:50 +01:00
Gina Häußge 9e27744a05 Fixed some merge errors 2014-12-19 12:40:49 +01:00
Gina Häußge 77df620237 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/printer/__init__.py
	src/octoprint/server/__init__.py
	src/octoprint/server/api/connection.py
	src/octoprint/util/virtual.py
2014-12-19 12:33:57 +01:00
Gina Häußge a0a6f958d9 Improved cancelling by new lock, should make it even more snappier 2014-11-13 13:08:11 +01:00
Gina Häußge 16d156b530 This should hopefully get cancelling to react a bit snappier again
TODO: figure out why sometimes writetimeouts show up
2014-11-12 17:26:41 +01:00
Gina Häußge 420226b6c0 Added command processing phase "sending" which replaces former phase "sent", which in turn was moved _after_ the command has actually been sent
This solves a deadlock which can occur if a blocking command is denied sending due to buffer restrictions. It couldn't then ever be actually sent after denied once.
2014-11-12 12:38:15 +01:00
Gina Häußge da8e72b0d6 Use a bounded semaphore for properly limiting the max count of items in the queue, also track removed items upon send_queue.clear 2014-11-12 12:35:06 +01:00
Gina Häußge ef13cbecfd Do not delete lines from the send queue upon cancel that were already prepared (got a line number) 2014-11-12 11:50:58 +01:00
Gina Häußge 5910bba30e Define G28 and G29 as blocking commands, since apparently the firmware blocks writes (even buffered ones) while those are active 2014-11-10 19:48:02 +01:00
Gina Häußge 19ba3b1f99 command might be None after hook processors are through with it 2014-11-10 16:39:20 +01:00
Gina Häußge 23bc6b8df7 Added keywords arguments to pause_print to disable toggle and only resume or pause
If the printer is paused and the method is called with only_pause=True, nothing will happen.

If the printer is printing and the method is called with only_resume=True, nothing will happen.
2014-11-10 13:11:46 +01:00
Gina Häußge 69bea0f5b0 Hooks always get the value of with_line_number, no need for a keyword argument there 2014-11-10 13:00:18 +01:00
Gina Häußge 3c53394f4b Plugin manager returned wrong data types when no plugins/hooks where found 2014-11-10 12:58:15 +01:00
Gina Häußge 8741053dfc Merge branch 'dattas-commRefactoring-hook' into commRefactoring 2014-11-10 12:33:39 +01:00
Gina Häußge 8752f70ff3 Added multiple hooks for the individual processing phases, gcode hooks now have to process the parsed command (might be unknown) 2014-11-10 12:33:24 +01:00
Gina Häußge 2b66df39b6 Merge branch 'commRefactoring-hooks' of http://github.com/dattas/OctoPrint into dattas-commRefactoring-hook 2014-11-10 12:23:36 +01:00
Gina Häußge 17bb0e693d Version resource was defined twice 2014-11-10 12:13:42 +01:00
Gina Häußge 94e5b5fdaf Virtual printer did not send repetier-style target temperature messages while heating up 2014-11-10 12:13:18 +01:00
Gina Häußge 497ec5c6b2 RepetierTextualProtocol now makes use of overriding RepRapProtocol.MESSAGE_TEMPERATURE 2014-11-10 12:12:33 +01:00
Gina Häußge eaeae8d5ec Some small refactorings
- _nack_lines, _nack_lock, _nacks_before_resend => _sent_lines, _sent_lock, _sent_before_resend
- some reordering in the message processing
- referal to MESSAGE and COMMAND instances via self.__class__ instead of RepRapProtocol => allows sub classes to override MESSAGE and COMMAND definitions
2014-11-10 12:11:45 +01:00
Gina Häußge 3a05a2653b Fixed issue where peek and pop on send_queue could act on different
entries.

After sending the sent entry is now not removed from the queue by a
pop but an explicit remove instead. Removal maintains the queue's
heap invariant.
2014-11-10 12:07:49 +01:00
Gina Häußge 0ca63017c7 Merge remote-tracking branch 'origin/commRefactoring-rxcache' into commRefactoring-rxcache 2014-11-10 09:23:56 +01:00
Gina Häußge ea3416693c Merge branch 'devel' into commRefactoring-rxcache 2014-11-10 09:22:20 +01:00
Dattas Moonchaser 6dc56af3fa Add octoprint.comm.protocol.gcode hooks 2014-11-08 14:36:57 -07:00
Gina Häußge af297c2031 Merge pull request #643 from dattas/commRefactoring-unknowncmds
commRefactoring-Unknown commands
2014-11-08 19:47:36 +01:00
Dattas Moonchaser 024cf81238 Allow gcode commands to get farther into the processing, but ensure they don't get pushed to the printer 2014-11-08 11:36:31 -07:00
Gina Häußge 9d5a500b25 Cancelling print jobs should now work again 2014-11-07 22:56:49 +01:00
Gina Häußge 4bab1975c8 Funnily enough that clear_for_send was still decremented at the wrong location 2014-11-07 14:26:40 +01:00
Gina Häußge eae4153158 Some performance optimizations
- self._clear_for_send was decremented at wrong location
- added semaphore for use in fill queue processing (max entries 20, fill queue acquires, send queue releases upon send)
- added signal of state for use in fill queue processing, no more sleep-wake-check-loops there
- CommandQueue.peek also was not synchronized

Found a couple of issue to tackle next (see TODOs)
2014-11-07 13:29:11 +01:00
Gina Häußge a92aa96623 Proper clearing of send queue on cancel and proper signaling of print job done when last command gets acknowledged 2014-11-06 18:44:40 +01:00
Gina Häußge ccf0ab3b51 Let's set the default buffer size to something that should fit most configurations
These appear to be the used rx cache sizes:

  - Marlin on AT90USB boards (e.g. Printrboard) => 63 bytes
  - Marlin anywhere else, using MarlinSerial implementation => 127 bytes
  - Repetier by default => 127 bytes
  - Repetier if EXTERNALSERIAL is defined in Configuration => 63 bytes

63 bytes should be pretty much safe in any case, user can increase that if falling into the 127 bytes group.
2014-11-06 14:32:51 +01:00
Gina Häußge 7259c1c2ef Fixed a race condition that made print jobs stall, also fixed temperature reporting and a couple other things
See #568
2014-11-06 14:22:48 +01:00
Gina Häußge d66675c672 Actually forward the protocol and transport options to the protocol and transport instances upon connect...
Yeah, I don't know why that was missing either.
2014-11-06 08:54:05 +01:00
Gina Häußge 38483b0c67 Further work on the communication layer
Write blocks on the serial interface are now handled gracefully (also the write timeout has been set to a more sane value, maybe that can be lowered more?).

I'm still observing some weird "stops" when printing the valentine dragon thingy on a Printrbot Simple, still trying to find out what's happening there exactly.
2014-11-05 15:52:31 +01:00
Gina Häußge 19de4053fe WIP: More work on the communication layer
Split command processing into "queued", "sent" and "acknowledged" events, added command acknowledgement tracking via nack_line queue, using that too for resend implementation

Problem: Deadlock when using a real printer after receiving first "ok" response to "N0 M110 S0" right at the beginning of the print.
2014-11-03 21:37:04 +01:00
Gina Häußge d0ff6d1579 Fix: it should not be possible to access/increment/decrement line numbers concurrently from different threads 2014-10-31 22:06:06 +01:00
Gina Häußge 105b68c807 Move the OK processing at the end of the message receiver for now to make temperature reporting outside of heatup work on Marlin again 2014-10-31 21:45:08 +01:00
Gina Häußge 97a6d8a15e Our transport timeout is a fairly normal thing and no reason for a warn in the log 2014-10-31 21:29:08 +01:00
Gina Häußge 26fa3df4aa Fixed line number generation outside of sending queue (and removed some left-overs) 2014-10-31 21:28:26 +01:00
Gina Häußge 9a336336d7 Removed unused method self._useChecksum 2014-10-31 19:04:12 +01:00
Gina Häußge 047d7f5046 self.disconnect had wrong signature 2014-10-31 19:02:48 +01:00
Gina Häußge 4fc561dab5 Always send checksum by default 2014-10-31 19:02:29 +01:00
Gina Häußge 785ac07de9 Removed self._ping_pong (can be done by setting self._rx_cache_size to 0) and self._rx_cache_fill (can be done by sum(self._nack_lines)), made self._rx_cache_size configurable 2014-10-31 18:51:54 +01:00
Gina Häußge 41c6978880 Changed some things refering to other things changed in devel 2014-10-31 17:59:05 +01:00
Gina Häußge f7ebc4ec11 Merge remote-tracking branch 'presslab-us/commRefactoring-rxcache' into commRefactoring-rxcache 2014-10-31 17:55:36 +01:00
Gina Häußge c06e8f47f0 Fixed queue processing of virtual printer 2014-10-31 17:54:01 +01:00
Gina Häußge dceb5dccd3 Made virtual printer a bit more "lifelike"
Added (configurable) queue for buffered G codes (G0, G1, G2, G3, G28, G29-G32), incoming queue and queue clearing upon resend

Needed for testing stuff for #568
2014-10-31 15:40:01 +01:00
Gina Häußge 7a50138ae3 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/settings.py
2014-10-31 14:50:59 +01:00
Gina Häußge 43cead8249 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/printer.py
	src/octoprint/server/api/files.py
2014-10-30 14:21:27 +01:00
Ryan Press 8492944fb5 Fix sign of 'nice' level. 2014-10-29 19:27:50 -07:00
Ryan Press f7433de2bf Fix temperature polling. 2014-10-26 12:51:27 -07:00
Ryan Press bbd46fd3a6 Reimplement missing events in commRefactoring. 2014-10-26 08:57:46 -07:00
Ryan Press 077486c838 Add support for rx cache to increase throughput to printer.
This can be disabled by ticking Ping-Pong in the settings.
2014-10-26 08:56:50 -07:00
Ryan Press baedab5931 Increase nice level in init script for higher priority. 2014-10-26 08:56:07 -07:00
Gina Häußge 36c8f25fd1 Honor paused state and don't eat the clear_for_send flag when not actually sending something 2014-09-17 18:15:10 +02:00
Gina Häußge b3050f1058 If command handler returns, _preprocess_command should return None not "None" 2014-09-17 17:33:58 +02:00
Gina Häußge a04a61f61b M0 command handler needs to return tuple, not just None 2014-09-17 17:23:51 +02:00
Gina Häußge 58204248bb Don't wait for "start" from printer if not configured like that 2014-09-17 17:08:35 +02:00
Gina Häußge a47740ae28 Merge branch 'devel' into commRefactoring 2014-09-15 21:55:35 +02:00
Gina Häußge 48d6a27fad Merge branch 'devel' into commRefactoring 2014-09-03 18:39:36 +02:00
Gina Häußge 5ffcd78f27 Merge remote-tracking branch 'origin/commRefactoring' into commRefactoring 2014-08-30 20:03:23 +02:00
Gina Häußge de9dd77b50 Merge branch 'devel' into commRefactoring 2014-08-30 20:02:36 +02:00
Gina Häußge 51c77be7a2 Don't overwrite query string of webcam URI
If there's a query already present, just append the timestamp to it with a & in between instead of creating a new query.
2014-08-11 22:25:09 +02:00
Gina Häußge f98563cbe9 Merge branch 'devel' into commRefactoring 2014-08-11 18:41:31 +02:00
Gina Häußge 8c8059db30 Protocol and Transport classes are now detected automatically and the one to use can be specified by config, also made standard control commands part of the protocol interface 2014-07-24 14:24:04 +02:00
Gina Häußge fa586426fa Connection handshake should now be more error resilient 2014-07-12 19:55:13 +02:00
Gina Häußge 60a1bf0d43 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/printer.py
2014-07-12 19:37:38 +02:00
Gina Häußge a48f194350 Repetier protocol specifics, better virtual printer, proper handling of finished print jobs 2014-06-02 00:32:29 +02:00
Gina Häußge 78f0ec94ea SD Upload appears to be working again 2014-06-01 18:43:13 +02:00
Gina Häußge 44f9e756da Merge branch 'devel' into commRefactoring 2014-06-01 11:54:14 +02:00
Gina Häußge 3d992d56cd And even more work, trying to get the SD stuff and the offsets working again, also refactored some things here and there 2014-06-01 11:52:06 +02:00
Gina Häußge 72f7b4627f Merge branch 'devel' into commRefactoring 2014-05-30 18:38:23 +02:00
Gina Häußge 5c1f165079 Connection options, sd initialization and releasing, refactoring ... more work, off I go then 2014-05-29 22:11:11 +02:00
Gina Häußge 95755ba515 Merge branch 'devel' into commRefactoring 2014-05-29 18:01:15 +02:00
Gina Häußge 791e4e26a9 More work, print jobs at least on the virtual printer are starting to work now 2014-05-29 17:40:49 +02:00
Gina Häußge 4d61963894 Merge branch 'devel' into commRefactoring 2014-05-29 13:17:31 +02:00
Gina Häußge 5622a9c565 more work on the comm refactoring, starting to resemble something working again 2014-05-29 13:02:25 +02:00
Gina Häußge 2e5069d5a1 Merge branch 'devel' into commRefactoring 2014-05-29 10:45:30 +02:00
Gina Häußge 4cd692e061 Merge branch 'commRefactoring' of https://github.com/foosel/OctoPrint into commRefactoring
Conflicts:
	src/octoprint/printer.py
2014-05-29 10:40:04 +02:00
Gina Häußge 216a88c00c WIP 2014-05-15 15:19:48 +02:00
Gina Häußge 10f1917589 Merge branch 'devel' into commRefactoring
Conflicts:
	src/octoprint/settings.py
	src/octoprint/util/virtual.py
2014-03-15 20:39:33 +01:00
Gina Häußge 26f7d6e517 Added logging and filtering of non-ASCII filenames of files returned from SD card, still WIP 2014-02-23 11:07:09 +01:00
Gina Häußge b7b2e99ab1 Merge branch 'devel' into commRefactoring 2014-02-17 11:39:21 +01:00
Gina Häußge 0966b231e8 Some more WIP 2014-01-31 11:41:40 +01:00
Gina Häußge 00e1a1962b Started working on new modular comm layer, checking in just for the record, not yet usable 2014-01-27 13:15:15 +01:00
22 changed files with 2714 additions and 304 deletions

No files matched your search

+2 -1
View File
@@ -19,6 +19,7 @@ PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="Octoprint Daemon"
NAME="Octoprint"
DAEMON=/usr/local/bin/octoprint
NICE=-10
PIDFILE=/var/run/$NAME.pid
PKGNAME=octoprint
SCRIPTNAME=/etc/init.d/$PKGNAME
@@ -72,7 +73,7 @@ do_start()
RETVAL="$?"
if [ $RETVAL != 0 ]; then
start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile \
start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile --nicelevel $NICE\
--exec $DAEMON --chuid $OCTOPRINT_USER --user $OCTOPRINT_USER --umask $UMASK -- $DAEMON_ARGS
RETVAL="$?"
fi
+6
View File
@@ -0,0 +1,6 @@
# coding=utf-8
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
+589
View File
@@ -0,0 +1,589 @@
# coding=utf-8
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
import logging
import os
import time
from octoprint.events import eventManager, Events
from octoprint.comm.transport import MessageReceiver, StateReceiver, LogReceiver, State as TransportState
from octoprint.filemanager.destinations import FileDestinations
from octoprint.settings import settings
class Protocol(MessageReceiver, StateReceiver, LogReceiver):
def __init__(self, transport_factory, protocol_listener=None):
self._logger = logging.getLogger(__name__)
self._transport = transport_factory(self, self, self)
self._transport_properties = self._transport.get_properties()
self._protocol_listener = protocol_listener
self._state = State.OFFLINE
self._heatup_start_time = None
self._heatup_time_lost = 0.0
self._pause_start_time = None
self._pause_time_lost = 0.0
self._current_file = None
self._current_z = 0.0
self._sd_available = False
self._sd_files = []
self._current_temperature = {}
self._temperature_offsets = {}
self._error = None
def _reset(self):
self._heatup_start_time = None
self._heatup_time_lost = 0.0
self._current_file = None
self._current_z = 0.0
self._sd_available = False
self._sd_files = []
self._current_temperature = {}
self._temperature_offsets = {}
self._error = None
##~~ public
def connect(self, protocol_options, transport_options):
self._transport.connect(transport_options)
def disconnect(self, on_error=False):
if self.is_printing():
payload = None
if self._current_file is not None:
payload = {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation()
}
eventManager().fire(Events.PRINT_FAILED, payload)
self._transport.disconnect(on_error)
def send_manually(self, command, high_priority=False):
pass
def select_file(self, filename, origin):
pass
def deselect_file(self):
pass
def start_print(self):
if self._current_file is None:
raise ValueError("No file selected for printing")
self._heatup_start_time = None
self._heatup_time_lost = 0.0
self._current_file.start()
self._changeState(State.PRINTING)
eventManager().fire(Events.PRINT_STARTED, {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation()
})
def pause_print(self, only_pause=None, only_resume=None):
payload = {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation()
}
if self._state == State.PRINTING and not only_resume:
self._pause_start_time = time.time()
self._changeState(State.PAUSED)
eventManager().fire(Events.PRINT_PAUSED, payload)
elif self._state == State.PAUSED and not only_pause:
if self._pause_start_time:
self._pause_time_lost += time.time() - self._pause_start_time
self._pause_start_time = None
self._changeState(State.PRINTING)
eventManager().fire(Events.PRINT_RESUMED, payload)
def cancel_print(self):
eventManager().fire(Events.PRINT_CANCELLED, {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation()
})
self._changeState(State.OPERATIONAL)
self._print_cancelled()
if self._protocol_listener is not None:
self._protocol_listener.onPrintjobCancelled(self)
def _print_cancelled(self):
pass
def init_sd(self):
pass
def release_sd(self):
pass
def refresh_sd_files(self):
pass
def add_sd_file(self, path, local, remote):
pass
def remove_sd_file(self, filename):
pass
def get_state(self):
return self._state
def get_current_temperatures(self):
return self._current_temperature
def get_temperature_offsets(self):
result = {}
result.update(self._temperature_offsets)
return result
def set_temperature_offsets(self, new_temperature_offsets):
offsets = {}
offsets.update(new_temperature_offsets)
self._temperature_offsets = offsets
def get_sd_files(self):
return self._sd_files
def get_print_time(self):
if self._current_file is None or self._current_file.getStartTime() is None:
return None
else:
return max(int(time.time() - self._current_file.getStartTime() - self._heatup_time_lost - self._pause_time_lost), 0)
def get_connection_options(self):
return self._transport.get_connection_options()
def get_current_connection(self):
return self._transport.get_current_connection()
##~~ granular state detection for implementations
def is_heating_up(self):
return self._heatup_start_time is not None
def is_printing(self):
return self._state == State.PRINTING or self._state == State.PAUSED
def is_sd_printing(self):
return isinstance(self._current_file, PrintingSdFileInformation) and self.is_busy()
def is_streaming(self):
return self._state == State.STREAMING
def is_busy(self):
return self.is_printing() or self.is_streaming()
def is_operational(self):
return self._state == State.OPERATIONAL
def is_sd_ready(self):
return self._sd_available
##~~ state tracking and reporting to protocol listener
def _changeState(self, newState):
oldState = self._state
self._state = newState
self._stateChanged(newState)
if self._protocol_listener is not None:
self._protocol_listener.onStateChange(self, oldState, newState)
def _stateChanged(self, newState):
pass
def _updateTemperature(self, temperatureData):
self._current_temperature = temperatureData
self._temperatureUpdated(temperatureData)
if self._protocol_listener is not None:
self._protocol_listener.onTemperatureUpdate(self, temperatureData)
def _temperatureUpdated(self, temperatureData):
pass
def _reportProgress(self, completion=None, filepos=None):
if completion is None:
completion = self._getPrintCompletion()
if filepos is None:
filepos = self._getPrintFilepos()
progress = {
"completion": completion,
"filepos": filepos,
"printTime": self.get_print_time()
}
self._progressReported(progress)
if self._protocol_listener is not None:
self._protocol_listener.onProgress(self, progress)
def _progressReported(self, progress):
pass
def _reportZChange(self, z):
old_z = self._current_z
self._current_z = z
self._zChangeReported(z)
if self._protocol_listener is not None:
self._protocol_listener.onZChange(self, old_z, z)
def _zChangeReported(self, newZ):
pass
def _changeSdState(self, sdAvailable):
self._sd_available = sdAvailable
self._sdStateChanged(sdAvailable)
if self._sd_available:
self.refresh_sd_files()
else:
self._sd_files = []
if self._protocol_listener is not None:
self._protocol_listener.onSdStateChange(self, sdAvailable)
def _sdStateChanged(self, sdAvailable):
pass
def _selectFile(self, currentFile):
self._current_file = currentFile
self._fileSelected(currentFile)
if self._protocol_listener is not None:
self._protocol_listener.onFileSelected(self, currentFile.getFilename(), currentFile.getFilesize(), currentFile.getFileLocation())
eventManager().fire(Events.FILE_SELECTED, {
"file": self._current_file.getFilename(),
"origin": self._current_file.getFileLocation()
})
def _fileSelected(self, currentFile):
pass
def _sendSdFiles(self):
self._sdFilesSent()
if self._protocol_listener is not None:
self._protocol_listener.onSdFiles(self, self._sd_files)
def _sdFilesSent(self):
pass
def _finishPrintjob(self):
self._reportProgress(completion=100, filepos=self._current_file.getFilesize())
self._changeState(State.OPERATIONAL)
if self._protocol_listener is not None:
self._protocol_listener.onPrintjobDone(self)
eventManager().fire(Events.PRINT_DONE, {
"file": self._current_file.getFilename(),
"filename": os.path.basename(self._current_file.getFilename()),
"origin": self._current_file.getFileLocation(),
"time": time.time() - self._current_file.getStartTime() if self._current_file.getStartTime() is not None else None
})
self._printJobFinished()
def _printJobFinished(self):
pass
def _startFileTransfer(self, filename, filesize):
self._fileTransferStarted(filename, filesize)
if self._protocol_listener is not None:
self._protocol_listener.onFileTransferStarted(self, filename, filesize)
def _fileTransferStarted(self, filename, filesize):
pass
def _finishFileTransfer(self):
self._changeState(State.OPERATIONAL)
current_file = self._current_file
self._current_file = None
self._fileTransferFinished(current_file)
if self._protocol_listener is not None:
self._protocol_listener.onFileTransferDone(self)
def _fileTransferFinished(self, current_file):
pass
def _addSdFile(self, filename, filesize):
"""
Adds a file to the SD file list
:param filename: the filename to add to the list
:param filesize: the filesize to add to the list, may be None
"""
self._sd_files.append((filename, filesize))
self._sdFileAdded(filename, filesize)
def _sdFileAdded(self, filename, filesize):
"""
Called when a file has been added to the SD file list, can be used by the underyling protocol implementation
to react to that.
:param filename: the filename to add to the list
:param filesize: the filesize to add to the list, may be None
"""
pass
def _addSdFiles(self, files):
"""
Adds a list of files to the SD file list
:param files: the list of file tuples (name, size) to add to the list, size may be None
"""
for f in files:
self._sd_files.append(f)
self._sdFilesAdded(files)
def _sdFilesAdded(self, files):
"""
Called when a list of files has been added to the SD file list, can be used by the underlying protocol
implementation to react to that.
:param files: the file tuples (name, size) added to the list, size may be None
"""
pass
def _resetSdFiles(self):
"""
Resets the SD file list
"""
self._sd_files = []
self._sdFilesReset()
def _sdFilesReset(self):
"""
Called when the list of SD files has been reset, can be used in the underlying protocol implementation to
react to that
"""
pass
def _heatupDetected(self):
"""
Called when the underlying protocol detects the beginning of a heat-up interval.
"""
self._heatup_start_time = time.time()
def _heatupDone(self):
"""
Called when the underlying protocol detects the end of a heat-up interval.
"""
if self._heatup_start_time is not None:
self._heatup_time_lost += time.time() - self._heatup_start_time
self._heatup_start_time = None
def _log_error(self, error):
if self._protocol_listener is not None:
self._protocol_listener.onLogError(self, error)
##~~ StateReceiver
def onStateChangeReceived(self, source, oldState, newState):
if self._transport != source:
return
if newState == TransportState.DETECTING_CONNECTION or newState == TransportState.OPENING_CONNECTION:
self._changeState(State.CONNECTING)
elif newState == TransportState.CONNECTED:
self._changeState(State.CONNECTED)
elif newState == TransportState.DISCONNECTED:
self._changeState(State.OFFLINE)
elif newState == TransportState.DISCONNECTED_WITH_ERROR or newState == TransportState.ERROR:
self.onError(self._transport.getError())
try:
self._transport.disconnect()
except:
# TODO do we need to handle that?
pass
##~~ MessageReceiver
def onError(self, error):
self._changeState(State.ERROR)
self._error = error
eventManager().fire(Events.ERROR, {"error": error})
##~~ LogReceiver
def onLogRx(self, source, rx):
if self._transport != source:
return
if self._protocol_listener is not None:
self._protocol_listener.onLogRx(self, rx)
def onLogTx(self, source, tx):
if self._transport != source:
return
if self._protocol_listener is not None:
self._protocol_listener.onLogTx(self, tx)
def onLogError(self, source, error):
if self._transport != source:
return
self._log_error(error)
##~~ helpers
def _getPrintCompletion(self):
if self._current_file is None:
return None
return self._current_file.getProgress() * 100
def _getPrintFilepos(self):
if self._current_file is None:
return None
return self._current_file.getFilepos()
class ProtocolListener(object):
def onStateChange(self, source, oldState, newState):
pass
def onTemperatureUpdate(self, source, temperatureData):
pass
def onProgress(self, source, progress):
pass
def onZChange(self, source, oldZ, newZ):
pass
def onFileSelected(self, source, filename, filesize, origin):
pass
def onPrintjobStarted(self, source):
pass
def onPrintjobDone(self, source):
pass
def onPrintjobCancelled(self, source):
pass
def onFileTransferStarted(self, source, filename, filesize):
pass
def onFileTransferDone(self, source):
pass
def onSdStateChange(self, source, sdAvailable):
pass
def onSdFiles(self, source, files):
pass
def onLogTx(self, source, tx):
pass
def onLogRx(self, source, rx):
pass
def onLogError(self, source, error):
pass
class State(object):
OFFLINE = "Offline"
CONNECTING = "Connecting"
CONNECTED = "Connected"
OPERATIONAL = "Operational"
PRINTING = "Printing"
STREAMING = "Streaming"
PAUSED = "Paused"
ERROR = "Error"
### Printing file information classes ##################################################################################
class PrintingFileInformation(object):
"""
Encapsulates information regarding the current file being printed: file name, current position, total size and
time the print started.
Allows to reset the current file position to 0 and to calculate the current progress as a floating point
value between 0 and 1.
"""
def __init__(self, filename):
self._filename = filename
self._filepos = 0
self._filesize = None
self._startTime = None
def getStartTime(self):
return self._startTime
def getFilename(self):
return self._filename
def getFilesize(self):
return self._filesize
def getFilepos(self):
return self._filepos
def getFileLocation(self):
return FileDestinations.LOCAL
def getProgress(self):
"""
The current progress of the file, calculated as relation between file position and absolute size. Returns -1
if file size is None or < 1.
"""
if self._filesize is None or not self._filesize > 0:
return -1
return float(self._filepos) / float(self._filesize)
def reset(self):
"""
Resets the current file position to 0.
"""
self._filepos = 0
def start(self):
"""
Marks the print job as started and remembers the start time.
"""
self._startTime = time.time()
class PrintingSdFileInformation(PrintingFileInformation):
"""
Encapsulates information regarding an ongoing print from SD.
"""
def __init__(self, filename, filesize):
PrintingFileInformation.__init__(self, filename)
self._filesize = filesize
def setFilepos(self, filepos):
"""
Sets the current file position.
"""
self._filepos = filepos
def getFileLocation(self):
return FileDestinations.SDCARD
+59
View File
@@ -0,0 +1,59 @@
# coding=utf-8
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
import re
from octoprint.comm.protocol.reprap import RepRapProtocol
class RepetierTextualProtocol(RepRapProtocol):
__protocolinfo__ = ("repetier", "RepRap (Repetier Flavor)", False)
MESSAGE_TARGET_TEMPERATURE = staticmethod(lambda line: "TargetExtr" in line or "TargetBed" in line)
MESSAGE_TEMPERATURE = staticmethod(lambda line: RepRapProtocol.MESSAGE_TEMPERATURE(line) or RepetierTextualProtocol.MESSAGE_TARGET_TEMPERATURE(line))
REGEX_POSITIVE_FLOAT = "[+]?[0-9]*\.?[0-9]+"
REGEX_TARGET_EXTRUDER_TEMPERATURE = re.compile("TargetExtr([0-9]+):(%s)" % REGEX_POSITIVE_FLOAT)
REGEX_TARGET_BED_TEMPERATURE = re.compile("TargetBed:(%s)" % REGEX_POSITIVE_FLOAT)
def __init__(self, transport_factory, protocol_listener=None):
RepRapProtocol.__init__(self, transport_factory, protocol_listener)
self._sd_available = True
def _reset(self, from_start=False):
RepRapProtocol._reset(self, from_start=from_start)
self._sd_available = True
def _process_temperatures(self, line):
if RepetierTextualProtocol.MESSAGE_TARGET_TEMPERATURE(line):
match_extr = RepetierTextualProtocol.REGEX_TARGET_EXTRUDER_TEMPERATURE.match(line)
match_bed = RepetierTextualProtocol.REGEX_TARGET_BED_TEMPERATURE.match(line)
current_temperatures = self.get_current_temperatures()
key = None
target = None
try:
if match_extr is not None:
tool_num = int(match_extr.group(1))
key = "tool%d" % tool_num
target = float(match_extr.group(2))
elif match_bed is not None:
key = "bed"
target = float(match_bed.group(1))
except ValueError:
pass
if key is None:
return False
if key in current_temperatures and current_temperatures[key] is not None and isinstance(current_temperatures[key], tuple):
(actual, old_target) = current_temperatures[key]
current_temperatures[key] = (actual, target)
else:
current_temperatures[key] = (None, target)
self._updateTemperature(current_temperatures)
else:
RepRapProtocol._process_temperatures(self, line)
@@ -0,0 +1,994 @@
# coding=utf-8
import Queue
from collections import deque
from octoprint.events import eventManager, Events
from octoprint.util import filterNonAscii
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
import re
import threading
import time
from octoprint.comm.protocol import State, Protocol, PrintingSdFileInformation
from octoprint.comm.protocol.reprap.util import GcodeCommand, CommandQueue, CommandQueueEntry, PrintingGcodeFileInformation, \
StreamingGcodeFileInformation, TypeAlreadyInQueue, SpecialCommandQueueEntry
from octoprint.comm.transport import SendTimeout
from octoprint.filemanager import valid_file_type
from octoprint.filemanager.destinations import FileDestinations
from octoprint.settings import settings
from octoprint.util import CountedEvent
import octoprint.plugin
class RepRapProtocol(Protocol):
__protocolinfo__ = ("reprap", "RepRap", False)
## Firmware messages
MESSAGE_OK = staticmethod(lambda line: line.startswith("ok"))
MESSAGE_START = staticmethod(lambda line: line.startswith("start"))
MESSAGE_WAIT = staticmethod(lambda line: line.startswith("wait"))
MESSAGE_RESEND = staticmethod(lambda line: line.lower().startswith("resend") or line.lower().startswith("rs"))
MESSAGE_TEMPERATURE = staticmethod(lambda line: " T:" in line or line.startswith("T:") or " T0:" in line or line.startswith("T0:"))
MESSAGE_SD_INIT_OK = staticmethod(lambda line: line.lower() == "sd card ok")
MESSAGE_SD_INIT_FAIL = staticmethod(lambda line: "sd init fail" in line.lower() or "volume.init failed" in line.lower() or "openroot failed" in line.lower())
MESSAGE_SD_FILE_OPENED = staticmethod(lambda line: line.lower().startswith("file opened"))
MESSAGE_SD_FILE_SELECTED = staticmethod(lambda line: line.lower().startswith("file selected"))
MESSAGE_SD_BEGIN_FILE_LIST = staticmethod(lambda line: line.lower().startswith("begin file list"))
MESSAGE_SD_END_FILE_LIST = staticmethod(lambda line: line.lower().startswith("end file list"))
MESSAGE_SD_PRINTING_BYTE = staticmethod(lambda line: "sd printing byte" in line.lower())
MESSAGE_SD_NOT_PRINTING = staticmethod(lambda line: "not sd printing" in line.lower())
MESSAGE_SD_DONE_PRINTING = staticmethod(lambda line: "done printing file" in line.lower())
MESSAGE_SD_BEGIN_WRITING = staticmethod(lambda line: "writing to file" in line.lower())
MESSAGE_SD_END_WRITING = staticmethod(lambda line: "done saving file" in line.lower())
MESSAGE_ERROR = staticmethod(lambda line: line.startswith("Error:") or line.startswith("!!"))
MESSAGE_ERROR_MULTILINE = staticmethod(lambda line: RepRapProtocol.REGEX_ERROR_MULTILINE.match(line))
MESSAGE_ERROR_COMMUNICATION = staticmethod(lambda line: 'checksum mismatch' in line.lower()
or 'wrong checksum' in line.lower()
or 'line number is not last line number' in line.lower()
or 'expected line' in line.lower()
or 'no line number with checksum' in line.lower()
or 'no checksum with line number' in line.lower()
or 'missing checksum' in line.lower())
MESSAGE_ERROR_COMMUNICATION_LINENUMBER = staticmethod(lambda line: 'line number is not line number' in line.lower()
or 'expected line' in line.lower())
TRANSFORM_ERROR = staticmethod(lambda line: line[6:] if line.startswith("Error:") else line[2:])
## Commands
COMMAND_GET_TEMP = staticmethod(lambda: GcodeCommand("M105"))
COMMAND_SET_EXTRUDER_TEMP = staticmethod(lambda s, t, w: GcodeCommand("M109", s=s, t=t) if w else GcodeCommand("M104", s=s, t=t))
COMMAND_SET_LINE = staticmethod(lambda n: GcodeCommand("M110 N%d" % n))
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_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_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_SD_REFRESH = staticmethod(lambda: GcodeCommand("M20"))
COMMAND_SD_INIT = staticmethod(lambda: GcodeCommand("M21"))
COMMAND_SD_RELEASE = staticmethod(lambda: GcodeCommand("M22"))
COMMAND_SD_SELECT_FILE = staticmethod(lambda name: GcodeCommand("M23", param=name))
COMMAND_SD_START = staticmethod(lambda: GcodeCommand("M24"))
COMMAND_SD_PAUSE = staticmethod(lambda: GcodeCommand("M25"))
COMMAND_SD_SET_POS = staticmethod(lambda pos: GcodeCommand("M26", s=pos))
COMMAND_SD_STATUS = staticmethod(lambda: GcodeCommand("M27"))
COMMAND_SD_BEGIN_WRITE = staticmethod(lambda name: GcodeCommand("M28", param=name))
COMMAND_SD_END_WRITE = staticmethod(lambda name: GcodeCommand("M29", param=name))
COMMAND_SD_DELETE = staticmethod(lambda name: GcodeCommand("M30", param=name))
## Command types
COMMAND_TYPE_TEMPERATURE = "temperature"
COMMAND_TYPE_SD_PROGRESS = "sd_progress"
# Regex matching temperature entries in line. Groups will be as follows:
# - 1: whole tool designator incl. optional toolNumber ("T", "Tn", "B")
# - 2: toolNumber, if given ("", "n", "")
# - 3: actual temperature
# - 4: whole target substring, if given (e.g. " / 22.0")
# - 5: target temperature
REGEX_TEMPERATURE = re.compile("(B|T(\d*)):\s*([-+]?\d*\.?\d+)(\s*\/?\s*([-+]?\d*\.?\d+))?")
# Regex matching "File opened" message. Groups will be as follows:
# - 1: name of the file that got opened (e.g. "file.gco")
# - 2: size of the file that got opened, in bytes, parseable to integer (e.g. "2392010")
REGEX_FILE_OPENED = re.compile("File opened:\s*(.*?)\s+Size:\s*([0-9]*)")
# Regex matching printing byte message. Groups will be as follows:
# - 1: current file position
# - 2: file size
REGEX_SD_PRINTING_BYTE = re.compile("([0-9]*)/([0-9]*)")
# Regex matching multi line errors
#
# Marlin reports MAXTEMP issues on extruders in the format
#
# Error:{int}
# Extruder switched off. {MIN|MAX}TEMP triggered !
#
# This regex matches the line initiating those multiline errors. If it is encountered, the next line has
# 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")
BLOCKING_COMMANDS = (
"M109", "M190", # set and wait for temperature (hotend & bed)
"G28", # home
"G29", "G30", "G31", "G32" # bed probing
)
def __init__(self, transport_factory, protocol_listener=None):
Protocol.__init__(self, transport_factory, protocol_listener)
self._lastTemperatureUpdate = time.time()
self._lastSdProgressUpdate = time.time()
self._startSeen = False
self._receivingSdFileList = False
self._send_queue = CommandQueue()
self._clear_for_send = CountedEvent(max=10)
self._force_checksum = True
self._wait_for_start = False
self._sd_always_available = False
self._rx_cache_size = 0
self._blocking_command_active = False
self._temperature_interval = 5.0
self._sdstatus_interval = 5.0
self._sent_lines = deque([])
self._send_lock = threading.RLock()
self._previous_resend = False
self._last_comm_error = None
self._last_resend_number = None
self._current_resend_count = 0
self._sent_before_resend = 0
self._send_queue_processing = True
self._thread = threading.Thread(target=self._handle_send_queue, name="SendQueueHandler")
self._thread.daemon = True
self._thread.start()
self._fill_queue_semaphore = threading.BoundedSemaphore(10)
self._fill_queue_state_signal = threading.Event()
self._fill_queue_mutex = threading.Lock()
self._fill_queue_processing = True
self._fill_thread = threading.Thread(target=self._fill_send_queue, name="FillQueueHandler")
self._fill_thread.daemon = True
self._fill_thread.start()
self._current_line = 1
self._current_extruder = 0
self._state = State.OFFLINE
self._pluginManager = octoprint.plugin.plugin_manager()
self._gcode_hooks = dict(
queued=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.queued").values(),
sending=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.sending").values(),
sent=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.sent").values(),
acknowledged=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.acknowledged").values()
)
self._preprocessors = dict()
self._setup_preprocessors()
self._reset()
def _setup_preprocessors(self):
self._preprocessors.clear()
for attr in dir(self):
if attr.startswith("_gcode") and (attr.endswith("_queued") or attr.endswith("_sending") or attr.endswith("_sent") or attr.endswith("_acknowledged")):
split_attr = attr.split("_")
if not len(split_attr) == 4:
continue
prefix, code, postfix = split_attr[1:]
if not postfix in self._preprocessors:
self._preprocessors[postfix] = dict()
self._preprocessors[postfix][code] = getattr(self, attr)
def _reset(self, from_start=False):
with self._send_lock:
self._lastTemperatureUpdate = time.time()
self._lastSdProgressUpdate = time.time()
self._blocking_command_active = False
if self._wait_for_start:
self._startSeen = from_start
else:
self._startSeen = True
if not self._startSeen:
self._clear_for_send.clear(completely=True)
else:
if self._clear_for_send.blocked():
self._clear_for_send.set()
self._receivingSdFileList = False
# clear the the send queue
self._send_queue.clear()
self._sent_lines.clear()
self._current_line = 1
self._current_extruder = 0
self._previous_resend = False
self._last_comm_error = None
self._last_resend_number = None
self._current_resend_count = 0
self._sent_before_resend = 0
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
self._sd_always_available = protocol_options["sdAlwaysAvailable"] if "sdAlwaysAvailable" in protocol_options else False
self._rx_cache_size = protocol_options["buffer"] if "buffer" in protocol_options else 0
self._temperature_interval = protocol_options["timeout"]["temperature"] if "timeout" in protocol_options and "temperature" in protocol_options["timeout"] else 5.0
self._sdstatus_interval = protocol_options["timeout"]["sdstatus"] if "timeout" in protocol_options and "sdstatus" in protocol_options["timeout"] else 5.0
self._reset()
# connect
Protocol.connect(self, protocol_options, transport_options)
# we'll send an M110 first to reset line numbers to 0
self._send(self.__class__.COMMAND_SET_LINE(0), high_priority=True)
# enqueue our first temperature query so it gets sent right on establishment of the connection
self._send_temperature_query(with_type=True)
def disconnect(self, on_error=False):
self._clear_for_send.clear(completely=True)
# disconnect
Protocol.disconnect(self, on_error=on_error)
def select_file(self, filename, origin):
if origin == FileDestinations.SDCARD:
if not self._sd_available:
return
self._send(self.__class__.COMMAND_SD_SELECT_FILE(filename), high_priority=True)
else:
self._selectFile(PrintingGcodeFileInformation(filename, self.get_temperature_offsets))
def start_print(self):
wasPaused = self._state == State.PAUSED
Protocol.start_print(self)
if isinstance(self._current_file, PrintingSdFileInformation):
if wasPaused:
self._send(self.__class__.COMMAND_SD_SET_POS(0))
self._current_file.setFilepos(0)
self._send(self.__class__.COMMAND_SD_START())
def cancel_print(self):
if isinstance(self._current_file, PrintingSdFileInformation):
self._send(self.__class__.COMMAND_SD_PAUSE)
self._send(self.__class__.COMMAND_SD_SET_POS(0))
Protocol.cancel_print(self)
def _print_cancelled(self):
with self._fill_queue_mutex:
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 init_sd(self):
Protocol.init_sd(self)
self._send(self.__class__.COMMAND_SD_INIT())
if self._sd_always_available:
self._changeSdState(True)
def release_sd(self):
Protocol.release_sd(self)
self._send(self.__class__.COMMAND_SD_RELEASE())
if self._sd_always_available:
self._changeSdState(False)
def refresh_sd_files(self):
if not self._sd_available:
return
Protocol.refresh_sd_files(self)
self._send(self.__class__.COMMAND_SD_REFRESH())
def add_sd_file(self, path, local, remote):
Protocol.add_sd_file(self, path, local, remote)
if not self.is_operational() or self.is_busy():
return
self.send_manually(self.__class__.COMMAND_SD_BEGIN_WRITE(remote))
self._current_file = StreamingGcodeFileInformation(path, local, remote)
self._current_file.start()
eventManager().fire(Events.TRANSFER_STARTED, {"local": local, "remote": remote})
self._startFileTransfer(remote, self._current_file.getFilesize())
self._changeState(State.STREAMING)
def remove_sd_file(self, filename):
Protocol.remove_sd_file(self, filename)
if not self.is_operational() or \
(self.is_busy() and isinstance(self._current_file, PrintingSdFileInformation) and
self._current_file.getFilename() == filename):
return
self.send_manually(self.__class__.COMMAND_SD_DELETE(filename))
self.refresh_sd_files()
def set_temperature(self, type, value):
if type.startswith("tool"):
if settings().getInt(["printerParameters", "numExtruders"]) > 1:
try:
tool_num = int(type[len("tool"):])
self.send_manually(self.__class__.COMMAND_SET_EXTRUDER_TEMP(value, tool_num, False))
except ValueError:
pass
else:
# set temperature without tool number
self.send_manually(self.__class__.COMMAND_SET_EXTRUDER_TEMP(value, None, False))
elif type == "bed":
self.send_manually(self.__class__.COMMAND_SET_BED_TEMP(value, False))
def jog(self, axis, amount, speed):
commands = (
self.__class__.COMMAND_SET_RELATIVE_POSITIONING(),
self.__class__.COMMAND_MOVE_AXIS(axis, amount, speed),
self.__class__.COMMAND_SET_ABSOLUTE_POSITIONING()
)
self.send_manually(commands)
def home(self, axes):
commands = (
self.__class__.COMMAND_SET_RELATIVE_POSITIONING(),
self.__class__.COMMAND_HOME_AXIS('x' in axes, 'y' in axes, 'z' in axes),
self.__class__.COMMAND_SET_ABSOLUTE_POSITIONING()
)
self.send_manually(commands)
def extrude(self, amount, speed):
commands = (
self.__class__.COMMAND_SET_RELATIVE_POSITIONING(),
self.__class__.COMMAND_EXTRUDE(amount, speed),
self.__class__.COMMAND_SET_ABSOLUTE_POSITIONING()
)
self.send_manually(commands)
def change_tool(self, tool):
try:
tool_num = int(tool[len("tool"):])
self.send_manually(self.__class__.COMMAND_SET_TOOL(tool_num))
except ValueError:
pass
def send_manually(self, command, high_priority=False):
if self.is_streaming():
return
if isinstance(command, (tuple, list)):
for c in command:
self._send(c, high_priority=high_priority)
else:
self._send(command, high_priority=high_priority)
def _fileTransferFinished(self, current_file):
if isinstance(current_file, StreamingGcodeFileInformation):
self.send_manually(self.__class__.COMMAND_SD_END_WRITE(current_file.getRemoteFilename()))
eventManager().fire(Events.TRANSFER_DONE, {
"local": current_file.getLocalFilename(),
"remote": current_file.getRemoteFilename(),
"time": self.get_print_time()
})
else:
self._logger.warn("Finished file transfer to printer's SD card, but could not determine remote filename, assuming 'unknown.gco' for end-write-command")
self.send_manually(self.__class__.COMMAND_SD_END_WRITE("unknown.gco"))
self.refresh_sd_files()
##~~ callback methods
def onMessageReceived(self, source, message):
if self._transport != source:
return
message = self._handle_errors(message.strip())
##~~ Control message processing: ok, resend, start, wait
if self.__class__.MESSAGE_OK(message):
if self._state == State.CONNECTED and self._startSeen:
# if we are currently connected, have seen start and just gotten an "ok" we are now operational
self._changeState(State.OPERATIONAL)
if self.is_heating_up():
self._heatupDone()
if not self._previous_resend:
# our most left line from the sent_lines just got acknowledged
self._process_acknowledgement()
else:
self._previous_resend = False
self._clear_for_send.set()
elif self.__class__.MESSAGE_START(message):
# initial handshake with the firmware
if self._state != State.CONNECTED:
# we received a "start" while running, this means the printer has unexpectedly reset
self._changeState(State.CONNECTED)
self._reset(from_start=True)
return
elif self.__class__.MESSAGE_RESEND(message):
self._previous_resend = True
self._handle_resend_request(message)
return
elif self.__class__.MESSAGE_WAIT(message):
#self._clear_for_send.set()
# TODO really?
return
# SD file list
if self._receivingSdFileList and not self.__class__.MESSAGE_SD_END_FILE_LIST(message):
fileinfo = message.strip().split(None, 2)
if len(fileinfo) > 1:
filename, size = fileinfo
filename = filename.lower()
try:
size = int(size)
except ValueError:
# whatever that was, it was not an integer, so we'll ignore it and set size to None
size = None
else:
filename = fileinfo[0].lower()
size = None
if valid_file_type(filename, "gcode"):
if filterNonAscii(filename):
self._logger.warn("Got a file from printer's SD that has a non-ascii filename (%s), that shouldn't happen according to the protocol" % filename)
else:
self._addSdFile(filename, size)
return
##~~ regular message processing
# temperature updates
if self.__class__.MESSAGE_TEMPERATURE(message):
self._process_temperatures(message)
if not self.__class__.MESSAGE_OK(message):
self._heatupDetected()
# sd state
elif self.__class__.MESSAGE_SD_INIT_OK(message):
self._changeSdState(True)
elif self.__class__.MESSAGE_SD_INIT_FAIL(message):
self._changeSdState(False)
# sd progress
elif self.__class__.MESSAGE_SD_PRINTING_BYTE(message):
match = self.__class__.REGEX_SD_PRINTING_BYTE.search(message)
if isinstance(self._current_file, PrintingSdFileInformation):
self._current_file.setFilepos(int(match.group(1)))
self._reportProgress()
elif self.__class__.MESSAGE_SD_DONE_PRINTING(message):
if isinstance(self._current_file, PrintingSdFileInformation):
self._current_file.setFilepos(0)
self._changeState(State.OPERATIONAL)
self._finishPrintjob()
# sd file list
elif self.__class__.MESSAGE_SD_BEGIN_FILE_LIST(message):
self._resetSdFiles()
self._receivingSdFileList = True
elif self.__class__.MESSAGE_SD_END_FILE_LIST(message):
self._receivingSdFileList = False
self._sendSdFiles()
# sd file selection
elif self.__class__.MESSAGE_SD_FILE_OPENED(message):
match = self.__class__.REGEX_FILE_OPENED.search(message)
self._selectFile(PrintingSdFileInformation(match.group(1), int(match.group(2))))
# sd file streaming
elif self.__class__.MESSAGE_SD_BEGIN_WRITING(message):
self._changeState(State.STREAMING)
elif self.__class__.MESSAGE_SD_END_WRITING(message):
self.refresh_sd_files()
# firmware specific messages
if not self._evaluate_firmware_specific_messages(source, message):
return
if not self.is_streaming():
if time.time() > self._lastTemperatureUpdate + self._temperature_interval:
self._send_temperature_query(with_type=True)
elif self.is_sd_printing() and time.time() > self._lastSdProgressUpdate + self._sdstatus_interval:
self._send_sd_progress_query(with_type=True)
def onTimeoutReceived(self, source):
if self._transport != source:
return
# allow sending to restart communication
if self._state != State.OFFLINE:
if self._clear_for_send.blocked():
self._clear_for_send.set()
def _stateChanged(self, newState):
if ((self._state == State.PRINTING and not isinstance(self._current_file, PrintingSdFileInformation))
or self._state == State.STREAMING):
self._fill_queue_state_signal.set()
else:
self._fill_queue_state_signal.clear()
##~~ private
def _process_acknowledgement(self):
with self._send_lock:
if len(self._sent_lines) > 0:
entry = self._sent_lines.popleft()
# process command as acknowledged
self._process_command(entry.command, "acknowledged", with_line_number=entry.line_number)
if entry.command is not None:
if entry.command.progress is not None:
# if we got a progress, report it
self._reportProgress(**entry.command.progress)
if entry.command.callback is not None:
# if we got a callback, call it
entry.command.callback(entry.command)
if len(self._sent_lines) > 0:
# let's take a look at the next item in the nack queue, it might be a special entry demanding some action
# from us now
following_entry = self._sent_lines[0]
if isinstance(following_entry, SpecialCommandQueueEntry):
if following_entry.type == SpecialCommandQueueEntry.TYPE_JOBDONE:
# we got a special queue item that marks that we just acknowledged the last command of
# an ongoing print job, so let's signal that now
if self.is_streaming():
self._finishFileTransfer()
else:
self._finishPrintjob()
# let's remove the special command, we should have processed it now...
self._sent_lines.popleft()
else:
self._logger.warn("Ooops, got an ok but had no unacknowledged command O.o")
# since we just got an acknowledgement, no more resends are pending
self._last_resend_number = None
self._current_resend_count = 0
self._sent_before_resend = 0
def _evaluate_firmware_specific_messages(self, source, message):
return True
def _send(self, command, high_priority=False, command_type=None, with_progress=None):
if command is None:
return
if isinstance(command, CommandQueueEntry):
entry = command
if entry.command is not None:
entry.command.progress = with_progress
else:
if not isinstance(command, GcodeCommand):
command = GcodeCommand.from_line(command)
command.progress = with_progress
command, with_line_number = self._process_command(command, "queued")
if command is None:
return
entry = CommandQueueEntry(
CommandQueueEntry.PRIORITY_HIGH if high_priority else CommandQueueEntry.PRIORITY_NORMAL,
command,
line_number=with_line_number,
command_type=command_type
)
try:
self._send_queue.put(entry)
except TypeAlreadyInQueue:
pass
# Called only from worker thread, not thread safe
def _send_next(self):
try:
command = self._current_file.getNext()
except ValueError:
# TODO _current_file might already be closed since the print ended asynchronously between our callee and here, causing a ValueError => find some nicer way to handle this
return None
if command is None:
command = SpecialCommandQueueEntry(SpecialCommandQueueEntry.TYPE_JOBDONE)
self._send(command, with_progress=dict(completion=self._getPrintCompletion(), filepos=self._getPrintFilepos()))
def _send_temperature_query(self, with_high_priority=False, with_type=False):
self._send(self.__class__.COMMAND_GET_TEMP(), high_priority=with_high_priority, command_type=self.__class__.COMMAND_TYPE_TEMPERATURE if with_type else None)
self._lastTemperatureUpdate = time.time()
def _send_sd_progress_query(self, with_high_priority=False, with_type=False):
self._send(self.__class__.COMMAND_SD_STATUS(), high_priority=with_high_priority, command_type=self.__class__.COMMAND_TYPE_SD_PROGRESS if with_type else None)
self._lastSdProgressUpdate = time.time()
def _handle_errors(self, line):
if self.__class__.MESSAGE_ERROR(line):
if self.__class__.MESSAGE_ERROR_MULTILINE(line):
error = self._transport.receive()
else:
error = self.__class__.TRANSFORM_ERROR(line)
# skip the communication errors as those get corrected via resend requests
if self.__class__.MESSAGE_ERROR_COMMUNICATION(error):
self._last_comm_error = error
pass
# handle the error
elif not self._state == State.ERROR:
self.onError(error)
return line
def _parse_temperatures(self, line):
result = {}
maxToolNum = 0
for match in re.finditer(self.__class__.REGEX_TEMPERATURE, line):
tool = match.group(1)
toolNumber = int(match.group(2)) if match.group(2) and len(match.group(2)) > 0 else None
if toolNumber > maxToolNum:
maxToolNum = toolNumber
try:
actual = float(match.group(3))
target = None
if match.group(4) and match.group(5):
target = float(match.group(5))
result[tool] = (toolNumber, actual, target)
except ValueError:
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
pass
if "T0" in result.keys() and "T" in result.keys():
del result["T"]
return maxToolNum, result
def _process_temperatures(self, line):
maxToolNum, parsedTemps = self._parse_temperatures(line)
import copy
result = copy.deepcopy(self._current_temperature)
# extruder temperatures
if not "T0" in parsedTemps.keys() and not "T1" in parsedTemps.keys() and "T" in parsedTemps.keys():
# no T1 so only single reporting, "T" is our one and only extruder temperature
toolNum, actual, target = parsedTemps["T"]
if target is not None:
result["tool0"] = (actual, target)
elif "tool0" in result and result["tool0"] is not None and isinstance(result["tool0"], tuple):
(oldActual, oldTarget) = result["tool0"]
result["tool0"] = (actual, oldTarget)
else:
result["tool0"] = (actual, None)
elif not "T0" in parsedTemps.keys() and "T" in parsedTemps.keys():
# Smoothieware sends multi extruder temperature data this way: "T:<first extruder> T1:<second extruder> ..." and therefore needs some special treatment...
# TODO: Move to Smoothieware sub class?
_, actual, target = parsedTemps["T"]
del parsedTemps["T"]
parsedTemps["T0"] = (0, actual, target)
if "T0" in parsedTemps.keys():
for n in range(maxToolNum + 1):
tool = "T%d" % n
if not tool in parsedTemps.keys():
continue
toolNum, actual, target = parsedTemps[tool]
key = "tool%d" % toolNum
if target is not None:
result[key] = (actual, target)
elif key in result and result[key] is not None and isinstance(result[key], tuple):
(oldActual, oldTarget) = result[key]
result[key] = (actual, oldTarget)
else:
result[key] = (actual, None)
# bed temperature
if "B" in parsedTemps.keys():
toolNum, actual, target = parsedTemps["B"]
if target is not None:
result["bed"] = (actual, target)
elif "bed" in result and result["bed"] is not None and isinstance(result["bed"], tuple):
(oldActual, oldTarget) = result["bed"]
result["bed"] = (actual, oldTarget)
else:
result["bed"] = (actual, None)
self._updateTemperature(result)
def _handle_resend_request(self, message):
line_to_resend = None
try:
line_to_resend = int(message.replace("N:", " ").replace("N", " ").replace(":", " ").split()[-1])
except:
if "rs" in message:
line_to_resend = int(message.split()[1])
last_comm_error = self._last_comm_error
self._last_comm_error = None
if line_to_resend is not None:
with self._send_lock:
if len(self._sent_lines) > 0:
nack_entry = self._sent_lines[0]
if last_comm_error is not None and \
self.__class__.MESSAGE_ERROR_COMMUNICATION_LINENUMBER(last_comm_error) \
and line_to_resend == self._last_resend_number \
and self._current_resend_count < self._sent_before_resend:
# this resend is a complaint about the wrong line_number, we already resent the requested
# one and didn't see more resend requests for those yet than we had additional lines in the sent
# buffer back then, so this is probably caused by leftovers in the printer's receive buffer
# (that got sent after the firmware cleared the receive buffer but before we'd fully processed
# the old resend request), we'll therefore just increment our counter and ignore this
self._current_resend_count += 1
return
else:
# this is either a resend request for a new line_number, or a resend request not caused by a
# line number mismatch, or we now saw more consecutive requests for that line number than there
# were additional lines in the nack buffer when we saw the first one, so we'll have to handle it
self._last_resend_number = line_to_resend
self._current_resend_count = 0
self._sent_before_resend = len(self._sent_lines) - 1
if nack_entry.line_number is not None and nack_entry.line_number == line_to_resend:
try:
while True:
entry = self._sent_lines.popleft()
entry.priority = CommandQueueEntry.PRIORITY_RESEND
try:
self._send_queue.put(entry)
except TypeAlreadyInQueue:
pass
except IndexError:
# that's ok, the nack lines are just empty
pass
return
elif line_to_resend < nack_entry.line_number:
# we'll ignore that resend request since that line was already acknowledged in the past
return
# if we've reached this point, we could not resend the requested line
error = "Printer requested line %d but no sufficient history is available, can't resend" % line_to_resend
self._logger.warn(error)
if self.is_printing():
# abort the print, there's nothing we can do to rescue it now
self.onError(error)
# reset line number local and remote
self._current_line = 1
self._sent_lines.clear()
self._send(self.__class__.COMMAND_SET_LINE(0))
##~~ handle queue filling in this thread when printing or streaming
def _fill_send_queue(self):
while self._fill_queue_processing:
with self._fill_queue_mutex:
self._fill_queue_state_signal.wait(0.1)
if not ((self._state == State.PRINTING and not isinstance(self._current_file, PrintingSdFileInformation))
or self._state == State.STREAMING):
continue
if self._fill_queue_semaphore.acquire(0.5):
self._send_next()
##~~ the actual send queue handling starts here
def _handle_send_queue(self):
while self._send_queue_processing:
if self._send_queue.qsize() == 0:
# queue is empty, wait a bit before checking again
if ((self._state == State.PRINTING and not isinstance(self._current_file, PrintingSdFileInformation))
or self._state == State.STREAMING):
self._logger.warn("Buffer under run while printing!")
time.sleep(0.1)
continue
if self._blocking_command_active:
# blocking command is active, no use to send anything to the printer right now
time.sleep(0.1)
continue
try:
with self._send_lock:
with self._send_queue.clearlock:
sent = self._send_from_queue()
except SendTimeout:
# we just got a send timeout, so we'll just try again on the next loop iteration
continue
if not sent or self._rx_cache_size <= 0:
# decrease the clear_for_send counter
self._clear_for_send.clear()
self._clear_for_send.wait()
def _send_from_queue(self):
item, entry = self._send_queue.peek()
if item is None:
if ((self._state == State.PRINTING and not isinstance(self._current_file, PrintingSdFileInformation))
or self._state == State.STREAMING):
self._logger.warn("Buffer under run while printing!")
return False
if not self._startSeen:
return False
if isinstance(item, SpecialCommandQueueEntry):
self._sent_lines.append(item)
else:
if item.prepared is None:
prepared, line_number = self._prepare_for_sending(item.command, with_line_number=item.line_number)
item.prepared = prepared
item.line_number = line_number
if item.prepared is not None:
# only actually send the command if it wasn't filtered out by preprocessing
current_size = sum(self._sent_lines)
new_size = current_size + item.size
if new_size > self._rx_cache_size > 0 and not (current_size == 0):
# Do not send if the left over space in the buffer is too small for this line. Exception: the buffer is empty
# and the line still doesn't fit
return False
# send the command - we might get a SendTimeout here which is supposed to bubble up since it's caught in the
# actual send loop
self._transport.send(item.prepared)
# add the queue item into the deque of commands not yet acknowledged
self._sent_lines.append(item)
self._process_command(item.command, "sent", with_line_number=item.line_number)
else:
self._logger.debug("Dropping command which was disabled through preprocessing: %s" % item.command)
# remove from send queue
try:
self._fill_queue_semaphore.release()
except ValueError:
# that's ok, the bounded semaphore complains that we just released more often than we acquired, but
# we do this explicitly an just use the bounded semaphore to guarantee an upper bound on the
# items added to the send queue by the fill thread
pass
self._send_queue.remove(entry)
return True
##~~ preprocessing of command in the three phases "queued", "sent" and "acknowledged"
def _process_command(self, command, phase, with_line_number=None):
if command is None:
return None, None, None
if not phase in ("queued", "sending", "sent", "acknowledged"):
return None
#handle our hooks, if any
for hook in self._gcode_hooks[phase]:
command, with_line_number = hook(self, command, with_line_number)
if phase in self._preprocessors and command is not None and command.command in self._preprocessors[phase]:
command, with_line_number = self._preprocessors[phase][command.command](command, with_line_number)
# blocking command?
if command is not None and command.command in self.__class__.BLOCKING_COMMANDS:
if phase == "sent":
self._logger.info("Waiting for a blocking command to finish: %s" % command.command)
self._blocking_command_active = True
elif phase == "acknowledged":
self._logger.info("Blocking command finished: %s" % command.command)
self._blocking_command_active = False
return command, with_line_number
def _prepare_for_sending(self, command, with_line_number=None):
command, with_line_number = self._process_command(command, "sending", with_line_number=with_line_number)
if command is None or command.unknown:
return None, None
if self._force_checksum:
if with_line_number is not None:
line_number = with_line_number
else:
line_number = self._current_line
command_to_send = "N%d %s" % (line_number, str(command))
checksum = reduce(lambda x, y: x ^ y, map(ord, command_to_send))
if with_line_number is None:
self._current_line += 1
return "%s*%d" % (command_to_send, checksum), line_number
else:
return str(command), None
##~~ specific command actions
def _gcode_T_acknowledged(self, command, with_line_number):
self._current_extruder = command.tool
return command, with_line_number
def _gcode_G0_acknowledged(self, command, with_line_number):
if command.z is not None:
z = command.z
self._reportZChange(z)
return command, with_line_number
_gcode_G1_acknowledged = _gcode_G0_acknowledged
def _gcode_M0_queued(self, command, with_line_number):
self.pause_print()
# Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
return None, with_line_number
_gcode_M1_queued = _gcode_M0_queued
def _gcode_M104_sent(self, command, with_line_number):
key = "tool%d" % command.t if command.t is not None else self._current_extruder
self._handle_temperature_code(command, key)
return command, with_line_number
_gcode_M109_sent = _gcode_M104_sent
def _gcode_M140_sent(self, command, with_line_number):
key = "bed"
self._handle_temperature_code(command, key)
return command, with_line_number
_gcode_M190_sent = _gcode_M140_sent
def _handle_temperature_code(self, command, key):
if command.s is not None:
target = command.s
if key in self._current_temperature and self._current_temperature[key] is not None and isinstance(self._current_temperature[key], tuple):
actual, old_target = self._current_temperature[key]
self._current_temperature[key] = (actual, target)
else:
self._current_temperature[key] = (None, target)
def _gcode_M110_sending(self, command, with_line_number):
if command.n is not None:
new_line_number = command.n
else:
new_line_number = 0
self._current_line = new_line_number + 1
# send M110 command with new line number
return command, new_line_number
def _gcode_M112_queued(self, command, with_line_number): # It's an emergency what todo? Canceling the print should be the minimum
self.cancel_print()
return command, with_line_number
+377
View File
@@ -0,0 +1,377 @@
# coding=utf-8
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
import Queue
import re
import heapq
import os
import time
import itertools
from octoprint.comm.protocol import PrintingFileInformation
class GcodeCommand(object):
KNOWN_FLOAT_ATTRIBUTES = ("x", "y", "z", "e", "s", "p", "r")
KNOWN_INT_ATTRIBUTES = ("f", "t", "n")
KNOWN_ATTRIBUTES = KNOWN_FLOAT_ATTRIBUTES + KNOWN_INT_ATTRIBUTES
COMMAND_REGEX = re.compile("^([GMT])(\d+)")
ARGUMENT_REGEX = re.compile("\s+([%s][-+]?\d*\.?\d+|[%s][-+]?\d+)" % ("".join(map(lambda x: x.upper(), KNOWN_FLOAT_ATTRIBUTES)), "".join(map(lambda x: x.upper(), KNOWN_INT_ATTRIBUTES))))
PARAM_REGEX = re.compile("^[GMT]\d+\s+(.*?)$")
@staticmethod
def from_line(line):
line = line.strip()
command = ""
args = {"original": line}
match = GcodeCommand.COMMAND_REGEX.match(line)
if match is None:
args["unknown"] = True
else:
commandType = match.group(1)
commandNumber = int(match.group(2))
command = "%s%d" % (commandType, commandNumber)
if commandType == "T":
args["tool"] = commandNumber
else:
matchedArgs = GcodeCommand.ARGUMENT_REGEX.findall(line)
if len(matchedArgs) == 0:
paramMatch = GcodeCommand.PARAM_REGEX.match(line)
if paramMatch is not None:
args["param"] = paramMatch.group(1)
else:
for arg in matchedArgs:
key = arg[0].lower()
if key in GcodeCommand.KNOWN_INT_ATTRIBUTES:
value = int(arg[1:])
elif key in GcodeCommand.KNOWN_FLOAT_ATTRIBUTES:
value = float(arg[1:])
else:
value = str(arg[1:])
args[key] = value
return GcodeCommand(command, **args)
def __init__(self, command, **kwargs):
self.command = command
self.x = None
self.y = None
self.z = None
self.e = None
self.s = None
self.p = None
self.r = None
self.f = None
self.t = None
self.n = None
self.tool = None
self.original = None
self.param = None
self.progress = None
self.callback = None
self.unknown = False
for key, value in kwargs.iteritems():
if key in GcodeCommand.KNOWN_ATTRIBUTES + ("tool", "original", "param", "progress", "callback", "unknown"):
self.__setattr__(key, value)
def isGetTemperatureCommand(self):
return self.command == "M105"
def isSetTemperatureCommand(self):
return self.command in ("M104", "M140", "M109", "M190")
def isSelectToolCommand(self):
return self.command.startswith("T")
def __repr__(self):
return "GcodeCommand(\"{str}\",progress={progress})".format(str=str(self), progress=self.progress)
def __str__(self):
if self.original is not None:
return self.original
else:
attr = []
for key in GcodeCommand.KNOWN_ATTRIBUTES:
value = self.__getattribute__(key)
if value is not None:
if key in GcodeCommand.KNOWN_INT_ATTRIBUTES:
attr.append("%s%d" % (key.upper(), value))
elif key in GcodeCommand.KNOWN_FLOAT_ATTRIBUTES:
attr.append("%s%f" % (key.upper(), value))
else:
attr.append("%s%r" % (key.upper(), value))
attributeStr = " ".join(attr)
return "%s%s%s" % (self.command.upper(), " " + attributeStr if attributeStr else "", " " + self.param if self.param else "")
class CommandQueueEntry(object):
PRIORITY_RESEND = 1
PRIORITY_HIGH = 2
PRIORITY_NORMAL = 3
def __init__(self, priority, command, line_number=None, command_type=None, prepared=None):
self.priority = priority
self.command = command
self.line_number = line_number
self.command_type = command_type
self._prepared = prepared
self._size = 0
@property
def prepared(self):
return self._prepared
@prepared.setter
def prepared(self, prepared):
self._prepared = prepared
self._size = (len(prepared) + 1) if prepared is not None else 0
@property
def size(self):
return self._size
def __radd__(self, other):
return other + self._size
def __repr__(self):
return "CommandQueueEntry({command},prepared={prepared})".format(command=repr(self.command), prepared=self.prepared)
class SpecialCommandQueueEntry(CommandQueueEntry):
TYPE_JOBDONE = "JobDone"
TYPE_JOBCANCELLED = "JobCancelled"
def __init__(self, type):
CommandQueueEntry.__init__(self, CommandQueueEntry.PRIORITY_NORMAL, None)
self.type = type
def __repr__(self):
return "SpecialCommandQueueEntry(type={type})".format(type=self.type)
class CommandQueue(Queue.Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first, followed by addition order).
Entries need to be of the form (priority, command). An optional third argument commandType may be given:
(priority, command, commandType), the queue will ensure that only one command of a given commandType will ever
be in the queue.
'''
def _init(self, maxsize):
self.queue = []
self.lookup = {}
self.counter = itertools.count()
import threading
self.clearlock = threading.RLock()
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item, heappush=heapq.heappush):
if not isinstance(item, CommandQueueEntry):
raise ValueError("queue can only take CommandQueueEntries, can't accept %r" % item)
command_type = item.command_type
if command_type is not None:
if command_type not in self.lookup:
self.lookup[command_type] = item
else:
raise TypeAlreadyInQueue()
heappush(self.queue, (item.priority, next(self.counter), item))
def _get(self, heappop=heapq.heappop):
priority, counter, item = heappop(self.queue)
if item.command_type in self.lookup:
del self.lookup[item.command_type]
return item
def _entry_at(self, index):
try:
return self.queue[index]
except IndexError:
return None
def _del(self, entry, heapify=True):
item = entry[2]
try:
self.queue.remove(entry)
if heapify:
heapq.heapify(self.queue)
except ValueError:
# that's ok, the entry probably just got removed already e.g. by print cancelling
pass
if item.command_type in self.lookup:
del self.lookup[item.command_type]
def peek(self):
"""
Returns the left most entry, result is either a tuple (priority, counter, CommandQueueEntry) or None (if queue
was empty).
"""
with self.mutex:
entry = self._entry_at(0)
return entry[2] if entry is not None else None, entry
def remove(self, entry):
with self.mutex:
self._del(entry)
def clear(self, matcher=None):
if matcher is None:
matcher = lambda x: True
cleared = []
with self.clearlock:
for entry in self.queue[:]:
priority, counter, item = entry
if matcher(item):
self._del(entry, heapify=False)
cleared.append(entry)
heapq.heapify(self.queue)
return cleared
def __repr__(self):
return repr(self.queue)
class TypeAlreadyInQueue(Exception):
pass
class PrintingGcodeFileInformation(PrintingFileInformation):
"""
Encapsulates information regarding an ongoing direct print. Takes care of the needed file handle and ensures
that the file is closed in case of an error.
"""
def __init__(self, filename, offsetCallback):
PrintingFileInformation.__init__(self, filename)
self._lineCount = None
self._firstLine = None
self._currentTool = 0
self._offsetCallback = offsetCallback
self._fileHandle = None
if not os.path.exists(self._filename) or not os.path.isfile(self._filename):
raise IOError("File %s does not exist" % self._filename)
self._filesize = os.stat(self._filename).st_size
def start(self):
"""
Opens the file for reading and determines the file size. Start time won't be recorded until 100 lines in
"""
self._filehandle = open(self._filename, "r")
self._lineCount = None
self._startTime = None
def getNext(self):
"""
Retrieves the next line for printing.
"""
if self._filehandle is None:
raise ValueError("File %s is not open for reading" % self._filename)
if self._lineCount is None:
self._lineCount = 0
self._startTime = time.time()
return GcodeCommand.from_line("M110 N0")
try:
command = None
while command is None:
if self._filehandle is None:
# file got closed just now
return None
line = self._filehandle.readline()
if not line:
self._filehandle.close()
self._filehandle = None
command = self._process_command(line)
self._lineCount += 1
self._filepos = self._filehandle.tell()
return command
except Exception as (e):
if self._filehandle is not None:
self._filehandle.close()
self._filehandle = None
raise e
def _process_command(self, line):
# remove all comments and trim the line
if ";" in line:
line = line[0:line.find(";")]
line = line.strip()
if len(line) > 0:
# we still got something left => parse the command
command = GcodeCommand.from_line(line)
if command is None:
return None
if command.isSelectToolCommand():
# track tool changes
self._currentTool = command.tool
elif command.isSetTemperatureCommand() and self._offsetCallback is not None:
# if we have a temperature command and an offset callback, retrieve current offsets
offsets = self._offsetCallback()
# extruder temperature, determine which one and retrieve corresponding offset
if command.command == "M104" or command.command == "M109":
tool_num = self._currentTool
if command.t is not None:
tool_num = command.t
key = "tool%d" % tool_num
# bed temperature
elif command.command == "M140" or command.command == "M190":
key = "bed"
# unknown, should never happen
else:
key = None
if key is not None and key in offsets:
offset = offsets[key]
command.s = command.s + offset
if command.original is not None:
command.original = None
# finally return the processed command
return command
else:
# no command, return None
return None
class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
def __init__(self, path, localFilename, remoteFilename):
PrintingGcodeFileInformation.__init__(self, path, None)
self._localFilename = localFilename
self._remoteFilename = remoteFilename
def start(self):
PrintingGcodeFileInformation.start(self)
self._startTime = time.time()
def getLocalFilename(self):
return self._localFilename
def getRemoteFilename(self):
return self._remoteFilename
+121
View File
@@ -0,0 +1,121 @@
# coding=utf-8
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
import logging
from octoprint.events import eventManager, Events
class TransportError(Exception):
pass
class SendTimeout(Exception):
pass
class Transport(object):
def __init__(self, messageReceiver=None, stateReceiver=None, logReceiver=None):
self._transport_logger = logging.getLogger("TRANSPORT")
self._messageReceiver = messageReceiver
self._stateReceiver = stateReceiver
self._logReceiver = logReceiver
self._state = State.DISCONNECTED
self._error = None
self._opt = {}
def get_properties(self):
raise NotImplemented()
def get_connection_options(self):
return []
def get_current_connection(self):
return self._opt
def connect(self, opt):
self._opt = opt
def disconnect(self, onError=False):
if onError:
self.changeState(State.DISCONNECTED_WITH_ERROR)
else:
self.changeState(State.DISCONNECTED)
eventManager().fire(Events.DISCONNECTED)
def send(self, command):
pass
def receive(self):
pass
def changeState(self, newState):
oldState = self._state
self._state = newState
if self._stateReceiver is not None:
self._stateReceiver.onStateChangeReceived(self, oldState, newState)
def onError(self, error):
self.changeState(State.ERROR)
self._error = error
def onTimeout(self):
if self._messageReceiver is not None:
self._messageReceiver.onTimeoutReceived(self)
def getError(self):
return self._error
def logTx(self, tx):
if self._logReceiver is not None:
self._logReceiver.onLogTx(self, tx)
def logRx(self, rx):
if self._logReceiver is not None:
self._logReceiver.onLogRx(self, rx)
def logError(self, error):
if self._logReceiver is not None:
self._logReceiver.onLogError(self, error)
def onMessageReceived(self, message):
if self._messageReceiver is not None:
self._messageReceiver.onMessageReceived(self, message)
class TransportProperties(object):
FLOWCONTROL = "flowControl"
class State(object):
OPENING_CONNECTION = "Opening connection"
DETECTING_CONNECTION = "Detecting connection"
CONNECTED = "Connected"
DISCONNECTED = "Disconnected"
DISCONNECTED_WITH_ERROR = "Disconnected with error"
ERROR = "Error"
class MessageReceiver(object):
def onMessageReceived(self, source, message):
pass
def onTimeoutReceived(self, source):
pass
class StateReceiver(object):
def onStateChangeReceived(self, source, oldState, newState):
pass
class LogReceiver(object):
def onLogTx(self, source, tx):
pass
def onLogRx(self, source, rx):
pass
def onLogError(self, source, error):
pass
@@ -0,0 +1,192 @@
# coding=utf-8
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
import os
import glob
import threading
import serial
try:
import _winreg
except:
pass
from . import Transport, TransportProperties, State, SendTimeout, TransportError
from octoprint.util import getExceptionString
from octoprint.util.virtual import VirtualPrinter
from octoprint.settings import settings
from octoprint.events import eventManager, Events
class SerialTransport(Transport):
__transportinfo__ = ("serial", "Serial", False)
def __init__(self, messageReceiver, stateReceiver, logReceiver):
Transport.__init__(self, messageReceiver, stateReceiver, logReceiver)
self._serial = None
self._port = None
self._baudrate = None
self._connectionTimeout = None
self._writeTimeout = None
self._readTimeout = None
self._timeoutCounter = 0
self._maxTimeouts = 20
self._thread = None
def get_properties(self):
return {
TransportProperties.FLOWCONTROL: False
}
def get_connection_options(self):
return {
"port": self.__getSerialList(),
"baudrate": self.__getBaudrateList()
}
def connect(self, opt):
Transport.connect(self, opt)
self._port = opt["port"] if "port" in opt else None
self._baudrate = opt["baudrate"] if "baudrate" in opt else None
self._readTimeout = opt["timeout"]["read"] if "timeout" in opt and "read" in opt["timeout"] else 5.0
self._writeTimeout = opt["timeout"]["write"] if "timeout" in opt and "write" in opt["timeout"] else 0.5
if self._connect():
self._thread = threading.Thread(target=self._monitor, name="SerialTransportMonitor")
self._thread.daemon = True
self._thread.start()
def disconnect(self, onError=False):
try:
if self._serial is not None:
self._serial.close()
finally:
self._serial = None
self._thread = None
Transport.disconnect(self, onError)
def send(self, command):
commandToSend = command + "\n"
try:
self._serial.write(commandToSend)
self._transport_logger.info("Send: %s" % command)
self.logTx(command)
except serial.SerialTimeoutException:
self._transport_logger.warn("Timeout while sending: %s" % command)
self.logError("Serial timeout while writing to serial port, try again later.")
raise SendTimeout()
except:
exceptionString = getExceptionString()
self.logError("Unexpected error while writing serial port: %s" % exceptionString)
self.onError(exceptionString)
self.disconnect(True)
raise TransportError()
def receive(self):
return self._readline()
def _monitor(self):
error = None
while True:
line = self._readline()
if line is None:
error = "Serial connection closed unexpectedly"
break
if line == "":
self._timeoutCounter += 1
self.onTimeout()
if self._maxTimeouts and self._timeoutCounter > self._maxTimeouts:
error = "Printer did not respond at all over %d retries, considering it dead" % self._maxTimeouts
break
else:
self._timeoutCounter = 0
self.onMessageReceived(line.strip())
if error is not None:
self._transport_logger.error(error)
self.logError(error)
self.onError(error)
# TODO further error handling
def _connect(self):
self.changeState(State.OPENING_CONNECTION)
if self._port == "VIRTUAL":
self._serial = VirtualPrinter(read_timeout=self._readTimeout, write_timeout=self._writeTimeout)
self.changeState(State.CONNECTED)
self._transport_logger.debug("Connected to %s" % self._serial)
else:
try:
self._serial = serial.Serial(self._port, self._baudrate, timeout=self._readTimeout, writeTimeout=self._writeTimeout)
self.changeState(State.CONNECTED)
self._transport_logger.debug("Connected to %s" % self._serial)
except:
self.logError("Unexpected error while connecting to serial port: %s %s" % (self._port, getExceptionString()))
self.onError("Failed to open serial port, permissions correct?")
return False
eventManager().fire(Events.CONNECTED, {"port": self._port, "baudrate": self._baudrate})
return True
def _readline(self):
if self._serial is None:
return None
try:
line = self._serial.readline()
except:
exceptionString = getExceptionString()
self.logError("Unexpected error while reading serial port: %s" % exceptionString)
self.onError(exceptionString)
self.disconnect()
return None
if line != "":
loggable_line = unicode(line, "ascii", "replace").encode("ascii", "replace").rstrip()
self._transport_logger.debug("Recv: %s" % loggable_line)
self.logRx(loggable_line)
return line
def __getSerialList(self):
baselist=[]
if os.name == "nt":
try:
key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM")
i=0
while(1):
baselist+=[_winreg.EnumValue(key,i)[1]]
i+=1
except:
pass
baselist = baselist \
+ glob.glob("/dev/ttyUSB*") \
+ glob.glob("/dev/ttyACM*") \
+ glob.glob("/dev/ttyAMA*") \
+ glob.glob("/dev/tty.usb*") \
+ glob.glob("/dev/cu.*") \
+ glob.glob("/dev/rfcomm*")
additionalPorts = settings().get(["serial", "additionalPorts"])
for additional in additionalPorts:
baselist += glob.glob(additional)
prev = settings().get(["serial", "port"])
if prev in baselist:
baselist.remove(prev)
baselist.insert(0, prev)
if settings().getBoolean(["devel", "virtualPrinter", "enabled"]):
baselist.append("VIRTUAL")
return baselist
def __getBaudrateList(self):
ret = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
prev = settings().getInt(["serial", "baudrate"])
if prev in ret:
ret.remove(prev)
ret.insert(0, prev)
return ret
+1 -1
View File
@@ -308,7 +308,7 @@ class CommandTrigger(GenericEventListener):
def _executeGcodeCommand(self, command):
commands = [command]
if isinstance(command, (list, tuple, set)):
self.logger.debug("Executing GCode commands: %r" % command)
self._logger.debug("Executing GCode commands: %r" % command)
commands = list(command)
else:
self._logger.debug("Executing GCode command: %s" % command)
+289 -262
View File
@@ -1,4 +1,7 @@
# coding=utf-8
from octoprint.comm.protocol.repetier import RepetierTextualProtocol
from octoprint.comm.transport import Transport
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
@@ -6,6 +9,7 @@ import time
import threading
import copy
import os
import re
import logging
import octoprint.util.comm as comm
@@ -16,6 +20,10 @@ from octoprint.events import eventManager, Events
from octoprint.filemanager.destinations import FileDestinations
from octoprint.comm.protocol import State as ProtocolState, Protocol
from octoprint.comm.protocol.reprap import RepRapProtocol
from octoprint.comm.transport.serialTransport import SerialTransport
from octoprint.plugin import plugin_manager, ProgressPlugin
def getConnectionOptions():
@@ -43,11 +51,6 @@ class Printer():
self._printerProfileManager = printerProfileManager
# state
# TODO do we really need to hold the temperature here?
self._temp = None
self._bedTemp = None
self._targetTemp = None
self._targetBedTemp = None
self._temps = deque([], 300)
self._tempBacklog = []
@@ -81,6 +84,8 @@ class Printer():
# comm
self._comm = None
self._protocol = self._createProtocol()
# callbacks
self._callbacks = []
@@ -118,6 +123,49 @@ class Printer():
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished)
eventManager().subscribe(Events.METADATA_STATISTICS_UPDATED, self.onMetadataStatisticsUpdated)
def _getTransportFactory(self):
transports = self._getSubclassAttributes(Transport, "__transportinfo__", validator=lambda x: not x[2])
transportType = settings().get(["communication", "transport"])
for t in transports:
id, name, abstract, factory = t
if transportType == id:
return factory
return SerialTransport
def _createProtocol(self):
transport = self._getTransportFactory()
protocol_type = settings().get(["communication", "protocol"])
protocols = self._getSubclassAttributes(Protocol, "__protocolinfo__", validator=lambda x: not x[2])
protocol_factory = RepRapProtocol
for p in protocols:
id, name, abstract, factory = p
if protocol_type == id:
protocol_factory = factory
break
return protocol_factory(transport, protocol_listener=self)
def _getSubclassAttributes(self, origin, attribute, converter=lambda o, v: v, validator=lambda x: True):
result = []
if hasattr(origin, attribute):
value = getattr(origin, attribute)
if validator(value):
converted = list(converter(origin, value))
converted.append(origin)
result.append(converted)
subclasses = origin.__subclasses__()
if subclasses:
for s in subclasses:
result.extend(self._getSubclassAttributes(s, attribute, converter, validator))
return result
#~~ callback handling
def registerCallback(self, callback):
@@ -158,6 +206,129 @@ class Printer():
try: callback.sendFeedbackCommandOutput(name, output)
except: self._logger.exception("Exception while pushing feedback command output")
#~~ callbacks from protocol
def onStateChange(self, source, oldState, newState):
if not source == self._protocol:
return
# forward relevant state changes to gcode manager
if oldState == ProtocolState.PRINTING:
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
if self._selectedFile is not None and newState == ProtocolState.OFFLINE or newState == ProtocolState.ERROR:
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._protocol.get_print_time(), False)
elif newState == ProtocolState.PRINTING:
self._analysisQueue.pause() # do not analyse files while printing
self._setState(newState)
def onTemperatureUpdate(self, source, temperatureData):
if not source == self._protocol:
return
self._addTemperatureData(temperatureData)
def onProgress(self, source, progress):
if not source == self._protocol:
return
self._setProgressData(progress["completion"], progress["filepos"], progress["printTime"])
def onZChange(self, source, oldZ, newZ):
if not source == self._protocol:
return
if newZ != oldZ:
# we have to react to all z-changes, even those that might "go backward" due to a slicer's retraction or
# anti-backlash-routines. Event subscribes should individually take care to filter out "wrong" z-changes
eventManager().fire(Events.Z_CHANGE, {"new": newZ, "old": oldZ})
self._setCurrentZ(newZ)
def onFileSelected(self, source, filename, filesize, origin):
if not source == self._protocol:
return
self._setJobData(filename, filesize, origin)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
if self._printAfterSelect:
self.startPrint()
pass
def onPrintjobDone(self, source):
if not source == self._protocol:
return
self._setProgressData(100.0, self._selectedFile["filesize"], self._protocol.get_print_time())
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
if self._selectedFile is not None:
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._protocol.get_print_time(), True, self._printerProfileManager.get_current_or_default()["id"])
def onPrintjobCancelled(self, source):
if not source == self._protocol:
return
if self._selectedFile is not None:
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._protocol.get_print_time(), False, self._printerProfileManager.get_current_or_default()["id"])
def onFileTransferStarted(self, source, filename, filesize):
if not source == self._protocol:
return
self._sdStreaming = True
self._setJobData(filename, filesize, FileDestinations.SDCARD)
self._setProgressData(0.0, 0, 0)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def onFileTransferDone(self, source):
if not source == self._protocol:
return
self._sdStreaming = False
if self._streamingFinishedCallback is not None:
self._streamingFinishedCallback(self._sdRemoteName, FileDestinations.SDCARD)
self._sdRemoteName = None
self._setCurrentZ(None)
self._setJobData(None, None, None)
self._setProgressData(None, None, None)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def onSdStateChange(self, source, sdAvailable):
if not source == self._protocol:
return
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def onSdFiles(self, source, files):
if not source == self._protocol:
return
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
self._sdFilelistAvailable.set()
def onLogTx(self, source, tx):
if not source == self._protocol:
return
self._addLog("Send: %s" % tx)
def onLogRx(self, source, rx):
if not source == self._protocol:
return
self._addLog("Recv: %s" % rx)
def onLogError(self, source, error):
if not source == self._protocol:
return
self._addLog("ERROR: %s" % error)
#~~ callback from metadata analysis event
def onMetadataAnalysisFinished(self, event, data):
@@ -193,117 +364,99 @@ class Printer():
#~~ printer commands
def connect(self, port=None, baudrate=None, profile=None):
def connect(self, protocol_option_overrides=None, transport_option_overrides=None, profile=None):
"""
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
will be attempted.
"""
if self._comm is not None:
self._comm.close()
self._comm = comm.MachineCom(port, baudrate, callbackObject=self)
self._protocol.disconnect()
protocol_options = settings().get(["communication", "protocolOptions"], merged=True)
if protocol_option_overrides is not None and isinstance(protocol_option_overrides, dict):
protocol_options = util.dict_merge(protocol_options, protocol_option_overrides)
transport_options = settings().get(["communication", "transportOptions"], merged=True)
if transport_option_overrides is not None and isinstance(transport_option_overrides, dict):
transport_options = util.dict_merge(transport_options, transport_option_overrides)
self._protocol.connect(protocol_options, transport_options)
self._printerProfileManager.select(profile)
def disconnect(self):
"""
Closes the connection to the printer.
"""
if self._comm is not None:
self._comm.close()
self._comm = None
self._protocol.disconnect()
self._printerProfileManager.deselect()
eventManager().fire(Events.DISCONNECTED)
def getConnectionOptions(self):
connection_options = self._protocol.get_connection_options()
return {
"ports": connection_options["port"],
"baudrates": connection_options["baudrate"],
"portPreference": settings().get(["serial", "port"]),
"baudratePreference": settings().getInt(["serial", "baudrate"]),
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
}
def command(self, command):
"""
Sends a single gcode command to the printer.
"""
self.commands([command])
self._protocol.send_manually(command)
def commands(self, commands):
"""
Sends multiple gcode commands (provided as a list) to the printer.
"""
if self._comm is None:
return
for command in commands:
self._comm.sendCommand(command)
self.command(commands)
def jog(self, axis, amount):
if not axis or not amount:
return
printer_profile = self._printerProfileManager.get_current_or_default()
movement_speed = printer_profile["axes"][axis]["speed"]
self.commands(["G91", "G1 %s%.4f F%d" % (axis.upper(), amount, movement_speed), "G90"])
axis = axis.lower()
if axis in printer_profile["axes"]:
speed = printer_profile["axes"][axis]["speed"]
self._protocol.jog(axis, amount, speed)
def home(self, axes):
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), axes)), "G90"])
self._protocol.home(axes)
def extrude(self, amount):
if not amount:
return
printer_profile = self._printerProfileManager.get_current_or_default()
extrusion_speed = printer_profile["axes"]["e"]["speed"]
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"])
if "e" in printer_profile["axes"]:
speed = printer_profile["axes"]["e"]["speed"]
self._protocol.extrude(amount, speed)
def changeTool(self, tool):
try:
toolNum = int(tool[len("tool"):])
self.command("T%d" % toolNum)
except ValueError:
pass
self._protocol.change_tool(tool)
def setTemperature(self, type, value):
if type.startswith("tool"):
printer_profile = self._printerProfileManager.get_current_or_default()
extruder_count = printer_profile["extruder"]["count"]
if extruder_count > 1:
try:
toolNum = int(type[len("tool"):])
self.command("M104 T%d S%f" % (toolNum, value))
except ValueError:
pass
else:
self.command("M104 S%f" % value)
elif type == "bed":
self.command("M140 S%f" % value)
self._protocol.set_temperature(type, value)
def setTemperatureOffset(self, offsets={}):
if self._comm is None:
return
def setTemperatureOffset(self, offsets):
current_offsets = self._protocol.get_temperature_offsets()
tool, bed = self._comm.getOffsets()
validatedOffsets = {}
new_offsets = {}
new_offsets.update(current_offsets)
for key in offsets:
value = offsets[key]
if key == "bed":
bed = value
validatedOffsets[key] = value
elif key.startswith("tool"):
try:
toolNum = int(key[len("tool"):])
tool[toolNum] = value
validatedOffsets[key] = value
except ValueError:
pass
if key == "bed" or re.match("tool\d+", key):
new_offsets[key] = offsets[key]
self._comm.setTemperatureOffset(tool, bed)
self._stateMonitor.setTempOffsets(validatedOffsets)
def selectFile(self, filename, sd, printAfterSelect=False):
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
self._logger.info("Cannot load file: printer not connected or currently busy")
return
self._protocol.set_temperature_offsets(new_offsets)
self._stateMonitor.setTempOffsets(new_offsets)
def selectFile(self, filename, origin, printAfterSelect=False):
self._printAfterSelect = printAfterSelect
self._comm.selectFile(filename, sd)
self._setProgressData(0, None, None, None)
self._protocol.select_file(filename, origin)
self._setProgressData(0, None, None)
self._setCurrentZ(None)
def unselectFile(self):
if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()):
return
self._comm.unselectFile()
self._setProgressData(0, None, None, None)
self._protocol.deselect_file()
self._setProgressData(0, None, None)
self._setCurrentZ(None)
def startPrint(self):
@@ -311,7 +464,7 @@ class Printer():
Starts the currently loaded print job.
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
"""
if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting():
if not self._protocol.is_operational() or self._protocol.is_busy():
return
if self._selectedFile is None:
return
@@ -319,25 +472,19 @@ class Printer():
self._timeEstimationData = TimeEstimationHelper()
self._lastProgressReport = None
self._setCurrentZ(None)
self._comm.startPrint()
self._protocol.start_print()
def togglePausePrint(self):
"""
Pause the current printjob.
"""
if self._comm is None:
return
self._comm.setPause(not self._comm.isPaused())
self._protocol.pause_print()
def cancelPrint(self, disableMotorsAndHeater=True):
"""
Cancel the current printjob.
"""
if self._comm is None:
return
self._comm.cancelPrint()
self._protocol.cancel_print()
if disableMotorsAndHeater:
printer_profile = self._printerProfileManager.get_current_or_default()
@@ -351,11 +498,11 @@ class Printer():
# reset progress, height, print time
self._setCurrentZ(None)
self._setProgressData(None, None, None, None)
self._setProgressData(None, None, None)
# mark print as failure
if self._selectedFile is not None:
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._protocol.get_print_time(), False, self._printerProfileManager.get_current_or_default()["id"])
payload = {
"file": self._selectedFile["filename"],
"origin": FileDestinations.LOCAL
@@ -388,7 +535,7 @@ class Printer():
return None
else:
newEstimate = printTime / progress
newEstimate = printTime * 100 / progress
self._timeEstimationData.update(newEstimate)
result = None
@@ -403,68 +550,61 @@ class Printer():
return result
def _setProgressData(self, progress, filepos, printTime, cleanedPrintTime):
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
def _setProgressData(self, progress, filepos, printTime):
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, printTime)
statisticalTotalPrintTime = None
totalPrintTime = estimatedTotalPrintTime
if self._selectedFile and "estimatedPrintTime" in self._selectedFile and self._selectedFile["estimatedPrintTime"]:
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
if progress and cleanedPrintTime:
if progress and printTime:
if estimatedTotalPrintTime is None:
totalPrintTime = statisticalTotalPrintTime
else:
if progress < 0.5:
sub_progress = progress * 2
if progress < 50:
sub_progress = progress * 2 / 100
else:
sub_progress = 1.0
totalPrintTime = (1 - sub_progress) * statisticalTotalPrintTime + sub_progress * estimatedTotalPrintTime
#self._printTimeLogger.info("{progress};{cleanedPrintTime};{estimatedTotalPrintTime};{statisticalTotalPrintTime};{totalPrintTime}".format(**locals()))
#self._printTimeLogger.info("{progress};{printTime};{estimatedTotalPrintTime};{statisticalTotalPrintTime};{totalPrintTime}".format(**locals()))
self._progress = progress
self._printTime = printTime
self._printTimeLeft = totalPrintTime - cleanedPrintTime if (totalPrintTime is not None and cleanedPrintTime is not None) else None
self._printTimeLeft = totalPrintTime - printTime if (totalPrintTime is not None and printTime is not None) else None
self._stateMonitor.setProgress({
"completion": self._progress * 100 if self._progress is not None else None,
"completion": self._progress,
"filepos": filepos,
"printTime": int(self._printTime) if self._printTime is not None else None,
"printTimeLeft": int(self._printTimeLeft) if self._printTimeLeft is not None else None
})
if progress:
progress_int = int(progress * 100)
progress_int = int(progress)
if self._lastProgressReport != progress_int:
self._lastProgressReport = progress_int
self._reportPrintProgressToPlugins(progress_int)
def _addTemperatureData(self, temp, bedTemp):
def _addTemperatureData(self, temperatureData):
currentTimeUtc = int(time.time())
data = {
"time": currentTimeUtc
}
for tool in temp.keys():
data["tool%d" % tool] = {
"actual": temp[tool][0],
"target": temp[tool][1]
}
if bedTemp is not None and isinstance(bedTemp, tuple):
data["bed"] = {
"actual": bedTemp[0],
"target": bedTemp[1]
for tool in temperatureData.keys():
data[tool] = {
"actual": temperatureData[tool][0],
"target": temperatureData[tool][1]
}
self._temps.append(data)
self._temp = temp
self._bedTemp = bedTemp
self._stateMonitor.addTemperature(data)
def _setJobData(self, filename, filesize, sd):
def _setJobData(self, filename, filesize, origin):
sd = origin == FileDestinations.SDCARD
if filename is not None:
self._selectedFile = {
"filename": filename,
@@ -525,7 +665,7 @@ class Printer():
self._stateMonitor.setJobData({
"file": {
"name": os.path.basename(filename) if filename is not None else None,
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
"origin": origin,
"size": filesize,
"date": date
},
@@ -562,149 +702,54 @@ class Printer():
#~~ callbacks triggered from self._comm
def mcLog(self, message):
"""
Callback method for the comm object, called upon log output.
"""
self._addLog(message)
def mcTempUpdate(self, temp, bedTemp):
self._addTemperatureData(temp, bedTemp)
def mcStateChange(self, state):
"""
Callback method for the comm object, called if the connection state changes.
"""
oldState = self._state
# forward relevant state changes to gcode manager
if self._comm is not None and oldState == self._comm.STATE_PRINTING:
if self._selectedFile is not None:
if state == self._comm.STATE_OPERATIONAL:
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), True, self._printerProfileManager.get_current_or_default()["id"])
elif state == self._comm.STATE_CLOSED or state == self._comm.STATE_ERROR or state == self._comm.STATE_CLOSED_WITH_ERROR:
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
elif self._comm is not None and state == self._comm.STATE_PRINTING:
self._analysisQueue.pause() # do not analyse files while printing
self._setState(state)
def mcMessage(self, message):
"""
Callback method for the comm object, called upon message exchanges via serial.
Stores the message in the message buffer, truncates buffer to the last 300 lines.
"""
self._addMessage(message)
def mcProgress(self):
"""
Callback method for the comm object, called upon any change in progress of the printjob.
Triggers storage of new values for printTime, printTimeLeft and the current progress.
"""
self._setProgressData(self._comm.getPrintProgress(), self._comm.getPrintFilepos(), self._comm.getPrintTime(), self._comm.getCleanedPrintTime())
def mcZChange(self, newZ):
"""
Callback method for the comm object, called upon change of the z-layer.
"""
oldZ = self._currentZ
if newZ != oldZ:
# we have to react to all z-changes, even those that might "go backward" due to a slicer's retraction or
# anti-backlash-routines. Event subscribes should individually take care to filter out "wrong" z-changes
eventManager().fire(Events.Z_CHANGE, {"new": newZ, "old": oldZ})
self._setCurrentZ(newZ)
def mcSdStateChange(self, sdReady):
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def mcSdFiles(self, files):
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
self._sdFilelistAvailable.set()
def mcFileSelected(self, filename, filesize, sd):
self._setJobData(filename, filesize, sd)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
if self._printAfterSelect:
self.startPrint()
def mcPrintjobDone(self):
self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.getPrintTime(), 0)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def mcFileTransferStarted(self, filename, filesize):
self._sdStreaming = True
self._setJobData(filename, filesize, True)
self._setProgressData(0.0, 0, 0, None)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def mcFileTransferDone(self, filename):
self._sdStreaming = False
if self._streamingFinishedCallback is not None:
# in case of SD files, both filename and absolutePath are the same, so we set the (remote) filename for
# both parameters
self._streamingFinishedCallback(filename, filename, FileDestinations.SDCARD)
self._setCurrentZ(None)
self._setJobData(None, None, None)
self._setProgressData(None, None, None, None)
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
def mcReceivedRegisteredMessage(self, command, output):
self._sendFeedbackCommandOutput(command, output)
#~~ sd file handling
def getSdFiles(self):
if self._comm is None or not self._comm.isSdReady():
if not self._protocol.is_sd_ready():
return []
return self._comm.getSdFiles()
return self._protocol.get_sd_files()
def addSdFile(self, filename, absolutePath, streamingFinishedCallback):
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
self._logger.error("No connection to printer or printer is busy")
if self._protocol.is_busy() or not self._protocol.is_sd_ready():
logging.error("No connection to printer or printer is busy")
return
self._streamingFinishedCallback = streamingFinishedCallback
self.refreshSdFiles(blocking=True)
existingSdFiles = map(lambda x: x[0], self._comm.getSdFiles())
existingSdFiles = map(lambda x: x[0], self._protocol.get_sd_files())
remoteName = util.getDosFilename(filename, existingSdFiles)
self._comm.startFileTransfer(absolutePath, filename, remoteName)
self._sdRemoteName = util.getDosFilename(filename, existingSdFiles)
self._protocol.add_sd_file(absolutePath, filename, self._sdRemoteName)
return remoteName
return self._sdRemoteName
def deleteSdFile(self, filename):
if not self._comm or not self._comm.isSdReady():
if not self._protocol.is_sd_ready():
return
self._comm.deleteSdFile(filename)
self._protocol.remove_sd_file(filename)
def initSdCard(self):
if not self._comm or self._comm.isSdReady():
return
self._comm.initSdCard()
self._protocol.init_sd()
def releaseSdCard(self):
if not self._comm or not self._comm.isSdReady():
if not self._protocol.is_sd_ready() or self._protocol.is_busy():
return
self._comm.releaseSdCard()
self._protocol.release_sd()
def refreshSdFiles(self, blocking=False):
"""
Refreshs the list of file stored on the SD card attached to printer (if available and printer communication
available). Optional blocking parameter allows making the method block (max 10s) until the file list has been
received (and can be accessed via self._comm.getSdFiles()). Defaults to a asynchronous operation.
received (and can be accessed via self._protocol.get_sd_files()). Defaults to a asynchronous operation.
"""
if not self._comm or not self._comm.isSdReady():
if not self._protocol.is_sd_ready():
return
self._sdFilelistAvailable.clear()
self._comm.refreshSdFiles()
self._protocol.refresh_sd_files()
if blocking:
self._sdFilelistAvailable.wait(10000)
@@ -714,10 +759,7 @@ class Printer():
"""
Returns a human readable string corresponding to the current communication state.
"""
if self._comm is None:
return "Offline"
else:
return self._comm.getStateString()
return self._state
def getCurrentData(self):
return self._stateMonitor.getCurrentData()
@@ -727,26 +769,13 @@ class Printer():
return currentData["job"]
def getCurrentTemperatures(self):
if self._comm is not None:
tempOffset, bedTempOffset = self._comm.getOffsets()
else:
tempOffset = {}
bedTempOffset = None
temperatures = self._protocol.get_current_temperatures()
offsets = self._protocol.get_temperature_offsets()
result = {}
if self._temp is not None:
for tool in self._temp.keys():
result["tool%d" % tool] = {
"actual": self._temp[tool][0],
"target": self._temp[tool][1],
"offset": tempOffset[tool] if tool in tempOffset.keys() and tempOffset[tool] is not None else 0
}
if self._bedTemp is not None:
result["bed"] = {
"actual": self._bedTemp[0],
"target": self._bedTemp[1],
"offset": bedTempOffset
}
result.update(temperatures)
for key, tool in result:
tool["offset"] = offsets[key] if key in offsets and offsets[key] is not None else 0
return result
@@ -754,36 +783,34 @@ class Printer():
return self._temps
def getCurrentConnection(self):
if self._comm is None:
return "Closed", None, None, None
port, baudrate = self._comm.getConnection()
printer_profile = self._printerProfileManager.get_current_or_default()
return self._comm.getStateString(), port, baudrate, printer_profile
opt = self._protocol.get_current_connection()
if "port" in opt.keys() and "baudrate" in opt.keys():
return self._protocol.get_state(), opt["port"], opt["baudrate"], self._printerProfileManager.get_current_or_default()
return self._protocol.get_state(), None, None, None
def isClosedOrError(self):
return self._comm is None or self._comm.isClosedOrError()
return self._protocol.get_state() == ProtocolState.OFFLINE or self._protocol == ProtocolState.ERROR
def isOperational(self):
return self._comm is not None and self._comm.isOperational()
return not self.isClosedOrError()
def isPrinting(self):
return self._comm is not None and self._comm.isPrinting()
return self._protocol.get_state() == ProtocolState.PRINTING
def isPaused(self):
return self._comm is not None and self._comm.isPaused()
return self._protocol.get_state() == ProtocolState.PAUSED
def isError(self):
return self._comm is not None and self._comm.isError()
return self._protocol.get_state() == ProtocolState.ERROR
def isReady(self):
return self.isOperational() and not self._comm.isStreaming()
return self.isOperational() and not self._protocol.is_streaming()
def isSdReady(self):
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
if not settings().getBoolean(["feature", "sdSupport"]):
return False
else:
return self._comm.isSdReady()
return self._protocol.is_sd_ready()
class StateMonitor(object):
def __init__(self, ratelimit, updateCallback, addTemperatureCallback, addLogCallback, addMessageCallback):
+4 -4
View File
@@ -348,7 +348,7 @@ class Server():
printer_profile = printerProfileManager.get_default()
connectionOptions = getConnectionOptions()
if port in connectionOptions["ports"]:
printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")
printer.connect(transport_option_overrides=dict(port=port, baudrate=baudrate), profile=printer_profile["id"] if "id" in printer_profile else "_default")
# start up watchdogs
observer = Observer()
@@ -438,7 +438,7 @@ class Server():
}
},
"loggers": {
"SERIAL": {
"TRANSPORT": {
"level": "CRITICAL",
"handlers": ["serialFile"],
"propagate": False
@@ -470,8 +470,8 @@ class Server():
if settings().getBoolean(["serial", "log"]):
# enable debug logging to serial.log
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
logging.getLogger("SERIAL").debug("Enabling serial logging")
logging.getLogger("TRANSPORT").setLevel(logging.DEBUG)
logging.getLogger("TRANSPORT").debug("Enabling transport logging")
if __name__ == "__main__":
server = Server()
+1 -1
View File
@@ -65,7 +65,7 @@ def connectionCommand():
if "autoconnect" in data.keys():
settings().setBoolean(["serial", "autoconnect"], data["autoconnect"])
settings().save()
printer.connect(port=port, baudrate=baudrate, profile=printerProfile)
printer.connect(transport_option_overrides=dict(port=port, baudrate=baudrate), profile=printerProfile)
elif command == "disconnect":
printer.disconnect()
+1 -3
View File
@@ -288,13 +288,11 @@ def gcodeFileCommand(filename, target):
return make_response("Printer is not operational, cannot directly start printing", 409)
printAfterLoading = True
sd = False
if target == FileDestinations.SDCARD:
filenameToSelect = filename
sd = True
else:
filenameToSelect = fileManager.get_absolute_path(target, filename)
printer.selectFile(filenameToSelect, sd, printAfterLoading)
printer.selectFile(filenameToSelect, target, printAfterLoading)
elif command == "slice":
if "slicer" in data.keys():
+4 -4
View File
@@ -164,12 +164,12 @@ def setSettings():
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
if oldLog and not s.getBoolean(["serial", "log"]):
# disable debug logging to serial.log
logging.getLogger("SERIAL").debug("Disabling serial logging")
logging.getLogger("SERIAL").setLevel(logging.CRITICAL)
logging.getLogger("TRANSPORT").debug("Disabling transport logging")
logging.getLogger("TRANSPORT").setLevel(logging.CRITICAL)
elif not oldLog and s.getBoolean(["serial", "log"]):
# enable debug logging to serial.log
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
logging.getLogger("SERIAL").debug("Enabling serial logging")
logging.getLogger("TRANSPORT").setLevel(logging.DEBUG)
logging.getLogger("TRANSPORT").debug("Enabling transport logging")
if "folder" in data.keys():
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
+30 -6
View File
@@ -23,6 +23,30 @@ def settings(init=False, configfile=None, basedir=None):
return instance
default_settings = {
"communication": {
"protocol": "reprap",
"protocolOptions": {
"buffer": 63,
"temperature": 5,
"sdStatus": 1,
"waitForStart": False,
"forceChecksum": True,
"sdAlwaysAvailable": False
},
"transport": "serial",
"transportOptions": {
"port": None,
"baudrate": None,
"timeout": {
"read": 5,
"write": 0.5
},
"additionalPorts": []
},
"autoconnect": False,
"log": False
},
# TODO Remove, not used by the new communication layer but apparently still by the layers above it!
"serial": {
"port": None,
"baudrate": None,
@@ -79,12 +103,12 @@ default_settings = {
},
"feature": {
"temperatureGraph": True,
"waitForStartOnConnect": False,
"alwaysSendChecksum": False,
"sdSupport": True,
"sdAlwaysAvailable": False,
"swallowOkAfterResend": True,
"repetierTargetTemp": False
"waitForStartOnConnect": False, # TODO move to protocol options or reprap protocol
"alwaysSendChecksum": True, # TODO move to protocol options
"sdSupport": True, # TODO remove (can be always on)
"sdAlwaysAvailable": False, # TODO move to protocol options
"swallowOkAfterResend": True, # TODO remove (must always be done!)
"repetierTargetTemp": False # TODO remove (built into repetier protocol implementation)
},
"folder": {
"uploads": None,
@@ -60,6 +60,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel, printerProfilesV
self.feature_temperatureGraph = ko.observable(undefined);
self.feature_waitForStart = ko.observable(undefined);
self.feature_alwaysSendChecksum = ko.observable(undefined);
self.feature_pingPong = ko.observable(undefined);
self.feature_sdSupport = ko.observable(undefined);
self.feature_sdAlwaysAvailable = ko.observable(undefined);
self.feature_swallowOkAfterResend = ko.observable(undefined);
+1 -1
View File
@@ -367,7 +367,7 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_alwaysSendChecksum" id="settings-featureAlwaysSendChecksum"> {{ _('Send a checksum with <strong>every</strong> command') }} <span class="label">{{ _('Repetier') }}</span>
<input type="checkbox" data-bind="checked: feature_alwaysSendChecksum" id="settings-featureAlwaysSendChecksum"> {{ _('Send a checksum with <strong>every</strong> command (reconnect after changing)') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
+40
View File
@@ -8,6 +8,7 @@ import sys
import time
import re
import tempfile
import threading
import logging
from flask import make_response
@@ -298,3 +299,42 @@ def address_for_client(host, port):
pass
class CountedEvent(object):
def __init__(self, value=0, max=None):
self._counter = 0
self._max = max
self._mutex = threading.Lock()
self._event = threading.Event()
self._internal_set(value)
def set(self):
with self._mutex:
self._internal_set(self._counter + 1)
def clear(self, completely=False):
with self._mutex:
if completely:
self._internal_set(0)
else:
self._internal_set(self._counter - 1)
def wait(self, timeout=None):
self._event.wait(timeout)
def blocked(self):
with self._mutex:
return self._counter == 0
def _internal_set(self, value):
self._counter = value
if self._counter <= 0:
self._counter = 0
self._event.clear()
else:
if self._max is not None and self._counter > self._max:
self._counter = self._max
self._event.set()
-4
View File
@@ -1,7 +1,3 @@
import os, struct, sys, time
from serial import Serial
import chipDB
class IspBase():
+1 -1
View File
@@ -1,7 +1,7 @@
import os, struct, sys, time
from serial import Serial
from serial import SerialException
from serial import SerialException, SerialTimeoutException
import ispBase, intelHex
-15
View File
@@ -510,21 +510,6 @@ class MachineCom(object):
def getSdFiles(self):
return self._sdFiles
def startSdFileTransfer(self, filename):
if not self.isOperational() or self.isBusy():
return
self._changeState(self.STATE_TRANSFERING_FILE)
self.sendCommand("M28 %s" % filename.lower())
def endSdFileTransfer(self, filename):
if not self.isOperational() or self.isBusy():
return
self.sendCommand("M29 %s" % filename.lower())
self._changeState(self.STATE_OPERATIONAL)
self.refreshSdFiles()
def deleteSdFile(self, filename):
if not self.isOperational() or (self.isBusy() and
isinstance(self._currentFile, PrintingSdFileInformation) and
+1 -1
View File
@@ -26,7 +26,7 @@ class VirtualPrinter():
for item in ['start\n', 'Marlin: Virtual Marlin!\n', '\x80\n', 'SD card ok\n']: # no sd card as default startup scenario
self.outgoing.put(item)
self.currentExtruder = 0
self.temp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
self.targetTemp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])