Repository navigation
Expand file tree
/
Copy pathdecoder.py
More file actions
130 lines (105 loc) · 5.36 KB
/
Copy pathdecoder.py
File metadata and controls
130 lines (105 loc) · 5.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
"""Apple SMC raw-value decoders.
Type-code convention (well documented, not guessed): for the 2-byte
fixed-point types `fpXY`/`spXY`, the two trailing hex digits are
(integer bits, fractional bits). `fp` is unsigned and the digits sum to 16;
`sp` is signed (two's complement) and they sum to 15 (one bit reserved for
sign). Decoded value is always raw_int / 2**fractional_bits.
Verified against the user's own worked example (walkroad.md): key TC0c,
raw bytes 0x27 0x00, type sp78 -> 0x2700 = 9984 as big-endian uint16;
9984 / 2**8 = 39.0, matching the stated expected output exactly. That also
means the documented invalid sentinels 0x8000/0x8100 decode to exactly
-128.0/-127.0 under this same formula -- consistent with walkroad.md's
invalid-value list, not a coincidence.
"""
from dataclasses import dataclass
from typing import Dict, List, Optional
import struct
_HEX_DIGITS = "0123456789abcdef"
@dataclass(frozen=True)
class DecodeResult:
value: object # float | int | bool | str
ok: bool
note: str = ""
@dataclass(frozen=True)
class BitInfo:
index: int
set: bool
label: str
def _parse_fixed_point_type(type_code: str) -> Optional[tuple]:
"""Returns (integer_bits, fractional_bits, signed) for a valid `fp`/`sp`
type code, or None -- a pure type-code check with no raw bytes needed,
so it also serves as "is this type code fixed-point-shaped at all"."""
if len(type_code) != 4:
return None
prefix, a, b = type_code[:2], type_code[2], type_code[3]
if prefix not in ("fp", "sp") or a not in _HEX_DIGITS or b not in _HEX_DIGITS:
return None
integer_bits, fractional_bits = int(a, 16), int(b, 16)
signed = prefix == "sp"
expected_total = 15 if signed else 16
if integer_bits + fractional_bits != expected_total:
return None
return integer_bits, fractional_bits, signed
def _fixed_point(type_code: str, raw: bytes) -> Optional[DecodeResult]:
parsed = _parse_fixed_point_type(type_code)
if parsed is None or len(raw) != 2:
return None
_integer_bits, fractional_bits, signed = parsed
raw_int = int.from_bytes(raw, byteorder="big", signed=signed)
return DecodeResult(value=raw_int / (2 ** fractional_bits), ok=True)
def is_temperature_shaped_type(type_code: str) -> bool:
"""True for any type code AppleSMC could plausibly use for a temperature
reading: the little-endian float, or any valid `fp`/`sp` fixed-point
code (not just the 4 seen so far -- the real iMac16,1 dump alone uses
at least a dozen distinct fp/sp variants across different quantities).
This is only an encoding-*shape* check; combined with
validator.is_temperature_key (the key-prefix half), it decides whether
a given reading gets temperature-specific treatment. Single source of
truth for both validator.py and analyzer.py -- previously duplicated
as a hardcoded 4-type set in each, which could silently drift."""
lowered = type_code.strip().lower()
return lowered == "flt" or _parse_fixed_point_type(lowered) is not None
def decode(type_code: str, raw: bytes) -> DecodeResult:
lowered = type_code.strip().lower()
if lowered == "flag":
return DecodeResult(value=bool(raw and raw[0]), ok=True)
if lowered in ("ui8", "ui16", "ui32", "si8", "si16", "si32"):
signed = lowered.startswith("si")
width_bytes = int(lowered[2:]) // 8
if len(raw) != width_bytes:
return DecodeResult(
value=raw.hex(), ok=False,
note=f"expected {width_bytes} bytes for {type_code!r}, got {len(raw)}",
)
return DecodeResult(value=int.from_bytes(raw, byteorder="big", signed=signed), ok=True)
if lowered == "flt":
if len(raw) != 4:
return DecodeResult(value=raw.hex(), ok=False, note="flt requires 4 bytes")
# AppleSMC stores `flt` little-endian, unlike every other numeric type here.
return DecodeResult(value=struct.unpack("<f", raw)[0], ok=True)
if lowered.startswith("ch"):
text = raw.decode("ascii", errors="replace").rstrip("\x00").strip()
return DecodeResult(value=text, ok=True)
# `{xxx` types (e.g. {rev, {ali, {alc) are undocumented binary structs,
# not strings -- decoding them as ASCII would both destroy real data
# (rstrip("\x00") eats trailing non-printable bytes that aren't padding)
# and falsely claim ok=True for a layout we don't actually know. Fall
# through to the honest raw-hex path below, same as any other unknown type.
fixed_point = _fixed_point(lowered, raw)
if fixed_point is not None:
return fixed_point
return DecodeResult(value=raw.hex(), ok=False, note=f"unrecognized type {type_code!r}")
def decode_bitfield(raw: bytes, labels: Optional[Dict[int, str]] = None) -> List[BitInfo]:
"""Purely mechanical bit decomposition. A label is only ever attached when
the dictionary documents one for that specific key -- otherwise bits are
reported by index alone (`bit0`, `bit1`, ...), never with an invented
meaning. This keeps the decoder honest about undocumented flag/ui16
bitfields the same way dictionary.py stays honest about unknown keys.
"""
labels = labels or {}
value = int.from_bytes(raw, byteorder="big", signed=False)
total_bits = len(raw) * 8
return [
BitInfo(index=i, set=bool(value & (1 << i)), label=labels.get(i, f"bit{i}"))
for i in range(total_bits)
]