Serial mode (--serialport): preloader "READY" bytes not drained before the handshake → "Sync error" (macOS, MT6580)

Open Beginner friendly
#458 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
65/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
embedded-iot

Research direction

Start in mtkclient/Library/Port.py at Port.run_serial_handshake() (the startcmd loop near line 69); the underlying handle is self.cdc.device, opened in mtkclient/Library/Serial.py. Compare that loop with the diff in the issue, then add the drain before the handshake and after each mismatch reset, following the existing ep_out helper's style. Done means the handshake still succeeds and the following GET_HW_CODE returns the expected bytes; reproduce on a preloader-mode device or a mocked pyserial port that emits READY. Note #367 is already on main, so check what the current code differs by.

Written by the indexing model from the issue text.

Description

👋 hello there

I was hacking my cooking robot (android tablet) with my mac and landed on this issue.
I don't write that much python, let me know if I need to add more tests, I am happy to dig in.

Here are the stack trace

Setup: mtkclient v2.1.4.1 (5a863ee), macOS on Apple silicon, Python 3.14, pyserial 3.5, --serialport DETECT. Device: MT6580 in preloader mode (0e8d:2000, /dev/cu.usbmodem…), "Device is unprotected". Through libusb the handshake never succeeds on this Mac (like #333), so the serial port is the only way.

Symptom (reproducible, device powered on once per attempt):

DeviceClass - Detected 0xe8d:0x2000 device at: /dev/cu.usbmodem100
Port - Device detected :)
Port - Handshake successful.
Preloader - [LIB]: Sync error. Please power off the device and retry.
DaHandler - Please disconnect, start mtkclient and reconnect.

Afterwards the device stays in preloader command mode (it echoes every byte back) until it is powered off.

Cause: as soon as its VCOM port opens, the preloader sends READY repeatedly. SerialClass.connect() disables reset_input_buffer during open(), and Port.run_serial_handshake() reads one byte per step without draining anything, so those bytes are taken as handshake echoes. The stream gets shifted: the handshake can still "succeed" on stale bytes, then echo(GET_HW_CODE) reads leftovers and fails.

A minimal pyserial probe (open, read what is pending, drain, handshake, GET_HW_CODE) shows it:

      0.0 ms port /dev/cu.usbmodem100
    264.7 ms opened
    318.4 ms unsolicited bytes before handshake: 52454144595245414459 b'READYREADY'
    324.4 ms TX a0  RX 52     5.6 ms
    347.2 ms    extra bytes: 45414459 b'EADY'
    347.5 ms TX a0  RX 5f     0.1 ms
    347.6 ms TX 0a  RX f5     0.1 ms
    347.8 ms TX 50  RX af     0.1 ms
    347.9 ms TX 05  RX fa     0.1 ms
    347.9 ms handshake OK after 2 tries
    402.9 ms bytes still pending after handshake: (none)
    403.3 ms GET_HW_CODE -> fd65800000  (0.1 ms; expected fd 6580 0000)

Fix that worked here: drain the input before the handshake and after each mismatch.

diff --git a/mtkclient/Library/Port.py b/mtkclient/Library/Port.py
index 8e2a58f..29fa94f 100644
--- a/mtkclient/Library/Port.py
+++ b/mtkclient/Library/Port.py
@@ -69,6 +69,9 @@ class Port(metaclass=LogBase):
         i = 0
         startcmd = b"\xa0\x0a\x50\x05"  # 5F F5 AF FA
         length = len(startcmd)
+        # the preloader sends "READY" as soon as its port opens. Left in the input
+        # buffer, those bytes are read as handshake echoes and shift every later reply (Sync error).
+        self._drain_serial_input()
         try:
             while i < length:
                 if ep_out(int.to_bytes(startcmd[i], 1, 'little')):
@@ -77,6 +80,8 @@ class Port(metaclass=LogBase):
                         i += 1
                     else:
                         i = 0
+                        time.sleep(0.02)
+                        self._drain_serial_input()
             self.info("Device detected :)")
             return True
         except Exception as serr:
@@ -84,6 +89,18 @@ class Port(metaclass=LogBase):
             time.sleep(0.005)
         return False
 
+    def _drain_serial_input(self):
+        # discard bytes already waiting on a serial port (pyserial only).
+        dev = getattr(self.cdc, "device", None)
+        if dev is None or not hasattr(dev, "in_waiting"):
+            return
+        try:
+            pending = dev.in_waiting
+            if pending:
+                dev.read(pending)
+        except Exception as err:
+            self.debug(str(err))
+
     def serial_handshake(self, maxtries=None, loop=0):
         counter = 0
         if not self.cdc.connected:

More notes from the same session, for the record:

  • SerialClass.write() calls flushOutput(), i.e. reset_output_buffer() / tcflush(TCOFLUSH), which discards bytes not sent yet on macOS: the DA stage 2 upload stopped half-way (Error on sending brom stage 2). Already fixed on main by #367, thanks! Could a release include it? v2.1.4.1 is still the latest one.
  • SerialClass.usbread() with no timeout uses 20 ms. We raised that to the class default (1 s) for DA ACK reads; we did not check whether it is still needed once the flush fix is in.
  • Side note: if the port disappears during run_serial_handshake() (device powered off), ep_out() returns False and the while i < length loop spins without sleeping; with --debugmode the log grew by hundreds of MB in a minute.

With these changes, reading two 16 MiB partitions worked three times in a row with identical results, and a write followed by a read-back verified, all through --serialport on macOS.

Dominant language
Python
Stars
1.5k
Forks
309
Avg merge
1d 7h
Merged PRs (30d)
2

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from bkerler/mtkclient

All issues in bkerler/mtkclient

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.