♻️ Rewrite port/baudrate detection

Now they no longer are separate processes but one merged one.

Port detection now will only test the two most common baudrates plus
any additionally configured ones if there is more than one port to test,
that way the additional overhead of having to cycle through both port
and baudrate should be greatly reduced.

As a consequence all avr_isp references have been finally removed.

Closes #3394
This commit is contained in:
Gina Häußge committed 2020-06-04 15:45:00 +02:00
1 parent a2c38dbc12
commit 2570b296ca
9 files changed
+129 -405

No files matched your search

@@ -25,16 +25,12 @@ SETTINGS_DEFAULTS = dict(enabled=False,
import serial
import requests.exceptions
import errno
import octoprint.util.avr_isp.ispBase
import tornado.websocket
IGNORED_EXCEPTIONS = [
# serial exceptions in octoprint.util.comm
(serial.SerialException, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"),
# isp errors during port auto detection in octoprint.util.comm
(octoprint.util.avr_isp.ispBase.IspError, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"),
# IOErrors of any kind due to a full file system
(IOError, lambda exc, logger, plugin, cb: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)),
+2 -3
View File
@@ -203,9 +203,8 @@ $(function() {
[
// printer states
gettext("Offline"),
gettext("Opening serial port"),
gettext("Detecting serial port"),
gettext("Detecting baudrate"),
gettext("Opening serial connection"),
gettext("Detecting serial connection"),
gettext("Connecting"),
gettext("Operational"),
gettext("Starting"),
-6
View File
@@ -1,6 +0,0 @@
The code in this sub package mostly originates from the Cura project (https://github.com/daid/Cura). It has been
slightly reorganized and adapted. The mapping to the original Cura source is the following:
* avr_isp.* => Cura.avr_isp.*
* comm => Cura.util.machineCom (highly modified now)
* gcodeInterpreter => Cura.util.gcodeInterpreter
-2
View File
@@ -1,2 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
-22
View File
@@ -1,22 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
avrChipDB = {
'ATMega1280': {
'signature': [0x1E, 0x97, 0x03],
'pageSize': 128,
'pageCount': 512,
},
'ATMega2560': {
'signature': [0x1E, 0x98, 0x01],
'pageSize': 128,
'pageCount': 1024,
},
}
def getChipFromDB(sig):
for chip in avrChipDB.values():
if chip['signature'] == sig:
return chip
return None
-39
View File
@@ -1,39 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import io
from builtins import range
def readHex(filename):
data = []
extraAddr = 0
f = io.open(filename, 'rt', encoding='utf-8')
for line in f:
line = line.strip()
if line[0] != ':':
raise Exception("Hex file has a line not starting with ':'")
recLen = int(line[1:3], 16)
addr = int(line[3:7], 16) + extraAddr
recType = int(line[7:9], 16)
if len(line) != recLen * 2 + 11:
raise Exception("Error in hex file: " + line)
checkSum = 0
for i in range(0, recLen + 5):
checkSum += int(line[i*2+1:i*2+3], 16)
checkSum &= 0xFF
if checkSum != 0:
raise Exception("Checksum error in hex file: " + line)
if recType == 0:#Data record
while len(data) < addr + recLen:
data.append(0)
for i in range(0, recLen):
data[addr + i] = int(line[i*2+9:i*2+11], 16)
elif recType == 1: #End Of File record
pass
elif recType == 2: #Extended Segment Address Record
extraAddr = int(line[9:13], 16) * 16
else:
print(recType, recLen, addr, checkSum, line)
f.close()
return data
-38
View File
@@ -1,38 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import os, struct, sys, time
from serial import Serial
from . import chipDB
class IspBase():
def programChip(self, flashData):
self.curExtAddr = -1
self.chip = chipDB.getChipFromDB(self.getSignature())
if not self.chip:
raise IspError("Chip with signature: " + str(self.getSignature()) + "not found")
self.chipErase()
print("Flashing %i bytes" % len(flashData))
self.writeFlash(flashData)
print("Verifying %i bytes" % len(flashData))
self.verifyFlash(flashData)
#low level ISP commands
def getSignature(self):
sig = []
sig.append(self.sendISP([0x30, 0x00, 0x00, 0x00])[3])
sig.append(self.sendISP([0x30, 0x00, 0x01, 0x00])[3])
sig.append(self.sendISP([0x30, 0x00, 0x02, 0x00])[3])
return sig
def chipErase(self):
self.sendISP([0xAC, 0x80, 0x00, 0x00])
class IspError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
-161
View File
@@ -1,161 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import os, struct, sys, time
from serial import Serial
from serial import SerialException, SerialTimeoutException
from builtins import range
from . import ispBase, intelHex
class Stk500v2(ispBase.IspBase):
def __init__(self):
self.serial = None
self.seq = 1
self.lastAddr = -1
self.progressCallback = None
def connect(self, port = 'COM22', speed = 115200):
if self.serial is not None:
self.close()
try:
self.serial = Serial(str(port), speed, timeout=1, writeTimeout=10000)
except SerialException:
raise ispBase.IspError("Failed to open serial port")
except Exception:
raise ispBase.IspError("Unexpected error while connecting to serial port:" + port + ":" + str(sys.exc_info()[0]))
self.seq = 1
#Reset the controller
self.serial.setDTR(1)
time.sleep(0.1)
self.serial.setDTR(0)
time.sleep(0.2)
self.sendMessage([1])
if self.sendMessage([0x10, 0xc8, 0x64, 0x19, 0x20, 0x00, 0x53, 0x03, 0xac, 0x53, 0x00, 0x00]) != [0x10, 0x00]:
self.close()
raise ispBase.IspError("Failed to enter programming mode")
def close(self):
if self.serial is not None:
self.serial.close()
self.serial = None
#Leave ISP does not reset the serial port, only resets the device, and returns the serial port after disconnecting it from the programming interface.
# This allows you to use the serial port without opening it again.
def leaveISP(self):
if self.serial is not None:
if self.sendMessage([0x11]) != [0x11, 0x00]:
raise ispBase.IspError("Failed to leave programming mode")
ret = self.serial
self.serial = None
return ret
return None
def isConnected(self):
return self.serial is not None
def sendISP(self, data):
recv = self.sendMessage([0x1D, 4, 4, 0, data[0], data[1], data[2], data[3]])
return recv[2:6]
def writeFlash(self, flashData):
#Set load addr to 0, in case we have more then 64k flash we need to enable the address extension
pageSize = self.chip['pageSize'] * 2
flashSize = pageSize * self.chip['pageCount']
if flashSize > 0xFFFF:
self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00])
else:
self.sendMessage([0x06, 0x00, 0x00, 0x00, 0x00])
loadCount = (len(flashData) + pageSize - 1) // pageSize
for i in range(0, loadCount):
self.sendMessage([0x13, pageSize >> 8, pageSize & 0xFF, 0xc1, 0x0a, 0x40, 0x4c, 0x20, 0x00, 0x00] + flashData[(i * pageSize):(i * pageSize + pageSize)])
if self.progressCallback is not None:
self.progressCallback(i + 1, loadCount*2)
def verifyFlash(self, flashData):
#Set load addr to 0, in case we have more then 64k flash we need to enable the address extension
flashSize = self.chip['pageSize'] * 2 * self.chip['pageCount']
if flashSize > 0xFFFF:
self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00])
else:
self.sendMessage([0x06, 0x00, 0x00, 0x00, 0x00])
loadCount = (len(flashData) + 0xFF) // 0x100
for i in range(0, loadCount):
recv = self.sendMessage([0x14, 0x01, 0x00, 0x20])[2:0x102]
if self.progressCallback is not None:
self.progressCallback(loadCount + i + 1, loadCount*2)
for j in range(0, 0x100):
if i * 0x100 + j < len(flashData) and flashData[i * 0x100 + j] != recv[j]:
raise ispBase.IspError('Verify error at: 0x%x' % (i * 0x100 + j))
def sendMessage(self, data):
message = struct.pack(">BBHB", 0x1B, self.seq, len(data), 0x0E)
for c in data:
message += struct.pack(">B", c)
checksum = 0
for c in bytearray(message):
checksum ^= c
message += struct.pack(">B", checksum)
try:
self.serial.write(message)
self.serial.flush()
except SerialTimeoutException:
raise ispBase.IspError('Serial send timeout')
self.seq = (self.seq + 1) & 0xFF
return self.recvMessage()
def recvMessage(self):
state = 'Start'
checksum = 0
while True:
for _ in range(0, 5):
s = self.serial.read()
if len(s) > 0:
break
else:
raise ispBase.IspError("Timeout")
b = struct.unpack(">B", s)[0]
checksum ^= b
#print(hex(b))
if state == 'Start':
if b == 0x1B:
state = 'GetSeq'
checksum = 0x1B
elif state == 'GetSeq':
state = 'MsgSize1'
elif state == 'MsgSize1':
msgSize = b << 8
state = 'MsgSize2'
elif state == 'MsgSize2':
msgSize |= b
state = 'Token'
elif state == 'Token':
if b != 0x0E:
state = 'Start'
else:
state = 'Data'
data = []
elif state == 'Data':
data.append(b)
if len(data) == msgSize:
state = 'Checksum'
elif state == 'Checksum':
if checksum != 0:
state = 'Start'
else:
return data
def main():
programmer = Stk500v2()
programmer.connect(port = sys.argv[1])
programmer.programChip(intelHex.readHex(sys.argv[2]))
sys.exit(1)
if __name__ == '__main__':
main()
+127 -130
View File
@@ -3,8 +3,12 @@ from __future__ import absolute_import, division, print_function, unicode_litera
__author__ = "Gina Häußge <osd@foosel.net> based on work by David Braam"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
__copyright__ = "Copyright (C) 2013 David Braam, Gina Häußge & others - Released under terms of the AGPLv3 License"
"""
The code in this file is based on Cura.util.machineCom from the Cura project from late 2012
(https://github.com/daid/Cura).
"""
import os
import glob
@@ -30,9 +34,6 @@ import octoprint.plugin
from collections import deque
from octoprint.util.avr_isp import stk500v2
from octoprint.util.avr_isp import ispBase
from octoprint.settings import settings, default_settings
from octoprint.events import eventManager, Events
from octoprint.filemanager import valid_file_type
@@ -192,9 +193,10 @@ def serialList():
baselist.append("VIRTUAL")
return baselist
def baudrateList():
# sorted by likelihood
candidates = [115200, 250000, 230400, 57600, 38400, 19200, 9600]
def baudrateList(candidates=None):
if candidates is None:
# sorted by likelihood
candidates = [115200, 250000, 230400, 57600, 38400, 19200, 9600]
# additional baudrates prepended, sorted descending
additionalBaudrates = settings().get(["serial", "additionalBaudrates"])
@@ -369,20 +371,19 @@ class MachineCom(object):
STATE_NONE = 0
STATE_OPEN_SERIAL = 1
STATE_DETECT_SERIAL = 2
STATE_DETECT_BAUDRATE = 3
STATE_CONNECTING = 4
STATE_OPERATIONAL = 5
STATE_STARTING = 6
STATE_PRINTING = 7
STATE_PAUSED = 8
STATE_PAUSING = 9
STATE_RESUMING = 10
STATE_FINISHING = 11
STATE_CLOSED = 12
STATE_ERROR = 13
STATE_CLOSED_WITH_ERROR = 14
STATE_TRANSFERING_FILE = 15
STATE_CANCELLING = 16
STATE_CONNECTING = 3
STATE_OPERATIONAL = 4
STATE_STARTING = 5
STATE_PRINTING = 6
STATE_PAUSED = 7
STATE_PAUSING = 8
STATE_RESUMING = 9
STATE_FINISHING = 10
STATE_CLOSED = 11
STATE_ERROR = 12
STATE_CLOSED_WITH_ERROR = 13
STATE_TRANSFERING_FILE = 14
STATE_CANCELLING = 15
# be sure to add anything here that signifies an operational state
OPERATIONAL_STATES = (STATE_PRINTING, STATE_STARTING, STATE_OPERATIONAL, STATE_PAUSED, STATE_CANCELLING,
@@ -401,6 +402,8 @@ class MachineCom(object):
CAPABILITY_SUPPORT_DETECTED = "detected"
CAPABILITY_SUPPORT_DISABLED = "disabled"
DETECTION_RETRIES = 3
def __init__(self, port=None, baudrate=None, callbackObject=None, printerProfileManager=None):
self._logger = logging.getLogger(__name__)
self._serialLogger = logging.getLogger("SERIAL")
@@ -423,8 +426,10 @@ class MachineCom(object):
self._printerProfileManager = printerProfileManager
self._state = self.STATE_NONE
self._serial = None
self._baudrateDetectList = []
self._baudrateDetectRetry = 0
self._detection_candidates = []
self._detection_retry = self.DETECTION_RETRIES
self._temperatureTargetSetThreshold = 25
self._tempOffsets = dict()
self._command_queue = CommandQueue()
@@ -706,11 +711,9 @@ class MachineCom(object):
if state == self.STATE_NONE:
return "Offline"
elif state == self.STATE_OPEN_SERIAL:
return "Opening serial port"
return "Opening serial connection"
elif state == self.STATE_DETECT_SERIAL:
return "Detecting serial port"
elif state == self.STATE_DETECT_BAUDRATE:
return "Detecting baudrate"
return "Detecting serial connection"
elif state == self.STATE_CONNECTING:
return "Connecting"
elif state == self.STATE_OPERATIONAL:
@@ -1635,25 +1638,21 @@ class MachineCom(object):
self._consecutive_timeouts = 0
#Open the serial port.
if not self._openSerial():
return
# Open the serial port
needs_detection = not (self._port and self._port != 'AUTO' and self._baudrate)
try_hello = False
try_hello = not settings().getBoolean(["serial", "waitForStartOnConnect"])
if not needs_detection:
self._changeState(self.STATE_OPEN_SERIAL)
if not self._open_serial(self._port, self._baudrate):
return
try_hello = not settings().getBoolean(["serial", "waitForStartOnConnect"])
self._changeState(self.STATE_CONNECTING)
else:
self._changeState(self.STATE_DETECT_SERIAL)
self._perform_detection_step(init=True)
self._log("Connected to: %s, starting monitor" % self._serial)
if self._baudrate == 0:
try_hello = False
self._log("Starting baud rate detection...")
self._changeState(self.STATE_DETECT_BAUDRATE)
# Some controllers (e.g. Original Prusa) don't appear to like too fast serial interaction after
# open, so let's wait a bit before the first baudrate detection step
time.sleep(settings().getFloat(["serial", "timeout", "baudrateDetectionPause"]))
self._perform_baudrate_detection_step(init=True)
else:
self._changeState(self.STATE_CONNECTING)
#Start monitoring the serial port.
self._timeout = self._ok_timeout = self._get_new_communication_timeout()
@@ -1715,7 +1714,7 @@ class MachineCom(object):
self._set_busy_protocol_interval(interval=busy_interval, callback=busyIntervalSet)
if self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_BAUDRATE):
if self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_SERIAL):
continue
##~~ debugging output handling
@@ -1752,7 +1751,7 @@ class MachineCom(object):
extra=dict(plugin=name))
continue
if self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_BAUDRATE):
if self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_SERIAL):
continue
def convert_line(line):
@@ -1836,7 +1835,7 @@ class MachineCom(object):
handled = self.isPrinting() and line == ""
# we don't have to process the rest if the line has already been handled fully
if handled and self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_BAUDRATE):
if handled and self._state not in (self.STATE_CONNECTING, self.STATE_DETECT_SERIAL):
continue
##~~ position report processing
@@ -2193,10 +2192,10 @@ class MachineCom(object):
elif "toggle" in pause_triggers and pause_triggers["toggle"].search(line) is not None:
self.setPause(not self.isPaused())
### Baudrate detection
if self._state == self.STATE_DETECT_BAUDRATE:
### Serial detection
if self._state == self.STATE_DETECT_SERIAL:
if line == '' or monotonic_time() > self._timeout:
self._perform_baudrate_detection_step()
self._perform_detection_step()
elif 'start' in line or line.startswith('ok'):
self._onConnected()
if 'start' in line:
@@ -2348,42 +2347,74 @@ class MachineCom(object):
self._log(message + " " + general_message)
self._clear_to_send.set()
def _perform_baudrate_detection_step(self, init=False):
def _perform_detection_step(self, init=False):
if init:
timeout = settings().getFloat(["serial", "timeout", "connection"])
self._baudrateDetectList = baudrateList()
port = self._port
baudrate = self._baudrate
if port and port != "AUTO":
port_candidates = [port]
else:
port_candidates = serialList()
if baudrate:
baudrate_candidates = [baudrate]
elif len(port_candidates) == 1:
baudrate_candidates = baudrateList()
else:
# if we have no baudrate and more than one port we limit tested baudrates to
# the two most common plus any additionally configured ones
baudrate_candidates = baudrateList([115200, 250000])
self._detection_candidates = [(p, b) for p in port_candidates for b in baudrate_candidates]
else:
timeout = settings().getFloat(["serial", "timeout", "detection"])
if self._baudrateDetectRetry > 0:
if self._serial.timeout != timeout:
self._serial.timeout = timeout
self._timeout = monotonic_time() + timeout
self._log("Baudrate test retry #{}".format(5 - self._baudrateDetectRetry))
self._baudrateDetectRetry -= 1
self._do_send_without_checksum(b"", log=False) # new line to reset things
self.sayHello(tags={"trigger:baudrate_detection", })
elif len(self._baudrateDetectList) > 0:
baudrate = self._baudrateDetectList.pop(0)
try:
self._serial.baudrate = baudrate
while len(self._detection_candidates) > 0:
if self._detection_retry < self.DETECTION_RETRIES:
if self._serial.timeout != timeout:
self._serial.timeout = timeout
self._timeout = monotonic_time() + timeout
self._log("Trying baudrate: {}".format(baudrate))
self._baudrateDetectRetry = 4
self._do_send_without_checksum(b"", log=False) # new line to reset things
self.sayHello(tags={"trigger:baudrate_detection", })
except Exception:
self._log("Unexpected error while setting baudrate {}: {}".format(baudrate, get_exception_string()))
self._logger.exception("Unexpected error while setting baudrate {}".format(baudrate))
message = "Handshake attempt #{}".format(self._detection_retry + 1)
self._log(message)
self._logger.info("Serial detection: {}".format(message))
else:
error_text = "No more baudrates to test, and no suitable baudrate found."
self._trigger_error(error_text, "autodetect_baudrate")
self._detection_retry += 1
self._do_send_without_checksum(b"", log=False) # new line to reset things
self.sayHello(tags={"trigger:detection", })
return
else:
(p, b) = self._detection_candidates.pop(0)
try:
if self._serial is None or self._serial.port != p:
if not self._open_serial(p, b, trigger_errors=False):
message = "Could not open port {}, baudrate {}, skipping".format(p, b)
self._log(message)
self._logger.info("Serial detection: {}".format(message))
continue
else:
self._serial.baudrate = b
if self._serial.timeout != timeout:
self._serial.timeout = timeout
self._timeout = monotonic_time() + timeout
message = "Trying port {}, baudrate {}".format(p, b)
self._log(message)
self._logger.info("Serial detection: {}".format(message))
self._detection_retry = 0
except Exception:
self._log("Unexpected error while setting baudrate {}: {}".format(b, get_exception_string()))
self._logger.exception("Unexpected error while setting baudrate {}".format(b))
error_text = "No more candidates to test, and no working port/baudrate combination detected."
self._trigger_error(error_text, "autodetect")
def _finish_heatup(self):
if self._heating:
@@ -2444,7 +2475,9 @@ class MachineCom(object):
except KeyError:
output = template.format(**match.groupdict())
except Exception:
self._logger.debug("Could not proces template %s: %s", template_key, template, exc_info=1)
self._logger.debug("Could not process template {}: {}".format(template_key,
template),
exc_info=1)
output = None
if output is not None:
@@ -2645,54 +2678,14 @@ class MachineCom(object):
finally:
self._command_queue.task_done()
def _detect_port(self):
potentials = serialList()
self._log("Serial port list: %s" % (str(potentials)))
if len(potentials) == 1:
# short cut: only one port, let's try that
return potentials[0]
elif len(potentials) > 1:
programmer = stk500v2.Stk500v2()
for p in potentials:
serial_obj = None
try:
self._log("Trying {}".format(p))
programmer.connect(p)
serial_obj = programmer.leaveISP()
except Exception as e:
self._log("Could not connect to or enter programming mode on {}, might not be a printer or just not allow programming mode".format(p))
self._logger.info("Could not enter programming mode on {}: {}".format(p, e))
found = serial_obj is not None
programmer.close()
if found:
return p
return None
def _openSerial(self):
def default(_, port, baudrate, read_timeout):
if port is None or port == 'AUTO':
# no known port, try auto detection
self._changeState(self.STATE_DETECT_SERIAL)
port = self._detect_port()
if port is None:
error_text = "Failed to autodetect serial port, please set it manually."
self._trigger_error(error_text, "autodetect_port")
self._log(error_text)
return None
def _open_serial(self, port, baudrate, trigger_errors=True):
def default(_, p, b, timeout):
# connect to regular serial port
self._log("Connecting to: %s" % port)
self._log("Connecting to port {}, baudrate {}".format(port, baudrate))
serial_port_args = {
"baudrate": baudrateList()[0] if baudrate == 0 else baudrate,
"timeout": read_timeout,
"baudrate": baudrate,
"timeout": timeout,
"write_timeout": 0,
}
@@ -2700,7 +2693,7 @@ class MachineCom(object):
serial_port_args["exclusive"] = True
serial_obj = serial.Serial(**serial_port_args)
serial_obj.port = str(port)
serial_obj.port = str(p)
use_parity_workaround = settings().get(["serial", "useParityWorkaround"])
needs_parity_workaround = get_os() == "linux" and os.path.exists("/etc/debian_version") # See #673
@@ -2727,23 +2720,27 @@ class MachineCom(object):
serial_factories = list(self._serial_factory_hooks.items()) + [("default", default)]
for name, factory in serial_factories:
try:
serial_obj = factory(self, self._port, self._baudrate, settings().getFloat(["serial", "timeout", "connection"]))
serial_obj = factory(self,
port,
baudrate,
settings().getFloat(["serial", "timeout", "connection"]))
except Exception:
exception_string = get_exception_string()
self._trigger_error("Connection error, see Terminal tab", "connection")
error_message = "Unexpected error while connecting to serial port: %s %s (hook %s)" % (self._port, exception_string, name)
if trigger_errors:
self._trigger_error("Connection error, see Terminal tab", "connection")
error_message = "Unexpected error while connecting to " \
"serial port {}, baudrate {} from hook {}: {}".format(port,
baudrate,
name,
exception_string)
self._log(error_message)
self._logger.exception(error_message)
if "failed to set custom baud rate" in exception_string.lower():
self._log("Your installation does not support custom baudrates (e.g. 250000) for connecting to your printer. This is a problem of the pyserial library that OctoPrint depends on. Please update to a pyserial version that supports your baudrate or switch your printer's firmware to a standard baudrate (e.g. 115200). See https://github.com/OctoPrint/OctoPrint/wiki/OctoPrint-support-for-250000-baud-rate-on-Raspbian")
return False
if serial_obj is not None:
# first hook to succeed wins, but any can pass on to the next
self._changeState(self.STATE_OPEN_SERIAL)
self._serial = serial_obj
self._clear_to_send.reset()
return True