mirror of
https://github.com/meshcore-dev/meshcore_py.git
synced 2026-04-20 22:13:49 +00:00
Add trace packet type
This commit is contained in:
parent
a5f1ec5c26
commit
ea2f17025f
5 changed files with 168 additions and 4 deletions
|
|
@ -224,4 +224,52 @@ class CommandHandler:
|
|||
async def send_cli(self, cmd):
|
||||
logger.debug(f"Sending CLI command: {cmd}")
|
||||
data = b"\x32" + cmd.encode('ascii')
|
||||
return await self.send(data, [EventType.CLI_RESPONSE, EventType.ERROR])
|
||||
return await self.send(data, [EventType.CLI_RESPONSE, EventType.ERROR])
|
||||
|
||||
async def send_trace(self, auth_code=0, tag=None, flags=0, path=None):
|
||||
"""
|
||||
Send a trace packet to test routing through specific repeaters
|
||||
|
||||
Args:
|
||||
auth_code: 32-bit authentication code (default: 0)
|
||||
tag: 32-bit integer to identify this trace (default: random)
|
||||
flags: 8-bit flags field (default: 0)
|
||||
path: Optional string with comma-separated hex values representing repeater pubkeys (e.g. "23,5f,3a")
|
||||
or a bytes/bytearray object with the raw path data
|
||||
|
||||
Returns:
|
||||
Dictionary with sent status, tag, and estimated timeout in milliseconds, or False if command failed
|
||||
"""
|
||||
# Generate random tag if not provided
|
||||
if tag is None:
|
||||
import random
|
||||
tag = random.randint(1, 0xFFFFFFFF)
|
||||
|
||||
logger.debug(f"Sending trace: tag={tag}, auth={auth_code}, flags={flags}, path={path}")
|
||||
|
||||
# Prepare the command packet: CMD(1) + tag(4) + auth_code(4) + flags(1) + [path]
|
||||
cmd_data = bytearray([36]) # CMD_SEND_TRACE_PATH
|
||||
cmd_data.extend(tag.to_bytes(4, 'little'))
|
||||
cmd_data.extend(auth_code.to_bytes(4, 'little'))
|
||||
cmd_data.append(flags)
|
||||
|
||||
# Process path if provided
|
||||
if path:
|
||||
if isinstance(path, str):
|
||||
# Convert comma-separated hex values to bytes
|
||||
try:
|
||||
path_bytes = bytearray()
|
||||
for hex_val in path.split(','):
|
||||
hex_val = hex_val.strip()
|
||||
path_bytes.append(int(hex_val, 16))
|
||||
cmd_data.extend(path_bytes)
|
||||
except ValueError as e:
|
||||
logger.error(f"Invalid path format: {e}")
|
||||
return False
|
||||
elif isinstance(path, (bytes, bytearray)):
|
||||
cmd_data.extend(path)
|
||||
else:
|
||||
logger.error(f"Unsupported path type: {type(path)}")
|
||||
return False
|
||||
|
||||
return await self.send(cmd_data, [EventType.MSG_SENT, EventType.ERROR])
|
||||
|
|
@ -2,7 +2,7 @@ from enum import Enum
|
|||
import logging
|
||||
from typing import Any, Dict, Optional, Callable, List, Union
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
logger = logging.getLogger("meshcore")
|
||||
|
||||
|
|
@ -30,6 +30,7 @@ class EventType(Enum):
|
|||
LOGIN_FAILED = "login_failed"
|
||||
STATUS_RESPONSE = "status_response"
|
||||
LOG_DATA = "log_data"
|
||||
TRACE_DATA = "trace_data"
|
||||
|
||||
# Command response types
|
||||
OK = "command_ok"
|
||||
|
|
@ -40,7 +41,7 @@ class EventType(Enum):
|
|||
class Event:
|
||||
type: EventType
|
||||
payload: Any
|
||||
attributes: Dict[str, Any] = {}
|
||||
attributes: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self):
|
||||
if self.attributes is None:
|
||||
|
|
|
|||
|
|
@ -27,4 +27,5 @@ class PacketType(Enum):
|
|||
LOGIN_SUCCESS = 0x85
|
||||
LOGIN_FAILED = 0x86
|
||||
STATUS_RESPONSE = 0x87
|
||||
LOG_DATA = 0x88
|
||||
LOG_DATA = 0x88
|
||||
TRACE_DATA = 0x89
|
||||
|
|
@ -230,6 +230,50 @@ class MessageReader:
|
|||
logger.debug("Received log data")
|
||||
await self.dispatcher.dispatch(Event(EventType.LOG_DATA, data[1:].decode('utf-8', errors='replace')))
|
||||
|
||||
elif packet_type_value == PacketType.TRACE_DATA.value:
|
||||
logger.debug(f"Received trace data: {data.hex()}")
|
||||
res = {}
|
||||
|
||||
# According to the source, format is:
|
||||
# 0x89, reserved(0), path_len, flags, tag(4), auth(4), path_hashes[], path_snrs[], final_snr
|
||||
|
||||
reserved = data[1]
|
||||
path_len = data[2]
|
||||
flags = data[3]
|
||||
tag = int.from_bytes(data[4:8], byteorder='little')
|
||||
auth_code = int.from_bytes(data[8:12], byteorder='little')
|
||||
|
||||
# Initialize result
|
||||
res["tag"] = tag
|
||||
res["auth"] = auth_code
|
||||
res["flags"] = flags
|
||||
res["path_len"] = path_len
|
||||
|
||||
# Process path as array of objects with hash and SNR
|
||||
path_nodes = []
|
||||
|
||||
if path_len > 0 and len(data) >= 12 + path_len*2 + 1:
|
||||
# Extract path with hash and SNR pairs
|
||||
for i in range(path_len):
|
||||
node = {
|
||||
"hash": f"{data[12+i]:02x}",
|
||||
# SNR is stored as a signed byte representing SNR * 4
|
||||
"snr": (data[12+path_len+i] if data[12+path_len+i] < 128 else data[12+path_len+i] - 256) / 4.0
|
||||
}
|
||||
path_nodes.append(node)
|
||||
|
||||
# Add the final node (our device) with its SNR
|
||||
final_snr_byte = data[12+path_len*2]
|
||||
final_snr = (final_snr_byte if final_snr_byte < 128 else final_snr_byte - 256) / 4.0
|
||||
path_nodes.append({
|
||||
"snr": final_snr
|
||||
})
|
||||
|
||||
res["path"] = path_nodes
|
||||
|
||||
logger.debug(f"Parsed trace data: {res}")
|
||||
await self.dispatcher.dispatch(Event(EventType.TRACE_DATA, res))
|
||||
|
||||
else:
|
||||
logger.debug(f"Unhandled data received {data}")
|
||||
logger.debug(f"Unhandled packet type: {packet_type_value}")
|
||||
Loading…
Add table
Add a link
Reference in a new issue