Skip to content
Open
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
100 changes: 100 additions & 0 deletions TOOLS/check_filament_usage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Read-only, bounded adaptation of lp55's cc-fw-tools PR #106 observer.

Source: https://github.com/OpenCentauri/cc-fw-tools/pull/106#issuecomment-5357240641
This script does not heat, move, extrude, upload files, or start a print.
"""
import argparse
import asyncio
import json
import math
import sys
import time

FIELDS = (
("TotalExtrusion", "54 6F 74 61 6C 45 78 74 72 75 73 69 6F 6E 00"),
("CurrentExtrusion", "43 75 72 72 65 6E 74 45 78 74 72 75 73 69 6F 6E 00"),
)


def extract_usage(message):
if not isinstance(message, dict):
return None
status = message.get("Status")
if not isinstance(status, dict) or not isinstance(status.get("PrintInfo"), dict):
return None
info = status["PrintInfo"]
result = {}
for plain, legacy in FIELDS:
key = plain if plain in info else legacy
value = info.get(key)
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
return None
result[key] = value
return result


def self_test():
normal = {"Status": {"PrintInfo": {"TotalExtrusion": 0.0, "CurrentExtrusion": -2.0}}}
assert extract_usage(normal) == normal["Status"]["PrintInfo"]
legacy = {"Status": {"PrintInfo": {FIELDS[0][1]: 10.0, FIELDS[1][1]: 3.0}}}
assert extract_usage(legacy) == legacy["Status"]["PrintInfo"]
mixed = {"Status": {"PrintInfo": {"TotalExtrusion": 0.0, FIELDS[0][1]: 99.0, FIELDS[1][1]: 0.0}}}
assert extract_usage(mixed) == {"TotalExtrusion": 0.0, FIELDS[1][1]: 0.0}
for value in (None, True, "1", float("nan"), float("inf")):
assert extract_usage({"Status": {"PrintInfo": {"TotalExtrusion": value, "CurrentExtrusion": 0.0}}}) is None
assert extract_usage({"Status": {"PrintInfo": {}}}) is None
assert extract_usage({"Data": {"TotalExtrusion": 10, "CurrentExtrusion": 3}}) is None
print("filament observer parser self-test passed")


async def observe(ip, seconds, require_change):
import websockets
good = 0
changed = False
deadline = time.monotonic() + seconds
# ponytail: no extra close-handshake wait after the observation deadline.
async with websockets.connect(f"ws://{ip}:3030/websocket", open_timeout=seconds, close_timeout=0) as ws:
while True:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
try:
raw = await asyncio.wait_for(ws.recv(), timeout=remaining)
except asyncio.TimeoutError:
break
try:
message = json.loads(raw)
except (ValueError, UnicodeDecodeError):
continue
usage = extract_usage(message)
if usage is not None:
good += 1
delta_key = FIELDS[1][0] if FIELDS[1][0] in usage else FIELDS[1][1]
changed |= usage[delta_key] != 0
print(json.dumps({"at": time.monotonic(), "Status": {"PrintInfo": usage}}), flush=True)
print(f"numeric_samples={good} nonzero_delta={changed}", file=sys.stderr)
return 0 if good and (changed or not require_change) else 1


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("ip", nargs="?")
parser.add_argument("--seconds", type=float, default=30.0)
parser.add_argument("--require-change", action="store_true")
parser.add_argument("--self-test", action="store_true")
args = parser.parse_args()
if args.self_test:
self_test()
return 0
if not args.ip or not math.isfinite(args.seconds) or args.seconds <= 0:
parser.error("provide a printer IP and a positive finite --seconds")
try:
return asyncio.run(observe(args.ip, args.seconds, args.require_change))
except Exception as exc:
print(f"filament observer failed: {type(exc).__name__}: {exc}", file=sys.stderr)
return 2


if __name__ == "__main__":
raise SystemExit(main())
34 changes: 34 additions & 0 deletions TOOLS/firmware_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,30 @@ def _git(repo_root: str, *args: str) -> str:
).stdout.strip()


def _declared_version(repo_root: str) -> str | None:
"""OC_VERSION from the build env, else from the active patch_config edition.

patch_planner injects the edition variables into the environment of the patch
scripts it launches, but the manifest and patch-summary tools run as separate
processes to that planner. Reading the edition file here keeps the reported
version identical to the one written into app/app.
"""
value = os.getenv("OC_VERSION")
if value:
return value
edition = os.path.join(repo_root, "oc-patches", "patch_config")
try:
with open(edition, encoding="utf-8") as stream:
for line in stream:
line = line.split("#", 1)[0].strip()
key, separator, val = line.partition("=")
if separator and key.strip() == "OC_VERSION" and val.strip():
return val.strip().strip("'\"")
except OSError:
return None
return None


def firmware_version(repo_root: str) -> str:
"""Return the OpenCentauri firmware version for the build commit."""
# Integration branches named vX.Y.Z-integrate are pre-release dev lines:
Expand All @@ -34,6 +58,16 @@ def firmware_version(repo_root: str) -> str:
)
return f"{m.group(1)}-beta-{sha[:7]}-oc"

# Release builds declare the version they ship instead of inheriting whatever
# tag git-describe lands on: main is always ahead of the last release tag, so
# describe would report the previous version plus a commit count.
declared = _declared_version(repo_root)
if declared:
m = re.fullmatch(r"v?(\d+\.\d+\.\d+)", declared.strip())
if not m:
raise ValueError(f"OC_VERSION must be X.Y.Z or vX.Y.Z, got {declared!r}")
return f"{m.group(1)}-oc"

command = ["describe", "--tags"]
build_commit = os.getenv("OC_BUILD_COMMIT")
if build_commit:
Expand Down
5 changes: 5 additions & 0 deletions firmware-editions/patched
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,9 @@ UPLOAD_DURING_PRINTING=true
UBOOT=true
UART=true
MISC_APP=true
# What release builds report as their firmware version. Bump this with each release
# and tag the same version; without it the build falls back to git-describe, which on
# main reports the previous release plus a commit count.
OC_VERSION='0.5.1'

SPOOF_SLICER_FIRMWARE_VERSION=true
38 changes: 27 additions & 11 deletions oc-patches/cc1-app/AGENT-1.4.49.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,20 @@ The 1.4.49 app binary uses rodata zero runs as caves (the whole rodata sits in t

| Cave Address | Used By | Size | End |
|--------------|---------|------|-----|
| `0x004517e0` | `spoof_slicer_firmware_version` (spoofed version string) | 8 bytes | `0x004517e7` |
| `0x004517e0` | `spoof_slicer_firmware_version` (spoofed version string, `1.4.49 OC`) | 11 bytes | `0x004517ea` |
| `0x004517f0` | `wait_for_chamber_temp` trampoline (code) | 216 bytes | `0x004518c8` |
| `0x004518d0` | `report_filament_usage` injected fn (code) | 196 bytes | `0x00451994` |
| `[0x4518d0,0x451994)` | `report_filament_usage` injected fn (code) | 196 bytes | `0x451993` |
| `0x004519a0` | `report_filament_usage` key strings (data) | 34 bytes | `0x004519c1` |

(All in the ~2KB rodata zero run `0x004517e0`–`0x00451fb8`. `report_filament_usage` also uses bss state doubles at `0x004b4788`/`0x004b4790` — runtime-zero, no file backing. Remaining free: `0x004519c2`–`0x00451fb8` (~1.5KB), the `0x00451fe3` run (~2KB), and four ~240B `0x0044exxx` slots. NOTE: the 1.4.46 cave `0x00450e00` is OCCUPIED in 1.4.49 — never reuse 1.4.46 cave addresses without checking. File→VA bias is `+0x10000` below file `0x48ed08` and `+0x20000` in the RW LOAD.)
(All in the ~2KB rodata zero run `0x004517e0`–`0x00451fb8`. `report_filament_usage` also uses private BSS doubles at `0x00522f08`/`0x00522f10`; writable ELF allocation and exported end symbols extended to `0x00522f18` — runtime-zero, no file backing. Remaining free: `0x004519c2`–`0x00451fb8` (~1.5KB), the `0x00451fe3` run (~2KB), and four ~240B `0x0044exxx` slots. NOTE: the 1.4.46 cave `0x00450e00` is OCCUPIED in 1.4.49 — never reuse 1.4.46 cave addresses without checking. File→VA bias is `+0x10000` below file `0x48ed08` and `+0x20000` in the RW LOAD.)

## Patch-by-Patch Breakdown

### `set-firmware-version-patch` (1.4.49)
**Type:** Data string replacement (script-driven)
- File offset `0x003FAE10` (VA `0x0040ae10`): stock `"1.4.49\0\0"` replaced with the OpenCentauri git-describe version (e.g. `"0.5.0-<sha>-oc"`).
- File offset `0x003FAE10` (VA `0x0040ae10`): stock `"1.4.49\0\0"` replaced with the OpenCentauri version (e.g. `"0.5.1-oc"`).
- Applied by `patch.py` with a stock-bytes guard. Version string consumers (~15 sites, all `movw`/`movt` pairs) are left pointing at the same address.
- The version comes from `TOOLS/firmware_version.py`: `vX.Y.Z-integrate` branches report `X.Y.Z-beta-<sha>-oc`, otherwise the `OC_VERSION` value declared in `firmware-editions/patched` wins, otherwise `git describe --tags`. Bump `OC_VERSION` with each release.
**No cave used.**

### `add-chamber-light-gcode-patch` (1.4.49)
Expand Down Expand Up @@ -54,8 +55,10 @@ The 1.4.49 app binary uses rodata zero runs as caves (the whole rodata sits in t
- WebSocket/MQTT attributes: site `0x0036bd64` (file `0x0035bd64`)
- Direct request-attribute: site `0x0037fbe4` (file `0x0036fbe4`)
- Guard bytes (all three sites): `103e0ae3 403040e3` → new bytes `e03701e3 453040e3` (`movw r3,#0x17e0; movt r3,#0x45`).
- Disjoint from `set-firmware-version`; write order does not matter. Slicer sees `1.4.49`, logs/UI/OTA keep the OC version.
**String cave at `0x004517e0`.** See `spoof-slicer-firmware-version/README.md`.
- Disjoint from `set-firmware-version`; write order does not matter. Slicer sees `1.4.49 OC`, logs/UI/OTA keep the OC version.
- The `OC` marker is load-bearing: Home Assistant's `elegoo_printer` only creates the OpenCentauri-only filament sensors when `FirmwareVersion` carries an `OC`/`O` marker (`sensor.py` → `printer.open_centauri` → `Printer._is_open_centauri`). Without it, HA never registers `total_extrusion`/`current_extrusion` and Spoolman sees nothing, no matter what the printer pushes.
- The patch validates all four regions before writing any byte, and refuses if the cave is no longer zero (another patch claimed it).
**String cave at `0x004517e0`, 11 bytes.** See `spoof-slicer-firmware-version/README.md`.

### `allow-uploads-during-printing-patch` (1.4.49)
**Type:** Python direct binary patch (`patch.py` via `patch.sh` FW_VER branch; two-pass byte-guarded)
Expand Down Expand Up @@ -87,14 +90,27 @@ The 1.4.49 app binary uses rodata zero runs as caves (the whole rodata sits in t

### `report-filament-usage` (1.4.49)
**Type:** Hook + code cave injected fn (`patch.py` writes assembled blob from `injected-1.4.49.S` + key strings)
- Hook `0x0037f9ec` (12B movw/movt/vcvt triplet) → `movw ip,#0x18d0; movt ip,#0x45; bx ip`; fn in cave `0x004518d0` (196B).
- Emits `TotalExtrusion` (key `0x4519a0`) + `CurrentExtrusion` (key `0x4519b0`) via JSON helper `0x2c9b80` (r0=json obj = r4 at hook); E total from `[[0x4b27bc]+0xf8]+0x1c0`; bss prev/delta at `0x4b4788`/`0x4b4790` (runtime-zero, no file backing); resume `0x37f9fc` (cave replays TotalLayer — no double-emit). Idle path `0x37f858` unhooked (parity).
**Caves `0x004518d0` + `0x004519a0`; bss `0x4b4788`/`0x4b4790`.** See `report-filament-usage/README-1.4.49.md`.
- Broadcast hook `0x36d310` / file `0x35d310`, replacing movt/vmov/vcvt.
- Pre-hook `movw r1,#0x96d0` remains stock; layer value is in r3.
- PrintInfo JSON object r8; native JSON-number helper `0x2c9b80` uses r0/r1/d0.
- Cave `[0x4518d0,0x451994)` is 196 bytes in the executable LOAD segment.
- Strings `0x4519a0` / `0x4519b0` hold the plain total/delta names.
- Private BSS doubles at `0x522f08` / `0x522f10`; allocated end `0x522f18`.
- Resume `0x36d320`, after the stock TotalLayer call; the cave emits it once.
- The former Agora hook `0x37f9ec` is left untouched.

Scratch is explicitly reserved by growing RW p_memsz (`0xc8`) from `0x741fc`
to `0x74210`, .bss sh_size (`0x492380`) from `0x710d4` to `0x710e8`, and the
four exported BSS/end symbol values at file offsets `0x1724`, `0x20a4`,
`0x3e34`, `0x4044` from `0x522f04` to `0x522f18`. File size/p_filesz do not grow.
The old port's `0x4b4788/0x4b4790` overlap stock PRNG state and are never used.

See `report-filament-usage/README-1.4.49.md`.

## 1.4.49 Binary Notes

- Stock `app-1.4.49` sha256: `1a899b50fc104a38fe3f77cf4988c810da6670f3d0cc457de5d876c49fd76843` (from `FW/FW-CentauriCarbon-v1.4.49-2026-07-29.bin`). The `unpacked/squashfs-root/app/app` in a built tree is **already patched** — never use it as a patch baseline.
- Uniform file→VA bias: `VA = file_offset + 0x10000` for all sections.
- Code/rodata VA = file offset + 0x10000; RW LOAD VA = file offset + 0x20000. BSS has no payload bytes in the file.
- String/code references are `movw`/`movt` pairs, but the compiler **interleaves the pair** (other instructions may sit between `movw` and its `movt`). When scanning for address references, allow a window of ~8 instructions between `movw rd, #lo` and `movt rd, #hi`.
- Gcode command strings live in a packed 8-byte-stride table in `.rodata` around `0x00416374`; handlers are registered by loading the handler address as an immediate next to the string load (see chamber-light README for the M8212/M8213 example).

Expand All @@ -105,4 +121,4 @@ The 1.4.49 app binary uses rodata zero runs as caves (the whole rodata sits in t
3. **Always run `patch_planner.py 1.4.49 --dry-run` after adding a new patch.** It shows the full ordered patch chain. Then build with `sudo ./build.sh 1.4.49` and disassemble the final app to verify all cave addresses.
4. **Document new caves in this file.** If you add a patch that uses a code cave, append its address range to the table above and update the summary.
5. **Prefer in-place single-instruction patches when possible.** If the fix is just forcing a constant or removing a branch, patch the single instruction directly. This avoids cave contention entirely.
6. **Claim the next free cave from the top.** No caves are claimed yet for 1.4.49. The 1.4.46 cave region lived at `0x00450100`+; re-discover zero-filled executable space in the 1.4.49 binary before claiming anything, and document exact start/end here and in the patch README.
6. **Claim the next free cave from the top.** Existing cave claims are listed above. Verify the stock ELF mapping and full patch chain before allocating additional space; never reuse 1.4.46 addresses by assumption.
Loading
Loading