Add compressed 171-byte OTA transport
This commit is contained in:
1 parent
ef92505429
commit
3f6eddd5c2
20 files changed
+2273
-46
No files matched your search
@@ -10,11 +10,13 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import asyncio
|
||||
import dataclasses
|
||||
import functools
|
||||
import shutil
|
||||
import signal
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
BLEAK_IMPORT_ERROR: ImportError | None = None
|
||||
@@ -50,10 +52,13 @@ MOTA_FLAG_ANOTHER_LINK_ACTIVE = 0x04
|
||||
OP_COUNT = 0x01
|
||||
OP_DESCRIBE = 0x02
|
||||
OP_READ = 0x03
|
||||
OP_DEFLATE_BLOCK = 0x09
|
||||
STATUS_OK = 0
|
||||
STATUS_ERR = 1
|
||||
MOTA_READ_MAX = 192
|
||||
MOTA_DEFLATE_CHUNK_MAX = 190
|
||||
MOTA_DESC_WIRE = 38
|
||||
MOTA_SOURCE_CAP_DEFLATE_BLOCK = 0x01
|
||||
MOTA_HEADER_LEN = 8
|
||||
MOTA_MANIFEST_LEN = 197
|
||||
MOTA_TRAILER = b"vk496"
|
||||
@@ -72,6 +77,28 @@ class MotaFile:
|
||||
size: int
|
||||
descriptor: bytes
|
||||
|
||||
@functools.lru_cache(maxsize=16)
|
||||
def deflated_block(self, block_index: int) -> bytes | None:
|
||||
"""Return one smaller raw-DEFLATE payload block, cached for chunk reads."""
|
||||
block_count = struct.unpack_from("<I", self.descriptor, 22)[0]
|
||||
payload_offset = struct.unpack_from("<I", self.descriptor, 26)[0]
|
||||
payload_size = struct.unpack_from("<I", self.descriptor, 30)[0]
|
||||
block_size = 1 << self.descriptor[34]
|
||||
if block_index < 0 or block_index >= block_count:
|
||||
return None
|
||||
raw_offset = block_index * block_size
|
||||
raw_length = min(block_size, payload_size - raw_offset)
|
||||
if raw_length <= 0 or raw_length > 1024 or self.path.stat().st_size != self.size:
|
||||
return None
|
||||
with self.path.open("rb") as stream:
|
||||
stream.seek(payload_offset + raw_offset)
|
||||
raw = stream.read(raw_length)
|
||||
if len(raw) != raw_length:
|
||||
return None
|
||||
compressor = zlib.compressobj(level=9, method=zlib.DEFLATED, wbits=-10)
|
||||
encoded = compressor.compress(raw) + compressor.flush()
|
||||
return encoded if 0 < len(encoded) < len(raw) else None
|
||||
|
||||
@staticmethod
|
||||
def load(path: Path) -> "MotaFile":
|
||||
size = path.stat().st_size
|
||||
@@ -117,6 +144,7 @@ class MotaFile:
|
||||
struct.pack_into("<I", descriptor, 26, payload_offset)
|
||||
struct.pack_into("<I", descriptor, 30, payload_size)
|
||||
descriptor[34] = block_size_log2
|
||||
descriptor[35] = MOTA_SOURCE_CAP_DEFLATE_BLOCK
|
||||
return MotaFile(path=path, size=size, descriptor=bytes(descriptor))
|
||||
|
||||
|
||||
@@ -195,6 +223,21 @@ class Catalog:
|
||||
status = STATUS_OK
|
||||
except OSError:
|
||||
payload = b""
|
||||
elif op == OP_DEFLATE_BLOCK and len(args) == 7:
|
||||
index = args[0]
|
||||
block = struct.unpack_from("<H", args, 1)[0]
|
||||
offset = struct.unpack_from("<H", args, 3)[0]
|
||||
length = struct.unpack_from("<H", args, 5)[0]
|
||||
if index < len(self.files) and length <= MOTA_DEFLATE_CHUNK_MAX:
|
||||
try:
|
||||
encoded = self.files[index].deflated_block(block)
|
||||
end = offset + length
|
||||
if (encoded is not None and end >= offset and end <= len(encoded)
|
||||
and (length != 0 or offset == 0)):
|
||||
payload = struct.pack("<H", len(encoded)) + encoded[offset:end]
|
||||
status = STATUS_OK
|
||||
except (OSError, zlib.error):
|
||||
payload = b""
|
||||
|
||||
response = bytearray(b"ms")
|
||||
response.extend((op, status))
|
||||
@@ -207,6 +250,11 @@ class Catalog:
|
||||
detail = f"index={args[0]}"
|
||||
elif op == OP_READ and len(args) == 7:
|
||||
detail = f"index={args[0]} offset={struct.unpack_from('<I', args, 1)[0]}"
|
||||
elif op == OP_DEFLATE_BLOCK and len(args) == 7:
|
||||
detail = (
|
||||
f"index={args[0]} block={struct.unpack_from('<H', args, 1)[0]} "
|
||||
f"offset={struct.unpack_from('<H', args, 3)[0]}"
|
||||
)
|
||||
else:
|
||||
detail = "invalid"
|
||||
print(f"mOTA op=0x{op:02x} {detail} status={status}")
|
||||
|
||||
@@ -1,10 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import struct
|
||||
import tempfile
|
||||
import unittest
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
import ble_mota_seeder as seeder
|
||||
|
||||
|
||||
def request_frame(op: int, args: bytes) -> bytes:
|
||||
return b"MS" + bytes((op,)) + args + bytes((seeder.xor_bytes(args, op),))
|
||||
|
||||
|
||||
def response_payload(response: bytes, op: int) -> tuple[int, bytes]:
|
||||
assert response[:2] == b"ms"
|
||||
assert response[2] == op
|
||||
assert response[-1] == seeder.xor_bytes(response[:-1])
|
||||
return response[3], response[4:-1]
|
||||
|
||||
|
||||
class TransportDeflateTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.path = Path(self.directory.name) / "test.mota"
|
||||
# This distribution makes zlib level 9 choose a dynamic-Huffman block, proving the
|
||||
# host is not silently constrained to the bootloader's separate fixed-only profile.
|
||||
self.raw = bytes(i % 31 if i % 7 else 0 for i in range(1024))
|
||||
payload_offset = 256
|
||||
self.path.write_bytes(bytes(payload_offset) + self.raw)
|
||||
descriptor = bytearray(seeder.MOTA_DESC_WIRE)
|
||||
struct.pack_into("<I", descriptor, 22, 1) # block_count
|
||||
struct.pack_into("<I", descriptor, 26, payload_offset)
|
||||
struct.pack_into("<I", descriptor, 30, len(self.raw))
|
||||
descriptor[34] = 10
|
||||
mota = seeder.MotaFile(self.path, self.path.stat().st_size, bytes(descriptor))
|
||||
self.catalog = seeder.Catalog([mota], False)
|
||||
|
||||
def tearDown(self):
|
||||
seeder.MotaFile.deflated_block.cache_clear()
|
||||
self.directory.cleanup()
|
||||
|
||||
def exchange(self, block: int, offset: int, length: int) -> tuple[int, bytes]:
|
||||
args = struct.pack("<BHHH", 0, block, offset, length)
|
||||
response = self.catalog.handle_request(
|
||||
request_frame(seeder.OP_DEFLATE_BLOCK, args)
|
||||
)
|
||||
self.assertIsNotNone(response)
|
||||
return response_payload(response, seeder.OP_DEFLATE_BLOCK)
|
||||
|
||||
def test_serves_independent_raw_deflate_in_bounded_chunks(self):
|
||||
status, payload = self.exchange(0, 0, 0)
|
||||
self.assertEqual(status, seeder.STATUS_OK)
|
||||
total = struct.unpack("<H", payload)[0]
|
||||
self.assertLess(total, len(self.raw))
|
||||
|
||||
encoded = bytearray()
|
||||
for offset in range(0, total, seeder.MOTA_DEFLATE_CHUNK_MAX):
|
||||
length = min(seeder.MOTA_DEFLATE_CHUNK_MAX, total - offset)
|
||||
status, payload = self.exchange(0, offset, length)
|
||||
self.assertEqual(status, seeder.STATUS_OK)
|
||||
self.assertEqual(struct.unpack_from("<H", payload)[0], total)
|
||||
encoded.extend(payload[2:])
|
||||
self.assertEqual((encoded[0] >> 1) & 0x03, 2) # dynamic Huffman (BTYPE=2)
|
||||
self.assertEqual(zlib.decompress(bytes(encoded), wbits=-10), self.raw)
|
||||
|
||||
def test_rejects_bad_block_range_and_oversized_chunk(self):
|
||||
self.assertEqual(self.exchange(1, 0, 0)[0], seeder.STATUS_ERR)
|
||||
self.assertEqual(
|
||||
self.exchange(0, 0, seeder.MOTA_DEFLATE_CHUNK_MAX + 1)[0],
|
||||
seeder.STATUS_ERR,
|
||||
)
|
||||
|
||||
|
||||
class SourceStatusTests(unittest.TestCase):
|
||||
def test_parses_current_status_with_packet_count(self):
|
||||
response = bytes.fromhex("0001030200020078563412")
|
||||
|
||||
Reference in new issue
Block a user