Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf69c4500d | ||
|
|
c7c6a08748 | ||
|
|
68e4fca347 | ||
|
|
05ac02770b | ||
|
|
25dc81a5d2 | ||
|
|
9e27744a05 | ||
|
|
77df620237 | ||
|
|
a0a6f958d9 | ||
|
|
16d156b530 | ||
|
|
420226b6c0 | ||
|
|
da8e72b0d6 | ||
|
|
ef13cbecfd | ||
|
|
5910bba30e | ||
|
|
19ba3b1f99 | ||
|
|
23bc6b8df7 | ||
|
|
69bea0f5b0 | ||
|
|
3c53394f4b | ||
|
|
8741053dfc | ||
|
|
8752f70ff3 | ||
|
|
2b66df39b6 | ||
|
|
17bb0e693d | ||
|
|
94e5b5fdaf | ||
|
|
497ec5c6b2 | ||
|
|
eaeae8d5ec | ||
|
|
3a05a2653b | ||
|
|
0ca63017c7 | ||
|
|
ea3416693c | ||
|
|
6dc56af3fa | ||
|
|
af297c2031 | ||
|
|
024cf81238 | ||
|
|
9d5a500b25 | ||
|
|
4bab1975c8 | ||
|
|
eae4153158 | ||
|
|
a92aa96623 | ||
|
|
ccf0ab3b51 | ||
|
|
7259c1c2ef | ||
|
|
d66675c672 | ||
|
|
38483b0c67 | ||
|
|
19de4053fe | ||
|
|
d0ff6d1579 | ||
|
|
105b68c807 | ||
|
|
97a6d8a15e | ||
|
|
26fa3df4aa | ||
|
|
9a336336d7 | ||
|
|
047d7f5046 | ||
|
|
4fc561dab5 | ||
|
|
785ac07de9 | ||
|
|
41c6978880 | ||
|
|
f7ebc4ec11 | ||
|
|
c06e8f47f0 | ||
|
|
dceb5dccd3 | ||
|
|
7a50138ae3 | ||
|
|
43cead8249 | ||
|
|
8492944fb5 | ||
|
|
f7433de2bf | ||
|
|
bbd46fd3a6 | ||
|
|
077486c838 | ||
|
|
baedab5931 | ||
|
|
36c8f25fd1 | ||
|
|
b3050f1058 | ||
|
|
a04a61f61b | ||
|
|
58204248bb | ||
|
|
a47740ae28 | ||
|
|
48d6a27fad | ||
|
|
5ffcd78f27 | ||
|
|
de9dd77b50 | ||
|
|
51c77be7a2 | ||
|
|
f98563cbe9 | ||
|
|
8c8059db30 | ||
|
|
fa586426fa | ||
|
|
60a1bf0d43 | ||
|
|
a48f194350 | ||
|
|
78f0ec94ea | ||
|
|
44f9e756da | ||
|
|
3d992d56cd | ||
|
|
72f7b4627f | ||
|
|
5c1f165079 | ||
|
|
95755ba515 | ||
|
|
791e4e26a9 | ||
|
|
4d61963894 | ||
|
|
5622a9c565 | ||
|
|
2e5069d5a1 | ||
|
|
4cd692e061 | ||
|
|
216a88c00c | ||
|
|
10f1917589 | ||
|
|
26f7d6e517 | ||
|
|
b7b2e99ab1 | ||
|
|
0966b231e8 | ||
|
|
00e1a1962b |
No files matched your search
@@ -19,6 +19,7 @@ PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
|
|||||||
DESC="Octoprint Daemon"
|
DESC="Octoprint Daemon"
|
||||||
NAME="Octoprint"
|
NAME="Octoprint"
|
||||||
DAEMON=/usr/local/bin/octoprint
|
DAEMON=/usr/local/bin/octoprint
|
||||||
|
NICE=-10
|
||||||
PIDFILE=/var/run/$NAME.pid
|
PIDFILE=/var/run/$NAME.pid
|
||||||
PKGNAME=octoprint
|
PKGNAME=octoprint
|
||||||
SCRIPTNAME=/etc/init.d/$PKGNAME
|
SCRIPTNAME=/etc/init.d/$PKGNAME
|
||||||
@@ -72,7 +73,7 @@ do_start()
|
|||||||
RETVAL="$?"
|
RETVAL="$?"
|
||||||
|
|
||||||
if [ $RETVAL != 0 ]; then
|
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
|
--exec $DAEMON --chuid $OCTOPRINT_USER --user $OCTOPRINT_USER --umask $UMASK -- $DAEMON_ARGS
|
||||||
RETVAL="$?"
|
RETVAL="$?"
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -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"
|
||||||
|
|
||||||
|
|
||||||
@@ -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
|
||||||
@@ -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)
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||||
|
|
||||||
@@ -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
|
||||||
@@ -308,7 +308,7 @@ class CommandTrigger(GenericEventListener):
|
|||||||
def _executeGcodeCommand(self, command):
|
def _executeGcodeCommand(self, command):
|
||||||
commands = [command]
|
commands = [command]
|
||||||
if isinstance(command, (list, tuple, set)):
|
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)
|
commands = list(command)
|
||||||
else:
|
else:
|
||||||
self._logger.debug("Executing GCode command: %s" % command)
|
self._logger.debug("Executing GCode command: %s" % command)
|
||||||
|
|||||||
+289
-262
@@ -1,4 +1,7 @@
|
|||||||
# coding=utf-8
|
# coding=utf-8
|
||||||
|
from octoprint.comm.protocol.repetier import RepetierTextualProtocol
|
||||||
|
from octoprint.comm.transport import Transport
|
||||||
|
|
||||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||||
|
|
||||||
@@ -6,6 +9,7 @@ import time
|
|||||||
import threading
|
import threading
|
||||||
import copy
|
import copy
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
import octoprint.util.comm as comm
|
import octoprint.util.comm as comm
|
||||||
@@ -16,6 +20,10 @@ from octoprint.events import eventManager, Events
|
|||||||
|
|
||||||
from octoprint.filemanager.destinations import FileDestinations
|
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
|
from octoprint.plugin import plugin_manager, ProgressPlugin
|
||||||
|
|
||||||
def getConnectionOptions():
|
def getConnectionOptions():
|
||||||
@@ -43,11 +51,6 @@ class Printer():
|
|||||||
self._printerProfileManager = printerProfileManager
|
self._printerProfileManager = printerProfileManager
|
||||||
|
|
||||||
# state
|
# 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._temps = deque([], 300)
|
||||||
self._tempBacklog = []
|
self._tempBacklog = []
|
||||||
|
|
||||||
@@ -81,6 +84,8 @@ class Printer():
|
|||||||
# comm
|
# comm
|
||||||
self._comm = None
|
self._comm = None
|
||||||
|
|
||||||
|
self._protocol = self._createProtocol()
|
||||||
|
|
||||||
# callbacks
|
# callbacks
|
||||||
self._callbacks = []
|
self._callbacks = []
|
||||||
|
|
||||||
@@ -118,6 +123,49 @@ class Printer():
|
|||||||
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished)
|
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished)
|
||||||
eventManager().subscribe(Events.METADATA_STATISTICS_UPDATED, self.onMetadataStatisticsUpdated)
|
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
|
#~~ callback handling
|
||||||
|
|
||||||
def registerCallback(self, callback):
|
def registerCallback(self, callback):
|
||||||
@@ -158,6 +206,129 @@ class Printer():
|
|||||||
try: callback.sendFeedbackCommandOutput(name, output)
|
try: callback.sendFeedbackCommandOutput(name, output)
|
||||||
except: self._logger.exception("Exception while pushing feedback command 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
|
#~~ callback from metadata analysis event
|
||||||
|
|
||||||
def onMetadataAnalysisFinished(self, event, data):
|
def onMetadataAnalysisFinished(self, event, data):
|
||||||
@@ -193,117 +364,99 @@ class Printer():
|
|||||||
|
|
||||||
#~~ printer commands
|
#~~ 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
|
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
|
||||||
will be attempted.
|
will be attempted.
|
||||||
"""
|
"""
|
||||||
if self._comm is not None:
|
self._protocol.disconnect()
|
||||||
self._comm.close()
|
|
||||||
self._comm = comm.MachineCom(port, baudrate, callbackObject=self)
|
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)
|
self._printerProfileManager.select(profile)
|
||||||
|
|
||||||
def disconnect(self):
|
def disconnect(self):
|
||||||
"""
|
"""
|
||||||
Closes the connection to the printer.
|
Closes the connection to the printer.
|
||||||
"""
|
"""
|
||||||
if self._comm is not None:
|
self._protocol.disconnect()
|
||||||
self._comm.close()
|
|
||||||
self._comm = None
|
|
||||||
self._printerProfileManager.deselect()
|
self._printerProfileManager.deselect()
|
||||||
eventManager().fire(Events.DISCONNECTED)
|
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):
|
def command(self, command):
|
||||||
"""
|
self._protocol.send_manually(command)
|
||||||
Sends a single gcode command to the printer.
|
|
||||||
"""
|
|
||||||
self.commands([command])
|
|
||||||
|
|
||||||
def commands(self, commands):
|
def commands(self, commands):
|
||||||
"""
|
self.command(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)
|
|
||||||
|
|
||||||
def jog(self, axis, amount):
|
def jog(self, axis, amount):
|
||||||
|
if not axis or not amount:
|
||||||
|
return
|
||||||
|
|
||||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||||
movement_speed = printer_profile["axes"][axis]["speed"]
|
axis = axis.lower()
|
||||||
self.commands(["G91", "G1 %s%.4f F%d" % (axis.upper(), amount, movement_speed), "G90"])
|
if axis in printer_profile["axes"]:
|
||||||
|
speed = printer_profile["axes"][axis]["speed"]
|
||||||
|
self._protocol.jog(axis, amount, speed)
|
||||||
|
|
||||||
def home(self, axes):
|
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):
|
def extrude(self, amount):
|
||||||
|
if not amount:
|
||||||
|
return
|
||||||
|
|
||||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||||
extrusion_speed = printer_profile["axes"]["e"]["speed"]
|
if "e" in printer_profile["axes"]:
|
||||||
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"])
|
speed = printer_profile["axes"]["e"]["speed"]
|
||||||
|
self._protocol.extrude(amount, speed)
|
||||||
|
|
||||||
def changeTool(self, tool):
|
def changeTool(self, tool):
|
||||||
try:
|
self._protocol.change_tool(tool)
|
||||||
toolNum = int(tool[len("tool"):])
|
|
||||||
self.command("T%d" % toolNum)
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def setTemperature(self, type, value):
|
def setTemperature(self, type, value):
|
||||||
if type.startswith("tool"):
|
self._protocol.set_temperature(type, value)
|
||||||
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)
|
|
||||||
|
|
||||||
def setTemperatureOffset(self, offsets={}):
|
def setTemperatureOffset(self, offsets):
|
||||||
if self._comm is None:
|
current_offsets = self._protocol.get_temperature_offsets()
|
||||||
return
|
|
||||||
|
|
||||||
tool, bed = self._comm.getOffsets()
|
new_offsets = {}
|
||||||
|
new_offsets.update(current_offsets)
|
||||||
validatedOffsets = {}
|
|
||||||
|
|
||||||
for key in offsets:
|
for key in offsets:
|
||||||
value = offsets[key]
|
if key == "bed" or re.match("tool\d+", key):
|
||||||
if key == "bed":
|
new_offsets[key] = offsets[key]
|
||||||
bed = value
|
|
||||||
validatedOffsets[key] = value
|
|
||||||
elif key.startswith("tool"):
|
|
||||||
try:
|
|
||||||
toolNum = int(key[len("tool"):])
|
|
||||||
tool[toolNum] = value
|
|
||||||
validatedOffsets[key] = value
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
self._comm.setTemperatureOffset(tool, bed)
|
self._protocol.set_temperature_offsets(new_offsets)
|
||||||
self._stateMonitor.setTempOffsets(validatedOffsets)
|
self._stateMonitor.setTempOffsets(new_offsets)
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
|
def selectFile(self, filename, origin, printAfterSelect=False):
|
||||||
self._printAfterSelect = printAfterSelect
|
self._printAfterSelect = printAfterSelect
|
||||||
self._comm.selectFile(filename, sd)
|
self._protocol.select_file(filename, origin)
|
||||||
self._setProgressData(0, None, None, None)
|
self._setProgressData(0, None, None)
|
||||||
self._setCurrentZ(None)
|
self._setCurrentZ(None)
|
||||||
|
|
||||||
def unselectFile(self):
|
def unselectFile(self):
|
||||||
if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()):
|
self._protocol.deselect_file()
|
||||||
return
|
self._setProgressData(0, None, None)
|
||||||
|
|
||||||
self._comm.unselectFile()
|
|
||||||
self._setProgressData(0, None, None, None)
|
|
||||||
self._setCurrentZ(None)
|
self._setCurrentZ(None)
|
||||||
|
|
||||||
def startPrint(self):
|
def startPrint(self):
|
||||||
@@ -311,7 +464,7 @@ class Printer():
|
|||||||
Starts the currently loaded print job.
|
Starts the currently loaded print job.
|
||||||
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
|
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
|
return
|
||||||
if self._selectedFile is None:
|
if self._selectedFile is None:
|
||||||
return
|
return
|
||||||
@@ -319,25 +472,19 @@ class Printer():
|
|||||||
self._timeEstimationData = TimeEstimationHelper()
|
self._timeEstimationData = TimeEstimationHelper()
|
||||||
self._lastProgressReport = None
|
self._lastProgressReport = None
|
||||||
self._setCurrentZ(None)
|
self._setCurrentZ(None)
|
||||||
self._comm.startPrint()
|
self._protocol.start_print()
|
||||||
|
|
||||||
def togglePausePrint(self):
|
def togglePausePrint(self):
|
||||||
"""
|
"""
|
||||||
Pause the current printjob.
|
Pause the current printjob.
|
||||||
"""
|
"""
|
||||||
if self._comm is None:
|
self._protocol.pause_print()
|
||||||
return
|
|
||||||
|
|
||||||
self._comm.setPause(not self._comm.isPaused())
|
|
||||||
|
|
||||||
def cancelPrint(self, disableMotorsAndHeater=True):
|
def cancelPrint(self, disableMotorsAndHeater=True):
|
||||||
"""
|
"""
|
||||||
Cancel the current printjob.
|
Cancel the current printjob.
|
||||||
"""
|
"""
|
||||||
if self._comm is None:
|
self._protocol.cancel_print()
|
||||||
return
|
|
||||||
|
|
||||||
self._comm.cancelPrint()
|
|
||||||
|
|
||||||
if disableMotorsAndHeater:
|
if disableMotorsAndHeater:
|
||||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||||
@@ -351,11 +498,11 @@ class Printer():
|
|||||||
|
|
||||||
# reset progress, height, print time
|
# reset progress, height, print time
|
||||||
self._setCurrentZ(None)
|
self._setCurrentZ(None)
|
||||||
self._setProgressData(None, None, None, None)
|
self._setProgressData(None, None, None)
|
||||||
|
|
||||||
# mark print as failure
|
# mark print as failure
|
||||||
if self._selectedFile is not None:
|
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 = {
|
payload = {
|
||||||
"file": self._selectedFile["filename"],
|
"file": self._selectedFile["filename"],
|
||||||
"origin": FileDestinations.LOCAL
|
"origin": FileDestinations.LOCAL
|
||||||
@@ -388,7 +535,7 @@ class Printer():
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
else:
|
else:
|
||||||
newEstimate = printTime / progress
|
newEstimate = printTime * 100 / progress
|
||||||
self._timeEstimationData.update(newEstimate)
|
self._timeEstimationData.update(newEstimate)
|
||||||
|
|
||||||
result = None
|
result = None
|
||||||
@@ -403,68 +550,61 @@ class Printer():
|
|||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def _setProgressData(self, progress, filepos, printTime, cleanedPrintTime):
|
def _setProgressData(self, progress, filepos, printTime):
|
||||||
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
|
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, printTime)
|
||||||
statisticalTotalPrintTime = None
|
statisticalTotalPrintTime = None
|
||||||
totalPrintTime = estimatedTotalPrintTime
|
totalPrintTime = estimatedTotalPrintTime
|
||||||
|
|
||||||
if self._selectedFile and "estimatedPrintTime" in self._selectedFile and self._selectedFile["estimatedPrintTime"]:
|
if self._selectedFile and "estimatedPrintTime" in self._selectedFile and self._selectedFile["estimatedPrintTime"]:
|
||||||
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
|
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
|
||||||
if progress and cleanedPrintTime:
|
if progress and printTime:
|
||||||
if estimatedTotalPrintTime is None:
|
if estimatedTotalPrintTime is None:
|
||||||
totalPrintTime = statisticalTotalPrintTime
|
totalPrintTime = statisticalTotalPrintTime
|
||||||
else:
|
else:
|
||||||
if progress < 0.5:
|
if progress < 50:
|
||||||
sub_progress = progress * 2
|
sub_progress = progress * 2 / 100
|
||||||
else:
|
else:
|
||||||
sub_progress = 1.0
|
sub_progress = 1.0
|
||||||
totalPrintTime = (1 - sub_progress) * statisticalTotalPrintTime + sub_progress * estimatedTotalPrintTime
|
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._progress = progress
|
||||||
self._printTime = printTime
|
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({
|
self._stateMonitor.setProgress({
|
||||||
"completion": self._progress * 100 if self._progress is not None else None,
|
"completion": self._progress,
|
||||||
"filepos": filepos,
|
"filepos": filepos,
|
||||||
"printTime": int(self._printTime) if self._printTime is not None else None,
|
"printTime": int(self._printTime) if self._printTime is not None else None,
|
||||||
"printTimeLeft": int(self._printTimeLeft) if self._printTimeLeft is not None else None
|
"printTimeLeft": int(self._printTimeLeft) if self._printTimeLeft is not None else None
|
||||||
})
|
})
|
||||||
|
|
||||||
if progress:
|
if progress:
|
||||||
progress_int = int(progress * 100)
|
progress_int = int(progress)
|
||||||
if self._lastProgressReport != progress_int:
|
if self._lastProgressReport != progress_int:
|
||||||
self._lastProgressReport = progress_int
|
self._lastProgressReport = progress_int
|
||||||
self._reportPrintProgressToPlugins(progress_int)
|
self._reportPrintProgressToPlugins(progress_int)
|
||||||
|
|
||||||
|
|
||||||
def _addTemperatureData(self, temp, bedTemp):
|
def _addTemperatureData(self, temperatureData):
|
||||||
currentTimeUtc = int(time.time())
|
currentTimeUtc = int(time.time())
|
||||||
|
|
||||||
data = {
|
data = {
|
||||||
"time": currentTimeUtc
|
"time": currentTimeUtc
|
||||||
}
|
}
|
||||||
for tool in temp.keys():
|
for tool in temperatureData.keys():
|
||||||
data["tool%d" % tool] = {
|
data[tool] = {
|
||||||
"actual": temp[tool][0],
|
"actual": temperatureData[tool][0],
|
||||||
"target": temp[tool][1]
|
"target": temperatureData[tool][1]
|
||||||
}
|
|
||||||
if bedTemp is not None and isinstance(bedTemp, tuple):
|
|
||||||
data["bed"] = {
|
|
||||||
"actual": bedTemp[0],
|
|
||||||
"target": bedTemp[1]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self._temps.append(data)
|
self._temps.append(data)
|
||||||
|
|
||||||
self._temp = temp
|
|
||||||
self._bedTemp = bedTemp
|
|
||||||
|
|
||||||
self._stateMonitor.addTemperature(data)
|
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:
|
if filename is not None:
|
||||||
self._selectedFile = {
|
self._selectedFile = {
|
||||||
"filename": filename,
|
"filename": filename,
|
||||||
@@ -525,7 +665,7 @@ class Printer():
|
|||||||
self._stateMonitor.setJobData({
|
self._stateMonitor.setJobData({
|
||||||
"file": {
|
"file": {
|
||||||
"name": os.path.basename(filename) if filename is not None else None,
|
"name": os.path.basename(filename) if filename is not None else None,
|
||||||
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
|
"origin": origin,
|
||||||
"size": filesize,
|
"size": filesize,
|
||||||
"date": date
|
"date": date
|
||||||
},
|
},
|
||||||
@@ -562,99 +702,6 @@ class Printer():
|
|||||||
|
|
||||||
#~~ callbacks triggered from self._comm
|
#~~ 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):
|
def mcReceivedRegisteredMessage(self, command, output):
|
||||||
self._sendFeedbackCommandOutput(command, output)
|
self._sendFeedbackCommandOutput(command, output)
|
||||||
|
|
||||||
@@ -664,50 +711,48 @@ class Printer():
|
|||||||
#~~ sd file handling
|
#~~ sd file handling
|
||||||
|
|
||||||
def getSdFiles(self):
|
def getSdFiles(self):
|
||||||
if self._comm is None or not self._comm.isSdReady():
|
if not self._protocol.is_sd_ready():
|
||||||
return []
|
return []
|
||||||
return self._comm.getSdFiles()
|
return self._protocol.get_sd_files()
|
||||||
|
|
||||||
def addSdFile(self, filename, absolutePath, streamingFinishedCallback):
|
def addSdFile(self, filename, absolutePath, streamingFinishedCallback):
|
||||||
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
|
if self._protocol.is_busy() or not self._protocol.is_sd_ready():
|
||||||
self._logger.error("No connection to printer or printer is busy")
|
logging.error("No connection to printer or printer is busy")
|
||||||
return
|
return
|
||||||
|
|
||||||
self._streamingFinishedCallback = streamingFinishedCallback
|
self._streamingFinishedCallback = streamingFinishedCallback
|
||||||
|
|
||||||
self.refreshSdFiles(blocking=True)
|
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._sdRemoteName = util.getDosFilename(filename, existingSdFiles)
|
||||||
self._comm.startFileTransfer(absolutePath, filename, remoteName)
|
self._protocol.add_sd_file(absolutePath, filename, self._sdRemoteName)
|
||||||
|
|
||||||
return remoteName
|
return self._sdRemoteName
|
||||||
|
|
||||||
def deleteSdFile(self, filename):
|
def deleteSdFile(self, filename):
|
||||||
if not self._comm or not self._comm.isSdReady():
|
if not self._protocol.is_sd_ready():
|
||||||
return
|
return
|
||||||
self._comm.deleteSdFile(filename)
|
self._protocol.remove_sd_file(filename)
|
||||||
|
|
||||||
def initSdCard(self):
|
def initSdCard(self):
|
||||||
if not self._comm or self._comm.isSdReady():
|
self._protocol.init_sd()
|
||||||
return
|
|
||||||
self._comm.initSdCard()
|
|
||||||
|
|
||||||
def releaseSdCard(self):
|
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
|
return
|
||||||
self._comm.releaseSdCard()
|
self._protocol.release_sd()
|
||||||
|
|
||||||
def refreshSdFiles(self, blocking=False):
|
def refreshSdFiles(self, blocking=False):
|
||||||
"""
|
"""
|
||||||
Refreshs the list of file stored on the SD card attached to printer (if available and printer communication
|
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
|
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
|
return
|
||||||
self._sdFilelistAvailable.clear()
|
self._sdFilelistAvailable.clear()
|
||||||
self._comm.refreshSdFiles()
|
self._protocol.refresh_sd_files()
|
||||||
if blocking:
|
if blocking:
|
||||||
self._sdFilelistAvailable.wait(10000)
|
self._sdFilelistAvailable.wait(10000)
|
||||||
|
|
||||||
@@ -717,10 +762,7 @@ class Printer():
|
|||||||
"""
|
"""
|
||||||
Returns a human readable string corresponding to the current communication state.
|
Returns a human readable string corresponding to the current communication state.
|
||||||
"""
|
"""
|
||||||
if self._comm is None:
|
return self._state
|
||||||
return "Offline"
|
|
||||||
else:
|
|
||||||
return self._comm.getStateString()
|
|
||||||
|
|
||||||
def getCurrentData(self):
|
def getCurrentData(self):
|
||||||
return self._stateMonitor.getCurrentData()
|
return self._stateMonitor.getCurrentData()
|
||||||
@@ -730,26 +772,13 @@ class Printer():
|
|||||||
return currentData["job"]
|
return currentData["job"]
|
||||||
|
|
||||||
def getCurrentTemperatures(self):
|
def getCurrentTemperatures(self):
|
||||||
if self._comm is not None:
|
temperatures = self._protocol.get_current_temperatures()
|
||||||
tempOffset, bedTempOffset = self._comm.getOffsets()
|
offsets = self._protocol.get_temperature_offsets()
|
||||||
else:
|
|
||||||
tempOffset = {}
|
|
||||||
bedTempOffset = None
|
|
||||||
|
|
||||||
result = {}
|
result = {}
|
||||||
if self._temp is not None:
|
result.update(temperatures)
|
||||||
for tool in self._temp.keys():
|
for key, tool in result:
|
||||||
result["tool%d" % tool] = {
|
tool["offset"] = offsets[key] if key in offsets and offsets[key] is not None else 0
|
||||||
"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
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@@ -757,36 +786,34 @@ class Printer():
|
|||||||
return self._temps
|
return self._temps
|
||||||
|
|
||||||
def getCurrentConnection(self):
|
def getCurrentConnection(self):
|
||||||
if self._comm is None:
|
opt = self._protocol.get_current_connection()
|
||||||
return "Closed", None, None, None
|
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()
|
||||||
port, baudrate = self._comm.getConnection()
|
return self._protocol.get_state(), None, None, None
|
||||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
|
||||||
return self._comm.getStateString(), port, baudrate, printer_profile
|
|
||||||
|
|
||||||
def isClosedOrError(self):
|
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):
|
def isOperational(self):
|
||||||
return self._comm is not None and self._comm.isOperational()
|
return not self.isClosedOrError()
|
||||||
|
|
||||||
def isPrinting(self):
|
def isPrinting(self):
|
||||||
return self._comm is not None and self._comm.isPrinting()
|
return self._protocol.get_state() == ProtocolState.PRINTING
|
||||||
|
|
||||||
def isPaused(self):
|
def isPaused(self):
|
||||||
return self._comm is not None and self._comm.isPaused()
|
return self._protocol.get_state() == ProtocolState.PAUSED
|
||||||
|
|
||||||
def isError(self):
|
def isError(self):
|
||||||
return self._comm is not None and self._comm.isError()
|
return self._protocol.get_state() == ProtocolState.ERROR
|
||||||
|
|
||||||
def isReady(self):
|
def isReady(self):
|
||||||
return self.isOperational() and not self._comm.isStreaming()
|
return self.isOperational() and not self._protocol.is_streaming()
|
||||||
|
|
||||||
def isSdReady(self):
|
def isSdReady(self):
|
||||||
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
|
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
return self._comm.isSdReady()
|
return self._protocol.is_sd_ready()
|
||||||
|
|
||||||
class StateMonitor(object):
|
class StateMonitor(object):
|
||||||
def __init__(self, ratelimit, updateCallback, addTemperatureCallback, addLogCallback, addMessageCallback):
|
def __init__(self, ratelimit, updateCallback, addTemperatureCallback, addLogCallback, addMessageCallback):
|
||||||
|
|||||||
@@ -355,7 +355,7 @@ class Server():
|
|||||||
printer_profile = printerProfileManager.get_default()
|
printer_profile = printerProfileManager.get_default()
|
||||||
connectionOptions = getConnectionOptions()
|
connectionOptions = getConnectionOptions()
|
||||||
if port in connectionOptions["ports"]:
|
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
|
# start up watchdogs
|
||||||
observer = Observer()
|
observer = Observer()
|
||||||
@@ -445,7 +445,7 @@ class Server():
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"loggers": {
|
"loggers": {
|
||||||
"SERIAL": {
|
"TRANSPORT": {
|
||||||
"level": "CRITICAL",
|
"level": "CRITICAL",
|
||||||
"handlers": ["serialFile"],
|
"handlers": ["serialFile"],
|
||||||
"propagate": False
|
"propagate": False
|
||||||
@@ -477,8 +477,8 @@ class Server():
|
|||||||
|
|
||||||
if settings().getBoolean(["serial", "log"]):
|
if settings().getBoolean(["serial", "log"]):
|
||||||
# enable debug logging to serial.log
|
# enable debug logging to serial.log
|
||||||
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
|
logging.getLogger("TRANSPORT").setLevel(logging.DEBUG)
|
||||||
logging.getLogger("SERIAL").debug("Enabling serial logging")
|
logging.getLogger("TRANSPORT").debug("Enabling transport logging")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
server = Server()
|
server = Server()
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ def connectionCommand():
|
|||||||
if "autoconnect" in data.keys():
|
if "autoconnect" in data.keys():
|
||||||
settings().setBoolean(["serial", "autoconnect"], data["autoconnect"])
|
settings().setBoolean(["serial", "autoconnect"], data["autoconnect"])
|
||||||
settings().save()
|
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":
|
elif command == "disconnect":
|
||||||
printer.disconnect()
|
printer.disconnect()
|
||||||
|
|
||||||
|
|||||||
@@ -288,13 +288,11 @@ def gcodeFileCommand(filename, target):
|
|||||||
return make_response("Printer is not operational, cannot directly start printing", 409)
|
return make_response("Printer is not operational, cannot directly start printing", 409)
|
||||||
printAfterLoading = True
|
printAfterLoading = True
|
||||||
|
|
||||||
sd = False
|
|
||||||
if target == FileDestinations.SDCARD:
|
if target == FileDestinations.SDCARD:
|
||||||
filenameToSelect = filename
|
filenameToSelect = filename
|
||||||
sd = True
|
|
||||||
else:
|
else:
|
||||||
filenameToSelect = fileManager.get_absolute_path(target, filename)
|
filenameToSelect = fileManager.get_absolute_path(target, filename)
|
||||||
printer.selectFile(filenameToSelect, sd, printAfterLoading)
|
printer.selectFile(filenameToSelect, target, printAfterLoading)
|
||||||
|
|
||||||
elif command == "slice":
|
elif command == "slice":
|
||||||
if "slicer" in data.keys():
|
if "slicer" in data.keys():
|
||||||
|
|||||||
@@ -164,12 +164,12 @@ def setSettings():
|
|||||||
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
|
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
|
||||||
if oldLog and not s.getBoolean(["serial", "log"]):
|
if oldLog and not s.getBoolean(["serial", "log"]):
|
||||||
# disable debug logging to serial.log
|
# disable debug logging to serial.log
|
||||||
logging.getLogger("SERIAL").debug("Disabling serial logging")
|
logging.getLogger("TRANSPORT").debug("Disabling transport logging")
|
||||||
logging.getLogger("SERIAL").setLevel(logging.CRITICAL)
|
logging.getLogger("TRANSPORT").setLevel(logging.CRITICAL)
|
||||||
elif not oldLog and s.getBoolean(["serial", "log"]):
|
elif not oldLog and s.getBoolean(["serial", "log"]):
|
||||||
# enable debug logging to serial.log
|
# enable debug logging to serial.log
|
||||||
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
|
logging.getLogger("TRANSPORT").setLevel(logging.DEBUG)
|
||||||
logging.getLogger("SERIAL").debug("Enabling serial logging")
|
logging.getLogger("TRANSPORT").debug("Enabling transport logging")
|
||||||
|
|
||||||
if "folder" in data.keys():
|
if "folder" in data.keys():
|
||||||
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
|
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
|
||||||
|
|||||||
@@ -23,6 +23,30 @@ def settings(init=False, configfile=None, basedir=None):
|
|||||||
return instance
|
return instance
|
||||||
|
|
||||||
default_settings = {
|
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": {
|
"serial": {
|
||||||
"port": None,
|
"port": None,
|
||||||
"baudrate": None,
|
"baudrate": None,
|
||||||
@@ -81,12 +105,12 @@ default_settings = {
|
|||||||
},
|
},
|
||||||
"feature": {
|
"feature": {
|
||||||
"temperatureGraph": True,
|
"temperatureGraph": True,
|
||||||
"waitForStartOnConnect": False,
|
"waitForStartOnConnect": False, # TODO move to protocol options or reprap protocol
|
||||||
"alwaysSendChecksum": False,
|
"alwaysSendChecksum": True, # TODO move to protocol options
|
||||||
"sdSupport": True,
|
"sdSupport": True, # TODO remove (can be always on)
|
||||||
"sdAlwaysAvailable": False,
|
"sdAlwaysAvailable": False, # TODO move to protocol options
|
||||||
"swallowOkAfterResend": True,
|
"swallowOkAfterResend": True, # TODO remove (must always be done!)
|
||||||
"repetierTargetTemp": False
|
"repetierTargetTemp": False # TODO remove (built into repetier protocol implementation)
|
||||||
},
|
},
|
||||||
"folder": {
|
"folder": {
|
||||||
"uploads": None,
|
"uploads": None,
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel, printerProfilesV
|
|||||||
self.feature_temperatureGraph = ko.observable(undefined);
|
self.feature_temperatureGraph = ko.observable(undefined);
|
||||||
self.feature_waitForStart = ko.observable(undefined);
|
self.feature_waitForStart = ko.observable(undefined);
|
||||||
self.feature_alwaysSendChecksum = ko.observable(undefined);
|
self.feature_alwaysSendChecksum = ko.observable(undefined);
|
||||||
|
self.feature_pingPong = ko.observable(undefined);
|
||||||
self.feature_sdSupport = ko.observable(undefined);
|
self.feature_sdSupport = ko.observable(undefined);
|
||||||
self.feature_sdAlwaysAvailable = ko.observable(undefined);
|
self.feature_sdAlwaysAvailable = ko.observable(undefined);
|
||||||
self.feature_swallowOkAfterResend = ko.observable(undefined);
|
self.feature_swallowOkAfterResend = ko.observable(undefined);
|
||||||
|
|||||||
@@ -367,7 +367,7 @@
|
|||||||
<div class="control-group">
|
<div class="control-group">
|
||||||
<div class="controls">
|
<div class="controls">
|
||||||
<label class="checkbox">
|
<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>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import sys
|
|||||||
import time
|
import time
|
||||||
import re
|
import re
|
||||||
import tempfile
|
import tempfile
|
||||||
|
import threading
|
||||||
import logging
|
import logging
|
||||||
from flask import make_response
|
from flask import make_response
|
||||||
|
|
||||||
@@ -300,3 +301,42 @@ def address_for_client(host, port):
|
|||||||
pass
|
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()
|
||||||
|
|
||||||
|
|
||||||
@@ -1,7 +1,3 @@
|
|||||||
import os, struct, sys, time
|
|
||||||
|
|
||||||
from serial import Serial
|
|
||||||
|
|
||||||
import chipDB
|
import chipDB
|
||||||
|
|
||||||
class IspBase():
|
class IspBase():
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import os, struct, sys, time
|
import os, struct, sys, time
|
||||||
|
|
||||||
from serial import Serial
|
from serial import Serial
|
||||||
from serial import SerialException
|
from serial import SerialException, SerialTimeoutException
|
||||||
|
|
||||||
import ispBase, intelHex
|
import ispBase, intelHex
|
||||||
|
|
||||||
|
|||||||
@@ -511,21 +511,6 @@ class MachineCom(object):
|
|||||||
def getSdFiles(self):
|
def getSdFiles(self):
|
||||||
return self._sdFiles
|
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):
|
def deleteSdFile(self, filename):
|
||||||
if not self.isOperational() or (self.isBusy() and
|
if not self.isOperational() or (self.isBusy() and
|
||||||
isinstance(self._currentFile, PrintingSdFileInformation) and
|
isinstance(self._currentFile, PrintingSdFileInformation) and
|
||||||
|
|||||||
@@ -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
|
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.outgoing.put(item)
|
||||||
|
|
||||||
self.currentExtruder = 0
|
self.currentExtruder = 0
|
||||||
self.temp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
|
self.temp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
|
||||||
self.targetTemp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
|
self.targetTemp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
|
||||||
|
|||||||
Reference in new issue
Block a user