Skip to content

Fix missing STX (0x02) DLE-escape in transmit()#19

Open
brocci wants to merge 1 commit into
madleech:masterfrom
brocci:fix-transmit-escape
Open

Fix missing STX (0x02) DLE-escape in transmit()#19
brocci wants to merge 1 commit into
madleech:masterfrom
brocci:fix-transmit-escape

Conversation

@brocci
Copy link
Copy Markdown

@brocci brocci commented May 10, 2026

Summary

  • Fix missing DLE escape for STX (0x02) in transmit() per NMRA CMRInet spec LCS-9.10.1 v1.1
  • The spec requires DLE (0x10) to be inserted before any data byte equal to STX (0x02), ETX (0x03), or DLE (0x10) in the message body
  • The current code only escapes ETX and DLE — an output data byte of 0x02 is sent raw, and the host (JMRI) may misinterpret it as start-of-text, breaking packet synchronization
  • Also fixes a misleading comment

Details

Problem: The NMRA CMRInet specification (LCS-9.10.1, §Data Link Escape (DLE) Processing) requires:

"Software must insert a DLE in front of any of these data values when forming a Transmit Data or Receive Data message."

The three values requiring DLE are STX (0x02), ETX (0x03), and DLE (0x10).

The current transmit() only checks two of the three:

if (_tx_buffer[i] == ETX)
    _serial.write(ESC);
if (_tx_buffer[i] == ESC)
    _serial.write(ESC);
_serial.write(_tx_buffer[i]);

STX (0x02) is not escaped. If any output data byte carries the value 0x02 (perfectly valid binary data), it is transmitted raw. A CMRInet host receiving this frame will see 0x02 in the data stream and interpret it as the start-of-text character, potentially corrupting the current frame and subsequent ones.

Fix: Combine the escape check into a single condition covering all three protocol character values (STX, ETX, DLE). The ESC constant in the code is already defined as 0x10 (DLE).

Changes

CMRI.cpptransmit() method:

 	for (int i=0; i<_tx_length; i++)
 	{
		if (_tx_buffer[i] == STX || _tx_buffer[i] == ETX || _tx_buffer[i] == ESC)
			_serial.write(ESC);
 		_serial.write(_tx_buffer[i]);
 	}

Closes #18

@brocci brocci force-pushed the fix-transmit-escape branch from cf1f8bc to bf8b8db Compare May 11, 2026 12:42
@brocci brocci force-pushed the fix-transmit-escape branch from bf8b8db to 003e127 Compare May 12, 2026 12:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

STX not escaped in transmit()

1 participant