Merge branch 'dev' into ez_disable_discoveredContact_eviction_PR

This commit is contained in:
zjs81 authored and GitHub committed 2026-10-07 20:59:37 -07:00
commit 956c779e2c
195 files changed
+26503 -6523

No files matched your search

File diff suppressed because it is too large. Load diff
+76 -15
View File
@@ -213,6 +213,7 @@ const int cmdGetStats = 56;
const int cmdSendAnonReq = 57;
const int cmdSetAutoAddConfig = 58;
const int cmdGetAutoAddConfig = 59;
const int cmdGetAllowedRepeatFreq = 60;
const int cmdSetPathHashMode = 61;
// Text message types
@@ -262,6 +263,7 @@ const int respCodeChannelMsgRecvV3 = 17;
const int respCodeChannelInfo = 18;
const int respCodeCustomVars = 21;
const int respCodeAutoAddConfig = 25;
const int respCodeAllowedRepeatFreq = 26;
const int respCodeStats = 24;
const int statsTypeCore = 0;
@@ -282,6 +284,8 @@ const int pushCodeNewAdvert = 0x8A;
const int pushCodeTelemetryResponse = 0x8B;
const int pushCodeBinaryResponse = 0x8C;
const int pushCodeControlData = 0x8E;
const int pushCodeContactDeleted = 0x8F;
const int pushCodeContactsFull = 0x90;
// Contact/advertisement types
const int advTypeChat = 1;
@@ -339,6 +343,10 @@ const int maxFrameSize = 172;
const int appProtocolVersion = 4;
// Matches firmware MAX_TEXT_LEN (10 * CIPHER_BLOCK_SIZE).
const int maxTextPayloadBytes = 160;
// From attempt 4 on the firmware appends [0][attempt] to the DM payload, so
// the text must fit in MAX_TEXT_LEN - 2 (BaseChatMesh::composeMsgPacket).
const int maxFullLengthTextAttempt = 3;
const int maxTextPayloadBytesAfterFullLengthAttempts = maxTextPayloadBytes - 2;
const int _sendTextMsgOverheadBytes =
1 + 1 + 1 + 4 + 6 + 1 + 2; // +2 safety margin
const int _sendChannelTextMsgOverheadBytes =
@@ -532,8 +540,12 @@ Uint8List buildSendTextMsgFrame(
// Build CMD_SEND_CHANNEL_TXT_MSG frame
// Format: [cmd][txt_type][channel_idx][timestamp x4][text...]
Uint8List buildSendChannelTextMsgFrame(int channelIndex, String text) {
final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
Uint8List buildSendChannelTextMsgFrame(
int channelIndex,
String text, {
int? timestamp,
}) {
timestamp ??= DateTime.now().millisecondsSinceEpoch ~/ 1000;
final writer = BufferWriter();
writer.writeByte(cmdSendChannelTxtMsg);
writer.writeByte(txtTypePlain);
@@ -589,7 +601,7 @@ Uint8List buildGetStatsFrame(int statsType) {
/// Path hash width on air: [61][0][mode], mode 0..3 → (mode+1) bytes per hop hash.
Uint8List buildSetPathHashModeFrame(int mode) {
final m = mode.clamp(0, 3).toInt();
final m = mode.clamp(0, 2).toInt();
return Uint8List.fromList([cmdSetPathHashMode, 0, m]);
}
@@ -713,7 +725,9 @@ Uint8List buildResetPathFrame(Uint8List pubKey) {
}
// Build CMD_ADD_UPDATE_CONTACT frame to set custom path
// Format: [cmd][pub_key x32][type][flags][path_len][path x64][name x32][Lat? x4, Lon? x4][timestamp? x4]
// Format: [cmd][pub_key x32][type][flags][path_len][path x64][name x32][last_advert x4][Lat? x4, Lon? x4][lastmod? x4]
// The firmware stores last_advert as the contact's replay guard, so it must be
// the contact's own advert timestamp (0 when unknown), never the phone clock.
Uint8List buildUpdateContactPathFrame(
Uint8List pubKey,
Uint8List path,
@@ -723,6 +737,7 @@ Uint8List buildUpdateContactPathFrame(
String name = '',
double? lat,
double? lon,
DateTime? lastAdvert,
DateTime? lastModified,
}) {
final writer = BufferWriter();
@@ -737,9 +752,10 @@ Uint8List buildUpdateContactPathFrame(
// Name (32 bytes, null-padded)
writer.writeCString(name, maxNameSize);
// Timestamp
final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
writer.writeUInt32LE(timestamp);
final lastAdvertSeconds = lastAdvert == null
? 0
: lastAdvert.millisecondsSinceEpoch ~/ 1000;
writer.writeUInt32LE(lastAdvertSeconds.clamp(0, 0xFFFFFFFF).toInt());
// Optional [Lat x4, Lon x4][timestamp x4] tail per the doc comment above.
// Emit 8 bytes of position (zero-filled when only lastModified is provided)
@@ -777,28 +793,51 @@ Uint8List buildGetAutoAddFlagsFrame() {
return Uint8List.fromList([cmdGetAutoAddConfig]);
}
Uint8List buildGetAllowedRepeatFreqFrame() {
return Uint8List.fromList([cmdGetAllowedRepeatFreq]);
}
typedef RepeatFreqRange = ({int lowKHz, int highKHz});
// RESP_ALLOWED_REPEAT_FREQ: [code] then [lower_khz u32][upper_khz u32] pairs.
List<RepeatFreqRange> parseAllowedRepeatFreqFrame(Uint8List frame) {
final ranges = <RepeatFreqRange>[];
final data = ByteData.sublistView(frame);
for (var i = 1; i + 8 <= frame.length; i += 8) {
ranges.add((
lowKHz: data.getUint32(i, Endian.little),
highKHz: data.getUint32(i + 4, Endian.little),
));
}
return ranges;
}
// Calculate LoRa airtime for a packet
// Based on Semtech SX127x datasheet formula
// Returns airtime in milliseconds
// Preamble defaults to the firmware's per-SF length (32 up to SF8, 16 above,
// RadioLibWrappers.h preambleLengthForSF); LDRO defaults to the RadioLib rule
// (symbol time > 16 ms).
int calculateLoRaAirtime({
required int payloadBytes,
required int spreadingFactor,
required int bandwidthHz,
required int codingRate,
int preambleSymbols = 8,
bool lowDataRateOptimize = false,
int? preambleSymbols,
bool? lowDataRateOptimize,
bool explicitHeader = true,
}) {
// Symbol duration (Ts) in milliseconds
final symbolDuration = (1 << spreadingFactor) / (bandwidthHz / 1000.0);
// Preamble time
final preambleTime = (preambleSymbols + 4.25) * symbolDuration;
final preamble = preambleSymbols ?? (spreadingFactor <= 8 ? 32 : 16);
final preambleTime = (preamble + 4.25) * symbolDuration;
// Payload symbol count
final headerBytes = explicitHeader ? 0 : 20;
final crc = 1; // CRC enabled
final de = lowDataRateOptimize ? 1 : 0;
final de = (lowDataRateOptimize ?? symbolDuration > 16.0) ? 1 : 0;
final numerator =
8 * payloadBytes - 4 * spreadingFactor + 28 + 16 * crc - headerBytes;
@@ -831,7 +870,6 @@ int calculateMessageTimeout({
spreadingFactor: sf,
bandwidthHz: bwHz,
codingRate: cr,
lowDataRateOptimize: sf >= 11,
);
if (pathLength < 0) {
@@ -1004,6 +1042,7 @@ Uint8List buildSetAutoAddConfigFrame({
required bool autoAddRoomServer,
required bool autoAddSensor,
required bool overwriteOldest,
int? maxHops,
}) {
final writer = BufferWriter();
writer.writeByte(cmdSetAutoAddConfig);
@@ -1014,6 +1053,8 @@ Uint8List buildSetAutoAddConfigFrame({
if (autoAddSensor) flags |= autoAddSensorFlag;
if (overwriteOldest) flags |= autoAddOverwriteOldestFlag;
writer.writeByte(flags);
// Optional autoadd_max_hops (firmware keeps its value when omitted).
if (maxHops != null) writer.writeByte(maxHops.clamp(0, 64).toInt());
return writer.toBytes();
}
@@ -1040,9 +1081,29 @@ Uint8List buildSetFloodScopeFrame(String region) {
return Uint8List.fromList([cmdSetFloodScope, 0]);
}
final name = region.startsWith('#') ? region : '#$region';
final hash = crypto.sha256.convert(utf8.encode(name)).bytes;
final scope = Uint8List.fromList(hash.sublist(0, 16));
final scope = floodScopeKeyForRegion(region);
return Uint8List.fromList([cmdSetFloodScope, 0, ...scope]);
}
Uint8List floodScopeKeyForRegion(String region) {
final name = region.startsWith('#') ? region : '#$region';
final hash = crypto.sha256.convert(utf8.encode(name)).bytes;
return Uint8List.fromList(hash.sublist(0, 16));
}
Uint8List floodTransportCode({
required Uint8List scopeKey,
required int payloadType,
required Uint8List payload,
}) {
final input = Uint8List(1 + payload.length)
..[0] = payloadType
..setRange(1, 1 + payload.length, payload);
final code = crypto.Hmac(crypto.sha256, scopeKey).convert(input).bytes;
if (code[0] == 0 && code[1] == 0) return Uint8List.fromList([1, 0]);
if (code[0] == 0xFF && code[1] == 0xFF) {
return Uint8List.fromList([0xFE, 0xFF]);
}
return Uint8List.fromList(code.sublist(0, 2));
}
+183
View File
@@ -0,0 +1,183 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../services/image_chunk_transport.dart' show cmdSendChannelData;
import 'meshcore_protocol.dart';
/// A command waiting for its reply from the companion firmware.
class PendingCommandReply {
final int commandCode;
/// Response code the firmware sends on success (RESP_CODE_OK or a specific
/// RESP_CODE_*). Any command may instead be answered with RESP_CODE_ERR.
final int replyCode;
/// For GET_CONTACT_BY_KEY: only a CONTACT frame for this key is the reply.
final Uint8List? matchKey;
final String? channelSendQueueId;
final Completer<void>? completer;
final DateTime createdAt = DateTime.now();
PendingCommandReply({
required this.commandCode,
required this.replyCode,
this.matchKey,
this.channelSendQueueId,
this.completer,
});
}
/// Success reply for each command whose single reply is OK/ERR or a specific
/// RESP_CODE (companion MyMesh.cpp handleCmdFrame). Commands with no reply
/// (REBOOT) or a multi-code reply (SYNC_NEXT_MESSAGE) are not tracked.
int? replyCodeForCommand(Uint8List data) {
switch (data[0]) {
case cmdSendChannelTxtMsg:
case cmdSetDeviceTime:
case cmdSendSelfAdvert:
case cmdSetAdvertName:
case cmdAddUpdateContact:
case cmdSetRadioParams:
case cmdSetRadioTxPower:
case cmdResetPath:
case cmdSetAdvertLatLon:
case cmdRemoveContact:
case cmdShareContact:
case cmdImportContact:
case cmdSetChannel:
case cmdSetOtherParams:
case cmdSetCustomVar:
case cmdSetFloodScope:
case cmdSendControlData:
case cmdSetAutoAddConfig:
case cmdSetPathHashMode:
case cmdSendChannelData:
return respCodeOk;
case cmdSendTxtMsg:
case cmdSendLogin:
case cmdSendStatusReq:
case cmdSendTracePath:
case cmdSendBinaryReq:
case cmdSendAnonReq:
return respCodeSent;
case cmdSendTelemetryReq:
// The 4-byte 'self' form answers with PUSH_CODE_TELEMETRY_RESPONSE.
return data.length > 4 ? respCodeSent : null;
case cmdAppStart:
return respCodeSelfInfo;
case cmdDeviceQuery:
return respCodeDeviceInfo;
case cmdGetContacts:
return respCodeContactsStart;
case cmdGetContactByKey:
return respCodeContact;
case cmdGetDeviceTime:
return respCodeCurrTime;
case cmdExportContact:
return respCodeExportContact;
case cmdGetBattAndStorage:
return respCodeBattAndStorage;
case cmdGetChannel:
return respCodeChannelInfo;
case cmdGetCustomVar:
return respCodeCustomVars;
case cmdGetStats:
return respCodeStats;
case cmdGetAutoAddConfig:
return respCodeAutoAddConfig;
case cmdGetAllowedRepeatFreq:
return respCodeAllowedRepeatFreq;
}
return null;
}
/// FIFO of commands awaiting a reply. The firmware handles commands in order
/// and answers each with OK, ERR or a specific RESP_CODE, so an ERR belongs
/// to the oldest pending command and an OK to the oldest one expecting OK.
class PendingCommandReplies {
PendingCommandReplies({required this.staleAfter});
/// Entries older than this are dropped so a lost reply cannot swallow a
/// later, unrelated OK/ERR. Awaited entries time out in sendFrame first.
final Duration staleAfter;
final List<PendingCommandReply> _queue = [];
int get length => _queue.length;
PendingCommandReply? track(
Uint8List data, {
String? channelSendQueueId,
bool expectsOk = false,
bool waitForReply = false,
}) {
if (data.isEmpty) return null;
final replyCode =
replyCodeForCommand(data) ?? (expectsOk ? respCodeOk : null);
if (replyCode == null) return null;
final pending = PendingCommandReply(
commandCode: data[0],
replyCode: replyCode,
matchKey: data[0] == cmdGetContactByKey && data.length >= 1 + pubKeySize
? Uint8List.fromList(data.sublist(1, 1 + pubKeySize))
: null,
channelSendQueueId: channelSendQueueId,
completer: waitForReply ? Completer<void>() : null,
);
if (pending.completer != null) {
// The sender awaits this future after transport I/O; attach an error
// handler now in case the ERR arrives first.
unawaited(pending.completer!.future.catchError((_) {}));
}
_queue.add(pending);
return pending;
}
void remove(PendingCommandReply pending) => _queue.remove(pending);
void clear() => _queue.clear();
/// Completes the oldest command whose success reply is [frame]'s code.
bool completeReply(Uint8List frame) {
if (frame.isEmpty) return false;
final code = frame[0];
if (code == respCodeOk || code == respCodeErr) return false;
final key = code == respCodeContact && frame.length >= 1 + pubKeySize
? frame.sublist(1, 1 + pubKeySize)
: null;
final index = _queue.indexWhere(
(p) =>
p.replyCode == code &&
(p.matchKey == null || listEquals(p.matchKey, key)),
);
if (index < 0) return false;
_queue.removeAt(index).completer?.complete();
return true;
}
/// Attributes RESP_CODE_OK; commands expecting a specific reply are skipped.
PendingCommandReply? takeOk() {
_pruneStale();
final index = _queue.indexWhere((p) => p.replyCode == respCodeOk);
if (index < 0) return null;
final pending = _queue.removeAt(index);
pending.completer?.complete();
return pending;
}
/// Attributes RESP_CODE_ERR to the oldest pending command.
PendingCommandReply? takeErr(int errCode) {
_pruneStale();
if (_queue.isEmpty) return null;
final pending = _queue.removeAt(0);
pending.completer?.completeError(
Exception('Command failed with error code $errCode'),
);
return pending;
}
void _pruneStale() {
final cutoff = DateTime.now().subtract(staleAfter);
_queue.removeWhere((p) => p.createdAt.isBefore(cutoff));
}
}