Protocol and Transport classes are now detected automatically and the one to use can be specified by config, also made standard control commands part of the protocol interface

This commit is contained in:
Gina Häußge committed 2014-07-24 14:24:04 +02:00
1 parent fa586426fa
commit 8c8059db30
6 files changed
+145 -37

No files matched your search

+1
View File
@@ -10,6 +10,7 @@ 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):
+2
View File
@@ -10,6 +10,8 @@ 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)
REGEX_POSITIVE_FLOAT = "[+]?[0-9]*\.?[0-9]+"
+65 -4
View File
@@ -18,10 +18,13 @@ from octoprint.comm.transport import TransportProperties
from octoprint.filemanager.destinations import FileDestinations
from octoprint.gcodefiles import isGcodeFileName
from octoprint.comm.transport.serialTransport import SerialTransport
from octoprint.settings import settings
class RepRapProtocol(Protocol):
__protocolinfo__ = ("reprap", "RepRap", False)
## Firmware messages
MESSAGE_OK = staticmethod(lambda line: line.startswith("ok"))
MESSAGE_START = staticmethod(lambda line: line.startswith("start"))
@@ -55,8 +58,13 @@ class RepRapProtocol(Protocol):
## Commands
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_EXTRUDER_TEMP = staticmethod(lambda s, t, w: GcodeCommand("M109", s=s, t=t) if w else GcodeCommand("M104", s=s, t=t))
COMMAND_SET_BED_TEMP = staticmethod(lambda s, w: GcodeCommand("M190", s=s) if w else GcodeCommand("M140", s=s))
COMMAND_SET_RELATIVE_POSITIONING = staticmethod(lambda: GcodeCommand("G91"))
COMMAND_SET_ABSOLUTE_POSITIONING = staticmethod(lambda: GcodeCommand("G90"))
COMMAND_MOVE_AXIS = staticmethod(lambda axis, amount, speed: GcodeCommand("G1", x=amount if axis=='x' else None, y=amount if axis=='y' else None, z=amount if axis=='z' else None, f=speed))
COMMAND_EXTRUDE = staticmethod(lambda amount, speed: GcodeCommand("G1", e=amount, f=speed))
COMMAND_HOME_AXIS = staticmethod(lambda x, y, z: GcodeCommand("G28", x=0 if x else None, y=0 if y else None, z=0 if z else None))
COMMAND_SET_TOOL = staticmethod(lambda t: GcodeCommand("T%d" % t))
COMMAND_SD_REFRESH = staticmethod(lambda: GcodeCommand("M20"))
COMMAND_SD_INIT = staticmethod(lambda: GcodeCommand("M21"))
@@ -224,10 +232,63 @@ class RepRapProtocol(Protocol):
self.send_manually(RepRapProtocol.COMMAND_SD_DELETE(filename))
self.refresh_sd_files()
def set_temperature(self, type, value):
if type.startswith("tool"):
if settings().getInt(["printerParameters", "numExtruders"]) > 1:
try:
tool_num = int(type[len("tool"):])
self.send_manually(RepRapProtocol.COMMAND_SET_EXTRUDER_TEMP(value, tool_num, False))
except ValueError:
pass
else:
# set temperature without tool number
self.send_manually(RepRapProtocol.COMMAND_SET_EXTRUDER_TEMP(value, None, False))
elif type == "bed":
self.send_manually(RepRapProtocol.COMMAND_SET_BED_TEMP(value, False))
def jog(self, axis, amount):
speeds = settings().get(["printerParameters", "movementSpeed", ["x", "y", "z"]], asdict=True)
commands = (
RepRapProtocol.COMMAND_SET_RELATIVE_POSITIONING(),
RepRapProtocol.COMMAND_MOVE_AXIS(axis, amount, speeds[axis]),
RepRapProtocol.COMMAND_SET_ABSOLUTE_POSITIONING()
)
self.send_manually(commands)
def home(self, axes):
commands = (
RepRapProtocol.COMMAND_SET_RELATIVE_POSITIONING(),
RepRapProtocol.COMMAND_HOME_AXIS('x' in axes, 'y' in axes, 'z' in axes),
RepRapProtocol.COMMAND_SET_ABSOLUTE_POSITIONING()
)
self.send_manually(commands)
def extrude(self, amount):
extrusionSpeed = settings().get(["printerParameters", "movementSpeed", "e"])
commands = (
RepRapProtocol.COMMAND_SET_RELATIVE_POSITIONING(),
RepRapProtocol.COMMAND_EXTRUDE(amount, extrusionSpeed),
RepRapProtocol.COMMAND_SET_ABSOLUTE_POSITIONING()
)
self.send_manually(commands)
def change_tool(self, tool):
try:
tool_num = int(tool[len("tool"):])
self.send_manually(RepRapProtocol.COMMAND_SET_TOOL(tool_num))
except ValueError:
pass
def send_manually(self, command, high_priority=False):
if self.is_streaming():
return
self._send(command, highPriority=high_priority, withChecksum=self._useChecksum())
if isinstance(command, (tuple, list)):
for c in command:
self._send(c, highPriority=high_priority, withChecksum=self._useChecksum())
else:
self._send(command, highPriority=high_priority, withChecksum=self._useChecksum())
def _fileTransferFinished(self, current_file):
if isinstance(current_file, StreamingGcodeFileInformation):
@@ -508,7 +569,7 @@ class RepRapProtocol(Protocol):
self._resend_delta = None
def _useChecksum(self):
return not self._transport_properties[TransportProperties.FLOWCONTROL] and self.is_busy()
return settings().getBoolean(["feature", "alwaysSendChecksum"]) or (not self._transport_properties[TransportProperties.FLOWCONTROL] and self.is_busy())
##~~ specific command actions
@@ -21,6 +21,8 @@ from octoprint.settings import settings
class SerialTransport(Transport):
__transportinfo__ = ("serial", "Serial", False)
def __init__(self, messageReceiver, stateReceiver, logReceiver):
Transport.__init__(self, messageReceiver, stateReceiver, logReceiver)
+56 -33
View File
@@ -1,4 +1,7 @@
# coding=utf-8
from octoprint.comm.protocol.repetier import RepetierTextualProtocol
from octoprint.comm.transport import Transport
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
@@ -18,7 +21,7 @@ from octoprint.events import eventManager, Events
from octoprint.filemanager.destinations import FileDestinations
from octoprint.comm.protocol import State as ProtocolState
from octoprint.comm.protocol import State as ProtocolState, Protocol
from octoprint.comm.protocol.reprap import RepRapProtocol
from octoprint.comm.transport.serialTransport import SerialTransport
@@ -74,7 +77,7 @@ class Printer():
# comm
self._comm = None
self._protocol = RepRapProtocol(SerialTransport, protocol_listener=self)
self._protocol = self._createProtocol()
# callbacks
self._callbacks = []
@@ -106,7 +109,50 @@ class Printer():
currentZ=None
)
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished);
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished)
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
@@ -313,48 +359,25 @@ class Printer():
}
def command(self, command):
"""
Sends a single gcode command to the printer.
"""
self.commands([command])
self._protocol.send_manually(command)
def commands(self, commands):
"""
Sends multiple gcode commands (provided as a list) to the printer.
"""
for command in commands:
self._protocol.send_manually(command)
self.command(commands)
def jog(self, axis, amount):
movementSpeed = settings().get(["printerParameters", "movementSpeed", ["x", "y", "z"]], asdict=True)
self.commands(["G91", "G1 %s%.4f F%d" % (axis.upper(), amount, movementSpeed[axis]), "G90"])
self._protocol.jog(axis, amount)
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):
extrusionSpeed = settings().get(["printerParameters", "movementSpeed", "e"])
self.commands(["G91", "G1 E%s F%d" % (amount, extrusionSpeed), "G90"])
self._protocol.extrude(amount)
def changeTool(self, tool):
try:
toolNum = int(tool[len("tool"):])
self.command("T%d" % toolNum)
except ValueError:
pass
self._protocol.change_tool(tool)
def setTemperature(self, type, value):
if type.startswith("tool"):
if settings().getInt(["printerParameters", "numExtruders"]) > 1:
try:
toolNum = int(type[len("tool"):])
self.command("M104 T%d S%f" % (toolNum, value))
except ValueError:
pass
else:
self.command("M104 S%f" % value)
elif type == "bed":
self.command("M140 S%f" % value)
self._protocol.set_temperature(type, value)
def setTemperatureOffset(self, offsets):
current_offsets = self._protocol.get_temperature_offsets()
+19
View File
@@ -23,6 +23,25 @@ def settings(init=False, configfile=None, basedir=None):
return instance
default_settings = {
"communication": {
"protocol": "reprap",
"protocolOptions": {},
"transport": "serial",
"transportOptions": {
"port": None,
"baudrate": None,
"timeout": {
"detection": 0.5,
"connection": 2,
"communication": 5,
"temperature": 5,
"sdStatus": 1
},
"additionalPorts": []
},
"autoconnect": False,
"log": False
},
"serial": {
"port": None,
"baudrate": None,