more work on the comm refactoring, starting to resemble something working again
This commit is contained in:
1 parent
2e5069d5a1
commit
5622a9c565
6 files changed
+235
-232
No files matched your search
@@ -14,22 +14,22 @@ from octoprint.filemanager.destinations import FileDestinations
|
||||
|
||||
class Protocol(MessageReceiver, StateReceiver, LogReceiver):
|
||||
|
||||
def __init__(self, transportFactory, protocolListener=None):
|
||||
def __init__(self, transport_factory, protocol_listener=None):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._transport = transportFactory(self, self, self)
|
||||
self._transportProperties = self._transport.getProperties()
|
||||
self._transport = transport_factory(self, self, self)
|
||||
self._transport_properties = self._transport.get_properties()
|
||||
|
||||
self._protocolListener = protocolListener
|
||||
self._protocol_listener = protocol_listener
|
||||
self._state = State.OFFLINE
|
||||
|
||||
self._heatupStartTime = None
|
||||
self._heatupTimeLost = 0.0
|
||||
self._heatup_start_time = None
|
||||
self._heatup_time_lost = 0.0
|
||||
|
||||
self._currentFile = None
|
||||
self._current_file = None
|
||||
|
||||
self._sdAvailable = False
|
||||
self._sdFiles = []
|
||||
self._sd_available = False
|
||||
self._sd_files = []
|
||||
|
||||
self._error = None
|
||||
|
||||
@@ -38,56 +38,94 @@ class Protocol(MessageReceiver, StateReceiver, LogReceiver):
|
||||
def connect(self, opt):
|
||||
self._transport.connect(opt)
|
||||
|
||||
def disconnect(self, onError=False):
|
||||
self._transport.disconnect(onError)
|
||||
def disconnect(self, on_error=False):
|
||||
self._transport.disconnect(on_error)
|
||||
|
||||
def sendManually(self, command, highPriority=False):
|
||||
def send_manually(self, command, high_priority=False):
|
||||
pass
|
||||
|
||||
def selectFile(self, filename, origin):
|
||||
def select_file(self, filename, origin):
|
||||
pass
|
||||
|
||||
def deselectFile(self):
|
||||
def deselect_file(self):
|
||||
pass
|
||||
|
||||
def startPrint(self):
|
||||
if self._currentFile is None:
|
||||
def start_print(self):
|
||||
if self._current_file is None:
|
||||
raise ValueError("No file selected for printing")
|
||||
|
||||
self._heatupStartTime = None
|
||||
self._heatupTimeLost = 0.0
|
||||
self._heatup_start_time = None
|
||||
self._heatup_time_lost = 0.0
|
||||
|
||||
self._changeState(State.PRINTING)
|
||||
self._currentFile.start()
|
||||
self._current_file.start()
|
||||
|
||||
def pausePrint(self):
|
||||
def pause_print(self):
|
||||
if self._state == State.PRINTING:
|
||||
self._changeState(State.PAUSED)
|
||||
elif self._state == State.PAUSED:
|
||||
self._changeState(State.PRINTING)
|
||||
|
||||
def cancelPrint(self):
|
||||
def cancel_print(self):
|
||||
eventManager().fire(Events.PRINT_CANCELLED, {
|
||||
"file": self._current_file.getFilename(),
|
||||
"origin": self._current_file.getFileLocation()
|
||||
})
|
||||
self._changeState(State.OPERATIONAL)
|
||||
|
||||
def refresh_sd_files(self):
|
||||
pass
|
||||
|
||||
def refreshSdFiles(self):
|
||||
pass
|
||||
def get_state(self):
|
||||
return self._state
|
||||
|
||||
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), 0)
|
||||
|
||||
def get_print_time_remaining_estimate(self):
|
||||
print_time = self.get_print_time()
|
||||
if print_time is None:
|
||||
return None
|
||||
|
||||
print_time /= 60
|
||||
progress = self._current_file.getProgress()
|
||||
if progress:
|
||||
print_time_total = print_time / progress
|
||||
return int(print_time_total - print_time)
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_current_connection(self):
|
||||
return self._transport.get_current_connection()
|
||||
|
||||
##~~ granular state detection for implementations
|
||||
|
||||
def _isHeatingUp(self):
|
||||
return self._heatupStartTime is not None
|
||||
def is_heating_up(self):
|
||||
return self._heatup_start_time is not None
|
||||
|
||||
def _isPrinting(self):
|
||||
def is_printing(self):
|
||||
return self._state == State.PRINTING or self._state == State.PAUSED
|
||||
|
||||
def _isSdPrinting(self):
|
||||
return isinstance(self._currentFile, PrintingSdFileInformation) and self._isBusy()
|
||||
def is_sd_printing(self):
|
||||
return isinstance(self._current_file, PrintingSdFileInformation) and self.is_busy()
|
||||
|
||||
def _isStreaming(self):
|
||||
def is_streaming(self):
|
||||
return self._state == State.STREAMING
|
||||
|
||||
def _isBusy(self):
|
||||
return self._isPrinting() or self._isStreaming()
|
||||
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
|
||||
|
||||
@@ -95,16 +133,16 @@ class Protocol(MessageReceiver, StateReceiver, LogReceiver):
|
||||
oldState = self._state
|
||||
self._state = newState
|
||||
self._stateChanged(newState)
|
||||
if self._protocolListener is not None:
|
||||
self._protocolListener.onStateChange(self, oldState, 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._temperatureUpdated(temperatureData)
|
||||
if self._protocolListener is not None:
|
||||
self._protocolListener.onTemperatureUpdate(self, temperatureData)
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onTemperatureUpdate(self, temperatureData)
|
||||
|
||||
def _temperatureUpdated(self, temperatureData):
|
||||
pass
|
||||
@@ -113,38 +151,38 @@ class Protocol(MessageReceiver, StateReceiver, LogReceiver):
|
||||
progress = {
|
||||
"completion": self.__getPrintCompletion(),
|
||||
"filepos": self.__getPrintFilepos(),
|
||||
"printTime": self.__getPrintTime(),
|
||||
"printTimeLeft": self.__getPrintTimeRemainingEstimate()
|
||||
"printTime": self.get_print_time(),
|
||||
"printTimeLeft": self.get_print_time_remaining_estimate()
|
||||
}
|
||||
|
||||
self._progressReported(progress)
|
||||
if self._protocolListener is not None:
|
||||
self._protocolListener.onProgress(self, progress)
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onProgress(self, progress)
|
||||
|
||||
def _progressReported(self, progress):
|
||||
pass
|
||||
|
||||
def _changeSdState(self, sdAvailable):
|
||||
self._sdAvailable = sdAvailable
|
||||
self._sd_available = sdAvailable
|
||||
self._sdStateChanged(sdAvailable)
|
||||
if self._sdAvailable:
|
||||
self.refreshSdFiles()
|
||||
if self._sd_available:
|
||||
self.refresh_sd_files()
|
||||
else:
|
||||
self._sdFiles = []
|
||||
if self._protocolListener is not None:
|
||||
self._protocolListener.onSdStateChange(self, sdAvailable)
|
||||
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._currentFile = currentFile
|
||||
self._current_file = currentFile
|
||||
self._fileSelected(currentFile)
|
||||
if self._protocolListener is not None:
|
||||
self._protocolListener.onFileSelected(self, currentFile.getFilename(), currentFile.getFilesize(), currentFile.getFileLocation())
|
||||
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._currentFile.getFilename(),
|
||||
"origin": self._currentFIle.getFileLocation()
|
||||
"file": self._current_file.getFilename(),
|
||||
"origin": self._current_file.getFileLocation()
|
||||
})
|
||||
|
||||
def _fileSelected(self, currentFile):
|
||||
@@ -152,21 +190,21 @@ class Protocol(MessageReceiver, StateReceiver, LogReceiver):
|
||||
|
||||
def _sendSdFiles(self):
|
||||
self._sdFilesSent()
|
||||
if self._protocolListener is not None:
|
||||
self._protocolListener.onSdFiles(self, self._sdFiles)
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onSdFiles(self, self._sd_files)
|
||||
|
||||
def _sdFilesSent(self):
|
||||
pass
|
||||
|
||||
def _finishPrintjob(self):
|
||||
self._changeState(State.OPERATIONAL)
|
||||
if self._protocolListener is not None:
|
||||
self._protocolListener.onPrintjobDone(self)
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onPrintjobDone(self)
|
||||
eventManager().fire(Events.PRINT_DONE, {
|
||||
"file": self._currentFile.getFilename(),
|
||||
"filename": os.path.basename(self._currentFile.getFilename()),
|
||||
"origin": self._currentFile.getFileLocation(),
|
||||
"time": time.time() - self._currentFile.getStartTime()
|
||||
"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
|
||||
})
|
||||
|
||||
def _printJobFinished(self):
|
||||
@@ -178,7 +216,7 @@ class Protocol(MessageReceiver, StateReceiver, LogReceiver):
|
||||
|
||||
:param filename: the filename to add to the list
|
||||
"""
|
||||
self._sdFiles.append(filename)
|
||||
self._sd_files.append(filename)
|
||||
self._sdFileAdded(filename)
|
||||
|
||||
def _sdFileAdded(self, filename):
|
||||
@@ -197,7 +235,7 @@ class Protocol(MessageReceiver, StateReceiver, LogReceiver):
|
||||
:param filenames: the list of filenames to add to the list
|
||||
"""
|
||||
for filename in filenames:
|
||||
self._sdFiles.append(filename)
|
||||
self._sd_files.append(filename)
|
||||
self._sdFilesAdded(filenames)
|
||||
|
||||
def _sdFilesAdded(self, filenames):
|
||||
@@ -213,7 +251,7 @@ class Protocol(MessageReceiver, StateReceiver, LogReceiver):
|
||||
"""
|
||||
Resets the SD file list
|
||||
"""
|
||||
self._sdFiles = []
|
||||
self._sd_files = []
|
||||
self._sdFilesReset()
|
||||
|
||||
def _sdFilesReset(self):
|
||||
@@ -227,15 +265,15 @@ class Protocol(MessageReceiver, StateReceiver, LogReceiver):
|
||||
"""
|
||||
Called when the underlying protocol detects the beginning of a heat-up interval.
|
||||
"""
|
||||
self._heatupStartTime = time.time()
|
||||
self._heatup_start_time = time.time()
|
||||
|
||||
def _heatupDone(self):
|
||||
"""
|
||||
Called when the underlying protocol detects the end of a heat-up interval.
|
||||
"""
|
||||
if self._heatupStartTime is not None:
|
||||
self._heatupTimeLost += time.time() - self._heatupStartTime
|
||||
self._heatupStartTime = None
|
||||
if self._heatup_start_time is not None:
|
||||
self._heatup_time_lost += time.time() - self._heatup_start_time
|
||||
self._heatup_start_time = None
|
||||
|
||||
##~~ StateReceiver
|
||||
|
||||
@@ -265,53 +303,34 @@ class Protocol(MessageReceiver, StateReceiver, LogReceiver):
|
||||
if self._transport != source:
|
||||
return
|
||||
|
||||
if self._protocolListener is not None:
|
||||
self._protocolListener.onLogRx(self, rx)
|
||||
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._protocolListener is not None:
|
||||
self._protocolListener.onLogTx(self, tx)
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onLogTx(self, tx)
|
||||
|
||||
def onLogError(self, source, error):
|
||||
if self._transport != source:
|
||||
return
|
||||
|
||||
if self._protocolListener is not None:
|
||||
self._protocolListener.onLogError(self, error)
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onLogError(self, error)
|
||||
|
||||
##~~ helpers
|
||||
|
||||
def __getPrintCompletion(self):
|
||||
if self._currentFile is None:
|
||||
if self._current_file is None:
|
||||
return None
|
||||
return self._currentFile.getProgress() * 100
|
||||
return self._current_file.getProgress() * 100
|
||||
|
||||
def __getPrintFilepos(self):
|
||||
if self._currentFile is None:
|
||||
return None
|
||||
return self._currentFile.getFilepos()
|
||||
|
||||
def __getPrintTime(self):
|
||||
if self._currentFile is None or self._currentFile.getStartTime() is None:
|
||||
return None
|
||||
else:
|
||||
return max(int(time.time() - self._currentFile.getStartTime() - self._heatupTimeLost), 0)
|
||||
|
||||
def __getPrintTimeRemainingEstimate(self):
|
||||
printTime = self.__getPrintTime()
|
||||
if printTime is None:
|
||||
return None
|
||||
|
||||
printTime /= 60
|
||||
progress = self._currentFile.getProgress()
|
||||
if progress:
|
||||
printTimeTotal = printTime / progress
|
||||
return int(printTimeTotal - printTime)
|
||||
else:
|
||||
if self._current_file is None:
|
||||
return None
|
||||
return self._current_file.getFilepos()
|
||||
|
||||
|
||||
class ProtocolListener(object):
|
||||
|
||||
@@ -88,8 +88,8 @@ class RepRapProtocol(Protocol):
|
||||
# - 2: file size
|
||||
REGEX_SD_PRINTING_BYTE = re.compile("([0-9]*)/([0-9]*)")
|
||||
|
||||
def __init__(self, transportFactory, protocolListener=None):
|
||||
Protocol.__init__(self, transportFactory, protocolListener)
|
||||
def __init__(self, transport_factory, protocol_listener=None):
|
||||
Protocol.__init__(self, transport_factory, protocol_listener)
|
||||
|
||||
self._lastTemperatureUpdate = time.time()
|
||||
self._lastSdProgressUpdate = time.time()
|
||||
@@ -116,38 +116,44 @@ class RepRapProtocol(Protocol):
|
||||
# enqueue our first temperature query so it get's sent right on establishment of the connection
|
||||
self._sendTemperatureQuery(withType=True)
|
||||
|
||||
|
||||
def selectFile(self, filename, origin):
|
||||
def select_file(self, filename, origin):
|
||||
if origin == FileDestinations.SDCARD:
|
||||
if not self._sdAvailable:
|
||||
if not self._sd_available:
|
||||
return
|
||||
self._send(RepRapProtocol.COMMAND_SD_SELECT_FILE(filename), highPriority=True)
|
||||
else:
|
||||
self._currentFile = PrintingGcodeFileInformation(filename, None)
|
||||
self._selectFile(PrintingGcodeFileInformation(filename, None))
|
||||
|
||||
def startPrint(self):
|
||||
def start_print(self):
|
||||
wasPaused = self._state == State.PAUSED
|
||||
|
||||
Protocol.startPrint(self)
|
||||
if isinstance(self._currentFile, PrintingSdFileInformation):
|
||||
Protocol.start_print(self)
|
||||
if isinstance(self._current_file, PrintingSdFileInformation):
|
||||
if wasPaused:
|
||||
self._send(RepRapProtocol.COMMAND_SD_SET_POS(0))
|
||||
self._currentFile.setFilepos(0)
|
||||
self._current_file.setFilepos(0)
|
||||
self._send(RepRapProtocol.COMMAND_SD_START())
|
||||
else:
|
||||
self._sendNext()
|
||||
|
||||
def refreshSdFiles(self):
|
||||
if not self._sdAvailable:
|
||||
def cancel_print(self):
|
||||
if isinstance(self._current_file, PrintingSdFileInformation):
|
||||
self._send(RepRapProtocol.COMMAND_SD_PAUSE)
|
||||
self._send(RepRapProtocol.COMMAND_SD_SET_POS(0))
|
||||
|
||||
Protocol.cancel_print(self)
|
||||
|
||||
def refresh_sd_files(self):
|
||||
if not self._sd_available:
|
||||
return
|
||||
|
||||
Protocol.refreshSdFiles(self)
|
||||
Protocol.refresh_sd_files(self)
|
||||
self._send(RepRapProtocol.COMMAND_SD_REFRESH())
|
||||
|
||||
def sendManually(self, command, highPriority=False):
|
||||
if self._isStreaming():
|
||||
def send_manually(self, command, high_priority=False):
|
||||
if self.is_streaming():
|
||||
return
|
||||
self._send(command, highPriority=highPriority, withChecksum=self._useChecksum())
|
||||
self._send(command, highPriority=high_priority, withChecksum=self._useChecksum())
|
||||
|
||||
##~~ callback methods
|
||||
|
||||
@@ -183,10 +189,12 @@ class RepRapProtocol(Protocol):
|
||||
# sd progress
|
||||
elif RepRapProtocol.MESSAGE_SD_PRINTING_BYTE(message):
|
||||
match = RepRapProtocol.REGEX_SD_PRINTING_BYTE.search(message)
|
||||
self._currentFile.setFilepos(int(match.group(1)))
|
||||
if isinstance(self._current_file, PrintingSdFileInformation):
|
||||
self._current_file.setFilepos(int(match.group(1)))
|
||||
self._reportProgress()
|
||||
elif RepRapProtocol.MESSAGE_SD_DONE_PRINTING(message):
|
||||
self._currentFile.setFilepos(0)
|
||||
if isinstance(self._current_file, PrintingSdFileInformation):
|
||||
self._current_file.setFilepos(0)
|
||||
self._changeState(State.OPERATIONAL)
|
||||
self._finishPrintjob()
|
||||
|
||||
@@ -208,7 +216,7 @@ class RepRapProtocol(Protocol):
|
||||
self._changeState(State.PRINTING)
|
||||
self._clearForSend.set()
|
||||
elif RepRapProtocol.MESSAGE_SD_END_WRITING(message):
|
||||
self.refreshSdFiles()
|
||||
self.refresh_sd_files()
|
||||
|
||||
# initial handshake with the firmware
|
||||
if self._state == State.CONNECTED:
|
||||
@@ -225,15 +233,15 @@ class RepRapProtocol(Protocol):
|
||||
|
||||
# ok == go ahead with sending
|
||||
if RepRapProtocol.MESSAGE_OK(message):
|
||||
if self._isHeatingUp():
|
||||
if self.is_heating_up():
|
||||
self._heatupDone()
|
||||
|
||||
if self._isPrinting():
|
||||
if self.is_printing():
|
||||
self._sendNext()
|
||||
if self._resendDelta is None:
|
||||
if time.time() > self._lastTemperatureUpdate + 5:
|
||||
self._sendTemperatureQuery(withType=True)
|
||||
elif self._isSdPrinting() and time.time() > self._lastSdProgressUpdate + 5:
|
||||
elif self.is_sd_printing() and time.time() > self._lastSdProgressUpdate + 5:
|
||||
self._sendSdProgressQuery(withType=True)
|
||||
self._clearForSend.set()
|
||||
|
||||
@@ -267,7 +275,7 @@ class RepRapProtocol(Protocol):
|
||||
if self._resendDelta <= 0:
|
||||
self._resendDelta = None
|
||||
else:
|
||||
command = self._currentFile.getNext()
|
||||
command = self._current_file.getNext()
|
||||
if command is None:
|
||||
self._finishPrintjob()
|
||||
return
|
||||
@@ -385,7 +393,7 @@ class RepRapProtocol(Protocol):
|
||||
if self._resendDelta > len(self._lastLines) or len(self._lastLines) == 0 or self._resendDelta <= 0:
|
||||
error = "Printer requested line %d but no sufficient history is available, can't resend" % lineToResend
|
||||
self._logger.warn(error)
|
||||
if self._isPrinting():
|
||||
if self.is_printing():
|
||||
# abort the print, there's nothing we can do to rescue it now
|
||||
self.onError(error)
|
||||
else:
|
||||
@@ -393,7 +401,7 @@ class RepRapProtocol(Protocol):
|
||||
self._resendDelta = None
|
||||
|
||||
def _useChecksum(self):
|
||||
return not self._transportProperties[TransportProperties.FLOWCONTROL] and self._isBusy()
|
||||
return not self._transport_properties[TransportProperties.FLOWCONTROL] and self.is_busy()
|
||||
|
||||
##~~ the actual send queue handling starts here
|
||||
|
||||
@@ -444,8 +452,8 @@ if __name__ == "__main__":
|
||||
if newState == State.OPERATIONAL and self.firstPrint:
|
||||
self.firstPrint = False
|
||||
print "Selecting file and starting print job"
|
||||
protocol.selectFile("C:/Users/Gina/AppData/Roaming/OctoPrint/uploads/whistle.gcode", FileDestinations.LOCAL)
|
||||
protocol.startPrint()
|
||||
protocol.select_file("C:/Users/Gina/AppData/Roaming/OctoPrint/uploads/whistle.gcode", FileDestinations.LOCAL)
|
||||
protocol.start_print()
|
||||
|
||||
def onTemperatureUpdate(self, source, temperatureData):
|
||||
print "### Temperature update: %r" % temperatureData
|
||||
@@ -468,7 +476,7 @@ if __name__ == "__main__":
|
||||
def onLogError(self, source, error):
|
||||
print "Error: %s" % error
|
||||
|
||||
protocol = RepRapProtocol(SerialTransport, protocolListener=DummyProtocolListener())
|
||||
protocol = RepRapProtocol(SerialTransport, protocol_listener=DummyProtocolListener())
|
||||
#from octoprint.comm.protocol.repetier import RepetierTextualProtocol
|
||||
#protocol = RepetierTextualProtocol(SerialTransport, protocolListener=DummyProtocolListener())
|
||||
protocol.connect({"port": "VIRTUAL"})
|
||||
|
||||
@@ -12,15 +12,19 @@ class Transport(object):
|
||||
self._logReceiver = logReceiver
|
||||
self._state = State.DISCONNECTED
|
||||
self._error = None
|
||||
self._opt = {}
|
||||
|
||||
def getProperties(self):
|
||||
def get_properties(self):
|
||||
raise NotImplemented()
|
||||
|
||||
def getConnectionOptions(self):
|
||||
def get_connection_options(self):
|
||||
return []
|
||||
|
||||
def get_current_connection(self):
|
||||
return self._opt
|
||||
|
||||
def connect(self, opt):
|
||||
pass
|
||||
self._opt = opt
|
||||
|
||||
def disconnect(self, onError=False):
|
||||
if onError:
|
||||
|
||||
@@ -35,18 +35,20 @@ class SerialTransport(Transport):
|
||||
|
||||
self._thread = None
|
||||
|
||||
def getProperties(self):
|
||||
def get_properties(self):
|
||||
return {
|
||||
TransportProperties.FLOWCONTROL: False
|
||||
}
|
||||
|
||||
def getConnectionOptions(self):
|
||||
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._connectionTimeout = opt["connectionTimeout"] if "connectionTimeout" in opt else 2.0
|
||||
@@ -60,7 +62,8 @@ class SerialTransport(Transport):
|
||||
|
||||
def disconnect(self, onError=False):
|
||||
try:
|
||||
self._serial.close()
|
||||
if self._serial is not None:
|
||||
self._serial.close()
|
||||
finally:
|
||||
self._serial = None
|
||||
self._thread = None
|
||||
|
||||
+65
-99
@@ -1,7 +1,4 @@
|
||||
# coding=utf-8
|
||||
from octoprint.comm.protocol.reprap import RepRapProtocol
|
||||
from octoprint.comm.transport.serialTransport import SerialTransport
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
@@ -20,6 +17,10 @@ from octoprint.events import eventManager, Events
|
||||
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
|
||||
from octoprint.comm.protocol import State as ProtocolState
|
||||
from octoprint.comm.protocol.reprap import RepRapProtocol
|
||||
from octoprint.comm.transport.serialTransport import SerialTransport
|
||||
|
||||
def getConnectionOptions():
|
||||
"""
|
||||
Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer.
|
||||
@@ -78,7 +79,7 @@ class Printer():
|
||||
# comm
|
||||
self._comm = None
|
||||
|
||||
self._protocol = RepRapProtocol(SerialTransport, protocolListener=self)
|
||||
self._protocol = RepRapProtocol(SerialTransport, protocol_listener=self)
|
||||
|
||||
# callbacks
|
||||
self._callbacks = []
|
||||
@@ -161,22 +162,40 @@ class Printer():
|
||||
#~~ callbacks from protocol
|
||||
|
||||
def onStateChange(self, source, oldState, newState):
|
||||
# forward relevant state changes to gcode manager
|
||||
if self._comm is not None and oldState == ProtocolState.PRINTING:
|
||||
if self._selectedFile is not None:
|
||||
if newState == ProtocolState.OPERATIONAL:
|
||||
self._gcodeManager.printSucceeded(self._selectedFile["filename"], self._protocol.get_print_time())
|
||||
elif newState == ProtocolState.OFFLINE or newState == ProtocolState.ERROR:
|
||||
self._gcodeManager.printFailed(self._selectedFile["filename"], self._protocol.get_print_time())
|
||||
self._gcodeManager.resumeAnalysis() # printing done, put those cpu cycles to good use
|
||||
elif newState == ProtocolState.PRINTING:
|
||||
self._gcodeManager.pauseAnalysis() # do not analyse gcode while printing
|
||||
|
||||
self._setState(newState)
|
||||
pass
|
||||
|
||||
def onTemperatureUpdate(self, source, temperatureData):
|
||||
self._addTemperatureData(temperatureData)
|
||||
|
||||
def onProgress(self, source, progress):
|
||||
pass
|
||||
self._setProgressData(progress["completion"], progress["filepos"], progress["printTime"], progress["printTimeLeft"])
|
||||
|
||||
def onFileSelected(self, source, filename, filesize, origin):
|
||||
self._setJobData(filename, filesize, origin)
|
||||
self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
if self._printAfterSelect:
|
||||
self.startPrint()
|
||||
pass
|
||||
|
||||
def onPrintjobDone(self, source):
|
||||
pass
|
||||
self._setProgressData(1.0, self._selectedFile["filesize"], self._protocol.get_print_time(), 0)
|
||||
self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def onSdStateChange(self, source, sdAvailable):
|
||||
pass
|
||||
self._stateMonitor.setState({"state": self._state, "stateString": self._state, "flags": self._getStateFlags()})
|
||||
|
||||
def onSdFiles(self, source, files):
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
|
||||
@@ -198,17 +217,14 @@ class Printer():
|
||||
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
|
||||
will be attempted.
|
||||
"""
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._comm = comm.MachineCom(port, baudrate, callbackObject=self)
|
||||
self._protocol.disconnect()
|
||||
self._protocol.connect({"port": port, "baudrate": baudrate})
|
||||
|
||||
def disconnect(self):
|
||||
"""
|
||||
Closes the connection to the printer.
|
||||
"""
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._comm = None
|
||||
self._protocol.disconnect()
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
|
||||
def command(self, command):
|
||||
@@ -221,11 +237,8 @@ class Printer():
|
||||
"""
|
||||
Sends multiple gcode commands (provided as a list) to the printer.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
for command in commands:
|
||||
self._comm.sendCommand(command)
|
||||
self._protocol.send_manually(command)
|
||||
|
||||
def jog(self, axis, amount):
|
||||
movementSpeed = settings().get(["printerParameters", "movementSpeed", ["x", "y", "z"]], asdict=True)
|
||||
@@ -259,6 +272,7 @@ class Printer():
|
||||
self.command("M140 S%f" % value)
|
||||
|
||||
def setTemperatureOffset(self, offsets={}):
|
||||
# TODO
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
@@ -284,12 +298,12 @@ class Printer():
|
||||
|
||||
def selectFile(self, filename, sd, printAfterSelect=False):
|
||||
self._printAfterSelect = printAfterSelect
|
||||
self._protocol.selectFile(filename, sd)
|
||||
self._protocol.select_file(filename, sd)
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def unselectFile(self):
|
||||
self._protocol.unselectFile()
|
||||
self._protocol.deselect_file()
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
@@ -298,25 +312,25 @@ class Printer():
|
||||
Starts the currently loaded print job.
|
||||
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
|
||||
"""
|
||||
if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting():
|
||||
if not self._protocol.is_operational() or self._protocol.is_busy():
|
||||
return
|
||||
if self._selectedFile is None:
|
||||
return
|
||||
|
||||
self._setCurrentZ(None)
|
||||
self._protocol.startPrint()
|
||||
self._protocol.start_print()
|
||||
|
||||
def togglePausePrint(self):
|
||||
"""
|
||||
Pause the current printjob.
|
||||
"""
|
||||
self._protocol.pausePrint()
|
||||
self._protocol.pause_print()
|
||||
|
||||
def cancelPrint(self, disableMotorsAndHeater=True):
|
||||
"""
|
||||
Cancel the current printjob.
|
||||
"""
|
||||
self._protocol.cancelPrint()
|
||||
self._protocol.cancel_print()
|
||||
|
||||
if disableMotorsAndHeater:
|
||||
# disable motors, switch off hotends, bed and fan
|
||||
@@ -331,7 +345,7 @@ class Printer():
|
||||
|
||||
# mark print as failure
|
||||
if self._selectedFile is not None:
|
||||
self._gcodeManager.printFailed(self._selectedFile["filename"], self._comm.getPrintTime())
|
||||
self._gcodeManager.printFailed(self._selectedFile["filename"], self._protocol.get_print_time())
|
||||
payload = {
|
||||
"file": self._selectedFile["filename"],
|
||||
"origin": FileDestinations.LOCAL
|
||||
@@ -364,7 +378,7 @@ class Printer():
|
||||
self._printTimeLeft = printTimeLeft
|
||||
|
||||
self._stateMonitor.setProgress({
|
||||
"completion": self._progress * 100 if self._progress is not None else None,
|
||||
"completion": self._progress,
|
||||
"filepos": filepos,
|
||||
"printTime": int(self._printTime) if self._printTime is not None else None,
|
||||
"printTimeLeft": int(self._printTimeLeft * 60) if self._printTimeLeft is not None else None
|
||||
@@ -455,54 +469,8 @@ class Printer():
|
||||
"sdReady": self.isSdReady()
|
||||
}
|
||||
|
||||
def getCurrentData(self):
|
||||
return self._stateMonitor.getCurrentData()
|
||||
|
||||
#~~ 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._gcodeManager.printSucceeded(self._selectedFile["filename"], self._comm.getPrintTime())
|
||||
elif state == self._comm.STATE_CLOSED or state == self._comm.STATE_ERROR or state == self._comm.STATE_CLOSED_WITH_ERROR:
|
||||
self._gcodeManager.printFailed(self._selectedFile["filename"], self._comm.getPrintTime())
|
||||
self._gcodeManager.resumeAnalysis() # printing done, put those cpu cycles to good use
|
||||
elif self._comm is not None and state == self._comm.STATE_PRINTING:
|
||||
self._gcodeManager.pauseAnalysis() # do not analyse gcode 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.getPrintTimeRemainingEstimate())
|
||||
|
||||
def mcZChange(self, newZ):
|
||||
"""
|
||||
Callback method for the comm object, called upon change of the z-layer.
|
||||
@@ -530,7 +498,7 @@ class Printer():
|
||||
self.startPrint()
|
||||
|
||||
def mcPrintjobDone(self):
|
||||
self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.getPrintTime(), 0)
|
||||
self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.get_print_time(), 0)
|
||||
self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcFileTransferStarted(self, filename, filesize):
|
||||
@@ -558,36 +526,40 @@ class Printer():
|
||||
#~~ sd file handling
|
||||
|
||||
def getSdFiles(self):
|
||||
if self._comm is None or not self._comm.isSdReady():
|
||||
if not self._protocol.is_sd_ready():
|
||||
return []
|
||||
return self._comm.getSdFiles()
|
||||
return self._protocol.get_sd_files()
|
||||
|
||||
def addSdFile(self, filename, absolutePath, streamingFinishedCallback):
|
||||
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
|
||||
if self._protocol.is_busy() or not self._protocol.is_sd_ready():
|
||||
logging.error("No connection to printer or printer is busy")
|
||||
return
|
||||
|
||||
self._streamingFinishedCallback = streamingFinishedCallback
|
||||
|
||||
self.refreshSdFiles(blocking=True)
|
||||
existingSdFiles = self._comm.getSdFiles()
|
||||
existingSdFiles = self._protocol.get_sd_files()
|
||||
|
||||
remoteName = util.getDosFilename(filename, existingSdFiles)
|
||||
# TODO
|
||||
self._comm.startFileTransfer(absolutePath, filename, remoteName)
|
||||
|
||||
return remoteName
|
||||
|
||||
def deleteSdFile(self, filename):
|
||||
# TODO
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._comm.deleteSdFile(filename)
|
||||
|
||||
def initSdCard(self):
|
||||
# TODO
|
||||
if not self._comm or self._comm.isSdReady():
|
||||
return
|
||||
self._comm.initSdCard()
|
||||
|
||||
def releaseSdCard(self):
|
||||
# TODO
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._comm.releaseSdCard()
|
||||
@@ -596,12 +568,12 @@ class Printer():
|
||||
"""
|
||||
Refreshs the list of file stored on the SD card attached to printer (if available and printer communication
|
||||
available). Optional blocking parameter allows making the method block (max 10s) until the file list has been
|
||||
received (and can be accessed via self._comm.getSdFiles()). Defaults to a asynchronous operation.
|
||||
received (and can be accessed via self._protocol.get_sd_files()). Defaults to a asynchronous operation.
|
||||
"""
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
if not self._protocol.is_sd_ready():
|
||||
return
|
||||
self._sdFilelistAvailable.clear()
|
||||
self._comm.refreshSdFiles()
|
||||
self._protocol.refresh_sd_files()
|
||||
if blocking:
|
||||
self._sdFilelistAvailable.wait(10000)
|
||||
|
||||
@@ -611,10 +583,7 @@ class Printer():
|
||||
"""
|
||||
Returns a human readable string corresponding to the current communication state.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return "Offline"
|
||||
else:
|
||||
return self._comm.getStateString()
|
||||
return self._state
|
||||
|
||||
def getCurrentData(self):
|
||||
return self._stateMonitor.getCurrentData()
|
||||
@@ -624,6 +593,7 @@ class Printer():
|
||||
return currentData["job"]
|
||||
|
||||
def getCurrentTemperatures(self):
|
||||
# TODO
|
||||
if self._comm is not None:
|
||||
tempOffset, bedTempOffset = self._comm.getOffsets()
|
||||
else:
|
||||
@@ -651,38 +621,34 @@ class Printer():
|
||||
return self._temps
|
||||
|
||||
def getCurrentConnection(self):
|
||||
if self._comm is None:
|
||||
return "Closed", None, None
|
||||
|
||||
port, baudrate = self._comm.getConnection()
|
||||
return self._comm.getStateString(), port, baudrate
|
||||
opt = self._protocol.get_current_connection()
|
||||
if "port" in opt.keys() and "baudrate" in opt.keys():
|
||||
return self._protocol.get_state(), opt["port"], opt["baudrate"]
|
||||
return self._protocol.get_state(), None, None
|
||||
|
||||
def isClosedOrError(self):
|
||||
return self._comm is None or self._comm.isClosedOrError()
|
||||
return self._protocol.get_state() == ProtocolState.OFFLINE or self._protocol == ProtocolState.ERROR
|
||||
|
||||
def isOperational(self):
|
||||
return self._comm is not None and self._comm.isOperational()
|
||||
return not self.isClosedOrError()
|
||||
|
||||
def isPrinting(self):
|
||||
return self._comm is not None and self._comm.isPrinting()
|
||||
return self._protocol.get_state() == ProtocolState.PRINTING
|
||||
|
||||
def isPaused(self):
|
||||
return self._comm is not None and self._comm.isPaused()
|
||||
return self._protocol.get_state() == ProtocolState.PAUSED
|
||||
|
||||
def isError(self):
|
||||
return self._comm is not None and self._comm.isError()
|
||||
return self._protocol.get_state() == ProtocolState.ERROR
|
||||
|
||||
def isReady(self):
|
||||
return self.isOperational() and not self._comm.isStreaming()
|
||||
return self.isOperational() and not self._protocol.is_streaming()
|
||||
|
||||
def isSdReady(self):
|
||||
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return False
|
||||
else:
|
||||
return self._comm.isSdReady()
|
||||
|
||||
def isLoading(self):
|
||||
return self._gcodeLoader is not None
|
||||
return self._protocol.is_sd_ready()
|
||||
|
||||
class StateMonitor(object):
|
||||
def __init__(self, ratelimit, updateCallback, addTemperatureCallback, addLogCallback, addMessageCallback):
|
||||
|
||||
@@ -296,13 +296,16 @@ class VirtualPrinter():
|
||||
except:
|
||||
pass
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]):
|
||||
self.readList.append("TargetBed:%d" % self.bedTargetTemp)
|
||||
|
||||
if "M190" in line:
|
||||
self._heatupThread = threading.Thread(target=self._waitForHeatup, args=["bed"])
|
||||
self._heatupThread.start()
|
||||
return False
|
||||
|
||||
self._sendOk()
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]):
|
||||
self.readList.append("TargetBed:%d" % self.bedTargetTemp)
|
||||
|
||||
return True
|
||||
|
||||
def _performMove(self, line):
|
||||
@@ -353,8 +356,8 @@ class VirtualPrinter():
|
||||
except:
|
||||
pass
|
||||
|
||||
if duration:
|
||||
time.sleep(duration)
|
||||
#if duration:
|
||||
# time.sleep(duration)
|
||||
|
||||
def _setPosition(self, line):
|
||||
matchX = re.search("X([0-9.]+)", line)
|
||||
|
||||
Reference in new issue
Block a user