Updating to new sending format of diy-sender

This commit is contained in:
2026-01-08 21:26:05 +00:00
parent 5b4340fab2
commit d1c1f63cb9
3 changed files with 125 additions and 118 deletions

View File

@@ -3,7 +3,7 @@
import json
import struct
from typing import Optional
from typing import Optional, Tuple, Dict
PAYLOAD_SIZE = 15
MAGIC1 = 0x42
@@ -83,72 +83,49 @@ def decode_pool_payload(candidate_bytes: bytes, expected_seq: Optional[int] = No
return best
# Test with the actual MQTT message
mqtt_message = {
"time": "2025-12-27T13:26:47",
"model": "pool",
"count": 1,
"num_rows": 1,
"rows": [
{
"len": 143,
"data": "429901013400a801f6002b0294272a000000"
}
],
"codes": ["{143}429901013400a801f6002b0294272a000000"]
}
def build_payload(seq: int, t_ds10: int, t_bme10: int, hum10: int, pres1: int) -> bytes:
"""Build a valid payload with CRC appended."""
header = struct.pack('<BBBBHhhHH', MAGIC1, MAGIC2, 1, 1, seq, t_ds10, t_bme10, hum10, pres1)
crc = crc8_xor(header)
return header + bytes([crc])
print("Testing pool payload decode with new MQTT format:")
print(f"MQTT message: {json.dumps(mqtt_message, indent=2)}")
print()
hex_data = mqtt_message['rows'][0]['data']
print(f"Hex data from rows[0]['data']: {hex_data}")
print(f"Hex data length: {len(hex_data)} chars ({len(hex_data)//2} bytes)")
def extract_pool_candidate_bytes(raw_bytes: bytes) -> Tuple[bytes, Dict[str, str]]:
"""Mirror runtime extraction: strip 0xAA preamble and optional sync bytes."""
trimmed = raw_bytes
while trimmed.startswith(b"\xaa"):
trimmed = trimmed[1:]
# Strip 'aaaaaa' prefix if present
if hex_data.startswith('aaaaaa'):
hex_data = hex_data[6:]
print(f"Stripped 'aaaaaa' prefix, remaining: {hex_data}")
for sync in (b"\x39\x14", b"\xd3\x91"):
idx = trimmed.find(sync)
if idx != -1 and idx + len(sync) < len(trimmed):
return trimmed[idx + len(sync):], {"source": "sync", "offset": idx, "sync": sync.hex()}
byte_data = bytes.fromhex(hex_data)
print(f"Byte data: {byte_data.hex()}")
print()
return trimmed, {"source": "raw"}
# Decode with sliding window
decoded = decode_pool_payload(byte_data)
if decoded:
print("✓ Payload decoded successfully!")
print(json.dumps(decoded, indent=2))
print()
print("Generated sensor messages:")
bme_msg = {
'time': mqtt_message['time'],
'model': 'pool',
'id': decoded['nodeId'] * 10 + 1,
'battery_ok': 1,
'temperature_C': decoded['t_bme_c'],
'humidity': decoded['humidity'],
'pressure_rel': decoded['pressure_hpa'],
'mic': 'CRC'
}
ds_msg = {
'time': mqtt_message['time'],
'model': 'pool',
'id': decoded['nodeId'] * 10 + 2,
'battery_ok': 1,
'temperature_C': decoded['t_ds_c'],
'mic': 'CRC'
}
print("BME280 message:")
print(json.dumps(bme_msg, indent=2))
print()
print("DS18B20 message:")
print(json.dumps(ds_msg, indent=2))
else:
print("✗ Failed to decode payload!")
def demo_decode(hex_stream: str, label: str):
print(f"\n--- {label} ---")
byte_stream = bytes.fromhex(hex_stream)
candidate_bytes, meta = extract_pool_candidate_bytes(byte_stream)
print(f"candidate source={meta['source']}, len={len(candidate_bytes)}, hex={candidate_bytes.hex()}")
decoded = decode_pool_payload(candidate_bytes)
if decoded:
print("✓ Decoded:")
print(json.dumps(decoded, indent=2))
else:
print("✗ Failed to decode")
# Construct a known-good payload and embed it in the new frame layout (aa preamble + sync 0x39 0x14)
payload = build_payload(seq=0x013d, t_ds10=231, t_bme10=223, hum10=550, pres1=10123)
preamble = b"\xaa" * 8
sync = b"\x39\x14"
new_frame_hex = (preamble + sync + payload).hex()
# Legacy frame: just the payload bytes
legacy_hex = payload.hex()
print("Testing pool payload decoding for both hardware generations")
demo_decode(new_frame_hex, "New hardware (preamble + sync)")
demo_decode(legacy_hex, "Legacy hardware (bare payload)")