Started working on new modular comm layer, checking in just for the record, not yet usable
This commit is contained in:
1 parent
858873dfa0
commit
00e1a1962b
11 files changed
+1224
-16
No files matched your search
@@ -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,229 @@
|
||||
# coding=utf-8
|
||||
import time
|
||||
|
||||
__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"
|
||||
|
||||
|
||||
from octoprint.comm.transport import MessageReceiver, StateReceiver, LogReceiver, State as TransportState
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
|
||||
|
||||
class Protocol(MessageReceiver, StateReceiver, LogReceiver):
|
||||
|
||||
def __init__(self, transportFactory, protocolListener=None):
|
||||
self._transport = transportFactory(self, self, self)
|
||||
self._transportProperties = self._transport.getProperties()
|
||||
|
||||
self._protocolListener = protocolListener
|
||||
self._state = State.OFFLINE
|
||||
|
||||
self._currentFile = None
|
||||
|
||||
self._error = None
|
||||
|
||||
# temperatures
|
||||
self._temp = {}
|
||||
self._targetTemp = {}
|
||||
self._bedTemp = 0
|
||||
self._bedTargetTemp = 0
|
||||
|
||||
self._tempOffset = {}
|
||||
self._bedTempOffset = 0
|
||||
|
||||
##~~ public
|
||||
|
||||
def connect(self, opt):
|
||||
self._transport.connect(opt)
|
||||
|
||||
def disconnect(self, onError=False):
|
||||
self._transport.disconnect(onError)
|
||||
|
||||
def sendManually(self, command, highPriority=False):
|
||||
pass
|
||||
|
||||
def selectFile(self, filename, origin):
|
||||
pass
|
||||
|
||||
def deselectFile(self):
|
||||
pass
|
||||
|
||||
def startPrint(self):
|
||||
if self._currentFile is None:
|
||||
raise ValueError("No file selected for printing")
|
||||
self._changeState(State.PRINTING)
|
||||
self._currentFile.start()
|
||||
|
||||
def pausePrint(self):
|
||||
if self._state == State.PRINTING:
|
||||
self._changeState(State.PAUSED)
|
||||
elif self._state == State.PAUSED:
|
||||
self._changeState(State.PRINTING)
|
||||
|
||||
def cancelPrint(self):
|
||||
pass
|
||||
|
||||
##~~ private
|
||||
|
||||
def _changeState(self, newState):
|
||||
oldState = self._state
|
||||
self._state = newState
|
||||
self._stateChanged(newState)
|
||||
if self._protocolListener is not None:
|
||||
self._protocolListener.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)
|
||||
|
||||
def _temperatureUpdated(self, temperatureData):
|
||||
pass
|
||||
|
||||
def onError(self, error):
|
||||
self._changeState(State.ERROR)
|
||||
self._error = 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._changeState(State.ERROR)
|
||||
|
||||
##~~ LogReceiver
|
||||
|
||||
def onLogRx(self, source, rx):
|
||||
if self._transport != source:
|
||||
return
|
||||
|
||||
if self._protocolListener is not None:
|
||||
self._protocolListener.onLogRx(self, rx)
|
||||
|
||||
def onLogTx(self, source, tx):
|
||||
if self._transport != source:
|
||||
return
|
||||
|
||||
if self._protocolListener is not None:
|
||||
self._protocolListener.onLogTx(self, tx)
|
||||
|
||||
def onLogError(self, source, error):
|
||||
if self._transport != source:
|
||||
return
|
||||
|
||||
if self._protocolListener is not None:
|
||||
self._protocolListener.onLogError(self, error)
|
||||
|
||||
|
||||
class ProtocolListener(object):
|
||||
def onStateChange(self, source, oldState, newState):
|
||||
pass
|
||||
|
||||
def onTemperatureUpdate(self, source, temperatureData):
|
||||
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"
|
||||
HEATING = "Heating"
|
||||
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,44 @@
|
||||
# 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"
|
||||
|
||||
from octoprint.comm.protocol import ProtocolListener, State
|
||||
from octoprint.comm.protocol.reprap.protocol import RepRapProtocol
|
||||
from octoprint.comm.transport.serialTransport import VirtualSerialTransport
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
|
||||
if __name__ == "__main__":
|
||||
from octoprint.settings import settings
|
||||
settings(True)
|
||||
|
||||
class DummyProtocolListener(ProtocolListener):
|
||||
def __init__(self):
|
||||
self.firstPrint = True
|
||||
|
||||
def onStateChange(self, source, oldState, newState):
|
||||
print "New State: %s" % newState
|
||||
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/short.gcode", FileDestinations.LOCAL)
|
||||
protocol.startPrint()
|
||||
|
||||
def onTemperatureUpdate(self, source, temperatureData):
|
||||
print "### Temperature update: %r" % temperatureData
|
||||
|
||||
def onLogTx(self, source, tx):
|
||||
print ">> %s" % tx
|
||||
|
||||
def onLogRx(self, source, rx):
|
||||
print "<< %s" % rx
|
||||
|
||||
def onLogError(self, source, error):
|
||||
print "Error: %s" % error
|
||||
|
||||
protocol = RepRapProtocol(VirtualSerialTransport, protocolListener=DummyProtocolListener())
|
||||
protocol.connect({})
|
||||
|
||||
import time
|
||||
while True:
|
||||
time.sleep(0.1)
|
||||
@@ -0,0 +1,293 @@
|
||||
# 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
|
||||
import threading
|
||||
import time
|
||||
from octoprint.comm.protocol import State, Protocol, PrintingSdFileInformation
|
||||
from octoprint.comm.protocol.reprap.util import GcodeCommand, CommandQueue, PrintingGcodeFileInformation
|
||||
from octoprint.comm.transport import TransportProperties
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
|
||||
|
||||
class RepRapProtocol(Protocol):
|
||||
|
||||
MESSAGE_OK = staticmethod(lambda line: line.startswith("ok"))
|
||||
MESSAGE_START = staticmethod(lambda line: line.startswith("start"))
|
||||
MESSAGE_WAIT = staticmethod(lambda line: line.startswith("wait"))
|
||||
|
||||
MESSAGE_SD_INIT_OK = staticmethod(lambda line: line == "SD card ok")
|
||||
MESSAGE_SD_INIT_FAIL = staticmethod(lambda line: "SD init fail" in line or "volume.init failed" in line or "" in line)
|
||||
MESSAGE_SD_FILE_OPENED = staticmethod(lambda line: line.startswith("File opened"))
|
||||
MESSAGE_SD_FILE_SELECTED = staticmethod(lambda line: line.startswith("File selected"))
|
||||
|
||||
MESSAGE_ERROR = staticmethod(lambda line: line.startswith("Error:") or line.startswith("!!"))
|
||||
MESSAGE_ERROR_COMMUNICATION = staticmethod(lambda line: 'checksum mismatch' in line.lower()
|
||||
or 'wrong checksum' in line.lower()
|
||||
or 'line number is not last line number' in line.lower()
|
||||
or 'expected line' in line.lower()
|
||||
or 'no line number with checksum' in line.lower()
|
||||
or 'no checksum with line number' in line.lower()
|
||||
or 'missing checksum' in line.lower())
|
||||
MESSAGE_RESEND = staticmethod(lambda line: line.lower().startswith("resend") or line.lower().startswith("rs"))
|
||||
|
||||
MESSAGE_TEMPERATURE = staticmethod(lambda x: ' T:' in x or x.startswith('T:') or ' T0:' in x or x.startswith('T0:'))
|
||||
|
||||
COMMAND_GET_TEMP = staticmethod(lambda: GcodeCommand("M105"))
|
||||
COMMAND_SET_EXTRUDER_TEMP = staticmethod(lambda x, w: GcodeCommand("M109", s=x) if w else GcodeCommand("M104", s=x))
|
||||
COMMAND_SET_BED_TEMP = staticmethod(lambda x, w: GcodeCommand("M190", s=x) if w else GcodeCommand("M140", s=x))
|
||||
COMMAND_SET_TOOL = staticmethod(lambda t: GcodeCommand("T%d" % t))
|
||||
COMMAND_SD_REFRESH = staticmethod(lambda: GcodeCommand("M20"))
|
||||
COMMAND_SD_INIT = staticmethod(lambda: GcodeCommand("M21"))
|
||||
COMMAND_SD_RELEASE = staticmethod(lambda: GcodeCommand("M22"))
|
||||
COMMAND_SD_SELECT_FILE = staticmethod(lambda name: GcodeCommand("M23", param=name))
|
||||
COMMAND_SD_START = staticmethod(lambda: GcodeCommand("M24"))
|
||||
COMMAND_SD_PAUSE = staticmethod(lambda: GcodeCommand("M25"))
|
||||
COMMAND_SD_SET_POS = staticmethod(lambda pos: GcodeCommand("M26", s=pos))
|
||||
COMMAND_SD_STATUS = staticmethod(lambda: GcodeCommand("M27"))
|
||||
COMMAND_SD_BEGIN_WRITE = staticmethod(lambda name: GcodeCommand("M28", param=name))
|
||||
COMMAND_SD_END_WRITE = staticmethod(lambda name: GcodeCommand("M29", param=name))
|
||||
COMMAND_SD_DELETE = staticmethod(lambda name: GcodeCommand("M30", param=name))
|
||||
|
||||
COMMAND_TYPE_TEMPERATURE = "temperature"
|
||||
COMMAND_TYPE_SD_PROGRESS = "sd_progress"
|
||||
|
||||
# Regex matching temperature entries in line. Groups will be as follows:
|
||||
# - 1: whole tool designator incl. optional toolNumber ("T", "Tn", "B")
|
||||
# - 2: toolNumber, if given ("", "n", "")
|
||||
# - 3: actual temperature
|
||||
# - 4: whole target substring, if given (e.g. " / 22.0")
|
||||
# - 5: target temperature
|
||||
REGEX_TEMPERATURE = re.compile("(B|T(\d*)):\s*([-+]?\d*\.?\d+)(\s*\/?\s*([-+]?\d*\.?\d+))?")
|
||||
|
||||
# Regex matching "File opened" message. Groups will be as follows:
|
||||
# - 1: name of the file that got opened (e.g. "file.gco")
|
||||
# - 2: size of the file that got opened, in bytes, parseable to integer (e.g. "2392010")
|
||||
REGEX_FILE_OPENED = re.compile("File opened:\s*(.*?)\s+Size:\s*([0-9]*)")
|
||||
|
||||
def __init__(self, transportFactory, protocolListener=None):
|
||||
Protocol.__init__(self, transportFactory, protocolListener)
|
||||
|
||||
self._lastTemperatureUpdate = time.time()
|
||||
self._startSeen = False
|
||||
self._sdAvailable = False
|
||||
|
||||
self._sendQueue = CommandQueue()
|
||||
|
||||
self._clearForSend = threading.Event()
|
||||
self._clearForSend.clear()
|
||||
|
||||
self._sendQueueProcessing = True
|
||||
self._thread = threading.Thread(target=self._handleSendQueue, name="SendQueueHandler")
|
||||
self._thread.daemon = True
|
||||
self._thread.start()
|
||||
|
||||
self._currentLine = 1
|
||||
self._state = State.OFFLINE
|
||||
|
||||
def selectFile(self, filename, origin):
|
||||
if origin == FileDestinations.SDCARD:
|
||||
if not self._sdAvailable:
|
||||
return
|
||||
self._send(RepRapProtocol.COMMAND_SD_SELECT_FILE(filename), highPriority=True)
|
||||
else:
|
||||
self._currentFile = PrintingGcodeFileInformation(filename, None)
|
||||
|
||||
def startPrint(self):
|
||||
wasPaused = self._state == State.PAUSED
|
||||
|
||||
Protocol.startPrint(self)
|
||||
|
||||
if isinstance(self._currentFile, PrintingSdFileInformation):
|
||||
if wasPaused:
|
||||
self._send(RepRapProtocol.COMMAND_SD_SET_POS(0))
|
||||
self._currentFile.setFilepos(0)
|
||||
self._send(RepRapProtocol.COMMAND_SD_START())
|
||||
else:
|
||||
self._sendNext()
|
||||
|
||||
def onMessageReceived(self, source, message):
|
||||
if self._transport != source:
|
||||
return
|
||||
|
||||
message = self._handleErrors(message.strip())
|
||||
|
||||
# message processing
|
||||
if RepRapProtocol.MESSAGE_TEMPERATURE(message):
|
||||
self._processTemperatures(message)
|
||||
|
||||
elif RepRapProtocol.MESSAGE_SD_INIT_OK(message):
|
||||
self._sdAvailable = True
|
||||
|
||||
elif RepRapProtocol.MESSAGE_SD_INIT_FAIL(message):
|
||||
self._sdAvailable = False
|
||||
|
||||
elif RepRapProtocol.MESSAGE_SD_FILE_OPENED(message):
|
||||
match = RepRapProtocol.REGEX_FILE_OPENED.search(message)
|
||||
self._currentFile = PrintingSdFileInformation(match.group(1), int(match.group(2)))
|
||||
|
||||
elif RepRapProtocol.MESSAGE_SD_FILE_SELECTED(message):
|
||||
# trigger callback and stuff
|
||||
pass
|
||||
|
||||
# initial handshake with the firmware
|
||||
if self._state == State.CONNECTED:
|
||||
|
||||
if RepRapProtocol.MESSAGE_START(message):
|
||||
self._startSeen = True
|
||||
elif RepRapProtocol.MESSAGE_WAIT(message) and self._startSeen:
|
||||
self._clearForSend.set()
|
||||
self._sendTemperatureQuery(withType=True)
|
||||
elif RepRapProtocol.MESSAGE_OK(message):
|
||||
self._changeState(State.OPERATIONAL)
|
||||
|
||||
# ok == go ahead with sending
|
||||
if RepRapProtocol.MESSAGE_OK(message):
|
||||
if self._state == State.PRINTING:
|
||||
if time.time() > self._lastTemperatureUpdate + 5:
|
||||
self._sendTemperatureQuery(withType=True)
|
||||
self._sendNext()
|
||||
self._clearForSend.set()
|
||||
|
||||
def onTimeoutReceived(self, source):
|
||||
if self._transport != source:
|
||||
return
|
||||
self._sendTemperatureQuery(withType=True)
|
||||
|
||||
def sendManually(self, command, highPriority=False):
|
||||
self._send(command, highPriority=highPriority, withChecksum=self._useChecksum())
|
||||
|
||||
def _send(self, command, highPriority=False, commandType=None, withChecksum=False):
|
||||
commandTuple = (str(command), withChecksum)
|
||||
|
||||
priority = 100
|
||||
if highPriority:
|
||||
priority = 1
|
||||
if commandType is not None:
|
||||
self._sendQueue.put((priority, commandTuple, commandType))
|
||||
else:
|
||||
self._sendQueue.put((priority, commandTuple))
|
||||
|
||||
def _sendNext(self):
|
||||
command = self._currentFile.getNext()
|
||||
if command is None:
|
||||
self._changeState(State.OPERATIONAL)
|
||||
return
|
||||
|
||||
self._send(command, withChecksum=self._useChecksum())
|
||||
|
||||
def _sendTemperatureQuery(self, withType=False):
|
||||
if withType:
|
||||
self._send(RepRapProtocol.COMMAND_GET_TEMP(), commandType=RepRapProtocol.COMMAND_TYPE_TEMPERATURE)
|
||||
else:
|
||||
self._send(RepRapProtocol.COMMAND_GET_TEMP())
|
||||
self._lastTemperatureUpdate = time.time()
|
||||
|
||||
def _handleErrors(self, line):
|
||||
# TODO Somehow figure out how to handle multiline errors here...
|
||||
|
||||
# No matter the state, if we see an error, goto the error state and store the error for reference.
|
||||
if line.startswith('Error:'):
|
||||
#Oh YEAH, consistency.
|
||||
# Marlin reports an MIN/MAX temp error as "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
|
||||
# But a bed temp error is reported as "Error: Temperature heated bed switched off. MAXTEMP triggered !!"
|
||||
# So we can have an extra newline in the most common case. Awesome work people.
|
||||
if re.match('Error:[0-9]\n', line):
|
||||
line = line.rstrip() + self._readline()
|
||||
#Skip the communication errors, as those get corrected.
|
||||
if RepRapProtocol.MESSAGE_ERROR_COMMUNICATION(line):
|
||||
pass
|
||||
elif not self._state == State.ERROR:
|
||||
self.onError(line[6:])
|
||||
return line
|
||||
|
||||
def _parseTemperatures(self, line):
|
||||
result = {}
|
||||
maxToolNum = 0
|
||||
for match in re.finditer(RepRapProtocol.REGEX_TEMPERATURE, line):
|
||||
tool = match.group(1)
|
||||
toolNumber = int(match.group(2)) if match.group(2) and len(match.group(2)) > 0 else None
|
||||
if toolNumber > maxToolNum:
|
||||
maxToolNum = toolNumber
|
||||
|
||||
try:
|
||||
actual = float(match.group(3))
|
||||
target = None
|
||||
if match.group(4) and match.group(5):
|
||||
target = float(match.group(5))
|
||||
|
||||
result[tool] = (toolNumber, actual, target)
|
||||
except ValueError:
|
||||
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
|
||||
pass
|
||||
|
||||
if "T0" in result.keys() and "T" in result.keys():
|
||||
del result["T"]
|
||||
|
||||
return maxToolNum, result
|
||||
|
||||
def _processTemperatures(self, line):
|
||||
maxToolNum, parsedTemps = self._parseTemperatures(line)
|
||||
|
||||
result = {}
|
||||
|
||||
# extruder temperatures
|
||||
if not "T0" in parsedTemps.keys() and "T" in parsedTemps.keys():
|
||||
# only single reporting, "T" is our one and only extruder temperature
|
||||
toolNum, actual, target = parsedTemps["T"]
|
||||
result["tool0"] = {
|
||||
"actual": actual,
|
||||
"target": target
|
||||
}
|
||||
elif "T0" in parsedTemps.keys():
|
||||
for n in range(maxToolNum + 1):
|
||||
tool = "T%d" % n
|
||||
if not tool in parsedTemps.keys():
|
||||
continue
|
||||
|
||||
toolNum, actual, target = parsedTemps[tool]
|
||||
result["tool%d" % toolNum] = {
|
||||
"actual": actual,
|
||||
"target": target
|
||||
}
|
||||
|
||||
# bed temperature
|
||||
if "B" in parsedTemps.keys():
|
||||
toolNum, actual, target = parsedTemps["B"]
|
||||
result["bed"] = {
|
||||
"actual": actual,
|
||||
"target": target
|
||||
}
|
||||
|
||||
self._updateTemperature(result)
|
||||
|
||||
def _useChecksum(self):
|
||||
return not self._transportProperties[TransportProperties.FLOWCONTROL] and \
|
||||
(self._state == State.PRINTING or self._state == State.HEATING)
|
||||
|
||||
##~~ the actual send queue handling starts here
|
||||
|
||||
def _handleSendQueue(self):
|
||||
while self._sendQueueProcessing:
|
||||
self._clearForSend.wait()
|
||||
self._clearForSend.clear()
|
||||
entry = self._sendQueue.get()
|
||||
if len(entry) == 3:
|
||||
priority, commandTuple, commandType = entry
|
||||
else:
|
||||
priority, commandTuple = entry
|
||||
|
||||
command, withChecksum = commandTuple
|
||||
self._transport._send(self._preprocessCommand(command, withChecksum=withChecksum))
|
||||
|
||||
def _preprocessCommand(self, command, withChecksum=False):
|
||||
if withChecksum:
|
||||
commandToSend = "N%d %s" % (self._currentLine, command)
|
||||
checksum = reduce(lambda x, y: x ^ y, map(ord, commandToSend))
|
||||
self._currentLine += 1
|
||||
return "%s*%d" % (commandToSend, checksum)
|
||||
else:
|
||||
return command
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
# 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 fromLine(line):
|
||||
line = line.strip()
|
||||
match = GcodeCommand.COMMAND_REGEX.match(line)
|
||||
if match is None:
|
||||
return None
|
||||
|
||||
commandType = match.group(1)
|
||||
commandNumber = int(match.group(2))
|
||||
command = "%s%d" % (commandType, commandNumber)
|
||||
args = {"original": line}
|
||||
|
||||
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
|
||||
|
||||
for key, value in kwargs.iteritems():
|
||||
if key in GcodeCommand.KNOWN_ATTRIBUTES + ("tool", "original", "param"):
|
||||
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 __str__(self):
|
||||
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 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()
|
||||
|
||||
def _qsize(self, len=len):
|
||||
return len(self.queue)
|
||||
|
||||
def _put(self, item, heappush=heapq.heappush):
|
||||
if len(item) == 3:
|
||||
priority, command, commandType = item
|
||||
else:
|
||||
priority, command = item
|
||||
commandType = None
|
||||
|
||||
if commandType is not None:
|
||||
if commandType not in self.lookup:
|
||||
self.lookup[commandType] = item
|
||||
else:
|
||||
return
|
||||
|
||||
heappush(self.queue, (priority, next(self.counter), command, commandType))
|
||||
|
||||
def _get(self, heappop=heapq.heappop):
|
||||
priority, count, command, commandType = heappop(self.queue)
|
||||
if commandType in self.lookup:
|
||||
del self.lookup[commandType]
|
||||
return priority, command, commandType
|
||||
|
||||
|
||||
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._tempCommandPattern = re.compile("M(104|109|140|190)")
|
||||
self._tempCommandTemperaturePattern = re.compile("S([-+]?/d*/.?/d+)")
|
||||
self._tempCommandToolPattern = re.compile("T(/d+)")
|
||||
self._toolCommandPattern = re.compile("^T(/d+)")
|
||||
|
||||
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
|
||||
return "M110 N0"
|
||||
|
||||
try:
|
||||
processedLine = None
|
||||
while processedLine 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
|
||||
processedLine = self._processLine(line)
|
||||
self._lineCount += 1
|
||||
self._filepos = self._filehandle.tell()
|
||||
|
||||
if self._lineCount >= 100 and self._startTime is None:
|
||||
self._startTime = time.time()
|
||||
|
||||
return processedLine
|
||||
except Exception as (e):
|
||||
if self._filehandle is not None:
|
||||
self._filehandle.close()
|
||||
self._filehandle = None
|
||||
raise e
|
||||
|
||||
def _processLine(self, line):
|
||||
if ";" in line:
|
||||
line = line[0:line.find(";")]
|
||||
line = line.strip()
|
||||
if len(line) > 0:
|
||||
toolMatch = self._toolCommandPattern.match(line)
|
||||
if toolMatch is not None:
|
||||
# track tool changes
|
||||
self._currentTool = int(toolMatch.group(1))
|
||||
else:
|
||||
## apply offsets
|
||||
if self._offsetCallback is not None:
|
||||
tempMatch = self._tempCommandPattern.match(line)
|
||||
if tempMatch is not None:
|
||||
# if we have a temperature command, retrieve current offsets
|
||||
tempOffset, bedTempOffset = self._offsetCallback()
|
||||
if tempMatch.group(1) == "104" or tempMatch.group(1) == "109":
|
||||
# extruder temperature, determine which one and retrieve corresponding offset
|
||||
toolNum = self._currentTool
|
||||
|
||||
toolNumMatch = self._tempCommandToolPattern.search(line)
|
||||
if toolNumMatch is not None:
|
||||
try:
|
||||
toolNum = int(toolNumMatch.group(1))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
offset = tempOffset[toolNum] if toolNum in tempOffset.keys() and tempOffset[toolNum] is not None else 0
|
||||
elif tempMatch.group(1) == "140" or tempMatch.group(1) == "190":
|
||||
# bed temperature
|
||||
offset = bedTempOffset
|
||||
else:
|
||||
# unknown, should never happen
|
||||
offset = 0
|
||||
|
||||
if not offset == 0:
|
||||
# if we have an offset != 0, we need to get the temperature to be set and apply the offset to it
|
||||
tempValueMatch = self._tempCommandTemperaturePattern.search(line)
|
||||
if tempValueMatch is not None:
|
||||
try:
|
||||
temp = float(tempValueMatch.group(1))
|
||||
if temp > 0:
|
||||
newTemp = temp + offset
|
||||
line = line.replace("S" + tempValueMatch.group(1), "S%f" % newTemp)
|
||||
except ValueError:
|
||||
pass
|
||||
return line
|
||||
else:
|
||||
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,103 @@
|
||||
# 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"
|
||||
|
||||
|
||||
class Transport(object):
|
||||
|
||||
def __init__(self, messageReceiver=None, stateReceiver=None, logReceiver=None):
|
||||
self._messageReceiver = messageReceiver
|
||||
self._stateReceiver = stateReceiver
|
||||
self._logReceiver = logReceiver
|
||||
self._state = State.DISCONNECTED
|
||||
self._error = None
|
||||
|
||||
def getProperties(self):
|
||||
raise NotImplemented()
|
||||
|
||||
def connect(self, opt):
|
||||
pass
|
||||
|
||||
def disconnect(self, onError=False):
|
||||
if onError:
|
||||
self.changeState(State.DISCONNECTED_WITH_ERROR)
|
||||
else:
|
||||
self.changeState(State.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,132 @@
|
||||
# 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 threading
|
||||
import serial
|
||||
|
||||
from . import Transport, TransportProperties, State
|
||||
from octoprint.util import getExceptionString
|
||||
from octoprint.util.virtual import VirtualPrinter
|
||||
|
||||
|
||||
class SerialTransport(Transport):
|
||||
|
||||
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._timeoutCounter = 0
|
||||
self._maxTimeouts = 20
|
||||
|
||||
self._thread = None
|
||||
|
||||
def getProperties(self):
|
||||
return {
|
||||
TransportProperties.FLOWCONTROL: False
|
||||
}
|
||||
|
||||
def 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
|
||||
self._communicationTimeout = opt["communicationTimeout"] if "communicationTimeout" in opt else 5.0
|
||||
self._writeTimeout = opt["writeTimeout"] if "writeTimeout" in opt else 10000
|
||||
|
||||
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:
|
||||
self._serial.close()
|
||||
finally:
|
||||
self._serial = None
|
||||
self._thread = None
|
||||
Transport.disconnect(self, onError)
|
||||
|
||||
def send(self, command):
|
||||
self.logTx(command)
|
||||
|
||||
commandToSend = command + "\n"
|
||||
try:
|
||||
self._serial.write(commandToSend)
|
||||
except serial.SerialTimeoutException:
|
||||
self.logError("Serial timeout while writing to serial port, trying again.")
|
||||
|
||||
try:
|
||||
self._serial.write(commandToSend)
|
||||
except:
|
||||
exceptionString = getExceptionString()
|
||||
self.logError("Unexpected error while writing serial port: %s" % exceptionString)
|
||||
self.onError(exceptionString)
|
||||
self.disconnect(True)
|
||||
except:
|
||||
exceptionString = getExceptionString()
|
||||
self.logError("Unexpected error while writing serial port: %s" % exceptionString)
|
||||
self.onError(exceptionString)
|
||||
self.disconnect(True)
|
||||
|
||||
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.logError(error)
|
||||
# TODO further error handling
|
||||
|
||||
def _connect(self):
|
||||
self.changeState(State.OPENING_CONNECTION)
|
||||
try:
|
||||
self._serial = serial.Serial(self._port, self._baudrate, timeout=self._communicationTimeout, writeTimeout=self._writeTimeout)
|
||||
return True
|
||||
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
|
||||
|
||||
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 != "":
|
||||
self.logRx(unicode(line, "ascii", "replace").encode("ascii", "replace").rstrip())
|
||||
return line
|
||||
|
||||
|
||||
class VirtualSerialTransport(SerialTransport):
|
||||
def _connect(self):
|
||||
self.changeState(State.OPENING_CONNECTION)
|
||||
self._serial = VirtualPrinter()
|
||||
self.changeState(State.CONNECTED)
|
||||
return True
|
||||
@@ -143,7 +143,13 @@ default_settings = {
|
||||
"forceChecksum": False,
|
||||
"okWithLinenumber": False,
|
||||
"numExtruders": 1,
|
||||
"includeCurrentToolInTemps": True
|
||||
"includeCurrentToolInTemps": True,
|
||||
"movementSpeed": {
|
||||
"x": 6000,
|
||||
"y": 6000,
|
||||
"z": 200,
|
||||
"e": 300
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import os, struct, sys, time
|
||||
|
||||
from serial import Serial
|
||||
|
||||
import chipDB
|
||||
|
||||
class IspBase():
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import os, struct, sys, time
|
||||
|
||||
from serial import Serial
|
||||
from serial import SerialException
|
||||
from serial import SerialException, SerialTimeoutException
|
||||
|
||||
import ispBase, intelHex
|
||||
|
||||
|
||||
+136
-10
@@ -14,13 +14,22 @@ from octoprint.settings import settings
|
||||
|
||||
class VirtualPrinter():
|
||||
def __init__(self):
|
||||
self.readList = ['start\n', 'Marlin: Virtual Marlin!\n', '\x80\n', 'SD init fail\n'] # no sd card as default startup scenario
|
||||
self.readList = ['start\n', 'Marlin: Virtual Marlin!\n', '\x80\n', 'SD card ok\n'] # no sd card as default startup scenario
|
||||
self.currentExtruder = 0
|
||||
self.temp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
|
||||
self.targetTemp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
|
||||
self.lastTempAt = time.time()
|
||||
self.bedTemp = 1.0
|
||||
self.bedTargetTemp = 1.0
|
||||
self.speeds = settings().get(["devel", "virtualPrinter", "movementSpeed"])
|
||||
|
||||
self._relative = True
|
||||
self._lastX = None
|
||||
self._lastY = None
|
||||
self._lastZ = None
|
||||
self._lastE = None
|
||||
|
||||
self._unitModifier = 1
|
||||
|
||||
self._virtualSd = settings().getBaseFolder("virtualSd")
|
||||
self._sdCardReady = False
|
||||
@@ -58,6 +67,7 @@ class VirtualPrinter():
|
||||
linenumber = int(re.search("N([0-9]+)", data).group(1))
|
||||
self.lastN = linenumber
|
||||
self.currentLine = linenumber
|
||||
self.readList.append("ok")
|
||||
return
|
||||
elif data.startswith("N"):
|
||||
linenumber = int(re.search("N([0-9]+)", data).group(1))
|
||||
@@ -68,14 +78,14 @@ class VirtualPrinter():
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "okAfterResend"]):
|
||||
self.readList.append("ok")
|
||||
return
|
||||
elif self.currentLine == 100:
|
||||
# simulate a resend at line 100 of the last 5 lines
|
||||
self.lastN = 94
|
||||
self.readList.append("Error: Line Number is not Last Line Number\n")
|
||||
self.readList.append("rs %d\n" % (self.currentLine - 5))
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "okAfterResend"]):
|
||||
self.readList.append("ok")
|
||||
return
|
||||
# elif self.currentLine == 100:
|
||||
# # simulate a resend at line 100 of the last 5 lines
|
||||
# self.lastN = 94
|
||||
# self.readList.append("Error: Line Number is not Last Line Number\n")
|
||||
# self.readList.append("rs %d\n" % (self.currentLine - 5))
|
||||
# if settings().getBoolean(["devel", "virtualPrinter", "okAfterResend"]):
|
||||
# self.readList.append("ok")
|
||||
# return
|
||||
else:
|
||||
self.lastN = linenumber
|
||||
data = data.split(None, 1)[1].strip()
|
||||
@@ -159,6 +169,41 @@ class VirtualPrinter():
|
||||
self.currentExtruder = int(re.search("T(\d+)", data).group(1))
|
||||
self._sendOk()
|
||||
self.readList.append("Active Extruder: %d" % self.currentExtruder)
|
||||
elif "G20" in data:
|
||||
self._unitModifier = 1.0 / 2.54
|
||||
if self._lastX is not None:
|
||||
self._lastX *= 2.54
|
||||
if self._lastY is not None:
|
||||
self._lastY *= 2.54
|
||||
if self._lastZ is not None:
|
||||
self._lastZ *= 2.54
|
||||
if self._lastE is not None:
|
||||
self._lastE *= 2.54
|
||||
self._sendOk()
|
||||
elif "G21" in data:
|
||||
self._unitModifier = 1.0
|
||||
if self._lastX is not None:
|
||||
self._lastX /= 2.54
|
||||
if self._lastY is not None:
|
||||
self._lastY /= 2.54
|
||||
if self._lastZ is not None:
|
||||
self._lastZ /= 2.54
|
||||
if self._lastE is not None:
|
||||
self._lastE /= 2.54
|
||||
self._sendOk()
|
||||
elif "G90" in data:
|
||||
self._relative = False
|
||||
self._sendOk()
|
||||
elif "G91" in data:
|
||||
self._relative = True
|
||||
self._sendOk()
|
||||
elif "G92" in data:
|
||||
self._setPosition(data)
|
||||
self._sendOk()
|
||||
elif "G0" in data or "G1" in data:
|
||||
# simulate movement duration -- no acceleration, only linear movement duration based on max speed
|
||||
self._performMove(data)
|
||||
self._sendOk()
|
||||
elif len(data.strip()) > 0:
|
||||
self._sendOk()
|
||||
|
||||
@@ -235,6 +280,87 @@ class VirtualPrinter():
|
||||
return False
|
||||
return True
|
||||
|
||||
def _performMove(self, line):
|
||||
matchX = re.search("X([0-9.]+)", line)
|
||||
matchY = re.search("Y([0-9.]+)", line)
|
||||
matchZ = re.search("Z([0-9.]+)", line)
|
||||
matchE = re.search("E([0-9.]+)", line)
|
||||
|
||||
duration = 0
|
||||
if matchX is not None:
|
||||
try:
|
||||
x = float(matchX.group(1))
|
||||
if self._relative or self._lastX is None:
|
||||
duration = max(duration, x * self._unitModifier / float(self.speeds["x"]) * 60.0)
|
||||
else:
|
||||
duration = max(duration, (x - self._lastX) * self._unitModifier / float(self.speeds["x"]) * 60.0)
|
||||
self._lastX = x
|
||||
except:
|
||||
pass
|
||||
if matchY is not None:
|
||||
try:
|
||||
y = float(matchY.group(1))
|
||||
if self._relative or self._lastY is None:
|
||||
duration = max(duration, y * self._unitModifier / float(self.speeds["y"]) * 60.0)
|
||||
else:
|
||||
duration = max(duration, (y - self._lastY) * self._unitModifier / float(self.speeds["y"]) * 60.0)
|
||||
self._lastY = y
|
||||
except:
|
||||
pass
|
||||
if matchZ is not None:
|
||||
try:
|
||||
z = float(matchZ.group(1))
|
||||
if self._relative or self._lastZ is None:
|
||||
duration = max(duration, z * self._unitModifier / float(self.speeds["z"]) * 60.0)
|
||||
else:
|
||||
duration = max(duration, (z - self._lastZ) * self._unitModifier / float(self.speeds["z"]) * 60.0)
|
||||
self._lastZ = z
|
||||
except:
|
||||
pass
|
||||
if matchE is not None:
|
||||
try:
|
||||
e = float(matchE.group(1))
|
||||
if self._relative or self._lastE is None:
|
||||
duration = max(duration, e * self._unitModifier / float(self.speeds["e"]) * 60.0)
|
||||
else:
|
||||
duration = max(duration, (e - self._lastE) * self._unitModifier / float(self.speeds["e"]) * 60.0)
|
||||
self._lastE = e
|
||||
except:
|
||||
pass
|
||||
|
||||
if duration:
|
||||
time.sleep(duration)
|
||||
|
||||
def _setPosition(self, line):
|
||||
matchX = re.search("X([0-9.]+)", line)
|
||||
matchY = re.search("Y([0-9.]+)", line)
|
||||
matchZ = re.search("Z([0-9.]+)", line)
|
||||
matchE = re.search("E([0-9.]+)", line)
|
||||
|
||||
if matchX is None and matchY is None and matchZ is None and matchE is None:
|
||||
self._lastX = self._lastY = self._lastZ = self._lastE = 0
|
||||
else:
|
||||
if matchX is not None:
|
||||
try:
|
||||
self._lastX = float(matchX.group(1))
|
||||
except:
|
||||
pass
|
||||
if matchY is not None:
|
||||
try:
|
||||
self._lastY = float(matchY.group(1))
|
||||
except:
|
||||
pass
|
||||
if matchZ is not None:
|
||||
try:
|
||||
self._lastZ = float(matchZ.group(1))
|
||||
except:
|
||||
pass
|
||||
if matchE is not None:
|
||||
try:
|
||||
self._lastE = float(matchE.group(1))
|
||||
except:
|
||||
pass
|
||||
|
||||
def _writeSdFile(self, filename):
|
||||
file = os.path.join(self._virtualSd, filename).lower()
|
||||
if os.path.exists(file):
|
||||
@@ -336,7 +462,7 @@ class VirtualPrinter():
|
||||
return ''
|
||||
if self.readList is None:
|
||||
return ''
|
||||
time.sleep(0.001)
|
||||
#time.sleep(0.001)
|
||||
return self.readList.pop(0)
|
||||
|
||||
def close(self):
|
||||
|
||||
Reference in new issue
Block a user