Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ async with opendisplay.connect("AA:BB:CC:DD:EE:FF") as dev:
config = await dev.config.read() # raises NoStoredConfigError when the device has none
```

`await dev.config.clear()` erases the stored config (CONFIG_CLEAR 0x0045) and refreshes the
profile. A claimed firmware 3.0 device keeps its reset-pin settings (the 0x27 packet).

`dev.profile` is built from the firmware version, the stored config and, on firmware 3.0 and up, the
device identity. Everything not yet on the new surface is reached through `dev.legacy`, the wrapped
`OpenDisplayDevice`. `OpenDisplayDevice` remains supported.
Expand Down Expand Up @@ -113,6 +116,17 @@ opendisplay backup-config --device OD4064C9 backup.json
opendisplay migrate --device OD4064C9 --dry-run
opendisplay migrate --device OD4064C9

# Set up a 3.0 display, or move a 2.x one to 3.0 (see "Setting up a display" below)
opendisplay setup --device OD4064C9 --claim
opendisplay upgrade --device OD5A2F4C --no-key --state-file en05.json

# Send a firmware 3.x image (see "Firmware 3.x updates" below)
opendisplay update --device OD4064C9 --file opendisplay-s3-n32r8-extuart-app.bin

# Debugging: send one command frame and print the reply as hex (nothing checks it)
opendisplay raw --device OD4064C9 --cmd 0043
opendisplay raw --device OD4064C9 --cmd 000f --no-reply

# Firmware 3.0 device keys (see "Firmware 3.0 security" below)
opendisplay claim --device OD4064C9
opendisplay rotate-key --device OD4064C9
Expand Down Expand Up @@ -534,6 +548,50 @@ async with opendisplay.connect(name="OD4064C9") as dev:
- **Home Assistant** passes `find_device=` (a coroutine giving the `BLEDevice` for an address),
so the update works through an ESPHome Bluetooth proxy.

### Setting up a display (setup and upgrade)

`opendisplay setup` takes a display from wherever it stands to set up, one step at a time:

- **No config, or a config that needs migration:** configure the panel.
- **Check the panel:** draw a test pattern and ask whether it looks right.
- **Key:** claim it, or use it without a key.
- **A claimed display with a 2.x key:** rotate that key.

It prints a line as each step starts. When it wrote the config itself, it always checks the panel
afterwards, with a key or without.

`opendisplay upgrade` is the same flow for a 2.x display:

1. **Back up** the config to `--backup` (default `opendisplay-backup-<device>.json`). The backup
holds the key, so it is written with mode 0600 and never over an earlier file.
2. **Install 3.0.** A BG22 is installed over Bluetooth through its AppLoader, after you type
`yes`, since it has no old image to return to. A board that needs USB pauses: the command names
the files and the website flasher and saves its state to `--state-file`.
3. **Go on.** Once the display runs 3.0, run the same command again. It goes on from the state
file, restores the config from the backup, then sets the display up.

```bash
opendisplay upgrade --device OD5A2F4C --no-key --state-file en05.json
# ... install over USB as it says, then (the display may advertise under a new name):
opendisplay upgrade --device ODD2292B --no-key --state-file en05.json
```

`--claim` / `--no-key` decide the key, otherwise it asks. `--board` names the board when several
share a chip (ESP32-S3), `--config FILE` gives a config when the display has none and there is no
backup, `--release TAG` picks a Firmware_Unified release (default: the latest; files are checked
against its manifest and cached), and `--yes-untested` writes drive data not yet seen on a panel
without asking.

In Python the flow is `opendisplay.setup`:

- `device_state()` and `plan_setup()` say where a device stands and which steps it needs.
- `SetupRun` performs those steps. `run_until_input(open_device)` returns the next request
(`NeedClaimCode`, `NeedConfirmation`, `NeedWiredInstall`, ...), or `None` once the display is
set up or the user declined a confirmation. `answer(request, value)` answers it.
- `on_step`, if set, is called with each step just before it runs.
- `to_json()` / `from_json()` save and restore a run across a restart; the saved run never holds a
secret. A resumed run reads the device again, so it never repeats a step the device shows as done.

### Encryption (firmware 2.x)

Firmware 2.x devices with encryption enabled require authentication before accepting any commands (except `read_firmware_version`). For firmware 3.0, see "Firmware 3.0 security" above. Pass the 16-byte AES-128 master key to the constructor — authentication and session setup happen automatically before the first interrogation.
Expand Down
2 changes: 2 additions & 0 deletions src/opendisplay/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
AuthenticationRequiredError,
BLEConnectionError,
BLETimeoutError,
ConfigClearError,
ConfigKeyMismatchError,
ConfigParseError,
ConfigSecretNeedsClaimError,
Expand Down Expand Up @@ -181,6 +182,7 @@ def _package_version() -> str:
"InvalidResponseError",
"ImageEncodingError",
"IntegrityCheckError",
"ConfigClearError",
"ConfigWriteBusyError",
"DriveModeSubstitutedError",
"DriveModeTemperatureError",
Expand Down
4 changes: 4 additions & 0 deletions src/opendisplay/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@
from .cli_drive import cmd_upload_mode
from .cli_info import _build_info_tree, _info_to_json, _InfoContext
from .cli_migrate import add_backup_config_parser, add_migrate_parser
from .cli_raw import add_raw_parser
from .cli_sec2 import add_sec2_parsers
from .cli_setup import add_setup_parsers
from .device import OpenDisplayDevice
from .discovery import discover_devices_with_adv
from .exceptions import (
Expand Down Expand Up @@ -823,6 +825,8 @@ def _build_parser() -> argparse.ArgumentParser:
add_backup_config_parser(subparsers)
add_migrate_parser(subparsers)
add_sec2_parsers(subparsers)
add_setup_parsers(subparsers)
add_raw_parser(subparsers)
return parser


Expand Down
109 changes: 16 additions & 93 deletions src/opendisplay/cli_migrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,22 @@
from .cli_common import _add_device_options, _console, _device_kwargs, _error, _handle_ble_error, _parse_hex_key, _run
from .device import connect
from .exceptions import OpenDisplayError
from .models.config import GlobalConfig, SecurityConfig, WifiConfig
from .models.config import GlobalConfig
from .models.config_json import config_from_json, config_to_json
from .models.panel_drive import LengthPrefixedPacket
from .panels import MigrationPlan, PanelDatabase, PanelEntry, apply_migration, plan_migration
from .protocol import config_parser as packet_ids
from .protocol.config_serializer import serialize_config
from .sec2.keystore import JsonFileKeyStore
from .setup.configure import (
ConfigMismatchError,
find_secrets,
strip_secrets,
unclaimed_form,
without_security,
write_and_verify,
)

_SHOW_KEY_ON_SCREEN = 0x02 # SecurityConfig.flags bit 1
# 0x2D FindMyConfig key fields (od_cfg_policy.c S2D_*): eik[32] at 8, net_a_adv_key[28] at 40,
# advertisement_key[20] at 76; the check applies to bodies of at least 96 bytes.
_FINDMY_KEY_FIELDS = ((8, 32), (40, 28), (76, 20))
_FINDMY_MIN_BODY = 96
_FINDMY_PACKET = 2 + packet_ids.FINDMY_CONFIG_SIZE # [number][0x2D][body]
_SECRETS_REFUSAL = (
"The backup carries secrets: {found}. An unclaimed firmware 3.0 device does not store secrets; "
"claim it first, then enter WiFi / FindMy settings again (run `opendisplay claim`, then migrate again "
Expand Down Expand Up @@ -53,78 +55,6 @@ def _ask(prompt: str) -> bool:
return False


# ── secrets (SECURITY_V2.md § 10.4, the closed list) ─────────────────────────


def _findmy_packets(raw: bytes) -> list[bytes]:
"""Split ``findmy_config_raw`` (every 0x2D packet, header included, in order) into packets."""
return [raw[i : i + _FINDMY_PACKET] for i in range(0, len(raw), _FINDMY_PACKET)]


def _findmy_has_keys(packet: bytes) -> bool:
body = packet[2:]
return len(body) >= _FINDMY_MIN_BODY and any(any(body[o : o + n]) for o, n in _FINDMY_KEY_FIELDS)


def _findmy_without_keys(packet: bytes) -> bytes:
if len(packet) - 2 < _FINDMY_MIN_BODY:
return packet
out = bytearray(packet)
for offset, size in _FINDMY_KEY_FIELDS:
out[2 + offset : 2 + offset + size] = bytes(size)
return bytes(out)


def find_secrets(config: GlobalConfig) -> list[str]:
"""The secrets a config carries, by name; never their values."""
found = []
security = config.security_config
if security is not None and (security.encryption_enabled or any(security.encryption_key)):
found.append("encryption key")
if config.wifi_config is not None and any(config.wifi_config.password):
found.append("WiFi password")
if config.findmy_config_raw and any(_findmy_has_keys(p) for p in _findmy_packets(config.findmy_config_raw)):
found.append("FindMy keys")
return found


def unclaimed_form(config: GlobalConfig) -> GlobalConfig:
"""The config with its 0x27 as an unclaimed 3.0 device stores every 0x27 it is written.

The firmware's ``unclaimed_form`` (od_cfg_policy.c) clears ``encryption_enabled``, the key,
the show-key flag and the first reserved byte on every write to an unclaimed device.
"""
security: SecurityConfig | None = config.security_config
if security is None:
return config
return dataclasses.replace(
config,
security_config=dataclasses.replace(
security,
encryption_enabled=0,
encryption_key=bytes(16),
flags=security.flags & ~_SHOW_KEY_ON_SCREEN,
reserved=bytes(1) + security.reserved[1:],
),
)


def strip_secrets(config: GlobalConfig) -> GlobalConfig:
"""The config without secrets, in the form an unclaimed 3.0 device stores.

The 0x27 in its unclaimed form (``unclaimed_form``), the 0x26 password zeroed, and the key
fields of every 0x2D zeroed in place; the other FindMy settings stay.
"""
config = unclaimed_form(config)
wifi: WifiConfig | None = config.wifi_config
if wifi is not None:
wifi = dataclasses.replace(wifi, password=bytes(len(wifi.password)))
findmy = config.findmy_config_raw
if findmy:
findmy = b"".join(_findmy_without_keys(p) for p in _findmy_packets(findmy))
return dataclasses.replace(config, wifi_config=wifi, findmy_config_raw=findmy)


# ── describing packets ───────────────────────────────────────────────────────


Expand Down Expand Up @@ -334,20 +264,13 @@ async def _restore(dev: Any, backup: GlobalConfig, *, dry_run: bool) -> None:
async def _write_and_verify(dev: Any, config: GlobalConfig) -> None:
"""Write ``config``, read it back and compare the bytes; exit 1 on a mismatch."""
_console.print("Writing...")
await dev.config.write(config)
stored = await dev.config.read()
expected, actual = serialize_config(config), serialize_config(stored)
if _without_security(stored) != _without_security(config):
_error(
f"The config read back ({len(actual)} bytes) does not match what was written ({len(expected)} bytes). "
"Keep your backup; the write may have been interrupted."
)
if actual != expected:
# The firmware rewrites 0x27 on store: unclaimed_form on an unclaimed device, the key at
# rest on a claimed one (od_cfg_policy.c), so the security packet is compared apart.
try:
rewrote_security = await write_and_verify(dev, config)
except ConfigMismatchError as exc:
_error(str(exc))
if rewrote_security:
_console.print("The device stored the security packet (0x27) in its own form; everything else matches.")
_console.print(f"Config written and verified ({len(expected)} bytes).")
_console.print(f"Config written and verified ({len(serialize_config(config))} bytes).")


def _without_security(config: GlobalConfig) -> bytes:
return serialize_config(dataclasses.replace(config, security_config=None))
__all__ = ["find_secrets", "strip_secrets", "unclaimed_form", "without_security"]
53 changes: 53 additions & 0 deletions src/opendisplay/cli_raw.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""`opendisplay raw`: send one command frame and print the reply (a debugging aid).

The frame is ``[cmd:2 big-endian][payload]``. On a device with a session it goes out encrypted
like any other command. The reply is printed as it arrived; nothing checks or interprets it, and
nothing stops a command that changes or erases the device.
"""

from __future__ import annotations

import argparse
import re

from .cli_common import _add_device_options, _console, _handle_ble_error, _run
from .cli_sec2 import _connect_kwargs
from .device import connect
from .exceptions import OpenDisplayError


def _command(text: str) -> int:
value = int(text, 16) if re.fullmatch(r"(0x)?[0-9a-fA-F]{1,4}", text) else -1
if not 0 <= value <= 0xFFFF:
raise argparse.ArgumentTypeError(f"{text!r} is not a 2-byte hex command such as 0045")
return value


def _payload(text: str) -> bytes:
try:
return bytes.fromhex(text)
except ValueError as err:
raise argparse.ArgumentTypeError(f"{text!r} is not hex bytes") from err


def add_raw_parser(subparsers: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
"""Register ``raw``."""
p = subparsers.add_parser("raw", help="Debug: send one command frame and print the reply as hex")
_add_device_options(p)
p.add_argument("--cmd", required=True, type=_command, metavar="HEX", help="The command code, e.g. 0045")
p.add_argument("--payload", type=_payload, default=b"", metavar="HEX", help="Bytes after the command code")
p.add_argument("--no-reply", action="store_true", help="Send and wait for nothing (e.g. a reboot)")
p.add_argument("--reply-timeout", type=float, default=10.0, metavar="S", help="How long to wait for the reply")
p.set_defaults(func=lambda args: _run(_raw(args)))


async def _raw(args: argparse.Namespace) -> None:
frame = args.cmd.to_bytes(2, "big") + args.payload
try:
async with connect(**_connect_kwargs(args)) as dev:
reply = await dev.legacy.send_raw(frame, reply=not args.no_reply, timeout=args.reply_timeout)
except OpenDisplayError as exc:
_handle_ble_error(exc)
_console.print(f"sent {frame.hex(' ')}")
if reply is not None:
print(f"reply {reply.hex(' ')}")
Loading