diff --git a/src/octoprint/comm/protocol/__init__.py b/src/octoprint/comm/protocol/__init__.py index dd7e09a3c..ee47b5db0 100644 --- a/src/octoprint/comm/protocol/__init__.py +++ b/src/octoprint/comm/protocol/__init__.py @@ -57,8 +57,8 @@ class Protocol(MessageReceiver, StateReceiver, LogReceiver): ##~~ public - def connect(self, opt): - self._transport.connect(opt) + def connect(self, protocol_options, transport_options): + self._transport.connect(transport_options) def disconnect(self, on_error=False): if self.is_printing(): diff --git a/src/octoprint/comm/protocol/repetier.py b/src/octoprint/comm/protocol/repetier.py index 3cd626766..2bb9bff10 100644 --- a/src/octoprint/comm/protocol/repetier.py +++ b/src/octoprint/comm/protocol/repetier.py @@ -22,7 +22,8 @@ class RepetierTextualProtocol(RepRapProtocol): RepRapProtocol.__init__(self, transport_factory, protocol_listener) self._sd_available = True - def _reset(self): + def _reset(self, from_start=False): + RepRapProtocol._reset(self, from_start=from_start) self._sd_available = True def _evaluate_firmware_specific_messages(self, source, message): @@ -55,6 +56,3 @@ class RepetierTextualProtocol(RepRapProtocol): self._updateTemperature(current_temperatures) return True - - def _useChecksum(self): - return True \ No newline at end of file diff --git a/src/octoprint/comm/protocol/reprap/__init__.py b/src/octoprint/comm/protocol/reprap/__init__.py index 5e4cceb94..d4c79f4ef 100644 --- a/src/octoprint/comm/protocol/reprap/__init__.py +++ b/src/octoprint/comm/protocol/reprap/__init__.py @@ -126,8 +126,14 @@ class RepRapProtocol(Protocol): self._clear_for_send = threading.Event() self._clear_for_send.clear() - self._force_checksum = settings().getBoolean(["feature", "alwaysSendChecksum"]) - self._rx_cache_size = settings().getInt(["communication", "protocolOptions", "buffer"]) + self._force_checksum = True + self._wait_for_start = False + self._sd_always_available = False + self._rx_cache_size = 0 + + self._temperature_interval = 5.0 + self._sdstatus_interval = 5.0 + self._nack_lines = deque([]) self._nack_lock = threading.RLock() @@ -158,7 +164,7 @@ class RepRapProtocol(Protocol): self._lastTemperatureUpdate = time.time() self._lastSdProgressUpdate = time.time() - if settings().getBoolean(["feature", "waitForStartOnConnect"]): + if self._wait_for_start: self._startSeen = from_start else: self._startSeen = True @@ -187,17 +193,24 @@ class RepRapProtocol(Protocol): self._current_resend_count = 0 self._nacks_before_resend = 0 - def connect(self, opt): + def connect(self, protocol_options, transport_options): + self._wait_for_start = protocol_options["waitForStart"] if "waitForStart" in protocol_options else False + self._force_checksum = protocol_options["checksum"] if "checksum" in protocol_options else True + self._sd_always_available = protocol_options["sdAlwaysAvailable"] if "sdAlwaysAvailable" in protocol_options else False + self._rx_cache_size = protocol_options["buffer"] if "buffer" in protocol_options else 0 + self._temperature_interval = protocol_options["timeout"]["temperature"] if "timeout" in protocol_options and "temperature" in protocol_options["timeout"] else 5.0 + self._sdstatus_interval = protocol_options["timeout"]["sdstatus"] if "timeout" in protocol_options and "sdstatus" in protocol_options["timeout"] else 5.0 + self._reset() # connect - Protocol.connect(self, opt) + Protocol.connect(self, protocol_options, transport_options) # we'll send an M110 first to reset line numbers to 0 - self._send(RepRapProtocol.COMMAND_SET_LINE(0), highPriority=True) + self._send(RepRapProtocol.COMMAND_SET_LINE(0), high_priority=True) # enqueue our first temperature query so it gets sent right on establishment of the connection - self._send_temperature_query(withType=True) + self._send_temperature_query(with_type=True) def disconnect(self, on_error=False): self._clear_for_send.clear() @@ -208,7 +221,7 @@ class RepRapProtocol(Protocol): if origin == FileDestinations.SDCARD: if not self._sd_available: return - self._send(RepRapProtocol.COMMAND_SD_SELECT_FILE(filename), highPriority=True) + self._send(RepRapProtocol.COMMAND_SD_SELECT_FILE(filename), high_priority=True) else: self._selectFile(PrintingGcodeFileInformation(filename, self.get_temperature_offsets)) @@ -232,13 +245,13 @@ class RepRapProtocol(Protocol): def init_sd(self): Protocol.init_sd(self) self._send(RepRapProtocol.COMMAND_SD_INIT()) - if settings().getBoolean(["feature", "sdAlwaysAvailable"]) == True: + if self._sd_always_available: self._changeSdState(True) def release_sd(self): Protocol.release_sd(self) self._send(RepRapProtocol.COMMAND_SD_RELEASE()) - if settings().getBoolean(["feature", "sdAlwaysAvailable"]) == True: + if self._sd_always_available: self._changeSdState(False) def refresh_sd_files(self): @@ -328,9 +341,9 @@ class RepRapProtocol(Protocol): return if isinstance(command, (tuple, list)): for c in command: - self._send(c, highPriority=high_priority) + self._send(c, high_priority=high_priority) else: - self._send(command, highPriority=high_priority) + self._send(command, high_priority=high_priority) def _fileTransferFinished(self, current_file): if isinstance(current_file, StreamingGcodeFileInformation): @@ -442,10 +455,10 @@ class RepRapProtocol(Protocol): self._reset(from_start=True) if not self.is_streaming(): - if time.time() > self._lastTemperatureUpdate + 5: - self._send_temperature_query(withType=True) - elif self.is_sd_printing() and time.time() > self._lastSdProgressUpdate + 5: - self._send_sd_progress_query(withType=True) + if time.time() > self._lastTemperatureUpdate + self._temperature_interval: + self._send_temperature_query(with_type=True) + elif self.is_sd_printing() and time.time() > self._lastSdProgressUpdate + self._sdstatus_interval: + self._send_sd_progress_query(with_type=True) # ok == go ahead with sending if RepRapProtocol.MESSAGE_OK(message): @@ -484,7 +497,7 @@ class RepRapProtocol(Protocol): def _evaluate_firmware_specific_messages(self, source, message): return True - def _send(self, command, highPriority=False, commandType=None, with_progress=None): + def _send(self, command, high_priority=False, command_type=None, with_progress=None): if command is None: return @@ -497,10 +510,10 @@ class RepRapProtocol(Protocol): try: self._send_queue.put(CommandQueueEntry( - CommandQueueEntry.PRIORITY_HIGH if highPriority else CommandQueueEntry.PRIORITY_NORMAL, + CommandQueueEntry.PRIORITY_HIGH if high_priority else CommandQueueEntry.PRIORITY_NORMAL, command, line_number=with_line_number, - command_type=commandType, + command_type=command_type, progress=with_progress) ) except TypeAlreadyInQueue: @@ -519,18 +532,12 @@ class RepRapProtocol(Protocol): self._send(command, with_progress=dict(completion=self._getPrintCompletion(), filepos=self._getPrintFilepos())) - def _send_temperature_query(self, withType=False): - if withType: - self._send(RepRapProtocol.COMMAND_GET_TEMP(), commandType=RepRapProtocol.COMMAND_TYPE_TEMPERATURE) - else: - self._send(RepRapProtocol.COMMAND_GET_TEMP()) + def _send_temperature_query(self, with_high_priority=False, with_type=False): + self._send(RepRapProtocol.COMMAND_GET_TEMP(), high_priority=with_high_priority, command_type=RepRapProtocol.COMMAND_TYPE_TEMPERATURE if with_type else None) self._lastTemperatureUpdate = time.time() - def _send_sd_progress_query(self, withType=False): - if withType: - self._send(RepRapProtocol.COMMAND_SD_STATUS(), commandType=RepRapProtocol.COMMAND_TYPE_SD_PROGRESS) - else: - self._send(RepRapProtocol.COMMAND_SD_STATUS()) + def _send_sd_progress_query(self, with_high_priority=False, with_type=False): + self._send(RepRapProtocol.COMMAND_SD_STATUS(), high_priority=with_high_priority, command_type=RepRapProtocol.COMMAND_TYPE_SD_PROGRESS if with_type else None) self._lastSdProgressUpdate = time.time() def _handle_errors(self, line): diff --git a/src/octoprint/comm/transport/serialTransport.py b/src/octoprint/comm/transport/serialTransport.py index d2df6b1da..672126ceb 100644 --- a/src/octoprint/comm/transport/serialTransport.py +++ b/src/octoprint/comm/transport/serialTransport.py @@ -31,6 +31,7 @@ class SerialTransport(Transport): self._baudrate = None self._connectionTimeout = None self._writeTimeout = None + self._readTimeout = None self._timeoutCounter = 0 self._maxTimeouts = 20 @@ -53,9 +54,9 @@ class SerialTransport(Transport): 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 500 + + self._readTimeout = opt["timeout"]["read"] if "timeout" in opt and "read" in opt["timeout"] else 5.0 + self._writeTimeout = opt["timeout"]["write"] if "timeout" in opt and "write" in opt["timeout"] else 0.5 if self._connect(): self._thread = threading.Thread(target=self._monitor, name="SerialTransportMonitor") @@ -117,12 +118,12 @@ class SerialTransport(Transport): def _connect(self): self.changeState(State.OPENING_CONNECTION) if self._port == "VIRTUAL": - self._serial = VirtualPrinter(timeout=self._communicationTimeout, writeTimeout=self._writeTimeout) + self._serial = VirtualPrinter(read_timeout=self._readTimeout, write_timeout=self._writeTimeout) self.changeState(State.CONNECTED) - self._transport_logger.debug("Connected to VIRTUAL printer") + self._transport_logger.debug("Connected to %s" % self._serial) else: try: - self._serial = serial.Serial(self._port, self._baudrate, timeout=self._communicationTimeout, writeTimeout=self._writeTimeout) + self._serial = serial.Serial(self._port, self._baudrate, timeout=self._readTimeout, writeTimeout=self._writeTimeout) self.changeState(State.CONNECTED) self._transport_logger.debug("Connected to %s" % self._serial) except: diff --git a/src/octoprint/printer.py b/src/octoprint/printer.py index e242ea39f..bfbae49e4 100644 --- a/src/octoprint/printer.py +++ b/src/octoprint/printer.py @@ -323,13 +323,22 @@ class Printer(): #~~ printer commands - def connect(self, port=None, baudrate=None): + def connect(self, protocol_option_overrides=None, transport_option_overrides=None): """ Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection will be attempted. """ self._protocol.disconnect() - self._protocol.connect({"port": port, "baudrate": baudrate}) + + protocol_options = settings().get(["communication", "protocolOptions"], merged=True) + if protocol_option_overrides is not None and isinstance(protocol_option_overrides, dict): + protocol_options = util.dict_merge(protocol_options, protocol_option_overrides) + + transport_options = settings().get(["communication", "transportOptions"], merged=True) + if transport_option_overrides is not None and isinstance(transport_option_overrides, dict): + transport_options = util.dict_merge(transport_options, transport_option_overrides) + + self._protocol.connect(protocol_options, transport_options) def disconnect(self): """ diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index d017ecd01..85c05a903 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -319,7 +319,7 @@ class Server(): (port, baudrate) = settings().get(["serial", "port"]), settings().getInt(["serial", "baudrate"]) connectionOptions = getConnectionOptions() if port in connectionOptions["ports"]: - printer.connect(port, baudrate) + printer.connect(transport_option_overrides=dict(port=port, baudrate=baudrate)) # start up watchdogs observer = Observer() diff --git a/src/octoprint/server/api/connection.py b/src/octoprint/server/api/connection.py index f947e8601..4cb886869 100644 --- a/src/octoprint/server/api/connection.py +++ b/src/octoprint/server/api/connection.py @@ -57,7 +57,7 @@ def connectionCommand(): if "autoconnect" in data.keys(): settings().setBoolean(["serial", "autoconnect"], data["autoconnect"]) settings().save() - printer.connect(port=port, baudrate=baudrate) + printer.connect(transport_option_overrides=dict(port=port, baudrate=baudrate)) elif command == "disconnect": printer.disconnect() diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 56ec32536..f80dd4471 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -26,24 +26,27 @@ default_settings = { "communication": { "protocol": "reprap", "protocolOptions": { - "buffer": 0 + "buffer": 0, + "temperature": 5, + "sdStatus": 1, + "waitForStart": False, + "forceChecksum": True, + "sdAlwaysAvailable": False }, "transport": "serial", "transportOptions": { "port": None, "baudrate": None, "timeout": { - "detection": 0.5, - "connection": 2, - "communication": 5, - "temperature": 5, - "sdStatus": 1 + "read": 5, + "write": 0.5 }, "additionalPorts": [] }, "autoconnect": False, "log": False }, + # TODO Remove, not used by the new communication layer but apparently still by the layers above it! "serial": { "port": None, "baudrate": None, @@ -100,12 +103,12 @@ default_settings = { }, "feature": { "temperatureGraph": True, - "waitForStartOnConnect": False, - "alwaysSendChecksum": True, - "sdSupport": True, - "sdAlwaysAvailable": False, - "swallowOkAfterResend": True, - "repetierTargetTemp": False + "waitForStartOnConnect": False, # TODO move to protocol options or reprap protocol + "alwaysSendChecksum": True, # TODO move to protocol options + "sdSupport": True, # TODO remove (can be always on) + "sdAlwaysAvailable": False, # TODO move to protocol options + "swallowOkAfterResend": True, # TODO remove (must always be done!) + "repetierTargetTemp": False # TODO remove (built into repetier protocol implementation) }, "folder": { "uploads": None, @@ -471,7 +474,9 @@ class Settings(object): #~~ getter - def get(self, path, asdict=False, defaults=None): + def get(self, path, asdict=False, defaults=None, merged=False): + import octoprint.util as util + if len(path) == 0: return None @@ -503,6 +508,8 @@ class Settings(object): for key in keys: if key in config.keys(): value = config[key] + if merged and key in defaults: + value = util.dict_merge(defaults[key], value) elif key in defaults: value = defaults[key] else: diff --git a/src/octoprint/util/virtual.py b/src/octoprint/util/virtual.py index 80188020b..abb2e03c7 100644 --- a/src/octoprint/util/virtual.py +++ b/src/octoprint/util/virtual.py @@ -16,9 +16,9 @@ from serial import SerialTimeoutException from octoprint.settings import settings class VirtualPrinter(): - def __init__(self, timeout=5.0, writeTimeout=10.0): - self._timeout = timeout - self._writeTimeout = writeTimeout + def __init__(self, read_timeout=5.0, write_timeout=10.0): + self._read_timeout = read_timeout + self._write_timeout = write_timeout self.incoming = CharCountingQueue(settings().getInt(["devel", "virtualPrinter", "rxBuffer"]), name="RxBuffer") self.outgoing = Queue.Queue() @@ -68,6 +68,10 @@ class VirtualPrinter(): bufferThread = threading.Thread(target=self._processBuffer) bufferThread.start() + def __str__(self): + return "VIRTUAL(read_timeout={read_timeout},write_timeout={write_timeout},options={options})"\ + .format(read_timeout=self._read_timeout, write_timeout=self._write_timeout, options=settings().get(["devel", "virtualPrinter"])) + def _clearQueue(self, queue): try: while queue.get(block=False): @@ -401,10 +405,10 @@ class VirtualPrinter(): if duration: if settings().getBoolean(["devel", "virtualPrinter", "waitOnLongMoves"]): slept = 0 - while duration - slept > self._timeout: - time.sleep(self._timeout) + while duration - slept > self._read_timeout: + time.sleep(self._read_timeout) self.outgoing.put("wait") - slept += self._timeout + slept += self._read_timeout else: time.sleep(duration) @@ -539,13 +543,13 @@ class VirtualPrinter(): if self.incoming is None or self.outgoing is None: return try: - self.incoming.put(data, timeout=self._writeTimeout) + self.incoming.put(data, timeout=self._write_timeout) except Queue.Full: raise SerialTimeoutException() def readline(self): try: - line = self.outgoing.get(timeout=self._timeout) + line = self.outgoing.get(timeout=self._read_timeout) time.sleep(settings().getFloat(["devel", "virtualPrinter", "throttle"])) return line except Queue.Empty: