From 9b842786079da41efd7e8c23dc1bdf482872f11b Mon Sep 17 00:00:00 2001 From: Janez T Date: Thu, 5 Mar 2026 13:23:23 +0100 Subject: [PATCH 01/10] feat: Add support for PAYLOAD_TYPE_GRP_DATA Docs changes are to reflect how it is currently in fw This adds ability to send datagram data to everyone in channel --- docs/companion_protocol.md | 67 +++++++++++++++++++++------- examples/companion_radio/MyMesh.cpp | 68 ++++++++++++++++++++++++++--- examples/companion_radio/MyMesh.h | 2 + src/helpers/BaseChatMesh.cpp | 28 +++++++++++- src/helpers/BaseChatMesh.h | 3 ++ src/helpers/TxtDataHelpers.h | 1 + 6 files changed, 148 insertions(+), 21 deletions(-) diff --git a/docs/companion_protocol.md b/docs/companion_protocol.md index 11ba0ab24c..0b83fddbe2 100644 --- a/docs/companion_protocol.md +++ b/docs/companion_protocol.md @@ -257,31 +257,56 @@ Bytes 34-49: Secret (16 bytes) --- -### 5. Send Channel Message +### 5. Send Channel Text Message -**Purpose**: Send a text message to a channel. +**Purpose**: Send a plain text message to a channel. **Command Format**: ``` Byte 0: 0x03 -Byte 1: 0x00 +Byte 1: Text Type Byte 2: Channel Index (0-7) Bytes 3-6: Timestamp (32-bit little-endian Unix timestamp, seconds) -Bytes 7+: Message Text (UTF-8, variable length) +Bytes 7+: UTF-8 text bytes (variable length) ``` **Timestamp**: Unix timestamp in seconds (32-bit unsigned integer, little-endian) +**Text Type**: +- Must be `0x00` (`TXT_TYPE_PLAIN`) for this command. + **Example** (send "Hello" to channel 1 at timestamp 1234567890): ``` 03 00 01 D2 02 96 49 48 65 6C 6C 6F ``` -**Response**: `PACKET_MSG_SENT` (0x06) on success +**Response**: `PACKET_OK` (0x00) on success + +--- + +### 6. Send Channel Data Datagram + +**Purpose**: Send binary datagram data to a channel. + +**Command Format**: +``` +Byte 0: 0x3E +Byte 1: Data Type (`txt_type`) +Byte 2: Channel Index (0-7) +Bytes 3-6: Timestamp (32-bit little-endian Unix timestamp, seconds) +Bytes 7+: Binary payload bytes (variable length) +``` + +**Data Type / Transport Mapping**: +- `0xFF` (`TXT_TYPE_CUSTOM_BINARY`) is the custom-app binary type. +- `0x00` (`TXT_TYPE_PLAIN`) is invalid for this command. +- Values other than `0xFF` are reserved for official protocol extensions. + +**Response**: `PACKET_OK` (0x00) on success --- -### 6. Get Message +### 7. Get Message **Purpose**: Request the next queued message from the device. @@ -304,7 +329,7 @@ Byte 0: 0x0A --- -### 7. Get Battery and Storage +### 8. Get Battery and Storage **Purpose**: Query device battery voltage and storage usage. @@ -446,7 +471,7 @@ Byte 1: Channel Index (0-7) Byte 2: Path Length Byte 3: Text Type Bytes 4-7: Timestamp (32-bit little-endian) -Bytes 8+: Message Text (UTF-8) +Bytes 8+: Payload bytes ``` **V3 Format** (`PACKET_CHANNEL_MSG_RECV_V3`, 0x11): @@ -458,9 +483,14 @@ Byte 4: Channel Index (0-7) Byte 5: Path Length Byte 6: Text Type Bytes 7-10: Timestamp (32-bit little-endian) -Bytes 11+: Message Text (UTF-8) +Bytes 11+: Payload bytes ``` +**Payload Meaning**: +- If `txt_type == 0x00`: payload is UTF-8 channel text. +- If `txt_type != 0x00`: payload is binary (for example image/voice fragments) and must be treated as raw bytes. + For custom app datagrams sent via `CMD_SEND_CHANNEL_DATA`, use `txt_type == 0xFF`. + **Parsing Pseudocode**: ```python def parse_channel_message(data): @@ -477,11 +507,17 @@ def parse_channel_message(data): path_len = data[offset + 1] txt_type = data[offset + 2] timestamp = int.from_bytes(data[offset+3:offset+7], 'little') - message = data[offset+7:].decode('utf-8') + payload = data[offset+7:] + if txt_type == 0: + message = payload.decode('utf-8') + else: + message = None return { 'channel_idx': channel_idx, + 'txt_type': txt_type, 'timestamp': timestamp, + 'payload': payload, 'message': message, 'snr': snr if packet_type == 0x11 else None } @@ -489,7 +525,7 @@ def parse_channel_message(data): ### Sending Messages -Use the `SEND_CHANNEL_MESSAGE` command (see [Commands](#commands)). +Use `CMD_SEND_CHANNEL_TXT_MSG` for plain text, and `CMD_SEND_CHANNEL_DATA` for binary datagrams (see [Commands](#commands)). **Important**: - Messages are limited to 133 characters per MeshCore specification @@ -510,7 +546,7 @@ Use the `SEND_CHANNEL_MESSAGE` command (see [Commands](#commands)). | 0x03 | PACKET_CONTACT | Contact information | | 0x04 | PACKET_CONTACT_END | End of contact list | | 0x05 | PACKET_SELF_INFO | Device self-information | -| 0x06 | PACKET_MSG_SENT | Message sent confirmation | +| 0x06 | PACKET_MSG_SENT | Direct message sent confirmation | | 0x07 | PACKET_CONTACT_MSG_RECV | Contact message (standard) | | 0x08 | PACKET_CHANNEL_MSG_RECV | Channel message (standard) | | 0x09 | PACKET_CURRENT_TIME | Current time response | @@ -675,7 +711,7 @@ def parse_self_info(data): return info ``` -**PACKET_MSG_SENT** (0x06): +**PACKET_MSG_SENT** (0x06, used by direct/contact send flows): ``` Byte 0: 0x06 Byte 1: Route Flag (0 = direct, 1 = flood) @@ -737,7 +773,8 @@ BLE implementations enqueue and deliver one protocol frame per BLE write/notific - `DEVICE_QUERY` → `PACKET_DEVICE_INFO` - `GET_CHANNEL` → `PACKET_CHANNEL_INFO` - `SET_CHANNEL` → `PACKET_OK` or `PACKET_ERROR` - - `SEND_CHANNEL_MESSAGE` → `PACKET_MSG_SENT` + - `CMD_SEND_CHANNEL_TXT_MSG` → `PACKET_OK` or `PACKET_ERROR` + - `CMD_SEND_CHANNEL_DATA` → `PACKET_OK` or `PACKET_ERROR` - `GET_MESSAGE` → `PACKET_CHANNEL_MSG_RECV`, `PACKET_CONTACT_MSG_RECV`, or `PACKET_NO_MORE_MSGS` - `GET_BATTERY` → `PACKET_BATTERY` @@ -809,7 +846,7 @@ command = build_channel_message(channel_index, message, timestamp) # 2. Send command send_command(rx_char, command) -response = wait_for_response(PACKET_MSG_SENT) +response = wait_for_response(PACKET_OK) ``` ### Receiving Messages diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 1f71a9bc6c..85df464fc1 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -58,6 +58,7 @@ #define CMD_GET_AUTOADD_CONFIG 59 #define CMD_GET_ALLOWED_REPEAT_FREQ 60 #define CMD_SET_PATH_HASH_MODE 61 +#define CMD_SEND_CHANNEL_DATA 62 // Stats sub-types for CMD_GET_STATS #define STATS_TYPE_CORE 0 @@ -564,6 +565,41 @@ void MyMesh::onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packe #endif } +void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, uint8_t txt_type, + const uint8_t *data, size_t data_len) { + int i = 0; + if (app_target_ver >= 3) { + out_frame[i++] = RESP_CODE_CHANNEL_MSG_RECV_V3; + out_frame[i++] = (int8_t)(pkt->getSNR() * 4); + out_frame[i++] = 0; // reserved1 + out_frame[i++] = 0; // reserved2 + } else { + out_frame[i++] = RESP_CODE_CHANNEL_MSG_RECV; + } + + uint8_t channel_idx = findChannelIdx(channel); + out_frame[i++] = channel_idx; + out_frame[i++] = pkt->isRouteFlood() ? pkt->path_len : 0xFF; + out_frame[i++] = txt_type; + memcpy(&out_frame[i], ×tamp, 4); + i += 4; + + size_t available = MAX_FRAME_SIZE - i; + if (data_len > available) data_len = available; + int copy_len = (int)data_len; + if (copy_len > 0) { + memcpy(&out_frame[i], data, copy_len); + i += copy_len; + } + addToOfflineQueue(out_frame, i); + + if (_serial->isConnected()) { + uint8_t frame[1]; + frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle' + _serial->writeFrame(frame, 1); + } +} + uint8_t MyMesh::onContactRequest(const ContactInfo &contact, uint32_t sender_timestamp, const uint8_t *data, uint8_t len, uint8_t *reply) { if (data[0] == REQ_TYPE_GET_TELEMETRY_DATA) { @@ -1031,26 +1067,48 @@ void MyMesh::handleCmdFrame(size_t len) { ? ERR_CODE_NOT_FOUND : ERR_CODE_UNSUPPORTED_CMD); // unknown recipient, or unsuported TXT_TYPE_* } - } else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG) { // send GroupChannel msg + } else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG) { // send GroupChannel text msg int i = 1; - uint8_t txt_type = cmd_frame[i++]; // should be TXT_TYPE_PLAIN + uint8_t txt_type = cmd_frame[i++]; uint8_t channel_idx = cmd_frame[i++]; uint32_t msg_timestamp; memcpy(&msg_timestamp, &cmd_frame[i], 4); i += 4; const char *text = (char *)&cmd_frame[i]; + int text_len = (len > (size_t)i) ? (int)(len - i) : 0; if (txt_type != TXT_TYPE_PLAIN) { writeErrFrame(ERR_CODE_UNSUPPORTED_CMD); } else { ChannelDetails channel; - bool success = getChannel(channel_idx, channel); - if (success && sendGroupMessage(msg_timestamp, channel.channel, _prefs.node_name, text, len - i)) { + if (!getChannel(channel_idx, channel)) { + writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx + } else if (sendGroupMessage(msg_timestamp, channel.channel, _prefs.node_name, text, text_len)) { writeOKFrame(); } else { - writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx + writeErrFrame(ERR_CODE_TABLE_FULL); } } + } else if (cmd_frame[0] == CMD_SEND_CHANNEL_DATA) { // send GroupChannel datagram + int i = 1; + uint8_t txt_type = cmd_frame[i++]; + uint8_t channel_idx = cmd_frame[i++]; + uint32_t msg_timestamp; + memcpy(&msg_timestamp, &cmd_frame[i], 4); + i += 4; + const uint8_t *payload = &cmd_frame[i]; + int payload_len = (len > (size_t)i) ? (int)(len - i) : 0; + + ChannelDetails channel; + if (!getChannel(channel_idx, channel)) { + writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx + } else if (txt_type != TXT_TYPE_CUSTOM_BINARY) { + writeErrFrame(ERR_CODE_UNSUPPORTED_CMD); + } else if (sendGroupData(msg_timestamp, channel.channel, txt_type, payload, payload_len)) { + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_TABLE_FULL); + } } else if (cmd_frame[0] == CMD_GET_CONTACTS) { // get Contact list if (_iter_started) { writeErrFrame(ERR_CODE_BAD_STATE); // iterator is currently busy diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 4d77b5ab7a..0e11264761 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -137,6 +137,8 @@ class MyMesh : public BaseChatMesh, public DataStoreHost { const uint8_t *sender_prefix, const char *text) override; void onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, const char *text) override; + void onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, uint8_t txt_type, + const uint8_t *data, size_t data_len) override; uint8_t onContactRequest(const ContactInfo &contact, uint32_t sender_timestamp, const uint8_t *data, uint8_t len, uint8_t *reply) override; diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index 33d7edbee4..e6f59a50b0 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -353,8 +353,10 @@ int BaseChatMesh::searchChannelsByHash(const uint8_t* hash, mesh::GroupChannel d #endif void BaseChatMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mesh::GroupChannel& channel, uint8_t* data, size_t len) { + if (len < 5) return; + uint8_t txt_type = data[4]; - if (type == PAYLOAD_TYPE_GRP_TXT && len > 5 && (txt_type >> 2) == 0) { // 0 = plain text msg + if (type == PAYLOAD_TYPE_GRP_TXT && (txt_type >> 2) == 0) { // 0 = plain text msg uint32_t timestamp; memcpy(×tamp, data, 4); @@ -363,6 +365,10 @@ void BaseChatMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mes // notify UI of this new message onChannelMessageRecv(channel, packet, timestamp, (const char *) &data[5]); // let UI know + } else if (type == PAYLOAD_TYPE_GRP_DATA) { + uint32_t timestamp; + memcpy(×tamp, data, 4); + onChannelDataRecv(channel, packet, timestamp, txt_type, &data[5], len - 5); } } @@ -454,6 +460,26 @@ bool BaseChatMesh::sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& chan return false; } +bool BaseChatMesh::sendGroupData(uint32_t timestamp, mesh::GroupChannel& channel, uint8_t txt_type, const uint8_t* data, int data_len) { + if (data_len < 0) return false; + // createGroupDatagram() accepts at most (MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE) + // plaintext bytes; subtract our 5-byte {timestamp, txt_type} header. + const int max_group_data_len = (MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE) - 5; + if (data_len > max_group_data_len) data_len = max_group_data_len; + + uint8_t temp[MAX_PACKET_PAYLOAD]; + memcpy(temp, ×tamp, 4); + temp[4] = txt_type; + if (data_len > 0) memcpy(&temp[5], data, data_len); + + auto pkt = createGroupDatagram(PAYLOAD_TYPE_GRP_DATA, channel, temp, 5 + data_len); + if (pkt) { + sendFloodScoped(channel, pkt); + return true; + } + return false; +} + bool BaseChatMesh::shareContactZeroHop(const ContactInfo& contact) { int plen = getBlobByKey(contact.id.pub_key, PUB_KEY_SIZE, temp_buf); // retrieve last raw advert packet if (plen == 0) return false; // not found diff --git a/src/helpers/BaseChatMesh.h b/src/helpers/BaseChatMesh.h index ab90d581be..02b2dfabb2 100644 --- a/src/helpers/BaseChatMesh.h +++ b/src/helpers/BaseChatMesh.h @@ -111,6 +111,8 @@ class BaseChatMesh : public mesh::Mesh { virtual uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const = 0; virtual void onSendTimeout() = 0; virtual void onChannelMessageRecv(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t timestamp, const char *text) = 0; + virtual void onChannelDataRecv(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t timestamp, uint8_t txt_type, + const uint8_t* data, size_t data_len) {} virtual uint8_t onContactRequest(const ContactInfo& contact, uint32_t sender_timestamp, const uint8_t* data, uint8_t len, uint8_t* reply) = 0; virtual void onContactResponse(const ContactInfo& contact, const uint8_t* data, uint8_t len) = 0; virtual void handleReturnPathRetry(const ContactInfo& contact, const uint8_t* path, uint8_t path_len); @@ -148,6 +150,7 @@ class BaseChatMesh : public mesh::Mesh { int sendMessage(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& expected_ack, uint32_t& est_timeout); int sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& est_timeout); bool sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& channel, const char* sender_name, const char* text, int text_len); + bool sendGroupData(uint32_t timestamp, mesh::GroupChannel& channel, uint8_t txt_type, const uint8_t* data, int data_len); int sendLogin(const ContactInfo& recipient, const char* password, uint32_t& est_timeout); int sendAnonReq(const ContactInfo& recipient, const uint8_t* data, uint8_t len, uint32_t& tag, uint32_t& est_timeout); int sendRequest(const ContactInfo& recipient, uint8_t req_type, uint32_t& tag, uint32_t& est_timeout); diff --git a/src/helpers/TxtDataHelpers.h b/src/helpers/TxtDataHelpers.h index 6ab84d3975..0fbbd25357 100644 --- a/src/helpers/TxtDataHelpers.h +++ b/src/helpers/TxtDataHelpers.h @@ -6,6 +6,7 @@ #define TXT_TYPE_PLAIN 0 // a plain text message #define TXT_TYPE_CLI_DATA 1 // a CLI command #define TXT_TYPE_SIGNED_PLAIN 2 // plain text, signed by sender +#define TXT_TYPE_CUSTOM_BINARY 0xFF // custom app binary payload (group/channel datagrams) class StrHelper { public: From 0e98939987a8f825c1f853d3ac1f7e2589d7929f Mon Sep 17 00:00:00 2001 From: Janez T Date: Thu, 5 Mar 2026 14:05:29 +0100 Subject: [PATCH 02/10] feat: Require 0xFF for custom payloads ref: --- docs/companion_protocol.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/companion_protocol.md b/docs/companion_protocol.md index 0b83fddbe2..bf030bfa50 100644 --- a/docs/companion_protocol.md +++ b/docs/companion_protocol.md @@ -298,7 +298,7 @@ Bytes 7+: Binary payload bytes (variable length) ``` **Data Type / Transport Mapping**: -- `0xFF` (`TXT_TYPE_CUSTOM_BINARY`) is the custom-app binary type. +- `0xFF` (`TXT_TYPE_CUSTOM_BINARY`) must be used for custom-protocol binary datagrams. - `0x00` (`TXT_TYPE_PLAIN`) is invalid for this command. - Values other than `0xFF` are reserved for official protocol extensions. @@ -489,7 +489,7 @@ Bytes 11+: Payload bytes **Payload Meaning**: - If `txt_type == 0x00`: payload is UTF-8 channel text. - If `txt_type != 0x00`: payload is binary (for example image/voice fragments) and must be treated as raw bytes. - For custom app datagrams sent via `CMD_SEND_CHANNEL_DATA`, use `txt_type == 0xFF`. + For custom app datagrams sent via `CMD_SEND_CHANNEL_DATA`, `txt_type` must be `0xFF`. **Parsing Pseudocode**: ```python From a21b83b1271884e6f08507d4734440a0349f71d1 Mon Sep 17 00:00:00 2001 From: Janez T Date: Sun, 8 Mar 2026 14:14:26 +0100 Subject: [PATCH 03/10] fix: address comments ref: --- docs/companion_protocol.md | 65 ++++++++++++++++++++++------- examples/companion_radio/MyMesh.cpp | 37 +++++++++------- examples/companion_radio/MyMesh.h | 2 +- src/MeshCore.h | 3 +- src/helpers/BaseChatMesh.cpp | 44 ++++++++++++------- src/helpers/BaseChatMesh.h | 4 +- src/helpers/TxtDataHelpers.h | 2 +- 7 files changed, 107 insertions(+), 50 deletions(-) diff --git a/docs/companion_protocol.md b/docs/companion_protocol.md index bf030bfa50..c00be4a202 100644 --- a/docs/companion_protocol.md +++ b/docs/companion_protocol.md @@ -291,17 +291,21 @@ Bytes 7+: UTF-8 text bytes (variable length) **Command Format**: ``` Byte 0: 0x3E -Byte 1: Data Type (`txt_type`) +Byte 1: Data Type (`data_type`) Byte 2: Channel Index (0-7) Bytes 3-6: Timestamp (32-bit little-endian Unix timestamp, seconds) Bytes 7+: Binary payload bytes (variable length) ``` **Data Type / Transport Mapping**: -- `0xFF` (`TXT_TYPE_CUSTOM_BINARY`) must be used for custom-protocol binary datagrams. +- `0xFF` (`DATA_TYPE_CUSTOM`) must be used for custom-protocol binary datagrams. - `0x00` (`TXT_TYPE_PLAIN`) is invalid for this command. - Values other than `0xFF` are reserved for official protocol extensions. +**Limits**: +- Maximum payload length is `163` bytes (`MAX_GROUP_DATA_LENGTH`). +- Larger payloads are rejected with `PACKET_ERROR` / `ERR_CODE_ILLEGAL_ARG`. + **Response**: `PACKET_OK` (0x00) on success --- @@ -322,6 +326,7 @@ Byte 0: 0x0A **Response**: - `PACKET_CHANNEL_MSG_RECV` (0x08) or `PACKET_CHANNEL_MSG_RECV_V3` (0x11) for channel messages +- `PACKET_CHANNEL_DATA_RECV` (0x1B) or `PACKET_CHANNEL_DATA_RECV_V3` (0x1C) for channel data - `PACKET_CONTACT_MSG_RECV` (0x07) or `PACKET_CONTACT_MSG_RECV_V3` (0x10) for contact messages - `PACKET_NO_MORE_MSGS` (0x0A) if no messages available @@ -391,11 +396,15 @@ Messages are received via the TX characteristic (notifications). The device send - `PACKET_CHANNEL_MSG_RECV` (0x08) - Standard format - `PACKET_CHANNEL_MSG_RECV_V3` (0x11) - Version 3 with SNR -2. **Contact Messages**: +2. **Channel Data**: + - `PACKET_CHANNEL_DATA_RECV` (0x1B) - Standard format + - `PACKET_CHANNEL_DATA_RECV_V3` (0x1C) - Version 3 with SNR + +3. **Contact Messages**: - `PACKET_CONTACT_MSG_RECV` (0x07) - Standard format - `PACKET_CONTACT_MSG_RECV_V3` (0x10) - Version 3 with SNR -3. **Notifications**: +4. **Notifications**: - `PACKET_MESSAGES_WAITING` (0x83) - Indicates messages are queued ### Contact Message Format @@ -489,37 +498,62 @@ Bytes 11+: Payload bytes **Payload Meaning**: - If `txt_type == 0x00`: payload is UTF-8 channel text. - If `txt_type != 0x00`: payload is binary (for example image/voice fragments) and must be treated as raw bytes. - For custom app datagrams sent via `CMD_SEND_CHANNEL_DATA`, `txt_type` must be `0xFF`. + For custom app datagrams sent via `CMD_SEND_CHANNEL_DATA`, `data_type` must be `0xFF`. + +### Channel Data Format + +**Standard Format** (`PACKET_CHANNEL_DATA_RECV`, 0x1B): +``` +Byte 0: 0x1B (packet type) +Byte 1: Channel Index (0-7) +Byte 2: Path Length +Byte 3: Data Type +Bytes 4-7: Timestamp (32-bit little-endian) +Bytes 8+: Payload bytes +``` + +**V3 Format** (`PACKET_CHANNEL_DATA_RECV_V3`, 0x1C): +``` +Byte 0: 0x1C (packet type) +Byte 1: SNR (signed byte, multiplied by 4) +Bytes 2-3: Reserved +Byte 4: Channel Index (0-7) +Byte 5: Path Length +Byte 6: Data Type +Bytes 7-10: Timestamp (32-bit little-endian) +Bytes 11+: Payload bytes +``` **Parsing Pseudocode**: ```python -def parse_channel_message(data): +def parse_channel_frame(data): packet_type = data[0] offset = 1 # Check for V3 format - if packet_type == 0x11: # V3 + if packet_type in (0x11, 0x1C): # V3 snr_byte = data[offset] snr = ((snr_byte if snr_byte < 128 else snr_byte - 256) / 4.0) offset += 3 # Skip SNR + reserved channel_idx = data[offset] path_len = data[offset + 1] - txt_type = data[offset + 2] + item_type = data[offset + 2] timestamp = int.from_bytes(data[offset+3:offset+7], 'little') payload = data[offset+7:] - if txt_type == 0: + is_text = packet_type in (0x08, 0x11) + if is_text and item_type == 0: message = payload.decode('utf-8') else: message = None return { 'channel_idx': channel_idx, - 'txt_type': txt_type, + 'item_type': item_type, 'timestamp': timestamp, 'payload': payload, 'message': message, - 'snr': snr if packet_type == 0x11 else None + 'snr': snr if packet_type in (0x11, 0x1C) else None } ``` @@ -556,6 +590,8 @@ Use `CMD_SEND_CHANNEL_TXT_MSG` for plain text, and `CMD_SEND_CHANNEL_DATA` for b | 0x10 | PACKET_CONTACT_MSG_RECV_V3 | Contact message (V3 with SNR) | | 0x11 | PACKET_CHANNEL_MSG_RECV_V3 | Channel message (V3 with SNR) | | 0x12 | PACKET_CHANNEL_INFO | Channel information | +| 0x1B | PACKET_CHANNEL_DATA_RECV | Channel data (standard) | +| 0x1C | PACKET_CHANNEL_DATA_RECV_V3| Channel data (V3 with SNR) | | 0x80 | PACKET_ADVERTISEMENT | Advertisement packet | | 0x82 | PACKET_ACK | Acknowledgment | | 0x83 | PACKET_MESSAGES_WAITING | Messages waiting notification | @@ -775,7 +811,7 @@ BLE implementations enqueue and deliver one protocol frame per BLE write/notific - `SET_CHANNEL` → `PACKET_OK` or `PACKET_ERROR` - `CMD_SEND_CHANNEL_TXT_MSG` → `PACKET_OK` or `PACKET_ERROR` - `CMD_SEND_CHANNEL_DATA` → `PACKET_OK` or `PACKET_ERROR` - - `GET_MESSAGE` → `PACKET_CHANNEL_MSG_RECV`, `PACKET_CONTACT_MSG_RECV`, or `PACKET_NO_MORE_MSGS` + - `GET_MESSAGE` → `PACKET_CHANNEL_MSG_RECV`, `PACKET_CHANNEL_DATA_RECV`, `PACKET_CONTACT_MSG_RECV`, or `PACKET_NO_MORE_MSGS` - `GET_BATTERY` → `PACKET_BATTERY` 4. **Timeout Handling**: @@ -855,8 +891,9 @@ response = wait_for_response(PACKET_OK) def on_notification_received(data): packet_type = data[0] - if packet_type == PACKET_CHANNEL_MSG_RECV or packet_type == PACKET_CHANNEL_MSG_RECV_V3: - message = parse_channel_message(data) + if packet_type in (PACKET_CHANNEL_MSG_RECV, PACKET_CHANNEL_MSG_RECV_V3, + PACKET_CHANNEL_DATA_RECV, PACKET_CHANNEL_DATA_RECV_V3): + message = parse_channel_frame(data) handle_channel_message(message) elif packet_type == PACKET_MESSAGES_WAITING: # Poll for messages diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 85df464fc1..490f34a134 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -92,6 +92,8 @@ #define RESP_CODE_STATS 24 // v8+, second byte is stats type #define RESP_CODE_AUTOADD_CONFIG 25 #define RESP_ALLOWED_REPEAT_FREQ 26 +#define RESP_CODE_CHANNEL_DATA_RECV 27 +#define RESP_CODE_CHANNEL_DATA_RECV_V3 28 #define SEND_TIMEOUT_BASE_MILLIS 500 #define FLOOD_SEND_TIMEOUT_FACTOR 16.0f @@ -205,7 +207,8 @@ void MyMesh::updateContactFromFrame(ContactInfo &contact, uint32_t& last_mod, co } bool MyMesh::Frame::isChannelMsg() const { - return buf[0] == RESP_CODE_CHANNEL_MSG_RECV || buf[0] == RESP_CODE_CHANNEL_MSG_RECV_V3; + return buf[0] == RESP_CODE_CHANNEL_MSG_RECV || buf[0] == RESP_CODE_CHANNEL_MSG_RECV_V3 || + buf[0] == RESP_CODE_CHANNEL_DATA_RECV || buf[0] == RESP_CODE_CHANNEL_DATA_RECV_V3; } void MyMesh::addToOfflineQueue(const uint8_t frame[], int len) { @@ -565,27 +568,30 @@ void MyMesh::onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packe #endif } -void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, uint8_t txt_type, +void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, uint8_t data_type, const uint8_t *data, size_t data_len) { int i = 0; if (app_target_ver >= 3) { - out_frame[i++] = RESP_CODE_CHANNEL_MSG_RECV_V3; + out_frame[i++] = RESP_CODE_CHANNEL_DATA_RECV_V3; out_frame[i++] = (int8_t)(pkt->getSNR() * 4); out_frame[i++] = 0; // reserved1 out_frame[i++] = 0; // reserved2 } else { - out_frame[i++] = RESP_CODE_CHANNEL_MSG_RECV; + out_frame[i++] = RESP_CODE_CHANNEL_DATA_RECV; } uint8_t channel_idx = findChannelIdx(channel); out_frame[i++] = channel_idx; out_frame[i++] = pkt->isRouteFlood() ? pkt->path_len : 0xFF; - out_frame[i++] = txt_type; + out_frame[i++] = data_type; memcpy(&out_frame[i], ×tamp, 4); i += 4; size_t available = MAX_FRAME_SIZE - i; - if (data_len > available) data_len = available; + if (data_len > available) { + MESH_DEBUG_PRINTLN("onChannelDataRecv(): payload_len=%d exceeds frame space=%d, truncating", (uint32_t)data_len, (uint32_t)available); + data_len = available; + } int copy_len = (int)data_len; if (copy_len > 0) { memcpy(&out_frame[i], data, copy_len); @@ -1069,29 +1075,27 @@ void MyMesh::handleCmdFrame(size_t len) { } } else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG) { // send GroupChannel text msg int i = 1; - uint8_t txt_type = cmd_frame[i++]; + uint8_t txt_type = cmd_frame[i++]; // should be TXT_TYPE_PLAIN uint8_t channel_idx = cmd_frame[i++]; uint32_t msg_timestamp; memcpy(&msg_timestamp, &cmd_frame[i], 4); i += 4; const char *text = (char *)&cmd_frame[i]; - int text_len = (len > (size_t)i) ? (int)(len - i) : 0; if (txt_type != TXT_TYPE_PLAIN) { writeErrFrame(ERR_CODE_UNSUPPORTED_CMD); } else { ChannelDetails channel; - if (!getChannel(channel_idx, channel)) { - writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx - } else if (sendGroupMessage(msg_timestamp, channel.channel, _prefs.node_name, text, text_len)) { + bool success = getChannel(channel_idx, channel); + if (success && sendGroupMessage(msg_timestamp, channel.channel, _prefs.node_name, text, len - i)) { writeOKFrame(); } else { - writeErrFrame(ERR_CODE_TABLE_FULL); + writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx } } } else if (cmd_frame[0] == CMD_SEND_CHANNEL_DATA) { // send GroupChannel datagram int i = 1; - uint8_t txt_type = cmd_frame[i++]; + uint8_t data_type = cmd_frame[i++]; uint8_t channel_idx = cmd_frame[i++]; uint32_t msg_timestamp; memcpy(&msg_timestamp, &cmd_frame[i], 4); @@ -1102,9 +1106,12 @@ void MyMesh::handleCmdFrame(size_t len) { ChannelDetails channel; if (!getChannel(channel_idx, channel)) { writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx - } else if (txt_type != TXT_TYPE_CUSTOM_BINARY) { + } else if (data_type != DATA_TYPE_CUSTOM) { writeErrFrame(ERR_CODE_UNSUPPORTED_CMD); - } else if (sendGroupData(msg_timestamp, channel.channel, txt_type, payload, payload_len)) { + } else if (payload_len > MAX_GROUP_DATA_LENGTH) { + MESH_DEBUG_PRINTLN("CMD_SEND_CHANNEL_DATA payload too long: %d > %d", payload_len, MAX_GROUP_DATA_LENGTH); + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } else if (sendGroupData(msg_timestamp, channel.channel, data_type, payload, payload_len)) { writeOKFrame(); } else { writeErrFrame(ERR_CODE_TABLE_FULL); diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 0e11264761..78ea6414e1 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -137,7 +137,7 @@ class MyMesh : public BaseChatMesh, public DataStoreHost { const uint8_t *sender_prefix, const char *text) override; void onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, const char *text) override; - void onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, uint8_t txt_type, + void onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, uint8_t data_type, const uint8_t *data, size_t data_len) override; uint8_t onContactRequest(const ContactInfo &contact, uint32_t sender_timestamp, const uint8_t *data, diff --git a/src/MeshCore.h b/src/MeshCore.h index 70cd0f0672..3eb4f9354e 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -17,6 +17,7 @@ #define PATH_HASH_SIZE 1 #define MAX_PACKET_PAYLOAD 184 +#define MAX_GROUP_DATA_LENGTH (MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE - 5) #define MAX_PATH_SIZE 64 #define MAX_TRANS_UNIT 255 @@ -100,4 +101,4 @@ class RTCClock { } }; -} \ No newline at end of file +} diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index e6f59a50b0..d8e089d545 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -353,10 +353,18 @@ int BaseChatMesh::searchChannelsByHash(const uint8_t* hash, mesh::GroupChannel d #endif void BaseChatMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mesh::GroupChannel& channel, uint8_t* data, size_t len) { - if (len < 5) return; + if (len < 5) { + MESH_DEBUG_PRINTLN("onGroupDataRecv: dropping short group payload len=%d", (uint32_t)len); + return; + } + + uint8_t data_type = data[4]; + if (type == PAYLOAD_TYPE_GRP_TXT) { + if ((data_type >> 2) != 0) { + MESH_DEBUG_PRINTLN("onGroupDataRecv: dropping unsupported group text type=%d", (uint32_t)data_type); + return; + } - uint8_t txt_type = data[4]; - if (type == PAYLOAD_TYPE_GRP_TXT && (txt_type >> 2) == 0) { // 0 = plain text msg uint32_t timestamp; memcpy(×tamp, data, 4); @@ -368,7 +376,7 @@ void BaseChatMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mes } else if (type == PAYLOAD_TYPE_GRP_DATA) { uint32_t timestamp; memcpy(×tamp, data, 4); - onChannelDataRecv(channel, packet, timestamp, txt_type, &data[5], len - 5); + onChannelDataRecv(channel, packet, timestamp, data_type, &data[5], len - 5); } } @@ -460,24 +468,28 @@ bool BaseChatMesh::sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& chan return false; } -bool BaseChatMesh::sendGroupData(uint32_t timestamp, mesh::GroupChannel& channel, uint8_t txt_type, const uint8_t* data, int data_len) { - if (data_len < 0) return false; - // createGroupDatagram() accepts at most (MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE) - // plaintext bytes; subtract our 5-byte {timestamp, txt_type} header. - const int max_group_data_len = (MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE) - 5; - if (data_len > max_group_data_len) data_len = max_group_data_len; +bool BaseChatMesh::sendGroupData(uint32_t timestamp, mesh::GroupChannel& channel, uint8_t data_type, const uint8_t* data, int data_len) { + if (data_len < 0) { + MESH_DEBUG_PRINTLN("sendGroupData: invalid negative data_len=%d", data_len); + return false; + } + if (data_len > MAX_GROUP_DATA_LENGTH) { + MESH_DEBUG_PRINTLN("sendGroupData: data_len=%d exceeds max=%d", data_len, MAX_GROUP_DATA_LENGTH); + return false; + } - uint8_t temp[MAX_PACKET_PAYLOAD]; + uint8_t temp[5 + MAX_GROUP_DATA_LENGTH]; memcpy(temp, ×tamp, 4); - temp[4] = txt_type; + temp[4] = data_type; if (data_len > 0) memcpy(&temp[5], data, data_len); auto pkt = createGroupDatagram(PAYLOAD_TYPE_GRP_DATA, channel, temp, 5 + data_len); - if (pkt) { - sendFloodScoped(channel, pkt); - return true; + if (pkt == NULL) { + MESH_DEBUG_PRINTLN("sendGroupData: unable to create group datagram, data_len=%d", data_len); + return false; } - return false; + sendFloodScoped(channel, pkt); + return true; } bool BaseChatMesh::shareContactZeroHop(const ContactInfo& contact) { diff --git a/src/helpers/BaseChatMesh.h b/src/helpers/BaseChatMesh.h index 02b2dfabb2..12fcb95719 100644 --- a/src/helpers/BaseChatMesh.h +++ b/src/helpers/BaseChatMesh.h @@ -111,7 +111,7 @@ class BaseChatMesh : public mesh::Mesh { virtual uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const = 0; virtual void onSendTimeout() = 0; virtual void onChannelMessageRecv(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t timestamp, const char *text) = 0; - virtual void onChannelDataRecv(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t timestamp, uint8_t txt_type, + virtual void onChannelDataRecv(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t timestamp, uint8_t data_type, const uint8_t* data, size_t data_len) {} virtual uint8_t onContactRequest(const ContactInfo& contact, uint32_t sender_timestamp, const uint8_t* data, uint8_t len, uint8_t* reply) = 0; virtual void onContactResponse(const ContactInfo& contact, const uint8_t* data, uint8_t len) = 0; @@ -150,7 +150,7 @@ class BaseChatMesh : public mesh::Mesh { int sendMessage(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& expected_ack, uint32_t& est_timeout); int sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& est_timeout); bool sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& channel, const char* sender_name, const char* text, int text_len); - bool sendGroupData(uint32_t timestamp, mesh::GroupChannel& channel, uint8_t txt_type, const uint8_t* data, int data_len); + bool sendGroupData(uint32_t timestamp, mesh::GroupChannel& channel, uint8_t data_type, const uint8_t* data, int data_len); int sendLogin(const ContactInfo& recipient, const char* password, uint32_t& est_timeout); int sendAnonReq(const ContactInfo& recipient, const uint8_t* data, uint8_t len, uint32_t& tag, uint32_t& est_timeout); int sendRequest(const ContactInfo& recipient, uint8_t req_type, uint32_t& tag, uint32_t& est_timeout); diff --git a/src/helpers/TxtDataHelpers.h b/src/helpers/TxtDataHelpers.h index 0fbbd25357..a853a64db3 100644 --- a/src/helpers/TxtDataHelpers.h +++ b/src/helpers/TxtDataHelpers.h @@ -6,7 +6,7 @@ #define TXT_TYPE_PLAIN 0 // a plain text message #define TXT_TYPE_CLI_DATA 1 // a CLI command #define TXT_TYPE_SIGNED_PLAIN 2 // plain text, signed by sender -#define TXT_TYPE_CUSTOM_BINARY 0xFF // custom app binary payload (group/channel datagrams) +#define DATA_TYPE_CUSTOM 0xFF // custom app binary payload (group/channel datagrams) class StrHelper { public: From f25d7a882ad5d99540fb9da3fa8f0f84ea85d0bd Mon Sep 17 00:00:00 2001 From: Janez T Date: Wed, 18 Mar 2026 20:14:22 +0100 Subject: [PATCH 04/10] fix: Align channel data framing ref: #1928 --- docs/companion_protocol.md | 42 ++++++++++++----------------- examples/companion_radio/MyMesh.cpp | 33 +++++++++++------------ src/MeshCore.h | 2 +- src/Packet.h | 2 +- src/helpers/BaseChatMesh.cpp | 40 ++++++++++++++++++--------- 5 files changed, 63 insertions(+), 56 deletions(-) diff --git a/docs/companion_protocol.md b/docs/companion_protocol.md index c00be4a202..a8c09bef3e 100644 --- a/docs/companion_protocol.md +++ b/docs/companion_protocol.md @@ -303,7 +303,7 @@ Bytes 7+: Binary payload bytes (variable length) - Values other than `0xFF` are reserved for official protocol extensions. **Limits**: -- Maximum payload length is `163` bytes (`MAX_GROUP_DATA_LENGTH`). +- Maximum payload length is `160` bytes. - Larger payloads are rejected with `PACKET_ERROR` / `ERR_CODE_ILLEGAL_ARG`. **Response**: `PACKET_OK` (0x00) on success @@ -326,7 +326,7 @@ Byte 0: 0x0A **Response**: - `PACKET_CHANNEL_MSG_RECV` (0x08) or `PACKET_CHANNEL_MSG_RECV_V3` (0x11) for channel messages -- `PACKET_CHANNEL_DATA_RECV` (0x1B) or `PACKET_CHANNEL_DATA_RECV_V3` (0x1C) for channel data +- `PACKET_CHANNEL_DATA_RECV` (0x1B) for channel data - `PACKET_CONTACT_MSG_RECV` (0x07) or `PACKET_CONTACT_MSG_RECV_V3` (0x10) for contact messages - `PACKET_NO_MORE_MSGS` (0x0A) if no messages available @@ -397,8 +397,7 @@ Messages are received via the TX characteristic (notifications). The device send - `PACKET_CHANNEL_MSG_RECV_V3` (0x11) - Version 3 with SNR 2. **Channel Data**: - - `PACKET_CHANNEL_DATA_RECV` (0x1B) - Standard format - - `PACKET_CHANNEL_DATA_RECV_V3` (0x1C) - Version 3 with SNR + - `PACKET_CHANNEL_DATA_RECV` (0x1B) - Includes SNR and reserved bytes 3. **Contact Messages**: - `PACKET_CONTACT_MSG_RECV` (0x07) - Standard format @@ -502,26 +501,17 @@ Bytes 11+: Payload bytes ### Channel Data Format -**Standard Format** (`PACKET_CHANNEL_DATA_RECV`, 0x1B): +**Format** (`PACKET_CHANNEL_DATA_RECV`, 0x1B): ``` Byte 0: 0x1B (packet type) -Byte 1: Channel Index (0-7) -Byte 2: Path Length -Byte 3: Data Type -Bytes 4-7: Timestamp (32-bit little-endian) -Bytes 8+: Payload bytes -``` - -**V3 Format** (`PACKET_CHANNEL_DATA_RECV_V3`, 0x1C): -``` -Byte 0: 0x1C (packet type) Byte 1: SNR (signed byte, multiplied by 4) Bytes 2-3: Reserved Byte 4: Channel Index (0-7) Byte 5: Path Length Byte 6: Data Type -Bytes 7-10: Timestamp (32-bit little-endian) -Bytes 11+: Payload bytes +Byte 7: Data Length +Bytes 8-11: Timestamp (32-bit little-endian) +Bytes 12+: Payload bytes ``` **Parsing Pseudocode**: @@ -529,9 +519,10 @@ Bytes 11+: Payload bytes def parse_channel_frame(data): packet_type = data[0] offset = 1 + snr = None - # Check for V3 format - if packet_type in (0x11, 0x1C): # V3 + # Formats with explicit SNR/reserved bytes + if packet_type in (0x11, 0x1B): snr_byte = data[offset] snr = ((snr_byte if snr_byte < 128 else snr_byte - 256) / 4.0) offset += 3 # Skip SNR + reserved @@ -539,8 +530,10 @@ def parse_channel_frame(data): channel_idx = data[offset] path_len = data[offset + 1] item_type = data[offset + 2] - timestamp = int.from_bytes(data[offset+3:offset+7], 'little') - payload = data[offset+7:] + data_len = data[offset + 3] if packet_type == 0x1B else None + timestamp = int.from_bytes(data[offset+4:offset+8], 'little') if packet_type == 0x1B else int.from_bytes(data[offset+3:offset+7], 'little') + payload_offset = offset + 8 if packet_type == 0x1B else offset + 7 + payload = data[payload_offset:payload_offset + data_len] if packet_type == 0x1B else data[payload_offset:] is_text = packet_type in (0x08, 0x11) if is_text and item_type == 0: message = payload.decode('utf-8') @@ -553,7 +546,7 @@ def parse_channel_frame(data): 'timestamp': timestamp, 'payload': payload, 'message': message, - 'snr': snr if packet_type in (0x11, 0x1C) else None + 'snr': snr } ``` @@ -590,8 +583,7 @@ Use `CMD_SEND_CHANNEL_TXT_MSG` for plain text, and `CMD_SEND_CHANNEL_DATA` for b | 0x10 | PACKET_CONTACT_MSG_RECV_V3 | Contact message (V3 with SNR) | | 0x11 | PACKET_CHANNEL_MSG_RECV_V3 | Channel message (V3 with SNR) | | 0x12 | PACKET_CHANNEL_INFO | Channel information | -| 0x1B | PACKET_CHANNEL_DATA_RECV | Channel data (standard) | -| 0x1C | PACKET_CHANNEL_DATA_RECV_V3| Channel data (V3 with SNR) | +| 0x1B | PACKET_CHANNEL_DATA_RECV | Channel data (includes SNR) | | 0x80 | PACKET_ADVERTISEMENT | Advertisement packet | | 0x82 | PACKET_ACK | Acknowledgment | | 0x83 | PACKET_MESSAGES_WAITING | Messages waiting notification | @@ -892,7 +884,7 @@ def on_notification_received(data): packet_type = data[0] if packet_type in (PACKET_CHANNEL_MSG_RECV, PACKET_CHANNEL_MSG_RECV_V3, - PACKET_CHANNEL_DATA_RECV, PACKET_CHANNEL_DATA_RECV_V3): + PACKET_CHANNEL_DATA_RECV): message = parse_channel_frame(data) handle_channel_message(message) elif packet_type == PACKET_MESSAGES_WAITING: diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 490f34a134..2a540c5be7 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -93,7 +93,8 @@ #define RESP_CODE_AUTOADD_CONFIG 25 #define RESP_ALLOWED_REPEAT_FREQ 26 #define RESP_CODE_CHANNEL_DATA_RECV 27 -#define RESP_CODE_CHANNEL_DATA_RECV_V3 28 + +#define MAX_CHANNEL_DATA_LENGTH (MAX_FRAME_SIZE - 12) #define SEND_TIMEOUT_BASE_MILLIS 500 #define FLOOD_SEND_TIMEOUT_FACTOR 16.0f @@ -208,7 +209,7 @@ void MyMesh::updateContactFromFrame(ContactInfo &contact, uint32_t& last_mod, co bool MyMesh::Frame::isChannelMsg() const { return buf[0] == RESP_CODE_CHANNEL_MSG_RECV || buf[0] == RESP_CODE_CHANNEL_MSG_RECV_V3 || - buf[0] == RESP_CODE_CHANNEL_DATA_RECV || buf[0] == RESP_CODE_CHANNEL_DATA_RECV_V3; + buf[0] == RESP_CODE_CHANNEL_DATA_RECV; } void MyMesh::addToOfflineQueue(const uint8_t frame[], int len) { @@ -570,28 +571,26 @@ void MyMesh::onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packe void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, uint8_t data_type, const uint8_t *data, size_t data_len) { - int i = 0; - if (app_target_ver >= 3) { - out_frame[i++] = RESP_CODE_CHANNEL_DATA_RECV_V3; - out_frame[i++] = (int8_t)(pkt->getSNR() * 4); - out_frame[i++] = 0; // reserved1 - out_frame[i++] = 0; // reserved2 - } else { - out_frame[i++] = RESP_CODE_CHANNEL_DATA_RECV; + if (data_len > MAX_CHANNEL_DATA_LENGTH) { + MESH_DEBUG_PRINTLN("onChannelDataRecv: dropping payload_len=%d exceeds frame limit=%d", + (uint32_t)data_len, (uint32_t)MAX_CHANNEL_DATA_LENGTH); + return; } + int i = 0; + out_frame[i++] = RESP_CODE_CHANNEL_DATA_RECV; + out_frame[i++] = (int8_t)(pkt->getSNR() * 4); + out_frame[i++] = 0; // reserved1 + out_frame[i++] = 0; // reserved2 + uint8_t channel_idx = findChannelIdx(channel); out_frame[i++] = channel_idx; out_frame[i++] = pkt->isRouteFlood() ? pkt->path_len : 0xFF; out_frame[i++] = data_type; + out_frame[i++] = (uint8_t)data_len; memcpy(&out_frame[i], ×tamp, 4); i += 4; - size_t available = MAX_FRAME_SIZE - i; - if (data_len > available) { - MESH_DEBUG_PRINTLN("onChannelDataRecv(): payload_len=%d exceeds frame space=%d, truncating", (uint32_t)data_len, (uint32_t)available); - data_len = available; - } int copy_len = (int)data_len; if (copy_len > 0) { memcpy(&out_frame[i], data, copy_len); @@ -1108,8 +1107,8 @@ void MyMesh::handleCmdFrame(size_t len) { writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx } else if (data_type != DATA_TYPE_CUSTOM) { writeErrFrame(ERR_CODE_UNSUPPORTED_CMD); - } else if (payload_len > MAX_GROUP_DATA_LENGTH) { - MESH_DEBUG_PRINTLN("CMD_SEND_CHANNEL_DATA payload too long: %d > %d", payload_len, MAX_GROUP_DATA_LENGTH); + } else if (payload_len > MAX_CHANNEL_DATA_LENGTH) { + MESH_DEBUG_PRINTLN("CMD_SEND_CHANNEL_DATA payload too long: %d > %d", payload_len, MAX_CHANNEL_DATA_LENGTH); writeErrFrame(ERR_CODE_ILLEGAL_ARG); } else if (sendGroupData(msg_timestamp, channel.channel, data_type, payload, payload_len)) { writeOKFrame(); diff --git a/src/MeshCore.h b/src/MeshCore.h index 3eb4f9354e..cf8f949e66 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -17,7 +17,7 @@ #define PATH_HASH_SIZE 1 #define MAX_PACKET_PAYLOAD 184 -#define MAX_GROUP_DATA_LENGTH (MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE - 5) +#define MAX_GROUP_DATA_LENGTH (MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE - 6) #define MAX_PATH_SIZE 64 #define MAX_TRANS_UNIT 255 diff --git a/src/Packet.h b/src/Packet.h index 7861954618..c5c5ab0084 100644 --- a/src/Packet.h +++ b/src/Packet.h @@ -22,7 +22,7 @@ namespace mesh { #define PAYLOAD_TYPE_ACK 0x03 // a simple ack #define PAYLOAD_TYPE_ADVERT 0x04 // a node advertising its Identity #define PAYLOAD_TYPE_GRP_TXT 0x05 // an (unverified) group text message (prefixed with channel hash, MAC) (enc data: timestamp, "name: msg") -#define PAYLOAD_TYPE_GRP_DATA 0x06 // an (unverified) group datagram (prefixed with channel hash, MAC) (enc data: timestamp, blob) +#define PAYLOAD_TYPE_GRP_DATA 0x06 // an (unverified) group datagram (prefixed with channel hash, MAC) (enc data: timestamp, data_type, data_len, blob) #define PAYLOAD_TYPE_ANON_REQ 0x07 // generic request (prefixed with dest_hash, ephemeral pub_key, MAC) (enc data: ...) #define PAYLOAD_TYPE_PATH 0x08 // returned path (prefixed with dest/src hashes, MAC) (enc data: path, extra) #define PAYLOAD_TYPE_TRACE 0x09 // trace a path, collecting SNI for each hop diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index d8e089d545..5f4e0d4da9 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -353,15 +353,15 @@ int BaseChatMesh::searchChannelsByHash(const uint8_t* hash, mesh::GroupChannel d #endif void BaseChatMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mesh::GroupChannel& channel, uint8_t* data, size_t len) { - if (len < 5) { - MESH_DEBUG_PRINTLN("onGroupDataRecv: dropping short group payload len=%d", (uint32_t)len); - return; - } - - uint8_t data_type = data[4]; if (type == PAYLOAD_TYPE_GRP_TXT) { - if ((data_type >> 2) != 0) { - MESH_DEBUG_PRINTLN("onGroupDataRecv: dropping unsupported group text type=%d", (uint32_t)data_type); + if (len < 5) { + MESH_DEBUG_PRINTLN("onGroupDataRecv: dropping short group text payload len=%d", (uint32_t)len); + return; + } + + uint8_t txt_type = data[4]; + if ((txt_type >> 2) != 0) { + MESH_DEBUG_PRINTLN("onGroupDataRecv: dropping unsupported group text type=%d", (uint32_t)txt_type); return; } @@ -374,9 +374,24 @@ void BaseChatMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mes // notify UI of this new message onChannelMessageRecv(channel, packet, timestamp, (const char *) &data[5]); // let UI know } else if (type == PAYLOAD_TYPE_GRP_DATA) { + if (len < 6) { + MESH_DEBUG_PRINTLN("onGroupDataRecv: dropping short group data payload len=%d", (uint32_t)len); + return; + } + uint32_t timestamp; memcpy(×tamp, data, 4); - onChannelDataRecv(channel, packet, timestamp, data_type, &data[5], len - 5); + uint8_t data_type = data[4]; + uint8_t data_len = data[5]; + size_t available_len = len - 6; + + if (data_len > available_len) { + MESH_DEBUG_PRINTLN("onGroupDataRecv: dropping malformed group data type=%d len=%d available=%d", + (uint32_t)data_type, (uint32_t)data_len, (uint32_t)available_len); + return; + } + + onChannelDataRecv(channel, packet, timestamp, data_type, &data[6], data_len); } } @@ -478,12 +493,13 @@ bool BaseChatMesh::sendGroupData(uint32_t timestamp, mesh::GroupChannel& channel return false; } - uint8_t temp[5 + MAX_GROUP_DATA_LENGTH]; + uint8_t temp[6 + MAX_GROUP_DATA_LENGTH]; memcpy(temp, ×tamp, 4); temp[4] = data_type; - if (data_len > 0) memcpy(&temp[5], data, data_len); + temp[5] = (uint8_t)data_len; + if (data_len > 0) memcpy(&temp[6], data, data_len); - auto pkt = createGroupDatagram(PAYLOAD_TYPE_GRP_DATA, channel, temp, 5 + data_len); + auto pkt = createGroupDatagram(PAYLOAD_TYPE_GRP_DATA, channel, temp, 6 + data_len); if (pkt == NULL) { MESH_DEBUG_PRINTLN("sendGroupData: unable to create group datagram, data_len=%d", data_len); return false; From 37b72ffc17ad5875ac53ec10946001dc81c3dcfc Mon Sep 17 00:00:00 2001 From: Janez T Date: Wed, 18 Mar 2026 20:29:49 +0100 Subject: [PATCH 05/10] fix: Scope group data docs ref: #1928 --- docs/companion_protocol.md | 281 +++++++++++++++++++++++-------------- 1 file changed, 174 insertions(+), 107 deletions(-) diff --git a/docs/companion_protocol.md b/docs/companion_protocol.md index a8c09bef3e..ffb4f84c50 100644 --- a/docs/companion_protocol.md +++ b/docs/companion_protocol.md @@ -1,6 +1,6 @@ # Companion Protocol -- **Last Updated**: 2026-03-08 +- **Last Updated**: 2026-01-03 - **Protocol Version**: Companion Firmware v1.12.0+ > NOTE: This document is still in development. Some information may be inaccurate. @@ -100,7 +100,7 @@ When writing commands to the RX characteristic, specify the write type: ### MTU (Maximum Transmission Unit) -The default BLE MTU is 23 bytes (20 bytes payload). For larger commands like `SET_CHANNEL` (50 bytes), you may need to: +The default BLE MTU is 23 bytes (20 bytes payload). For larger commands like `SET_CHANNEL` (66 bytes), you may need to: 1. **Request Larger MTU**: Request MTU of 512 bytes if supported - Android: `gatt.requestMtu(512)` @@ -167,16 +167,16 @@ The first byte indicates the packet type (see [Response Parsing](#response-parsi **Command Format**: ``` Byte 0: 0x01 -Bytes 1-7: Reserved (currently ignored by firmware) -Bytes 8+: Application name (UTF-8, optional) +Byte 1: 0x03 +Bytes 2-10: "mccli" (ASCII, null-padded to 9 bytes) ``` **Example** (hex): ``` -01 00 00 00 00 00 00 00 6d 63 63 6c 69 +01 03 6d 63 63 6c 69 00 00 00 00 ``` -**Response**: `PACKET_SELF_INFO` (0x05) +**Response**: `PACKET_OK` (0x00) --- @@ -216,6 +216,8 @@ Byte 1: Channel Index (0-7) **Response**: `PACKET_CHANNEL_INFO` (0x12) with channel details +**Note**: The device does not return channel secrets for security reasons. Store secrets locally when creating channels. + --- ### 4. Set Channel @@ -227,10 +229,10 @@ Byte 1: Channel Index (0-7) Byte 0: 0x20 Byte 1: Channel Index (0-7) Bytes 2-33: Channel Name (32 bytes, UTF-8, null-padded) -Bytes 34-49: Secret (16 bytes) +Bytes 34-65: Secret (32 bytes) ``` -**Total Length**: 50 bytes +**Total Length**: 66 bytes **Channel Index**: - Index 0: Reserved for public channels (no secret) @@ -241,46 +243,41 @@ Bytes 34-49: Secret (16 bytes) - Maximum 32 bytes - Padded with null bytes (0x00) if shorter -**Secret Field** (16 bytes): -- For **private channels**: 16-byte secret +**Secret Field** (32 bytes): +- For **private channels**: 32-byte secret - For **public channels**: All zeros (0x00) **Example** (create channel "YourChannelName" at index 1 with secret): ``` 20 01 53 4D 53 00 00 ... (name padded to 32 bytes) - [16 bytes of secret] + [32 bytes of secret] ``` -**Note**: The 32-byte secret variant is unsupported and returns `PACKET_ERROR`. - **Response**: `PACKET_OK` (0x00) on success, `PACKET_ERROR` (0x01) on failure --- -### 5. Send Channel Text Message +### 5. Send Channel Message -**Purpose**: Send a plain text message to a channel. +**Purpose**: Send a text message to a channel. **Command Format**: ``` Byte 0: 0x03 -Byte 1: Text Type +Byte 1: 0x00 Byte 2: Channel Index (0-7) Bytes 3-6: Timestamp (32-bit little-endian Unix timestamp, seconds) -Bytes 7+: UTF-8 text bytes (variable length) +Bytes 7+: Message Text (UTF-8, variable length) ``` **Timestamp**: Unix timestamp in seconds (32-bit unsigned integer, little-endian) -**Text Type**: -- Must be `0x00` (`TXT_TYPE_PLAIN`) for this command. - **Example** (send "Hello" to channel 1 at timestamp 1234567890): ``` 03 00 01 D2 02 96 49 48 65 6C 6C 6F ``` -**Response**: `PACKET_OK` (0x00) on success +**Response**: `PACKET_MSG_SENT` (0x06) on success --- @@ -299,12 +296,12 @@ Bytes 7+: Binary payload bytes (variable length) **Data Type / Transport Mapping**: - `0xFF` (`DATA_TYPE_CUSTOM`) must be used for custom-protocol binary datagrams. -- `0x00` (`TXT_TYPE_PLAIN`) is invalid for this command. +- `0x00` is invalid for this command. - Values other than `0xFF` are reserved for official protocol extensions. **Limits**: - Maximum payload length is `160` bytes. -- Larger payloads are rejected with `PACKET_ERROR` / `ERR_CODE_ILLEGAL_ARG`. +- Larger payloads are rejected with `PACKET_ERROR`. **Response**: `PACKET_OK` (0x00) on success @@ -334,9 +331,9 @@ Byte 0: 0x0A --- -### 8. Get Battery and Storage +### 8. Get Battery -**Purpose**: Query device battery voltage and storage usage. +**Purpose**: Query device battery level. **Command Format**: ``` @@ -348,7 +345,7 @@ Byte 0: 0x14 14 ``` -**Response**: `PACKET_BATTERY` (0x0C) with battery millivolts and storage information +**Response**: `PACKET_BATTERY` (0x0C) with battery percentage --- @@ -376,7 +373,7 @@ Byte 0: 0x14 1. **Set Channel**: - Fetch all channel slots, and find one with empty name and all-zero secret - Generate or provide a 16-byte secret - - Send `CMD_SET_CHANNEL` with name and a 16-byte secret + - Send `CMD_SET_CHANNEL` with name and secret 2. **Get Channel**: - Send `CMD_GET_CHANNEL` with channel index - Parse `RESP_CODE_CHANNEL_INFO` response @@ -390,7 +387,7 @@ Byte 0: 0x14 ### Receiving Messages -Messages are received via the TX characteristic (notifications). The device sends: +Messages are received via the RX characteristic (notifications). The device sends: 1. **Channel Messages**: - `PACKET_CHANNEL_MSG_RECV` (0x08) - Standard format @@ -479,7 +476,7 @@ Byte 1: Channel Index (0-7) Byte 2: Path Length Byte 3: Text Type Bytes 4-7: Timestamp (32-bit little-endian) -Bytes 8+: Payload bytes +Bytes 8+: Message Text (UTF-8) ``` **V3 Format** (`PACKET_CHANNEL_MSG_RECV_V3`, 0x11): @@ -491,13 +488,34 @@ Byte 4: Channel Index (0-7) Byte 5: Path Length Byte 6: Text Type Bytes 7-10: Timestamp (32-bit little-endian) -Bytes 11+: Payload bytes +Bytes 11+: Message Text (UTF-8) ``` -**Payload Meaning**: -- If `txt_type == 0x00`: payload is UTF-8 channel text. -- If `txt_type != 0x00`: payload is binary (for example image/voice fragments) and must be treated as raw bytes. - For custom app datagrams sent via `CMD_SEND_CHANNEL_DATA`, `data_type` must be `0xFF`. +**Parsing Pseudocode**: +```python +def parse_channel_message(data): + packet_type = data[0] + offset = 1 + + # Check for V3 format + if packet_type == 0x11: # V3 + snr_byte = data[offset] + snr = ((snr_byte if snr_byte < 128 else snr_byte - 256) / 4.0) + offset += 3 # Skip SNR + reserved + + channel_idx = data[offset] + path_len = data[offset + 1] + txt_type = data[offset + 2] + timestamp = int.from_bytes(data[offset+3:offset+7], 'little') + message = data[offset+7:].decode('utf-8') + + return { + 'channel_idx': channel_idx, + 'timestamp': timestamp, + 'message': message, + 'snr': snr if packet_type == 0x11 else None + } +``` ### Channel Data Format @@ -516,43 +534,29 @@ Bytes 12+: Payload bytes **Parsing Pseudocode**: ```python -def parse_channel_frame(data): - packet_type = data[0] - offset = 1 - snr = None - - # Formats with explicit SNR/reserved bytes - if packet_type in (0x11, 0x1B): - snr_byte = data[offset] - snr = ((snr_byte if snr_byte < 128 else snr_byte - 256) / 4.0) - offset += 3 # Skip SNR + reserved - - channel_idx = data[offset] - path_len = data[offset + 1] - item_type = data[offset + 2] - data_len = data[offset + 3] if packet_type == 0x1B else None - timestamp = int.from_bytes(data[offset+4:offset+8], 'little') if packet_type == 0x1B else int.from_bytes(data[offset+3:offset+7], 'little') - payload_offset = offset + 8 if packet_type == 0x1B else offset + 7 - payload = data[payload_offset:payload_offset + data_len] if packet_type == 0x1B else data[payload_offset:] - is_text = packet_type in (0x08, 0x11) - if is_text and item_type == 0: - message = payload.decode('utf-8') - else: - message = None - +def parse_channel_data(data): + snr_byte = data[1] + snr = ((snr_byte if snr_byte < 128 else snr_byte - 256) / 4.0) + channel_idx = data[4] + path_len = data[5] + data_type = data[6] + data_len = data[7] + timestamp = int.from_bytes(data[8:12], 'little') + payload = data[12:12 + data_len] + return { 'channel_idx': channel_idx, - 'item_type': item_type, + 'path_len': path_len, + 'data_type': data_type, 'timestamp': timestamp, 'payload': payload, - 'message': message, - 'snr': snr + 'snr': snr, } ``` ### Sending Messages -Use `CMD_SEND_CHANNEL_TXT_MSG` for plain text, and `CMD_SEND_CHANNEL_DATA` for binary datagrams (see [Commands](#commands)). +Use the `SEND_CHANNEL_MESSAGE` command for plain text messages. Use `CMD_SEND_CHANNEL_DATA` for binary datagrams (see [Commands](#commands)). **Important**: - Messages are limited to 133 characters per MeshCore specification @@ -573,7 +577,7 @@ Use `CMD_SEND_CHANNEL_TXT_MSG` for plain text, and `CMD_SEND_CHANNEL_DATA` for b | 0x03 | PACKET_CONTACT | Contact information | | 0x04 | PACKET_CONTACT_END | End of contact list | | 0x05 | PACKET_SELF_INFO | Device self-information | -| 0x06 | PACKET_MSG_SENT | Direct message sent confirmation | +| 0x06 | PACKET_MSG_SENT | Message sent confirmation | | 0x07 | PACKET_CONTACT_MSG_RECV | Contact message (standard) | | 0x08 | PACKET_CHANNEL_MSG_RECV | Channel message (standard) | | 0x09 | PACKET_CURRENT_TIME | Current time response | @@ -608,10 +612,10 @@ Byte 1: Error code (optional) Byte 0: 0x12 Byte 1: Channel Index Bytes 2-33: Channel Name (32 bytes, null-terminated) -Bytes 34-49: Secret (16 bytes) +Bytes 34-65: Secret (32 bytes, but device typically only returns 20 bytes total) ``` -**Note**: The device returns the 16-byte channel secret in this response. +**Note**: The device may not return the full 66-byte packet. Parse what is available. The secret field is typically not returned for security reasons. **PACKET_DEVICE_INFO** (0x0D): ``` @@ -626,8 +630,6 @@ Bytes 4-7: BLE PIN (32-bit little-endian) Bytes 8-19: Firmware Build (12 bytes, UTF-8, null-padded) Bytes 20-59: Model (40 bytes, UTF-8, null-padded) Bytes 60-79: Version (20 bytes, UTF-8, null-padded) -Byte 80: Client repeat enabled/preferred (firmware v9+) -Byte 81: Path hash mode (firmware v10+) ``` **Parsing Pseudocode**: @@ -653,7 +655,9 @@ def parse_device_info(data): **PACKET_BATTERY** (0x0C): ``` Byte 0: 0x0C -Bytes 1-2: Battery Voltage (16-bit little-endian, millivolts) +Bytes 1-2: Battery Level (16-bit little-endian, percentage 0-100) + +Optional (if data size > 3): Bytes 3-6: Used Storage (32-bit little-endian, KB) Bytes 7-10: Total Storage (32-bit little-endian, KB) ``` @@ -664,12 +668,14 @@ def parse_battery(data): if len(data) < 3: return None - mv = int.from_bytes(data[1:3], 'little') - info = {'battery_mv': mv} + level = int.from_bytes(data[1:3], 'little') + info = {'level': level} - if len(data) >= 11: - info['used_kb'] = int.from_bytes(data[3:7], 'little') - info['total_kb'] = int.from_bytes(data[7:11], 'little') + if len(data) > 3: + used_kb = int.from_bytes(data[3:7], 'little') + total_kb = int.from_bytes(data[7:11], 'little') + info['used_kb'] = used_kb + info['total_kb'] = total_kb return info ``` @@ -691,7 +697,7 @@ Bytes 48-51: Radio Frequency (32-bit little-endian, divided by 1000.0) Bytes 52-55: Radio Bandwidth (32-bit little-endian, divided by 1000.0) Byte 56: Radio Spreading Factor Byte 57: Radio Coding Rate -Bytes 58+: Device Name (UTF-8, variable length, no null terminator required) +Bytes 58+: Device Name (UTF-8, variable length, null-terminated) ``` **Parsing Pseudocode**: @@ -739,12 +745,12 @@ def parse_self_info(data): return info ``` -**PACKET_MSG_SENT** (0x06, used by direct/contact send flows): +**PACKET_MSG_SENT** (0x06): ``` Byte 0: 0x06 -Byte 1: Route Flag (0 = direct, 1 = flood) -Bytes 2-5: Tag / Expected ACK (4 bytes, little-endian) -Bytes 6-9: Suggested Timeout (32-bit little-endian, milliseconds) +Byte 1: Message Type +Bytes 2-5: Expected ACK (4 bytes, hex) +Bytes 6-9: Suggested Timeout (32-bit little-endian, seconds) ``` **PACKET_ACK** (0x82): @@ -772,36 +778,93 @@ Bytes 1-6: ACK Code (6 bytes, hex) **Note**: Error codes may vary by firmware version. Always check byte 1 of `PACKET_ERROR` response. -### Frame Handling +### Partial Packet Handling -BLE implementations enqueue and deliver one protocol frame per BLE write/notification at the firmware layer. +BLE notifications may arrive in chunks, especially for larger packets. Implement buffering: -- Apps should treat each characteristic write/notification as exactly one companion protocol frame -- Apps should still validate frame lengths before parsing -- Future transports or firmware revisions may differ, so avoid assuming fixed payload sizes for variable-length responses +**Implementation**: +```python +class PacketBuffer: + def __init__(self): + self.buffer = bytearray() + self.expected_length = None + + def add_data(self, data): + self.buffer.extend(data) + + # Check if we have a complete packet + if len(self.buffer) >= 1: + packet_type = self.buffer[0] + + # Determine expected length based on packet type + expected = self.get_expected_length(packet_type) + + if expected is not None and len(self.buffer) >= expected: + # Complete packet + packet = bytes(self.buffer[:expected]) + self.buffer = self.buffer[expected:] + return packet + elif expected is None: + # Variable length packet - try to parse what we have + # Some packets have minimum length requirements + if self.can_parse_partial(packet_type): + return self.try_parse_partial() + + return None # Incomplete packet + + def get_expected_length(self, packet_type): + # Fixed-length packets + fixed_lengths = { + 0x00: 5, # PACKET_OK (minimum) + 0x01: 2, # PACKET_ERROR (minimum) + 0x0A: 1, # PACKET_NO_MORE_MSGS + 0x14: 3, # PACKET_BATTERY (minimum) + } + return fixed_lengths.get(packet_type) + + def can_parse_partial(self, packet_type): + # Some packets can be parsed partially + return packet_type in [0x12, 0x08, 0x11, 0x1B, 0x07, 0x10, 0x05, 0x0D] + + def try_parse_partial(self): + # Try to parse with available data + # Return packet if successfully parsed, None otherwise + # This is packet-type specific + pass +``` + +**Usage**: +```python +buffer = PacketBuffer() + +def on_notification_received(data): + packet = buffer.add_data(data) + if packet: + parse_and_handle_packet(packet) +``` ### Response Handling 1. **Command-Response Pattern**: - - Send command via RX characteristic - - Wait for response via TX characteristic (notification) + - Send command via TX characteristic + - Wait for response via RX characteristic (notification) - Match response to command using sequence numbers or command type - Handle timeout (typically 5 seconds) - Use command queue to prevent concurrent commands 2. **Asynchronous Messages**: - - Device may send messages at any time via TX characteristic + - Device may send messages at any time via RX characteristic - Handle `PACKET_MESSAGES_WAITING` (0x83) by polling `GET_MESSAGE` command - Parse incoming messages and route to appropriate handlers - - Validate frame length before decoding + - Buffer partial packets until complete 3. **Response Matching**: - Match responses to commands by expected packet type: - - `APP_START` → `PACKET_SELF_INFO` + - `APP_START` → `PACKET_OK` - `DEVICE_QUERY` → `PACKET_DEVICE_INFO` - `GET_CHANNEL` → `PACKET_CHANNEL_INFO` - `SET_CHANNEL` → `PACKET_OK` or `PACKET_ERROR` - - `CMD_SEND_CHANNEL_TXT_MSG` → `PACKET_OK` or `PACKET_ERROR` + - `SEND_CHANNEL_MESSAGE` → `PACKET_MSG_SENT` - `CMD_SEND_CHANNEL_DATA` → `PACKET_OK` or `PACKET_ERROR` - `GET_MESSAGE` → `PACKET_CHANNEL_MSG_RECV`, `PACKET_CHANNEL_DATA_RECV`, `PACKET_CONTACT_MSG_RECV`, or `PACKET_NO_MORE_MSGS` - `GET_BATTERY` → `PACKET_BATTERY` @@ -831,16 +894,16 @@ device = scan_for_device("MeshCore") gatt = connect_to_device(device) # 3. Discover services and characteristics -service = discover_service(gatt, "6E400001-B5A3-F393-E0A9-E50E24DCCA9E") -rx_char = discover_characteristic(service, "6E400002-B5A3-F393-E0A9-E50E24DCCA9E") -tx_char = discover_characteristic(service, "6E400003-B5A3-F393-E0A9-E50E24DCCA9E") +service = discover_service(gatt, "0000ff00-0000-1000-8000-00805f9b34fb") +rx_char = discover_characteristic(service, "0000ff01-0000-1000-8000-00805f9b34fb") +tx_char = discover_characteristic(service, "0000ff02-0000-1000-8000-00805f9b34fb") -# 4. Enable notifications on TX characteristic -enable_notifications(tx_char, on_notification_received) +# 4. Enable notifications on RX characteristic +enable_notifications(rx_char, on_notification_received) # 5. Send AppStart command -send_command(rx_char, build_app_start()) -wait_for_response(PACKET_SELF_INFO) +send_command(tx_char, build_app_start()) +wait_for_response(PACKET_OK) ``` ### Creating a Private Channel @@ -850,16 +913,21 @@ wait_for_response(PACKET_SELF_INFO) secret_16_bytes = generate_secret(16) # Use CSPRNG secret_hex = secret_16_bytes.hex() -# 2. Build SET_CHANNEL command +# 2. Expand secret to 32 bytes using SHA-512 +import hashlib +sha512_hash = hashlib.sha512(secret_16_bytes).digest() +secret_32_bytes = sha512_hash[:32] + +# 3. Build SET_CHANNEL command channel_name = "YourChannelName" channel_index = 1 # Use 1-7 for private channels -command = build_set_channel(channel_index, channel_name, secret_16_bytes) +command = build_set_channel(channel_index, channel_name, secret_32_bytes) -# 3. Send command -send_command(rx_char, command) +# 4. Send command +send_command(tx_char, command) response = wait_for_response(PACKET_OK) -# 4. Store secret locally +# 5. Store secret locally (device won't return it) store_channel_secret(channel_index, secret_hex) ``` @@ -873,8 +941,8 @@ timestamp = int(time.time()) command = build_channel_message(channel_index, message, timestamp) # 2. Send command -send_command(rx_char, command) -response = wait_for_response(PACKET_OK) +send_command(tx_char, command) +response = wait_for_response(PACKET_MSG_SENT) ``` ### Receiving Messages @@ -883,13 +951,12 @@ response = wait_for_response(PACKET_OK) def on_notification_received(data): packet_type = data[0] - if packet_type in (PACKET_CHANNEL_MSG_RECV, PACKET_CHANNEL_MSG_RECV_V3, - PACKET_CHANNEL_DATA_RECV): - message = parse_channel_frame(data) + if packet_type == PACKET_CHANNEL_MSG_RECV or packet_type == PACKET_CHANNEL_MSG_RECV_V3: + message = parse_channel_message(data) handle_channel_message(message) elif packet_type == PACKET_MESSAGES_WAITING: # Poll for messages - send_command(rx_char, build_get_message()) + send_command(tx_char, build_get_message()) ``` --- From 896d60c02610a237c06475d0d8155976b5b8d4bf Mon Sep 17 00:00:00 2001 From: Janez T Date: Wed, 18 Mar 2026 20:32:47 +0100 Subject: [PATCH 06/10] fix: Keep data docs only ref: #1928 --- docs/companion_protocol.md | 57 +++++--------------------------------- 1 file changed, 7 insertions(+), 50 deletions(-) diff --git a/docs/companion_protocol.md b/docs/companion_protocol.md index ffb4f84c50..e74c527469 100644 --- a/docs/companion_protocol.md +++ b/docs/companion_protocol.md @@ -307,7 +307,7 @@ Bytes 7+: Binary payload bytes (variable length) --- -### 7. Get Message +### 6. Get Message **Purpose**: Request the next queued message from the device. @@ -323,7 +323,6 @@ Byte 0: 0x0A **Response**: - `PACKET_CHANNEL_MSG_RECV` (0x08) or `PACKET_CHANNEL_MSG_RECV_V3` (0x11) for channel messages -- `PACKET_CHANNEL_DATA_RECV` (0x1B) for channel data - `PACKET_CONTACT_MSG_RECV` (0x07) or `PACKET_CONTACT_MSG_RECV_V3` (0x10) for contact messages - `PACKET_NO_MORE_MSGS` (0x0A) if no messages available @@ -331,7 +330,7 @@ Byte 0: 0x0A --- -### 8. Get Battery +### 7. Get Battery **Purpose**: Query device battery level. @@ -393,14 +392,11 @@ Messages are received via the RX characteristic (notifications). The device send - `PACKET_CHANNEL_MSG_RECV` (0x08) - Standard format - `PACKET_CHANNEL_MSG_RECV_V3` (0x11) - Version 3 with SNR -2. **Channel Data**: - - `PACKET_CHANNEL_DATA_RECV` (0x1B) - Includes SNR and reserved bytes - -3. **Contact Messages**: +2. **Contact Messages**: - `PACKET_CONTACT_MSG_RECV` (0x07) - Standard format - `PACKET_CONTACT_MSG_RECV_V3` (0x10) - Version 3 with SNR -4. **Notifications**: +3. **Notifications**: - `PACKET_MESSAGES_WAITING` (0x83) - Indicates messages are queued ### Contact Message Format @@ -517,46 +513,9 @@ def parse_channel_message(data): } ``` -### Channel Data Format - -**Format** (`PACKET_CHANNEL_DATA_RECV`, 0x1B): -``` -Byte 0: 0x1B (packet type) -Byte 1: SNR (signed byte, multiplied by 4) -Bytes 2-3: Reserved -Byte 4: Channel Index (0-7) -Byte 5: Path Length -Byte 6: Data Type -Byte 7: Data Length -Bytes 8-11: Timestamp (32-bit little-endian) -Bytes 12+: Payload bytes -``` - -**Parsing Pseudocode**: -```python -def parse_channel_data(data): - snr_byte = data[1] - snr = ((snr_byte if snr_byte < 128 else snr_byte - 256) / 4.0) - channel_idx = data[4] - path_len = data[5] - data_type = data[6] - data_len = data[7] - timestamp = int.from_bytes(data[8:12], 'little') - payload = data[12:12 + data_len] - - return { - 'channel_idx': channel_idx, - 'path_len': path_len, - 'data_type': data_type, - 'timestamp': timestamp, - 'payload': payload, - 'snr': snr, - } -``` - ### Sending Messages -Use the `SEND_CHANNEL_MESSAGE` command for plain text messages. Use `CMD_SEND_CHANNEL_DATA` for binary datagrams (see [Commands](#commands)). +Use the `SEND_CHANNEL_MESSAGE` command (see [Commands](#commands)). **Important**: - Messages are limited to 133 characters per MeshCore specification @@ -587,7 +546,6 @@ Use the `SEND_CHANNEL_MESSAGE` command for plain text messages. Use `CMD_SEND_CH | 0x10 | PACKET_CONTACT_MSG_RECV_V3 | Contact message (V3 with SNR) | | 0x11 | PACKET_CHANNEL_MSG_RECV_V3 | Channel message (V3 with SNR) | | 0x12 | PACKET_CHANNEL_INFO | Channel information | -| 0x1B | PACKET_CHANNEL_DATA_RECV | Channel data (includes SNR) | | 0x80 | PACKET_ADVERTISEMENT | Advertisement packet | | 0x82 | PACKET_ACK | Acknowledgment | | 0x83 | PACKET_MESSAGES_WAITING | Messages waiting notification | @@ -824,7 +782,7 @@ class PacketBuffer: def can_parse_partial(self, packet_type): # Some packets can be parsed partially - return packet_type in [0x12, 0x08, 0x11, 0x1B, 0x07, 0x10, 0x05, 0x0D] + return packet_type in [0x12, 0x08, 0x11, 0x07, 0x10, 0x05, 0x0D] def try_parse_partial(self): # Try to parse with available data @@ -865,8 +823,7 @@ def on_notification_received(data): - `GET_CHANNEL` → `PACKET_CHANNEL_INFO` - `SET_CHANNEL` → `PACKET_OK` or `PACKET_ERROR` - `SEND_CHANNEL_MESSAGE` → `PACKET_MSG_SENT` - - `CMD_SEND_CHANNEL_DATA` → `PACKET_OK` or `PACKET_ERROR` - - `GET_MESSAGE` → `PACKET_CHANNEL_MSG_RECV`, `PACKET_CHANNEL_DATA_RECV`, `PACKET_CONTACT_MSG_RECV`, or `PACKET_NO_MORE_MSGS` + - `GET_MESSAGE` → `PACKET_CHANNEL_MSG_RECV`, `PACKET_CONTACT_MSG_RECV`, or `PACKET_NO_MORE_MSGS` - `GET_BATTERY` → `PACKET_BATTERY` 4. **Timeout Handling**: From 2fe3c36b8fc249db6cf78f4ed3f852e425f68029 Mon Sep 17 00:00:00 2001 From: Janez T Date: Wed, 18 Mar 2026 20:34:15 +0100 Subject: [PATCH 07/10] fix: Trim grp docs ref: #1928 --- docs/companion_protocol.md | 176 ++++++++++++------------------------- 1 file changed, 56 insertions(+), 120 deletions(-) diff --git a/docs/companion_protocol.md b/docs/companion_protocol.md index e74c527469..917df1df83 100644 --- a/docs/companion_protocol.md +++ b/docs/companion_protocol.md @@ -1,6 +1,6 @@ # Companion Protocol -- **Last Updated**: 2026-01-03 +- **Last Updated**: 2026-03-08 - **Protocol Version**: Companion Firmware v1.12.0+ > NOTE: This document is still in development. Some information may be inaccurate. @@ -100,7 +100,7 @@ When writing commands to the RX characteristic, specify the write type: ### MTU (Maximum Transmission Unit) -The default BLE MTU is 23 bytes (20 bytes payload). For larger commands like `SET_CHANNEL` (66 bytes), you may need to: +The default BLE MTU is 23 bytes (20 bytes payload). For larger commands like `SET_CHANNEL` (50 bytes), you may need to: 1. **Request Larger MTU**: Request MTU of 512 bytes if supported - Android: `gatt.requestMtu(512)` @@ -167,16 +167,16 @@ The first byte indicates the packet type (see [Response Parsing](#response-parsi **Command Format**: ``` Byte 0: 0x01 -Byte 1: 0x03 -Bytes 2-10: "mccli" (ASCII, null-padded to 9 bytes) +Bytes 1-7: Reserved (currently ignored by firmware) +Bytes 8+: Application name (UTF-8, optional) ``` **Example** (hex): ``` -01 03 6d 63 63 6c 69 00 00 00 00 +01 00 00 00 00 00 00 00 6d 63 63 6c 69 ``` -**Response**: `PACKET_OK` (0x00) +**Response**: `PACKET_SELF_INFO` (0x05) --- @@ -216,8 +216,6 @@ Byte 1: Channel Index (0-7) **Response**: `PACKET_CHANNEL_INFO` (0x12) with channel details -**Note**: The device does not return channel secrets for security reasons. Store secrets locally when creating channels. - --- ### 4. Set Channel @@ -229,10 +227,10 @@ Byte 1: Channel Index (0-7) Byte 0: 0x20 Byte 1: Channel Index (0-7) Bytes 2-33: Channel Name (32 bytes, UTF-8, null-padded) -Bytes 34-65: Secret (32 bytes) +Bytes 34-49: Secret (16 bytes) ``` -**Total Length**: 66 bytes +**Total Length**: 50 bytes **Channel Index**: - Index 0: Reserved for public channels (no secret) @@ -243,16 +241,18 @@ Bytes 34-65: Secret (32 bytes) - Maximum 32 bytes - Padded with null bytes (0x00) if shorter -**Secret Field** (32 bytes): -- For **private channels**: 32-byte secret +**Secret Field** (16 bytes): +- For **private channels**: 16-byte secret - For **public channels**: All zeros (0x00) **Example** (create channel "YourChannelName" at index 1 with secret): ``` 20 01 53 4D 53 00 00 ... (name padded to 32 bytes) - [32 bytes of secret] + [16 bytes of secret] ``` +**Note**: The 32-byte secret variant is unsupported and returns `PACKET_ERROR`. + **Response**: `PACKET_OK` (0x00) on success, `PACKET_ERROR` (0x01) on failure --- @@ -330,9 +330,9 @@ Byte 0: 0x0A --- -### 7. Get Battery +### 7. Get Battery and Storage -**Purpose**: Query device battery level. +**Purpose**: Query device battery voltage and storage usage. **Command Format**: ``` @@ -344,7 +344,7 @@ Byte 0: 0x14 14 ``` -**Response**: `PACKET_BATTERY` (0x0C) with battery percentage +**Response**: `PACKET_BATTERY` (0x0C) with battery millivolts and storage information --- @@ -372,7 +372,7 @@ Byte 0: 0x14 1. **Set Channel**: - Fetch all channel slots, and find one with empty name and all-zero secret - Generate or provide a 16-byte secret - - Send `CMD_SET_CHANNEL` with name and secret + - Send `CMD_SET_CHANNEL` with name and a 16-byte secret 2. **Get Channel**: - Send `CMD_GET_CHANNEL` with channel index - Parse `RESP_CODE_CHANNEL_INFO` response @@ -386,7 +386,7 @@ Byte 0: 0x14 ### Receiving Messages -Messages are received via the RX characteristic (notifications). The device sends: +Messages are received via the TX characteristic (notifications). The device sends: 1. **Channel Messages**: - `PACKET_CHANNEL_MSG_RECV` (0x08) - Standard format @@ -570,10 +570,10 @@ Byte 1: Error code (optional) Byte 0: 0x12 Byte 1: Channel Index Bytes 2-33: Channel Name (32 bytes, null-terminated) -Bytes 34-65: Secret (32 bytes, but device typically only returns 20 bytes total) +Bytes 34-49: Secret (16 bytes) ``` -**Note**: The device may not return the full 66-byte packet. Parse what is available. The secret field is typically not returned for security reasons. +**Note**: The device returns the 16-byte channel secret in this response. **PACKET_DEVICE_INFO** (0x0D): ``` @@ -588,6 +588,8 @@ Bytes 4-7: BLE PIN (32-bit little-endian) Bytes 8-19: Firmware Build (12 bytes, UTF-8, null-padded) Bytes 20-59: Model (40 bytes, UTF-8, null-padded) Bytes 60-79: Version (20 bytes, UTF-8, null-padded) +Byte 80: Client repeat enabled/preferred (firmware v9+) +Byte 81: Path hash mode (firmware v10+) ``` **Parsing Pseudocode**: @@ -613,9 +615,7 @@ def parse_device_info(data): **PACKET_BATTERY** (0x0C): ``` Byte 0: 0x0C -Bytes 1-2: Battery Level (16-bit little-endian, percentage 0-100) - -Optional (if data size > 3): +Bytes 1-2: Battery Voltage (16-bit little-endian, millivolts) Bytes 3-6: Used Storage (32-bit little-endian, KB) Bytes 7-10: Total Storage (32-bit little-endian, KB) ``` @@ -626,14 +626,12 @@ def parse_battery(data): if len(data) < 3: return None - level = int.from_bytes(data[1:3], 'little') - info = {'level': level} + mv = int.from_bytes(data[1:3], 'little') + info = {'battery_mv': mv} - if len(data) > 3: - used_kb = int.from_bytes(data[3:7], 'little') - total_kb = int.from_bytes(data[7:11], 'little') - info['used_kb'] = used_kb - info['total_kb'] = total_kb + if len(data) >= 11: + info['used_kb'] = int.from_bytes(data[3:7], 'little') + info['total_kb'] = int.from_bytes(data[7:11], 'little') return info ``` @@ -655,7 +653,7 @@ Bytes 48-51: Radio Frequency (32-bit little-endian, divided by 1000.0) Bytes 52-55: Radio Bandwidth (32-bit little-endian, divided by 1000.0) Byte 56: Radio Spreading Factor Byte 57: Radio Coding Rate -Bytes 58+: Device Name (UTF-8, variable length, null-terminated) +Bytes 58+: Device Name (UTF-8, variable length, no null terminator required) ``` **Parsing Pseudocode**: @@ -706,9 +704,9 @@ def parse_self_info(data): **PACKET_MSG_SENT** (0x06): ``` Byte 0: 0x06 -Byte 1: Message Type -Bytes 2-5: Expected ACK (4 bytes, hex) -Bytes 6-9: Suggested Timeout (32-bit little-endian, seconds) +Byte 1: Route Flag (0 = direct, 1 = flood) +Bytes 2-5: Tag / Expected ACK (4 bytes, little-endian) +Bytes 6-9: Suggested Timeout (32-bit little-endian, milliseconds) ``` **PACKET_ACK** (0x82): @@ -736,89 +734,32 @@ Bytes 1-6: ACK Code (6 bytes, hex) **Note**: Error codes may vary by firmware version. Always check byte 1 of `PACKET_ERROR` response. -### Partial Packet Handling - -BLE notifications may arrive in chunks, especially for larger packets. Implement buffering: - -**Implementation**: -```python -class PacketBuffer: - def __init__(self): - self.buffer = bytearray() - self.expected_length = None - - def add_data(self, data): - self.buffer.extend(data) - - # Check if we have a complete packet - if len(self.buffer) >= 1: - packet_type = self.buffer[0] - - # Determine expected length based on packet type - expected = self.get_expected_length(packet_type) - - if expected is not None and len(self.buffer) >= expected: - # Complete packet - packet = bytes(self.buffer[:expected]) - self.buffer = self.buffer[expected:] - return packet - elif expected is None: - # Variable length packet - try to parse what we have - # Some packets have minimum length requirements - if self.can_parse_partial(packet_type): - return self.try_parse_partial() - - return None # Incomplete packet - - def get_expected_length(self, packet_type): - # Fixed-length packets - fixed_lengths = { - 0x00: 5, # PACKET_OK (minimum) - 0x01: 2, # PACKET_ERROR (minimum) - 0x0A: 1, # PACKET_NO_MORE_MSGS - 0x14: 3, # PACKET_BATTERY (minimum) - } - return fixed_lengths.get(packet_type) - - def can_parse_partial(self, packet_type): - # Some packets can be parsed partially - return packet_type in [0x12, 0x08, 0x11, 0x07, 0x10, 0x05, 0x0D] - - def try_parse_partial(self): - # Try to parse with available data - # Return packet if successfully parsed, None otherwise - # This is packet-type specific - pass -``` +### Frame Handling -**Usage**: -```python -buffer = PacketBuffer() +BLE implementations enqueue and deliver one protocol frame per BLE write/notification at the firmware layer. -def on_notification_received(data): - packet = buffer.add_data(data) - if packet: - parse_and_handle_packet(packet) -``` +- Apps should treat each characteristic write/notification as exactly one companion protocol frame +- Apps should still validate frame lengths before parsing +- Future transports or firmware revisions may differ, so avoid assuming fixed payload sizes for variable-length responses ### Response Handling 1. **Command-Response Pattern**: - - Send command via TX characteristic - - Wait for response via RX characteristic (notification) + - Send command via RX characteristic + - Wait for response via TX characteristic (notification) - Match response to command using sequence numbers or command type - Handle timeout (typically 5 seconds) - Use command queue to prevent concurrent commands 2. **Asynchronous Messages**: - - Device may send messages at any time via RX characteristic + - Device may send messages at any time via TX characteristic - Handle `PACKET_MESSAGES_WAITING` (0x83) by polling `GET_MESSAGE` command - Parse incoming messages and route to appropriate handlers - - Buffer partial packets until complete + - Validate frame length before decoding 3. **Response Matching**: - Match responses to commands by expected packet type: - - `APP_START` → `PACKET_OK` + - `APP_START` → `PACKET_SELF_INFO` - `DEVICE_QUERY` → `PACKET_DEVICE_INFO` - `GET_CHANNEL` → `PACKET_CHANNEL_INFO` - `SET_CHANNEL` → `PACKET_OK` or `PACKET_ERROR` @@ -851,16 +792,16 @@ device = scan_for_device("MeshCore") gatt = connect_to_device(device) # 3. Discover services and characteristics -service = discover_service(gatt, "0000ff00-0000-1000-8000-00805f9b34fb") -rx_char = discover_characteristic(service, "0000ff01-0000-1000-8000-00805f9b34fb") -tx_char = discover_characteristic(service, "0000ff02-0000-1000-8000-00805f9b34fb") +service = discover_service(gatt, "6E400001-B5A3-F393-E0A9-E50E24DCCA9E") +rx_char = discover_characteristic(service, "6E400002-B5A3-F393-E0A9-E50E24DCCA9E") +tx_char = discover_characteristic(service, "6E400003-B5A3-F393-E0A9-E50E24DCCA9E") -# 4. Enable notifications on RX characteristic -enable_notifications(rx_char, on_notification_received) +# 4. Enable notifications on TX characteristic +enable_notifications(tx_char, on_notification_received) # 5. Send AppStart command -send_command(tx_char, build_app_start()) -wait_for_response(PACKET_OK) +send_command(rx_char, build_app_start()) +wait_for_response(PACKET_SELF_INFO) ``` ### Creating a Private Channel @@ -870,21 +811,16 @@ wait_for_response(PACKET_OK) secret_16_bytes = generate_secret(16) # Use CSPRNG secret_hex = secret_16_bytes.hex() -# 2. Expand secret to 32 bytes using SHA-512 -import hashlib -sha512_hash = hashlib.sha512(secret_16_bytes).digest() -secret_32_bytes = sha512_hash[:32] - -# 3. Build SET_CHANNEL command +# 2. Build SET_CHANNEL command channel_name = "YourChannelName" channel_index = 1 # Use 1-7 for private channels -command = build_set_channel(channel_index, channel_name, secret_32_bytes) +command = build_set_channel(channel_index, channel_name, secret_16_bytes) -# 4. Send command -send_command(tx_char, command) +# 3. Send command +send_command(rx_char, command) response = wait_for_response(PACKET_OK) -# 5. Store secret locally (device won't return it) +# 4. Store secret locally store_channel_secret(channel_index, secret_hex) ``` @@ -898,7 +834,7 @@ timestamp = int(time.time()) command = build_channel_message(channel_index, message, timestamp) # 2. Send command -send_command(tx_char, command) +send_command(rx_char, command) response = wait_for_response(PACKET_MSG_SENT) ``` @@ -913,7 +849,7 @@ def on_notification_received(data): handle_channel_message(message) elif packet_type == PACKET_MESSAGES_WAITING: # Poll for messages - send_command(tx_char, build_get_message()) + send_command(rx_char, build_get_message()) ``` --- From 1fb26e76235754ff203b4de7ef5072f47936e745 Mon Sep 17 00:00:00 2001 From: Janez T Date: Thu, 19 Mar 2026 09:22:12 +0100 Subject: [PATCH 08/10] fix: Drop grp data timestamp ref: #1928 --- docs/companion_protocol.md | 7 ++++--- examples/companion_radio/MyMesh.cpp | 11 +++-------- examples/companion_radio/MyMesh.h | 2 +- src/MeshCore.h | 2 +- src/Packet.h | 2 +- src/helpers/BaseChatMesh.cpp | 25 +++++++++++-------------- src/helpers/BaseChatMesh.h | 4 ++-- 7 files changed, 23 insertions(+), 30 deletions(-) diff --git a/docs/companion_protocol.md b/docs/companion_protocol.md index 917df1df83..2ec9a51288 100644 --- a/docs/companion_protocol.md +++ b/docs/companion_protocol.md @@ -290,8 +290,7 @@ Bytes 7+: Message Text (UTF-8, variable length) Byte 0: 0x3E Byte 1: Data Type (`data_type`) Byte 2: Channel Index (0-7) -Bytes 3-6: Timestamp (32-bit little-endian Unix timestamp, seconds) -Bytes 7+: Binary payload bytes (variable length) +Bytes 3+: Binary payload bytes (variable length) ``` **Data Type / Transport Mapping**: @@ -299,8 +298,10 @@ Bytes 7+: Binary payload bytes (variable length) - `0x00` is invalid for this command. - Values other than `0xFF` are reserved for official protocol extensions. +**Note**: Applications that need a timestamp should encode it inside the binary payload. + **Limits**: -- Maximum payload length is `160` bytes. +- Maximum payload length is `166` bytes. - Larger payloads are rejected with `PACKET_ERROR`. **Response**: `PACKET_OK` (0x00) on success diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 2a540c5be7..ac5afe243b 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -94,7 +94,7 @@ #define RESP_ALLOWED_REPEAT_FREQ 26 #define RESP_CODE_CHANNEL_DATA_RECV 27 -#define MAX_CHANNEL_DATA_LENGTH (MAX_FRAME_SIZE - 12) +#define MAX_CHANNEL_DATA_LENGTH (MAX_FRAME_SIZE - 8) #define SEND_TIMEOUT_BASE_MILLIS 500 #define FLOOD_SEND_TIMEOUT_FACTOR 16.0f @@ -569,7 +569,7 @@ void MyMesh::onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packe #endif } -void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, uint8_t data_type, +void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint8_t data_type, const uint8_t *data, size_t data_len) { if (data_len > MAX_CHANNEL_DATA_LENGTH) { MESH_DEBUG_PRINTLN("onChannelDataRecv: dropping payload_len=%d exceeds frame limit=%d", @@ -588,8 +588,6 @@ void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet * out_frame[i++] = pkt->isRouteFlood() ? pkt->path_len : 0xFF; out_frame[i++] = data_type; out_frame[i++] = (uint8_t)data_len; - memcpy(&out_frame[i], ×tamp, 4); - i += 4; int copy_len = (int)data_len; if (copy_len > 0) { @@ -1096,9 +1094,6 @@ void MyMesh::handleCmdFrame(size_t len) { int i = 1; uint8_t data_type = cmd_frame[i++]; uint8_t channel_idx = cmd_frame[i++]; - uint32_t msg_timestamp; - memcpy(&msg_timestamp, &cmd_frame[i], 4); - i += 4; const uint8_t *payload = &cmd_frame[i]; int payload_len = (len > (size_t)i) ? (int)(len - i) : 0; @@ -1110,7 +1105,7 @@ void MyMesh::handleCmdFrame(size_t len) { } else if (payload_len > MAX_CHANNEL_DATA_LENGTH) { MESH_DEBUG_PRINTLN("CMD_SEND_CHANNEL_DATA payload too long: %d > %d", payload_len, MAX_CHANNEL_DATA_LENGTH); writeErrFrame(ERR_CODE_ILLEGAL_ARG); - } else if (sendGroupData(msg_timestamp, channel.channel, data_type, payload, payload_len)) { + } else if (sendGroupData(channel.channel, data_type, payload, payload_len)) { writeOKFrame(); } else { writeErrFrame(ERR_CODE_TABLE_FULL); diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 78ea6414e1..485b8af1ca 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -137,7 +137,7 @@ class MyMesh : public BaseChatMesh, public DataStoreHost { const uint8_t *sender_prefix, const char *text) override; void onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, const char *text) override; - void onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, uint8_t data_type, + void onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint8_t data_type, const uint8_t *data, size_t data_len) override; uint8_t onContactRequest(const ContactInfo &contact, uint32_t sender_timestamp, const uint8_t *data, diff --git a/src/MeshCore.h b/src/MeshCore.h index cf8f949e66..5613599583 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -17,7 +17,7 @@ #define PATH_HASH_SIZE 1 #define MAX_PACKET_PAYLOAD 184 -#define MAX_GROUP_DATA_LENGTH (MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE - 6) +#define MAX_GROUP_DATA_LENGTH (MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE - 2) #define MAX_PATH_SIZE 64 #define MAX_TRANS_UNIT 255 diff --git a/src/Packet.h b/src/Packet.h index c5c5ab0084..60f6526af5 100644 --- a/src/Packet.h +++ b/src/Packet.h @@ -22,7 +22,7 @@ namespace mesh { #define PAYLOAD_TYPE_ACK 0x03 // a simple ack #define PAYLOAD_TYPE_ADVERT 0x04 // a node advertising its Identity #define PAYLOAD_TYPE_GRP_TXT 0x05 // an (unverified) group text message (prefixed with channel hash, MAC) (enc data: timestamp, "name: msg") -#define PAYLOAD_TYPE_GRP_DATA 0x06 // an (unverified) group datagram (prefixed with channel hash, MAC) (enc data: timestamp, data_type, data_len, blob) +#define PAYLOAD_TYPE_GRP_DATA 0x06 // an (unverified) group datagram (prefixed with channel hash, MAC) (enc data: data_type, data_len, blob) #define PAYLOAD_TYPE_ANON_REQ 0x07 // generic request (prefixed with dest_hash, ephemeral pub_key, MAC) (enc data: ...) #define PAYLOAD_TYPE_PATH 0x08 // returned path (prefixed with dest/src hashes, MAC) (enc data: path, extra) #define PAYLOAD_TYPE_TRACE 0x09 // trace a path, collecting SNI for each hop diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index 5f4e0d4da9..2a4290edcb 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -374,16 +374,14 @@ void BaseChatMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mes // notify UI of this new message onChannelMessageRecv(channel, packet, timestamp, (const char *) &data[5]); // let UI know } else if (type == PAYLOAD_TYPE_GRP_DATA) { - if (len < 6) { + if (len < 2) { MESH_DEBUG_PRINTLN("onGroupDataRecv: dropping short group data payload len=%d", (uint32_t)len); return; } - uint32_t timestamp; - memcpy(×tamp, data, 4); - uint8_t data_type = data[4]; - uint8_t data_len = data[5]; - size_t available_len = len - 6; + uint8_t data_type = data[0]; + uint8_t data_len = data[1]; + size_t available_len = len - 2; if (data_len > available_len) { MESH_DEBUG_PRINTLN("onGroupDataRecv: dropping malformed group data type=%d len=%d available=%d", @@ -391,7 +389,7 @@ void BaseChatMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mes return; } - onChannelDataRecv(channel, packet, timestamp, data_type, &data[6], data_len); + onChannelDataRecv(channel, packet, data_type, &data[2], data_len); } } @@ -483,7 +481,7 @@ bool BaseChatMesh::sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& chan return false; } -bool BaseChatMesh::sendGroupData(uint32_t timestamp, mesh::GroupChannel& channel, uint8_t data_type, const uint8_t* data, int data_len) { +bool BaseChatMesh::sendGroupData(mesh::GroupChannel& channel, uint8_t data_type, const uint8_t* data, int data_len) { if (data_len < 0) { MESH_DEBUG_PRINTLN("sendGroupData: invalid negative data_len=%d", data_len); return false; @@ -493,13 +491,12 @@ bool BaseChatMesh::sendGroupData(uint32_t timestamp, mesh::GroupChannel& channel return false; } - uint8_t temp[6 + MAX_GROUP_DATA_LENGTH]; - memcpy(temp, ×tamp, 4); - temp[4] = data_type; - temp[5] = (uint8_t)data_len; - if (data_len > 0) memcpy(&temp[6], data, data_len); + uint8_t temp[2 + MAX_GROUP_DATA_LENGTH]; + temp[0] = data_type; + temp[1] = (uint8_t)data_len; + if (data_len > 0) memcpy(&temp[2], data, data_len); - auto pkt = createGroupDatagram(PAYLOAD_TYPE_GRP_DATA, channel, temp, 6 + data_len); + auto pkt = createGroupDatagram(PAYLOAD_TYPE_GRP_DATA, channel, temp, 2 + data_len); if (pkt == NULL) { MESH_DEBUG_PRINTLN("sendGroupData: unable to create group datagram, data_len=%d", data_len); return false; diff --git a/src/helpers/BaseChatMesh.h b/src/helpers/BaseChatMesh.h index 12fcb95719..08a5500525 100644 --- a/src/helpers/BaseChatMesh.h +++ b/src/helpers/BaseChatMesh.h @@ -111,7 +111,7 @@ class BaseChatMesh : public mesh::Mesh { virtual uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const = 0; virtual void onSendTimeout() = 0; virtual void onChannelMessageRecv(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t timestamp, const char *text) = 0; - virtual void onChannelDataRecv(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t timestamp, uint8_t data_type, + virtual void onChannelDataRecv(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint8_t data_type, const uint8_t* data, size_t data_len) {} virtual uint8_t onContactRequest(const ContactInfo& contact, uint32_t sender_timestamp, const uint8_t* data, uint8_t len, uint8_t* reply) = 0; virtual void onContactResponse(const ContactInfo& contact, const uint8_t* data, uint8_t len) = 0; @@ -150,7 +150,7 @@ class BaseChatMesh : public mesh::Mesh { int sendMessage(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& expected_ack, uint32_t& est_timeout); int sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& est_timeout); bool sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& channel, const char* sender_name, const char* text, int text_len); - bool sendGroupData(uint32_t timestamp, mesh::GroupChannel& channel, uint8_t data_type, const uint8_t* data, int data_len); + bool sendGroupData(mesh::GroupChannel& channel, uint8_t data_type, const uint8_t* data, int data_len); int sendLogin(const ContactInfo& recipient, const char* password, uint32_t& est_timeout); int sendAnonReq(const ContactInfo& recipient, const uint8_t* data, uint8_t len, uint32_t& tag, uint32_t& est_timeout); int sendRequest(const ContactInfo& recipient, uint8_t req_type, uint32_t& tag, uint32_t& est_timeout); From 2f68769185ba5a1d0a22afd2b9c7f50387f189be Mon Sep 17 00:00:00 2001 From: Janez T Date: Thu, 19 Mar 2026 09:25:42 +0100 Subject: [PATCH 09/10] fix: Widen grp data type ref: #1928 --- docs/companion_protocol.md | 14 +++++++------- docs/faq.md | 2 +- examples/companion_radio/MyMesh.cpp | 18 ++++++++++++------ examples/companion_radio/MyMesh.h | 2 +- src/MeshCore.h | 2 +- src/Packet.h | 2 +- src/helpers/BaseChatMesh.cpp | 23 ++++++++++++----------- src/helpers/BaseChatMesh.h | 4 ++-- src/helpers/TxtDataHelpers.h | 8 ++++---- 9 files changed, 41 insertions(+), 34 deletions(-) diff --git a/docs/companion_protocol.md b/docs/companion_protocol.md index 2ec9a51288..ce3953ec58 100644 --- a/docs/companion_protocol.md +++ b/docs/companion_protocol.md @@ -288,20 +288,20 @@ Bytes 7+: Message Text (UTF-8, variable length) **Command Format**: ``` Byte 0: 0x3E -Byte 1: Data Type (`data_type`) -Byte 2: Channel Index (0-7) -Bytes 3+: Binary payload bytes (variable length) +Bytes 1-2: Data Type (`data_type`, 16-bit little-endian) +Byte 3: Channel Index (0-7) +Bytes 4+: Binary payload bytes (variable length) ``` **Data Type / Transport Mapping**: -- `0xFF` (`DATA_TYPE_CUSTOM`) must be used for custom-protocol binary datagrams. -- `0x00` is invalid for this command. -- Values other than `0xFF` are reserved for official protocol extensions. +- `0x0000` is invalid for this command. +- `0xFFFF` (`DATA_TYPE_CUSTOM`) is the generic custom-app namespace. +- Other non-zero values can be used as assigned application/community namespaces. **Note**: Applications that need a timestamp should encode it inside the binary payload. **Limits**: -- Maximum payload length is `166` bytes. +- Maximum payload length is `163` bytes. - Larger payloads are rejected with `PACKET_ERROR`. **Response**: `PACKET_OK` (0x00) on success diff --git a/docs/faq.md b/docs/faq.md index 530f97013b..560e3f629b 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -386,7 +386,7 @@ https://github.com/meshcore-dev/MeshCore/blob/main/src/Packet.h#L19 #define PAYLOAD_TYPE_TXT_MSG 0x02 // a plain text message (prefixed with dest/src hashes, MAC) (enc data: timestamp, text) #define PAYLOAD_TYPE_ACK 0x03 // a simple ack #define PAYLOAD_TYPE_ADVERT 0x04 // a node advertising its Identity #define PAYLOAD_TYPE_GRP_TXT 0x05 // an (unverified) group text message (prefixed with channel hash, MAC) (enc data: timestamp, "name: msg") - #define PAYLOAD_TYPE_GRP_DATA 0x06 // an (unverified) group datagram (prefixed with channel hash, MAC) (enc data: timestamp, blob) + #define PAYLOAD_TYPE_GRP_DATA 0x06 // an (unverified) group datagram (prefixed with channel hash, MAC) (enc data: data_type, data_len, blob) #define PAYLOAD_TYPE_ANON_REQ 0x07 // generic request (prefixed with dest_hash, ephemeral pub_key, MAC) (enc data: ...) #define PAYLOAD_TYPE_PATH 0x08 // returned path (prefixed with dest/src hashes, MAC) (enc data: path, extra) diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index ac5afe243b..cb82c954e6 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -94,7 +94,7 @@ #define RESP_ALLOWED_REPEAT_FREQ 26 #define RESP_CODE_CHANNEL_DATA_RECV 27 -#define MAX_CHANNEL_DATA_LENGTH (MAX_FRAME_SIZE - 8) +#define MAX_CHANNEL_DATA_LENGTH (MAX_FRAME_SIZE - 9) #define SEND_TIMEOUT_BASE_MILLIS 500 #define FLOOD_SEND_TIMEOUT_FACTOR 16.0f @@ -569,7 +569,7 @@ void MyMesh::onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packe #endif } -void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint8_t data_type, +void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint16_t data_type, const uint8_t *data, size_t data_len) { if (data_len > MAX_CHANNEL_DATA_LENGTH) { MESH_DEBUG_PRINTLN("onChannelDataRecv: dropping payload_len=%d exceeds frame limit=%d", @@ -586,7 +586,8 @@ void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet * uint8_t channel_idx = findChannelIdx(channel); out_frame[i++] = channel_idx; out_frame[i++] = pkt->isRouteFlood() ? pkt->path_len : 0xFF; - out_frame[i++] = data_type; + out_frame[i++] = (uint8_t)(data_type & 0xFF); + out_frame[i++] = (uint8_t)(data_type >> 8); out_frame[i++] = (uint8_t)data_len; int copy_len = (int)data_len; @@ -1091,8 +1092,13 @@ void MyMesh::handleCmdFrame(size_t len) { } } } else if (cmd_frame[0] == CMD_SEND_CHANNEL_DATA) { // send GroupChannel datagram + if (len < 4) { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + return; + } int i = 1; - uint8_t data_type = cmd_frame[i++]; + uint16_t data_type = ((uint16_t)cmd_frame[i]) | (((uint16_t)cmd_frame[i + 1]) << 8); + i += 2; uint8_t channel_idx = cmd_frame[i++]; const uint8_t *payload = &cmd_frame[i]; int payload_len = (len > (size_t)i) ? (int)(len - i) : 0; @@ -1100,8 +1106,8 @@ void MyMesh::handleCmdFrame(size_t len) { ChannelDetails channel; if (!getChannel(channel_idx, channel)) { writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx - } else if (data_type != DATA_TYPE_CUSTOM) { - writeErrFrame(ERR_CODE_UNSUPPORTED_CMD); + } else if (data_type == 0) { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); } else if (payload_len > MAX_CHANNEL_DATA_LENGTH) { MESH_DEBUG_PRINTLN("CMD_SEND_CHANNEL_DATA payload too long: %d > %d", payload_len, MAX_CHANNEL_DATA_LENGTH); writeErrFrame(ERR_CODE_ILLEGAL_ARG); diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 485b8af1ca..33d615d504 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -137,7 +137,7 @@ class MyMesh : public BaseChatMesh, public DataStoreHost { const uint8_t *sender_prefix, const char *text) override; void onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, const char *text) override; - void onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint8_t data_type, + void onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint16_t data_type, const uint8_t *data, size_t data_len) override; uint8_t onContactRequest(const ContactInfo &contact, uint32_t sender_timestamp, const uint8_t *data, diff --git a/src/MeshCore.h b/src/MeshCore.h index 5613599583..2db1d4c3ec 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -17,7 +17,7 @@ #define PATH_HASH_SIZE 1 #define MAX_PACKET_PAYLOAD 184 -#define MAX_GROUP_DATA_LENGTH (MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE - 2) +#define MAX_GROUP_DATA_LENGTH (MAX_PACKET_PAYLOAD - CIPHER_BLOCK_SIZE - 3) #define MAX_PATH_SIZE 64 #define MAX_TRANS_UNIT 255 diff --git a/src/Packet.h b/src/Packet.h index 60f6526af5..0886a06c4e 100644 --- a/src/Packet.h +++ b/src/Packet.h @@ -22,7 +22,7 @@ namespace mesh { #define PAYLOAD_TYPE_ACK 0x03 // a simple ack #define PAYLOAD_TYPE_ADVERT 0x04 // a node advertising its Identity #define PAYLOAD_TYPE_GRP_TXT 0x05 // an (unverified) group text message (prefixed with channel hash, MAC) (enc data: timestamp, "name: msg") -#define PAYLOAD_TYPE_GRP_DATA 0x06 // an (unverified) group datagram (prefixed with channel hash, MAC) (enc data: data_type, data_len, blob) +#define PAYLOAD_TYPE_GRP_DATA 0x06 // an (unverified) group datagram (prefixed with channel hash, MAC) (enc data: data_type(uint16), data_len, blob) #define PAYLOAD_TYPE_ANON_REQ 0x07 // generic request (prefixed with dest_hash, ephemeral pub_key, MAC) (enc data: ...) #define PAYLOAD_TYPE_PATH 0x08 // returned path (prefixed with dest/src hashes, MAC) (enc data: path, extra) #define PAYLOAD_TYPE_TRACE 0x09 // trace a path, collecting SNI for each hop diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index 2a4290edcb..78e197bee2 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -374,14 +374,14 @@ void BaseChatMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mes // notify UI of this new message onChannelMessageRecv(channel, packet, timestamp, (const char *) &data[5]); // let UI know } else if (type == PAYLOAD_TYPE_GRP_DATA) { - if (len < 2) { + if (len < 3) { MESH_DEBUG_PRINTLN("onGroupDataRecv: dropping short group data payload len=%d", (uint32_t)len); return; } - uint8_t data_type = data[0]; - uint8_t data_len = data[1]; - size_t available_len = len - 2; + uint16_t data_type = ((uint16_t)data[0]) | (((uint16_t)data[1]) << 8); + uint8_t data_len = data[2]; + size_t available_len = len - 3; if (data_len > available_len) { MESH_DEBUG_PRINTLN("onGroupDataRecv: dropping malformed group data type=%d len=%d available=%d", @@ -389,7 +389,7 @@ void BaseChatMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mes return; } - onChannelDataRecv(channel, packet, data_type, &data[2], data_len); + onChannelDataRecv(channel, packet, data_type, &data[3], data_len); } } @@ -481,7 +481,7 @@ bool BaseChatMesh::sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& chan return false; } -bool BaseChatMesh::sendGroupData(mesh::GroupChannel& channel, uint8_t data_type, const uint8_t* data, int data_len) { +bool BaseChatMesh::sendGroupData(mesh::GroupChannel& channel, uint16_t data_type, const uint8_t* data, int data_len) { if (data_len < 0) { MESH_DEBUG_PRINTLN("sendGroupData: invalid negative data_len=%d", data_len); return false; @@ -491,12 +491,13 @@ bool BaseChatMesh::sendGroupData(mesh::GroupChannel& channel, uint8_t data_type, return false; } - uint8_t temp[2 + MAX_GROUP_DATA_LENGTH]; - temp[0] = data_type; - temp[1] = (uint8_t)data_len; - if (data_len > 0) memcpy(&temp[2], data, data_len); + uint8_t temp[3 + MAX_GROUP_DATA_LENGTH]; + temp[0] = (uint8_t)(data_type & 0xFF); + temp[1] = (uint8_t)(data_type >> 8); + temp[2] = (uint8_t)data_len; + if (data_len > 0) memcpy(&temp[3], data, data_len); - auto pkt = createGroupDatagram(PAYLOAD_TYPE_GRP_DATA, channel, temp, 2 + data_len); + auto pkt = createGroupDatagram(PAYLOAD_TYPE_GRP_DATA, channel, temp, 3 + data_len); if (pkt == NULL) { MESH_DEBUG_PRINTLN("sendGroupData: unable to create group datagram, data_len=%d", data_len); return false; diff --git a/src/helpers/BaseChatMesh.h b/src/helpers/BaseChatMesh.h index 08a5500525..c2f9d9154a 100644 --- a/src/helpers/BaseChatMesh.h +++ b/src/helpers/BaseChatMesh.h @@ -111,7 +111,7 @@ class BaseChatMesh : public mesh::Mesh { virtual uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const = 0; virtual void onSendTimeout() = 0; virtual void onChannelMessageRecv(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t timestamp, const char *text) = 0; - virtual void onChannelDataRecv(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint8_t data_type, + virtual void onChannelDataRecv(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint16_t data_type, const uint8_t* data, size_t data_len) {} virtual uint8_t onContactRequest(const ContactInfo& contact, uint32_t sender_timestamp, const uint8_t* data, uint8_t len, uint8_t* reply) = 0; virtual void onContactResponse(const ContactInfo& contact, const uint8_t* data, uint8_t len) = 0; @@ -150,7 +150,7 @@ class BaseChatMesh : public mesh::Mesh { int sendMessage(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& expected_ack, uint32_t& est_timeout); int sendCommandData(const ContactInfo& recipient, uint32_t timestamp, uint8_t attempt, const char* text, uint32_t& est_timeout); bool sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& channel, const char* sender_name, const char* text, int text_len); - bool sendGroupData(mesh::GroupChannel& channel, uint8_t data_type, const uint8_t* data, int data_len); + bool sendGroupData(mesh::GroupChannel& channel, uint16_t data_type, const uint8_t* data, int data_len); int sendLogin(const ContactInfo& recipient, const char* password, uint32_t& est_timeout); int sendAnonReq(const ContactInfo& recipient, const uint8_t* data, uint8_t len, uint32_t& tag, uint32_t& est_timeout); int sendRequest(const ContactInfo& recipient, uint8_t req_type, uint32_t& tag, uint32_t& est_timeout); diff --git a/src/helpers/TxtDataHelpers.h b/src/helpers/TxtDataHelpers.h index a853a64db3..ad845b40ea 100644 --- a/src/helpers/TxtDataHelpers.h +++ b/src/helpers/TxtDataHelpers.h @@ -3,10 +3,10 @@ #include #include -#define TXT_TYPE_PLAIN 0 // a plain text message -#define TXT_TYPE_CLI_DATA 1 // a CLI command -#define TXT_TYPE_SIGNED_PLAIN 2 // plain text, signed by sender -#define DATA_TYPE_CUSTOM 0xFF // custom app binary payload (group/channel datagrams) +#define TXT_TYPE_PLAIN 0 // a plain text message +#define TXT_TYPE_CLI_DATA 1 // a CLI command +#define TXT_TYPE_SIGNED_PLAIN 2 // plain text, signed by sender +#define DATA_TYPE_CUSTOM 0xFFFF // generic custom app namespace for group/channel datagrams class StrHelper { public: From ae9fcb3c0bb5a9a8d8bf7006b8c8a747450bd1dd Mon Sep 17 00:00:00 2001 From: Janez T Date: Thu, 19 Mar 2026 09:35:02 +0100 Subject: [PATCH 10/10] fix: Rename grp dev type ref: #1928 --- docs/companion_protocol.md | 2 +- src/helpers/TxtDataHelpers.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/companion_protocol.md b/docs/companion_protocol.md index ce3953ec58..bbad1e40f0 100644 --- a/docs/companion_protocol.md +++ b/docs/companion_protocol.md @@ -295,7 +295,7 @@ Bytes 4+: Binary payload bytes (variable length) **Data Type / Transport Mapping**: - `0x0000` is invalid for this command. -- `0xFFFF` (`DATA_TYPE_CUSTOM`) is the generic custom-app namespace. +- `0xFFFF` (`DATA_TYPE_DEV`) is the developer namespace for experimenting and developing apps. - Other non-zero values can be used as assigned application/community namespaces. **Note**: Applications that need a timestamp should encode it inside the binary payload. diff --git a/src/helpers/TxtDataHelpers.h b/src/helpers/TxtDataHelpers.h index ad845b40ea..47bbc0ded9 100644 --- a/src/helpers/TxtDataHelpers.h +++ b/src/helpers/TxtDataHelpers.h @@ -6,7 +6,7 @@ #define TXT_TYPE_PLAIN 0 // a plain text message #define TXT_TYPE_CLI_DATA 1 // a CLI command #define TXT_TYPE_SIGNED_PLAIN 2 // plain text, signed by sender -#define DATA_TYPE_CUSTOM 0xFFFF // generic custom app namespace for group/channel datagrams +#define DATA_TYPE_DEV 0xFFFF // developer namespace for experimenting with group/channel datagrams and building apps class StrHelper { public: