mirror of
https://github.com/maziggy/bambuddy.git
synced 2026-10-02 12:15:36 +02:00
@@ -69,6 +69,7 @@ class APIClient:
|
||||
calibration_factor: float = 1.0,
|
||||
nfc_reader_type: str | None = None,
|
||||
nfc_connection: str | None = None,
|
||||
backend_url: str | None = None,
|
||||
has_backlight: bool = False,
|
||||
) -> dict | None:
|
||||
while True:
|
||||
@@ -85,6 +86,7 @@ class APIClient:
|
||||
"calibration_factor": calibration_factor,
|
||||
"nfc_reader_type": nfc_reader_type,
|
||||
"nfc_connection": nfc_connection,
|
||||
"backend_url": backend_url,
|
||||
"has_backlight": has_backlight,
|
||||
},
|
||||
)
|
||||
@@ -105,18 +107,24 @@ class APIClient:
|
||||
firmware_version: str | None = None,
|
||||
nfc_reader_type: str | None = None,
|
||||
nfc_connection: str | None = None,
|
||||
backend_url: str | None = None,
|
||||
system_stats: dict | None = None,
|
||||
) -> dict | None:
|
||||
payload: dict = {
|
||||
"nfc_ok": nfc_ok,
|
||||
"scale_ok": scale_ok,
|
||||
"uptime_s": uptime_s,
|
||||
"ip_address": ip_address,
|
||||
"firmware_version": firmware_version,
|
||||
"nfc_reader_type": nfc_reader_type,
|
||||
"nfc_connection": nfc_connection,
|
||||
"backend_url": backend_url,
|
||||
}
|
||||
if system_stats is not None:
|
||||
payload["system_stats"] = system_stats
|
||||
result = await self._post(
|
||||
f"/devices/{device_id}/heartbeat",
|
||||
{
|
||||
"nfc_ok": nfc_ok,
|
||||
"scale_ok": scale_ok,
|
||||
"uptime_s": uptime_s,
|
||||
"ip_address": ip_address,
|
||||
"firmware_version": firmware_version,
|
||||
"nfc_reader_type": nfc_reader_type,
|
||||
"nfc_connection": nfc_connection,
|
||||
},
|
||||
payload,
|
||||
)
|
||||
if result and self._buffer:
|
||||
await self._flush_buffer()
|
||||
@@ -188,3 +196,37 @@ class APIClient:
|
||||
f"/devices/{device_id}/update-status",
|
||||
{"status": status, "message": message},
|
||||
)
|
||||
|
||||
async def diagnostic_result(
|
||||
self,
|
||||
device_id: str,
|
||||
diagnostic: str,
|
||||
success: bool,
|
||||
output: str,
|
||||
exit_code: int,
|
||||
) -> dict | None:
|
||||
return await self._post(
|
||||
f"/diagnostics/{device_id}/result",
|
||||
{
|
||||
"diagnostic": diagnostic,
|
||||
"success": success,
|
||||
"output": output,
|
||||
"exit_code": exit_code,
|
||||
},
|
||||
)
|
||||
|
||||
async def system_command_result(
|
||||
self,
|
||||
device_id: str,
|
||||
command: str,
|
||||
success: bool,
|
||||
message: str | None = None,
|
||||
) -> dict | None:
|
||||
return await self._post(
|
||||
f"/devices/{device_id}/system/command-result",
|
||||
{
|
||||
"command": command,
|
||||
"success": success,
|
||||
"message": message,
|
||||
},
|
||||
)
|
||||
|
||||
+206
-118
@@ -3,16 +3,14 @@
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import shutil
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# Add scripts/ to sys.path so hardware drivers (read_tag, scale_diag) are importable
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
|
||||
|
||||
from . import __version__
|
||||
from . import __version__, system_stats
|
||||
from .api_client import APIClient
|
||||
from .config import Config
|
||||
from .display_control import DisplayControl
|
||||
@@ -25,6 +23,36 @@ logging.basicConfig(
|
||||
datefmt="%H:%M:%S",
|
||||
)
|
||||
logger = logging.getLogger("spoolbuddy")
|
||||
logging.getLogger("daemon.pn5180").setLevel(logging.DEBUG)
|
||||
|
||||
|
||||
def _spoolbuddy_env_path() -> Path:
|
||||
# installer writes this at <install>/spoolbuddy/.env; allow override for custom setups/tests
|
||||
override = os.environ.get("SPOOLBUDDY_ENV_FILE", "").strip()
|
||||
if override:
|
||||
return Path(override)
|
||||
return Path(__file__).resolve().parent.parent / ".env"
|
||||
|
||||
|
||||
def _set_env_value(path: Path, key: str, value: str):
|
||||
lines: list[str] = []
|
||||
if path.exists():
|
||||
lines = path.read_text(encoding="utf-8").splitlines()
|
||||
|
||||
updated = False
|
||||
new_lines: list[str] = []
|
||||
for line in lines:
|
||||
if line.startswith(f"{key}="):
|
||||
new_lines.append(f"{key}={value}")
|
||||
updated = True
|
||||
else:
|
||||
new_lines.append(line)
|
||||
|
||||
if not updated:
|
||||
new_lines.append(f"{key}={value}")
|
||||
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def _get_ip() -> str:
|
||||
@@ -38,16 +66,45 @@ def _get_ip() -> str:
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _deploy_ssh_key(public_key: str) -> None:
|
||||
"""Write Bambuddy's SSH public key to authorized_keys if not already present."""
|
||||
home = Path.home()
|
||||
ssh_dir = home / ".ssh"
|
||||
auth_keys = ssh_dir / "authorized_keys"
|
||||
|
||||
try:
|
||||
ssh_dir.mkdir(mode=0o700, exist_ok=True)
|
||||
|
||||
# Check if key already deployed
|
||||
if auth_keys.exists():
|
||||
existing = auth_keys.read_text()
|
||||
if public_key.strip() in existing:
|
||||
return
|
||||
|
||||
# Append key
|
||||
with auth_keys.open("a") as f:
|
||||
f.write(public_key.strip() + "\n")
|
||||
auth_keys.chmod(0o600)
|
||||
logger.info("SSH public key deployed to %s", auth_keys)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to deploy SSH key: %s", e)
|
||||
|
||||
|
||||
async def nfc_poll_loop(config: Config, api: APIClient, shared: dict):
|
||||
"""Continuous NFC polling loop — runs in asyncio with blocking reads offloaded."""
|
||||
nfc: NFCReader = shared["nfc"]
|
||||
display: DisplayControl = shared["display"]
|
||||
if not nfc.ok:
|
||||
logger.warning("NFC reader not available, skipping NFC polling")
|
||||
return
|
||||
|
||||
try:
|
||||
while True:
|
||||
if shared.get("nfc_scan_paused", False):
|
||||
await asyncio.sleep(config.nfc_poll_interval)
|
||||
continue
|
||||
|
||||
nfc: NFCReader | None = shared.get("nfc")
|
||||
if not nfc or not nfc.ok:
|
||||
await asyncio.sleep(config.nfc_poll_interval)
|
||||
continue
|
||||
|
||||
event_type, event_data = await asyncio.to_thread(nfc.poll)
|
||||
|
||||
if event_type == "tag_detected":
|
||||
@@ -67,21 +124,41 @@ async def nfc_poll_loop(config: Config, api: APIClient, shared: dict):
|
||||
|
||||
# Check for pending write command
|
||||
pending = shared.get("pending_write")
|
||||
if pending and nfc.state == NFCState.TAG_PRESENT and nfc.current_sak == 0x00:
|
||||
logger.info("Executing pending tag write for spool %d", pending["spool_id"])
|
||||
success, msg = await asyncio.to_thread(nfc.write_ntag, pending["ndef_data"])
|
||||
await api.write_tag_result(
|
||||
device_id=config.device_id,
|
||||
spool_id=pending["spool_id"],
|
||||
tag_uid=nfc.current_uid or "",
|
||||
success=success,
|
||||
message=msg,
|
||||
)
|
||||
shared.pop("pending_write", None)
|
||||
if pending and nfc.state == NFCState.TAG_PRESENT:
|
||||
if nfc.current_sak in (0x00, 0x04):
|
||||
logger.info("Executing pending tag write for spool %d", pending["spool_id"])
|
||||
success, msg = await asyncio.to_thread(nfc.write_ntag, pending["ndef_data"])
|
||||
await api.write_tag_result(
|
||||
device_id=config.device_id,
|
||||
spool_id=pending["spool_id"],
|
||||
tag_uid=nfc.current_uid or "",
|
||||
success=success,
|
||||
message=msg,
|
||||
)
|
||||
shared.pop("pending_write", None)
|
||||
else:
|
||||
# Fail fast when a non-NTAG is presented during write mode.
|
||||
# Without this, UI can appear stuck on "waiting for SpoolBuddy".
|
||||
sak = nfc.current_sak
|
||||
await api.write_tag_result(
|
||||
device_id=config.device_id,
|
||||
spool_id=pending["spool_id"],
|
||||
tag_uid=nfc.current_uid or "",
|
||||
success=False,
|
||||
message=f"Incompatible tag type (SAK=0x{sak:02X}). Place an NTAG tag to write.",
|
||||
)
|
||||
logger.warning(
|
||||
"Write aborted for spool %d: incompatible tag type SAK=0x%02X",
|
||||
pending["spool_id"],
|
||||
sak,
|
||||
)
|
||||
shared.pop("pending_write", None)
|
||||
|
||||
await asyncio.sleep(config.nfc_poll_interval)
|
||||
finally:
|
||||
nfc.close()
|
||||
nfc: NFCReader | None = shared.get("nfc")
|
||||
if nfc:
|
||||
nfc.close()
|
||||
|
||||
|
||||
async def scale_poll_loop(config: Config, api: APIClient, shared: dict):
|
||||
@@ -123,93 +200,6 @@ async def scale_poll_loop(config: Config, api: APIClient, shared: dict):
|
||||
scale.close()
|
||||
|
||||
|
||||
async def _perform_update(config: Config, api: APIClient):
|
||||
"""Pull latest code from git, install deps, then exit for systemd restart."""
|
||||
# Determine repo root (install path) — daemon runs from <repo>/spoolbuddy/
|
||||
repo_root = Path(__file__).resolve().parent.parent.parent
|
||||
|
||||
await api.report_update_status(config.device_id, "updating", "Fetching latest code...")
|
||||
|
||||
git_path = shutil.which("git") or "/usr/bin/git"
|
||||
git_config = ["-c", f"safe.directory={repo_root}"]
|
||||
|
||||
# git fetch origin main
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
git_path,
|
||||
*git_config,
|
||||
"fetch",
|
||||
"origin",
|
||||
"main",
|
||||
cwd=str(repo_root),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
_, stderr = await proc.communicate()
|
||||
if proc.returncode != 0:
|
||||
msg = f"git fetch failed: {stderr.decode()[:200]}"
|
||||
logger.error(msg)
|
||||
await api.report_update_status(config.device_id, "error", msg)
|
||||
return
|
||||
|
||||
await api.report_update_status(config.device_id, "updating", "Applying update...")
|
||||
|
||||
# git reset --hard origin/main
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
git_path,
|
||||
*git_config,
|
||||
"reset",
|
||||
"--hard",
|
||||
"origin/main",
|
||||
cwd=str(repo_root),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
_, stderr = await proc.communicate()
|
||||
if proc.returncode != 0:
|
||||
msg = f"git reset failed: {stderr.decode()[:200]}"
|
||||
logger.error(msg)
|
||||
await api.report_update_status(config.device_id, "error", msg)
|
||||
return
|
||||
|
||||
await api.report_update_status(config.device_id, "updating", "Installing dependencies...")
|
||||
|
||||
# pip install daemon deps (use the venv pip)
|
||||
venv_pip = repo_root / "spoolbuddy" / "venv" / "bin" / "pip"
|
||||
pip_packages = ["spidev", "gpiod", "smbus2", "httpx"]
|
||||
|
||||
if venv_pip.exists():
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
str(venv_pip),
|
||||
"install",
|
||||
"--upgrade",
|
||||
*pip_packages,
|
||||
cwd=str(repo_root),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
else:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
sys.executable,
|
||||
"-m",
|
||||
"pip",
|
||||
"install",
|
||||
"--upgrade",
|
||||
*pip_packages,
|
||||
cwd=str(repo_root),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
await proc.communicate()
|
||||
if proc.returncode != 0:
|
||||
logger.warning("pip install returned non-zero (continuing anyway)")
|
||||
|
||||
await api.report_update_status(config.device_id, "complete", "Update complete, restarting...")
|
||||
logger.info("Update complete, exiting for systemd restart")
|
||||
|
||||
# Exit cleanly — systemd Restart=always will bring us back with the new code
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
async def heartbeat_loop(config: Config, api: APIClient, start_time: float, shared: dict):
|
||||
"""Periodic heartbeat to keep device registered and pick up commands."""
|
||||
display: DisplayControl = shared["display"]
|
||||
@@ -221,6 +211,7 @@ async def heartbeat_loop(config: Config, api: APIClient, start_time: float, shar
|
||||
nfc = shared.get("nfc")
|
||||
scale = shared.get("scale")
|
||||
uptime = int(time.monotonic() - start_time)
|
||||
stats = await asyncio.to_thread(system_stats.collect)
|
||||
result = await api.heartbeat(
|
||||
device_id=config.device_id,
|
||||
nfc_ok=nfc.ok if nfc else False,
|
||||
@@ -230,19 +221,13 @@ async def heartbeat_loop(config: Config, api: APIClient, start_time: float, shar
|
||||
firmware_version=__version__,
|
||||
nfc_reader_type=nfc.reader_type if nfc else None,
|
||||
nfc_connection=nfc.connection if nfc else None,
|
||||
backend_url=config.backend_url,
|
||||
system_stats=stats,
|
||||
)
|
||||
|
||||
if result:
|
||||
cmd = result.get("pending_command")
|
||||
if cmd == "update":
|
||||
logger.info("Update command received, starting update...")
|
||||
try:
|
||||
await _perform_update(config, api)
|
||||
except Exception as e:
|
||||
logger.error("Update failed: %s", e)
|
||||
await api.report_update_status(config.device_id, "error", str(e)[:255])
|
||||
continue
|
||||
elif cmd == "tare":
|
||||
if cmd == "tare":
|
||||
scale = shared.get("scale")
|
||||
if scale and scale.ok:
|
||||
new_offset = await asyncio.to_thread(scale.tare)
|
||||
@@ -253,6 +238,103 @@ async def heartbeat_loop(config: Config, api: APIClient, start_time: float, shar
|
||||
logger.warning("Tare command received but scale not available")
|
||||
# Skip calibration sync — this heartbeat response predates the tare
|
||||
continue
|
||||
elif cmd == "apply_system_config":
|
||||
payload = result.get("pending_system_payload") or {}
|
||||
backend_url = str(payload.get("backend_url", "")).strip()
|
||||
api_key_value = payload.get("api_key")
|
||||
api_key = str(api_key_value).strip() if api_key_value is not None else ""
|
||||
|
||||
if not backend_url:
|
||||
await api.system_command_result(
|
||||
config.device_id,
|
||||
"apply_system_config",
|
||||
False,
|
||||
"Missing backend_url payload",
|
||||
)
|
||||
continue
|
||||
|
||||
try:
|
||||
env_path = _spoolbuddy_env_path()
|
||||
await asyncio.to_thread(_set_env_value, env_path, "SPOOLBUDDY_BACKEND_URL", backend_url)
|
||||
if api_key:
|
||||
await asyncio.to_thread(_set_env_value, env_path, "SPOOLBUDDY_API_KEY", api_key)
|
||||
|
||||
await api.system_command_result(
|
||||
config.device_id,
|
||||
"apply_system_config",
|
||||
True,
|
||||
f"Updated {env_path}",
|
||||
)
|
||||
|
||||
logger.info("Applied system config update")
|
||||
except Exception as e:
|
||||
logger.exception("Failed to apply system config")
|
||||
await api.system_command_result(
|
||||
config.device_id,
|
||||
"apply_system_config",
|
||||
False,
|
||||
str(e),
|
||||
)
|
||||
continue
|
||||
elif cmd in ("run_nfc_diag", "run_scale_diag", "run_read_tag_diag"):
|
||||
if cmd == "run_scale_diag":
|
||||
diagnostic = "scale"
|
||||
script_name = "scale_diag.py"
|
||||
elif cmd == "run_read_tag_diag":
|
||||
diagnostic = "read_tag"
|
||||
script_name = "read_tag.py"
|
||||
else:
|
||||
diagnostic = "nfc"
|
||||
script_name = "pn5180_diag.py"
|
||||
script_path = Path(__file__).resolve().parent.parent / "scripts" / script_name
|
||||
|
||||
if diagnostic in ("nfc", "read_tag"):
|
||||
logger.info("Pausing NFC continuous scan for diagnostic")
|
||||
shared["nfc_scan_paused"] = True
|
||||
nfc_for_diag = shared.get("nfc")
|
||||
if nfc_for_diag:
|
||||
await asyncio.to_thread(nfc_for_diag.close)
|
||||
shared["nfc"] = None
|
||||
|
||||
logger.info("Running %s diagnostic via %s", diagnostic, script_path)
|
||||
try:
|
||||
proc = await asyncio.to_thread(
|
||||
subprocess.run,
|
||||
[sys.executable, str(script_path)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=45,
|
||||
)
|
||||
output = (proc.stdout or "") + (("\n" + proc.stderr) if proc.stderr else "")
|
||||
await api.diagnostic_result(
|
||||
config.device_id,
|
||||
diagnostic,
|
||||
proc.returncode == 0,
|
||||
output,
|
||||
proc.returncode,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
await api.diagnostic_result(
|
||||
config.device_id,
|
||||
diagnostic,
|
||||
False,
|
||||
"Diagnostic timed out after 45 seconds",
|
||||
-1,
|
||||
)
|
||||
except Exception as e:
|
||||
await api.diagnostic_result(
|
||||
config.device_id,
|
||||
diagnostic,
|
||||
False,
|
||||
f"Diagnostic execution failed: {e}",
|
||||
-1,
|
||||
)
|
||||
finally:
|
||||
if diagnostic in ("nfc", "read_tag"):
|
||||
logger.info("Reinitializing NFC continuous scan after diagnostic")
|
||||
shared["nfc"] = NFCReader()
|
||||
shared["nfc_scan_paused"] = False
|
||||
continue
|
||||
elif cmd == "write_tag":
|
||||
write_payload = result.get("pending_write_payload")
|
||||
if write_payload:
|
||||
@@ -313,6 +395,7 @@ async def main():
|
||||
calibration_factor=config.calibration_factor,
|
||||
nfc_reader_type=nfc.reader_type,
|
||||
nfc_connection=nfc.connection,
|
||||
backend_url=config.backend_url,
|
||||
has_backlight=display.has_backlight,
|
||||
)
|
||||
|
||||
@@ -322,9 +405,14 @@ async def main():
|
||||
config.calibration_factor = reg.get("calibration_factor", config.calibration_factor)
|
||||
scale.update_calibration(config.tare_offset, config.calibration_factor)
|
||||
|
||||
# Auto-deploy Bambuddy's SSH public key for remote updates
|
||||
ssh_key = reg.get("ssh_public_key")
|
||||
if ssh_key:
|
||||
_deploy_ssh_key(ssh_key)
|
||||
|
||||
logger.info("Device registered, starting poll loops")
|
||||
|
||||
shared: dict = {"nfc": nfc, "scale": scale, "display": display}
|
||||
shared: dict = {"nfc": nfc, "scale": scale, "display": display, "nfc_scan_paused": False}
|
||||
try:
|
||||
await asyncio.gather(
|
||||
nfc_poll_loop(config, api, shared),
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
"""NAU7802 24-bit ADC driver for load cell / scale applications.
|
||||
|
||||
I2C address: 0x2A
|
||||
Bus: /dev/i2c-1 (GPIO2/GPIO3 on RPi)
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import struct
|
||||
import time
|
||||
|
||||
import smbus2
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _env_int(name: str, default: int) -> int:
|
||||
value = os.environ.get(name)
|
||||
if value is None or value == "":
|
||||
return default
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
|
||||
I2C_BUS = _env_int("SPOOLBUDDY_I2C_BUS", 1)
|
||||
NAU7802_ADDR = 0x2A
|
||||
|
||||
# Register addresses
|
||||
REG_PU_CTRL = 0x00
|
||||
REG_CTRL1 = 0x01
|
||||
REG_CTRL2 = 0x02
|
||||
REG_ADCO_B2 = 0x12 # ADC output MSB
|
||||
REG_ADCO_B1 = 0x13
|
||||
REG_ADCO_B0 = 0x14 # ADC output LSB
|
||||
REG_ADC = 0x15
|
||||
REG_PGA = 0x1B
|
||||
REG_PWR_CTRL = 0x1C
|
||||
REG_REVISION = 0x1F
|
||||
|
||||
# PU_CTRL bits
|
||||
PU_RR = 0x01 # Register reset
|
||||
PU_PUD = 0x02 # Power up digital
|
||||
PU_PUA = 0x04 # Power up analog
|
||||
PU_PUR = 0x08 # Power up ready (read-only)
|
||||
PU_CS = 0x10 # Cycle start
|
||||
PU_CR = 0x20 # Cycle ready (read-only)
|
||||
PU_OSCS = 0x40 # Oscillator select
|
||||
PU_AVDDS = 0x80 # AVDD source select
|
||||
|
||||
|
||||
class NAU7802:
|
||||
def __init__(self, bus: int = I2C_BUS, addr: int = NAU7802_ADDR):
|
||||
self._bus_num = bus
|
||||
self._bus = smbus2.SMBus(bus)
|
||||
self._addr = addr
|
||||
|
||||
# CTRL2 bits for AFE calibration
|
||||
_CTRL2_CALS = 1 << 2
|
||||
_CTRL2_CAL_ERROR = 1 << 3
|
||||
|
||||
def close(self):
|
||||
self._bus.close()
|
||||
|
||||
def read_reg(self, reg: int) -> int:
|
||||
return self._bus.read_byte_data(self._addr, reg)
|
||||
|
||||
def write_reg(self, reg: int, val: int):
|
||||
self._bus.write_byte_data(self._addr, reg, val & 0xFF)
|
||||
|
||||
def _update_bits(self, reg: int, mask: int, value: int):
|
||||
cur = self.read_reg(reg)
|
||||
self.write_reg(reg, (cur & ~mask) | (value & mask))
|
||||
|
||||
def _set_bit(self, reg: int, bit: int, enabled: bool):
|
||||
mask = 1 << bit
|
||||
self._update_bits(reg, mask, mask if enabled else 0)
|
||||
|
||||
def _set_field(self, reg: int, shift: int, width: int, value: int):
|
||||
mask = ((1 << width) - 1) << shift
|
||||
self._update_bits(reg, mask, value << shift)
|
||||
|
||||
def init(self):
|
||||
"""Initialize NAU7802 per datasheet power-on sequencing (Section 8.1).
|
||||
|
||||
Datasheet steps:
|
||||
1. RR=1 (reset all registers)
|
||||
2. RR=0, PUD=1 (enter normal operation; PUD auto-starts AD conversion)
|
||||
3. Wait ~200µs for PUR=1
|
||||
4. Configure (LDO, gain, rate, etc.)
|
||||
5. Tuning (ADC chopper, PGA caps)
|
||||
6. (Optional) calibration and flush transients
|
||||
"""
|
||||
|
||||
# Step 1: Reset (set RR=1, then RR=0)
|
||||
self._set_bit(REG_PU_CTRL, 0, True) # RR=1
|
||||
time.sleep(0.010)
|
||||
self._set_bit(REG_PU_CTRL, 0, False) # RR=0 exits reset
|
||||
# Datasheet says "about 200 microseconds" before PUR is set
|
||||
time.sleep(0.001)
|
||||
|
||||
# Step 2: Power up digital (PUD=1 auto-starts AD conversion)
|
||||
self._set_bit(REG_PU_CTRL, 1, True) # PUD=1
|
||||
# Step 2b: Power up analog (PUA=1)
|
||||
self._set_bit(REG_PU_CTRL, 2, True) # PUA=1
|
||||
time.sleep(0.600) # Wait for LDO and analog section to stabilize
|
||||
|
||||
# Step 3: Wait for power-up ready (PUR bit 3)
|
||||
|
||||
for _ in range(100):
|
||||
status = self.read_reg(REG_PU_CTRL)
|
||||
if status & PU_PUR:
|
||||
logger.debug(" Power-up ready")
|
||||
break
|
||||
time.sleep(0.001)
|
||||
else:
|
||||
raise TimeoutError("NAU7802 power-up timeout (PUR bit not set)")
|
||||
|
||||
# Check revision register low nibble (datasheet expects 0xF).
|
||||
|
||||
revision = self.read_reg(REG_REVISION)
|
||||
logger.debug(f" Revision: 0x{revision:02X}")
|
||||
if (revision & 0x0F) != 0x0F:
|
||||
raise RuntimeError(f"Unexpected NAU7802 revision: 0x{revision:02X} (expected 0x_F)")
|
||||
|
||||
# Step 4: Configure device
|
||||
# Internal LDO enable (AVDDS=1, bit 7) and set voltage to 3.0V
|
||||
|
||||
self._set_bit(REG_PU_CTRL, 7, True) # AVDDS=1
|
||||
self._set_field(REG_CTRL1, shift=3, width=3, value=0b101) # VLDO=3.0V
|
||||
logger.debug(" LDO: 3.0V (internal)")
|
||||
|
||||
# Set gain to 128x (CTRL1 bits 2:0 = 0b111)
|
||||
|
||||
self._set_field(REG_CTRL1, shift=0, width=3, value=0b111)
|
||||
logger.debug(" Gain: 128x")
|
||||
|
||||
# Set sample rate to 10 SPS (CTRL2 bits 6:4 = 0b000)
|
||||
# Note: At 10 SPS, each sample takes ~100ms; first 4 samples = ~400ms to settle
|
||||
|
||||
self._set_field(REG_CTRL2, shift=4, width=3, value=0b000)
|
||||
logger.debug(" Sample rate: 10 SPS")
|
||||
|
||||
# Step 5: Tuning per application notes
|
||||
# Disable ADC chopper clock (ADC bits 5:4 = 0b11)
|
||||
self._set_field(REG_ADC, shift=4, width=2, value=0b11)
|
||||
# Enable low-ESR caps on PGA (PGA bit 6 = 0 for improved accuracy)
|
||||
self._set_bit(REG_PGA, 6, False)
|
||||
|
||||
# Step 6: Trigger fresh AD conversion and wait for first result
|
||||
# CS bit transition 0→1 starts fresh conversion; takes ~4-sample time for result
|
||||
|
||||
self._set_bit(REG_PU_CTRL, 4, True) # CS=1
|
||||
logger.debug(" Conversion started")
|
||||
|
||||
# Flush startup transients before calibration
|
||||
# At 10 SPS, initial 4 samples may contain settling artifacts
|
||||
|
||||
self.flush_readings(count=4, timeout_s=1.5)
|
||||
|
||||
# Run AFE calibration (internal mode), then flush result
|
||||
self.calibrate_afe(timeout_ms=1000, mode=0)
|
||||
self.flush_readings(count=2, timeout_s=1.0)
|
||||
logger.debug(" Initialization complete")
|
||||
|
||||
def begin_calibrate_afe(self, mode: int = 0) -> None:
|
||||
"""Start asynchronous AFE calibration.
|
||||
|
||||
mode values match NAU7802 CALMOD: 0=internal, 1=offset, 2=gain.
|
||||
"""
|
||||
ctrl2 = self.read_reg(REG_CTRL2)
|
||||
ctrl2 &= 0xFC # clear CALMOD bits[1:0]
|
||||
ctrl2 |= mode & 0x03
|
||||
self.write_reg(REG_CTRL2, ctrl2)
|
||||
|
||||
# Set CALS (bit 2) to start calibration.
|
||||
self.write_reg(REG_CTRL2, self.read_reg(REG_CTRL2) | self._CTRL2_CALS)
|
||||
|
||||
def wait_for_calibrate_afe(self, timeout_ms: int = 1000) -> bool:
|
||||
deadline = time.monotonic() + (timeout_ms / 1000.0) if timeout_ms > 0 else None
|
||||
|
||||
while True:
|
||||
ctrl2 = self.read_reg(REG_CTRL2)
|
||||
if (ctrl2 & self._CTRL2_CALS) == 0:
|
||||
return (ctrl2 & self._CTRL2_CAL_ERROR) == 0
|
||||
|
||||
if deadline is not None and time.monotonic() >= deadline:
|
||||
return False
|
||||
time.sleep(0.001)
|
||||
|
||||
def calibrate_afe(self, timeout_ms: int = 1000, mode: int = 0) -> None:
|
||||
"""Run AFE calibration per datasheet CTRL2[2] CALS bit sequence.
|
||||
|
||||
Datasheet says:
|
||||
- Write 1 to CALS to start (mode in CALMOD bits [1:0])
|
||||
- CALS=1 during calibration, 0 when complete
|
||||
- Check CAL_ERR bit after completion
|
||||
"""
|
||||
self.begin_calibrate_afe(mode=mode)
|
||||
if not self.wait_for_calibrate_afe(timeout_ms=timeout_ms):
|
||||
raise RuntimeError(f"NAU7802 AFE calibration timed out after {timeout_ms}ms")
|
||||
# Check CAL_ERR bit to ensure no error during calibration
|
||||
ctrl2 = self.read_reg(REG_CTRL2)
|
||||
if ctrl2 & self._CTRL2_CAL_ERROR:
|
||||
raise RuntimeError("NAU7802 AFE calibration completed with CAL_ERR set")
|
||||
logger.debug(" AFE calibration: OK")
|
||||
|
||||
def wait_data_ready(self, timeout_s: float = 1.0) -> bool:
|
||||
deadline = time.monotonic() + timeout_s
|
||||
while time.monotonic() < deadline:
|
||||
if self.data_ready():
|
||||
return True
|
||||
time.sleep(0.001)
|
||||
return False
|
||||
|
||||
def flush_readings(self, count: int = 4, timeout_s: float = 1.0) -> None:
|
||||
flushed = 0
|
||||
while flushed < count:
|
||||
if not self.wait_data_ready(timeout_s=timeout_s):
|
||||
raise TimeoutError("Timeout while flushing startup scale readings")
|
||||
_ = self.read_raw()
|
||||
flushed += 1
|
||||
|
||||
def data_ready(self) -> bool:
|
||||
return bool(self.read_reg(REG_PU_CTRL) & PU_CR)
|
||||
|
||||
def read_raw(self) -> int:
|
||||
"""Read 24-bit signed ADC value."""
|
||||
b2 = self.read_reg(REG_ADCO_B2)
|
||||
b1 = self.read_reg(REG_ADCO_B1)
|
||||
b0 = self.read_reg(REG_ADCO_B0)
|
||||
raw = (b2 << 16) | (b1 << 8) | b0
|
||||
# Sign extend 24-bit to 32-bit
|
||||
if raw & 0x800000:
|
||||
raw |= 0xFF000000
|
||||
raw = struct.unpack("i", struct.pack("I", raw))[0]
|
||||
return raw
|
||||
@@ -28,7 +28,7 @@ class NFCReader:
|
||||
self._last_status_log = 0.0
|
||||
|
||||
try:
|
||||
from read_tag import PN5180
|
||||
from .pn5180 import PN5180
|
||||
|
||||
self._nfc = PN5180()
|
||||
self._init_rf()
|
||||
@@ -98,7 +98,7 @@ class NFCReader:
|
||||
"""
|
||||
if self._state != NFCState.TAG_PRESENT:
|
||||
return False, "No tag present"
|
||||
if self._current_sak != 0x00:
|
||||
if self._current_sak not in (0x00, 0x04):
|
||||
return False, f"Not an NTAG (SAK=0x{self._current_sak:02X})"
|
||||
if not self._nfc:
|
||||
return False, "NFC reader not available"
|
||||
@@ -205,7 +205,7 @@ class NFCReader:
|
||||
|
||||
# Try reading Bambu tag data
|
||||
tray_uuid = None
|
||||
tag_type = "mifare_classic" if sak in (0x08, 0x18) else "ntag" if sak == 0x00 else "unknown"
|
||||
tag_type = "mifare_classic" if sak in (0x08, 0x18) else "ntag" if sak in (0x00, 0x04) else "unknown"
|
||||
|
||||
if sak in (0x08, 0x18):
|
||||
blocks = self._nfc.read_bambu_tag(uid_bytes)
|
||||
@@ -240,13 +240,24 @@ class NFCReader:
|
||||
|
||||
def _extract_tray_uuid(blocks: dict[int, bytes]) -> str | None:
|
||||
"""Extract tray_uuid from Bambu MIFARE Classic data blocks."""
|
||||
# Block 4-5 contain the 32-char tray UUID (first 16 bytes from block 4 + 5)
|
||||
# Block 4-5 contain the tray UUID as 32 ASCII hex chars across 32 bytes.
|
||||
if 4 in blocks and 5 in blocks:
|
||||
raw = blocks[4] + blocks[5]
|
||||
# UUID is stored as ASCII hex in the first 16 bytes of blocks 4-5
|
||||
uuid_bytes = raw[:16]
|
||||
try:
|
||||
uuid_str = uuid_bytes.hex().upper()
|
||||
# Preferred path: decode full ASCII payload, keep only hex chars.
|
||||
ascii_candidate = raw.decode("ascii", errors="ignore")
|
||||
hex_chars = "".join(ch for ch in ascii_candidate if ch in "0123456789abcdefABCDEF")
|
||||
if len(hex_chars) >= 32:
|
||||
uuid_str = hex_chars[:32].upper()
|
||||
if uuid_str != "0" * 32:
|
||||
return uuid_str
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
# Fallback for partially decoded payloads: use first 16 raw bytes as hex.
|
||||
# This preserves compatibility with older decoding behavior.
|
||||
uuid_str = raw[:16].hex().upper()
|
||||
if uuid_str and uuid_str != "0" * 32:
|
||||
return uuid_str
|
||||
except Exception:
|
||||
|
||||
@@ -0,0 +1,570 @@
|
||||
"""PN5180 NFC frontend driver — ported from working Pico firmware (pico-nfc-bridge.ino).
|
||||
|
||||
Key learnings from pico-nfc-bridge.ino:
|
||||
- Must call setTransceiveMode() before every SEND_DATA
|
||||
- waitBusy() must wait for HIGH then LOW (not just LOW)
|
||||
- Bambu tags are MIFARE Classic 1K (ISO 14443A), not ISO 15693
|
||||
- SPI at 500kHz, 5us CS setup, 100us post-CS delay
|
||||
- MFC_AUTHENTICATE (0x0C) is a PN5180 host command — Crypto1 handled in hardware
|
||||
- HKDF-SHA256 derives per-sector keys from master key + UID
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
|
||||
import gpiod
|
||||
import spidev
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _env_int(name: str, default: int) -> int:
|
||||
value = os.environ.get(name)
|
||||
if value is None or value == "":
|
||||
return default
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
|
||||
BUSY_PIN = _env_int("SPOOLBUDDY_NFC_BUSY_PIN", 25)
|
||||
RST_PIN = _env_int("SPOOLBUDDY_NFC_RST_PIN", 24)
|
||||
NSS_PIN = _env_int("SPOOLBUDDY_NFC_NSS_PIN", 23) # Manual CS by default
|
||||
SPI_BUS = _env_int("SPOOLBUDDY_NFC_SPI_BUS", 0)
|
||||
SPI_DEVICE = _env_int("SPOOLBUDDY_NFC_SPI_DEVICE", 0)
|
||||
SPI_SPEED_HZ = _env_int("SPOOLBUDDY_NFC_SPI_SPEED_HZ", 500_000)
|
||||
|
||||
# Bambu Lab MIFARE Classic key derivation constants (from pico-nfc-bridge.ino)
|
||||
BAMBU_MASTER_KEY = bytes(
|
||||
[
|
||||
0x9A,
|
||||
0x75,
|
||||
0x9C,
|
||||
0xF2,
|
||||
0xC4,
|
||||
0xF7,
|
||||
0xCA,
|
||||
0xFF,
|
||||
0x22,
|
||||
0x2C,
|
||||
0xB9,
|
||||
0x76,
|
||||
0x9B,
|
||||
0x41,
|
||||
0xBC,
|
||||
0x96,
|
||||
]
|
||||
)
|
||||
BAMBU_CONTEXT = b"RFID-A\x00" # 7 bytes including null terminator
|
||||
|
||||
# Blocks to read for Bambu tag data
|
||||
BAMBU_BLOCKS = [1, 2, 4, 5]
|
||||
|
||||
|
||||
def hkdf_derive_keys(uid: bytes) -> bytes:
|
||||
"""Derive 96 bytes of MIFARE key material (16 sectors * 6 bytes each).
|
||||
|
||||
Uses HKDF-SHA256 with the Bambu master key as salt and the tag UID as IKM.
|
||||
"""
|
||||
# HKDF-Extract: PRK = HMAC-SHA256(salt=master_key, IKM=uid)
|
||||
prk = hmac.new(BAMBU_MASTER_KEY, uid, hashlib.sha256).digest()
|
||||
|
||||
# HKDF-Expand: generate 96 bytes using context "RFID-A\0"
|
||||
okm = b""
|
||||
t = b""
|
||||
counter = 1
|
||||
while len(okm) < 96:
|
||||
t = hmac.new(prk, t + BAMBU_CONTEXT + bytes([counter]), hashlib.sha256).digest()
|
||||
okm += t
|
||||
counter += 1
|
||||
return okm[:96]
|
||||
|
||||
|
||||
def get_sector_key(keys: bytes, block: int) -> bytes:
|
||||
"""Get the 6-byte key for the sector containing the given block."""
|
||||
sector = block // 4
|
||||
return keys[sector * 6 : sector * 6 + 6]
|
||||
|
||||
|
||||
def _find_gpio_chip():
|
||||
for path in ["/dev/gpiochip4", "/dev/gpiochip0"]:
|
||||
try:
|
||||
chip = gpiod.Chip(path)
|
||||
if "pinctrl" in chip.get_info().label:
|
||||
return chip
|
||||
chip.close()
|
||||
except (FileNotFoundError, PermissionError, OSError):
|
||||
continue
|
||||
raise RuntimeError("No GPIO chip")
|
||||
|
||||
|
||||
class PN5180:
|
||||
def __init__(self):
|
||||
self._chip = _find_gpio_chip()
|
||||
self._lines = self._chip.request_lines(
|
||||
consumer="pn5180",
|
||||
config={
|
||||
BUSY_PIN: gpiod.LineSettings(direction=gpiod.line.Direction.INPUT),
|
||||
RST_PIN: gpiod.LineSettings(
|
||||
direction=gpiod.line.Direction.OUTPUT, output_value=gpiod.line.Value.ACTIVE
|
||||
),
|
||||
NSS_PIN: gpiod.LineSettings(
|
||||
direction=gpiod.line.Direction.OUTPUT, output_value=gpiod.line.Value.ACTIVE
|
||||
),
|
||||
},
|
||||
)
|
||||
self._spi = spidev.SpiDev()
|
||||
self._spi.open(SPI_BUS, SPI_DEVICE)
|
||||
self._spi.max_speed_hz = SPI_SPEED_HZ
|
||||
self._spi.mode = 0b00
|
||||
self._spi.no_cs = True
|
||||
|
||||
def close(self):
|
||||
self._spi.close()
|
||||
self._lines.release()
|
||||
self._chip.close()
|
||||
|
||||
def _cs_low(self):
|
||||
self._lines.set_value(NSS_PIN, gpiod.line.Value.INACTIVE)
|
||||
time.sleep(0.000005) # 5us setup
|
||||
|
||||
def _cs_high(self):
|
||||
self._lines.set_value(NSS_PIN, gpiod.line.Value.ACTIVE)
|
||||
time.sleep(0.000100) # 100us post-CS delay
|
||||
|
||||
def _wait_busy(self, timeout_s=1.0):
|
||||
"""Wait for BUSY to go HIGH (processing) then LOW (done) — matches Pico firmware."""
|
||||
deadline = time.monotonic() + min(timeout_s, 0.010)
|
||||
# Wait for BUSY HIGH (PN5180 started processing)
|
||||
while self._lines.get_value(BUSY_PIN) != gpiod.line.Value.ACTIVE:
|
||||
if time.monotonic() > deadline:
|
||||
break # Timeout waiting for HIGH — command may have processed already
|
||||
time.sleep(0.00001)
|
||||
# Wait for BUSY LOW (PN5180 done)
|
||||
deadline = time.monotonic() + timeout_s
|
||||
while self._lines.get_value(BUSY_PIN) == gpiod.line.Value.ACTIVE:
|
||||
if time.monotonic() > deadline:
|
||||
raise TimeoutError("BUSY timeout")
|
||||
time.sleep(0.0001)
|
||||
|
||||
def _cmd(self, data):
|
||||
self._cs_low()
|
||||
self._spi.xfer2(list(data))
|
||||
self._cs_high()
|
||||
self._wait_busy()
|
||||
|
||||
def _read_response(self, n):
|
||||
self._cs_low()
|
||||
result = self._spi.xfer2([0xFF] * n)
|
||||
self._cs_high()
|
||||
return result
|
||||
|
||||
# -- Register ops --
|
||||
|
||||
def write_reg(self, reg, val):
|
||||
self._cmd([0x00, reg, val & 0xFF, (val >> 8) & 0xFF, (val >> 16) & 0xFF, (val >> 24) & 0xFF])
|
||||
|
||||
def write_reg_or(self, reg, mask):
|
||||
self._cmd([0x01, reg, mask & 0xFF, (mask >> 8) & 0xFF, (mask >> 16) & 0xFF, (mask >> 24) & 0xFF])
|
||||
|
||||
def write_reg_and(self, reg, mask):
|
||||
self._cmd([0x02, reg, mask & 0xFF, (mask >> 8) & 0xFF, (mask >> 16) & 0xFF, (mask >> 24) & 0xFF])
|
||||
|
||||
def read_reg(self, reg):
|
||||
self._cmd([0x04, reg])
|
||||
time.sleep(0.000100) # Extra 100us before read
|
||||
return int.from_bytes(self._read_response(4), "little")
|
||||
|
||||
def read_eeprom(self, addr, length):
|
||||
self._cmd([0x07, addr, length])
|
||||
time.sleep(0.000100)
|
||||
return bytes(self._read_response(length))
|
||||
|
||||
# -- Commands --
|
||||
|
||||
def reset(self):
|
||||
self._lines.set_value(RST_PIN, gpiod.line.Value.INACTIVE)
|
||||
time.sleep(0.050)
|
||||
self._lines.set_value(RST_PIN, gpiod.line.Value.ACTIVE)
|
||||
time.sleep(0.100)
|
||||
self._wait_busy(2.0)
|
||||
time.sleep(0.050)
|
||||
|
||||
def load_rf_config(self, tx, rx):
|
||||
self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs first
|
||||
time.sleep(0.000100)
|
||||
self._cmd([0x11, tx, rx])
|
||||
time.sleep(0.010)
|
||||
|
||||
def rf_on(self):
|
||||
self._cmd([0x16, 0x00])
|
||||
time.sleep(0.010)
|
||||
|
||||
def rf_off(self):
|
||||
self._cmd([0x17, 0x00])
|
||||
time.sleep(0.005)
|
||||
|
||||
def set_pin(self, pin: int, value: bool) -> None:
|
||||
"""Set the state of a control pin (NSS or RST). Value: True=ACTIVE, False=INACTIVE."""
|
||||
if pin not in (NSS_PIN, RST_PIN):
|
||||
raise ValueError("Only NSS_PIN and RST_PIN can be set via set_pin().")
|
||||
self._lines.set_value(pin, gpiod.line.Value.ACTIVE if value else gpiod.line.Value.INACTIVE)
|
||||
|
||||
def get_pin(self, pin: int) -> bool:
|
||||
"""Get the state of a control pin (NSS or RST). Returns True if ACTIVE, False if INACTIVE."""
|
||||
if pin not in (NSS_PIN, RST_PIN):
|
||||
raise ValueError("Only NSS_PIN and RST_PIN can be read via get_pin().")
|
||||
return self._lines.get_value(pin) == gpiod.line.Value.ACTIVE
|
||||
|
||||
def set_transceive_mode(self):
|
||||
"""Set SYSTEM_CONFIG command bits to TRANSCEIVE (0x03) — CRITICAL!"""
|
||||
sys_cfg = self.read_reg(0x00)
|
||||
sys_cfg = (sys_cfg & 0xFFFFFFF8) | 0x03
|
||||
self.write_reg(0x00, sys_cfg)
|
||||
|
||||
def send_data(self, data, valid_bits=0x00):
|
||||
self._cs_low()
|
||||
self._spi.xfer2([0x09, valid_bits] + list(data))
|
||||
self._cs_high()
|
||||
time.sleep(0.000100)
|
||||
self._wait_busy()
|
||||
|
||||
def read_data(self, length):
|
||||
self._cmd([0x0A, 0x00])
|
||||
return bytes(self._read_response(length))
|
||||
|
||||
# -- ISO 14443A --
|
||||
|
||||
def activate_type_a(self):
|
||||
"""Full Type A activation: WUPA -> Anticollision -> SELECT. Returns (uid, sak) or None."""
|
||||
# Crypto off, CRC off
|
||||
self.write_reg_and(0x00, 0xFFFFFFBF)
|
||||
self.write_reg_and(0x12, 0xFFFFFFFE)
|
||||
self.write_reg_and(0x19, 0xFFFFFFFE)
|
||||
self.write_reg(0x03, 0xFFFFFFFF)
|
||||
|
||||
# Reset to IDLE then TRANSCEIVE
|
||||
sys_cfg = self.read_reg(0x00)
|
||||
self.write_reg(0x00, sys_cfg & 0xFFFFFFF8) # IDLE
|
||||
time.sleep(0.001)
|
||||
self.write_reg(0x00, (sys_cfg & 0xFFFFFFF8) | 0x03) # TRANSCEIVE
|
||||
time.sleep(0.002)
|
||||
|
||||
# WUPA (7-bit)
|
||||
self.send_data([0x52], valid_bits=0x07)
|
||||
time.sleep(0.005)
|
||||
|
||||
rx_status = self.read_reg(0x13)
|
||||
rx_len = rx_status & 0x1FF
|
||||
if rx_len < 2 or rx_len == 511:
|
||||
# Try REQA
|
||||
self.write_reg(0x03, 0xFFFFFFFF)
|
||||
time.sleep(0.002)
|
||||
self.set_transceive_mode()
|
||||
time.sleep(0.002)
|
||||
self.send_data([0x26], valid_bits=0x07)
|
||||
time.sleep(0.005)
|
||||
rx_status = self.read_reg(0x13)
|
||||
rx_len = rx_status & 0x1FF
|
||||
if rx_len < 2 or rx_len == 511:
|
||||
return None
|
||||
|
||||
atqa = self.read_data(2)
|
||||
if atqa[0] == 0xFF or atqa[0] == 0x00:
|
||||
return None
|
||||
|
||||
# Anti-collision Level 1
|
||||
self.write_reg(0x03, 0xFFFFFFFF)
|
||||
self.set_transceive_mode()
|
||||
time.sleep(0.002)
|
||||
|
||||
self.send_data([0x93, 0x20])
|
||||
time.sleep(0.010)
|
||||
|
||||
rx_status = self.read_reg(0x13)
|
||||
rx_len = rx_status & 0x1FF
|
||||
if rx_len < 5 or rx_len > 64:
|
||||
return None
|
||||
|
||||
uid_buf = self.read_data(5)
|
||||
uid = uid_buf[:4]
|
||||
bcc = uid[0] ^ uid[1] ^ uid[2] ^ uid[3]
|
||||
if bcc != uid_buf[4]:
|
||||
return None
|
||||
|
||||
# SELECT
|
||||
self.write_reg(0x03, 0xFFFFFFFF)
|
||||
self.set_transceive_mode()
|
||||
time.sleep(0.002)
|
||||
|
||||
# Enable CRC for SELECT
|
||||
self.write_reg_or(0x19, 0x01)
|
||||
self.write_reg_or(0x12, 0x01)
|
||||
|
||||
self.send_data([0x93, 0x70, uid[0], uid[1], uid[2], uid[3], bcc])
|
||||
time.sleep(0.010)
|
||||
|
||||
rx_status = self.read_reg(0x13)
|
||||
rx_len = rx_status & 0x1FF
|
||||
if rx_len < 1:
|
||||
return None
|
||||
|
||||
sak_buf = self.read_data(min(rx_len, 3))
|
||||
sak = sak_buf[0]
|
||||
|
||||
return bytes(uid), sak
|
||||
|
||||
# -- MIFARE Classic --
|
||||
|
||||
def mfc_authenticate(self, block: int, key: bytes, uid: bytes) -> bool:
|
||||
"""MIFARE Classic authentication via PN5180 MFC_AUTHENTICATE (0x0C).
|
||||
|
||||
The PN5180 handles Crypto1 internally. After success, bit 6 of
|
||||
SYSTEM_CONFIG is set (MFC_CRYPTO1_ON) and all subsequent RF
|
||||
communication is encrypted/decrypted by the hardware.
|
||||
|
||||
Args:
|
||||
block: Block number to authenticate
|
||||
key: 6-byte MIFARE Key A
|
||||
uid: 4-byte tag UID
|
||||
Returns:
|
||||
True if authentication succeeded
|
||||
"""
|
||||
# Wait for BUSY LOW before starting
|
||||
deadline = time.monotonic() + 0.100
|
||||
while self._lines.get_value(BUSY_PIN) == gpiod.line.Value.ACTIVE:
|
||||
if time.monotonic() > deadline:
|
||||
return False
|
||||
time.sleep(0.001)
|
||||
|
||||
# MFC_AUTHENTICATE: [0x0C][key 6B][keyType][blockNo][uid 4B] = 13 bytes
|
||||
cmd = [0x0C] + list(key) + [0x60, block] + list(uid[:4])
|
||||
self._cs_low()
|
||||
self._spi.xfer2(cmd)
|
||||
self._cs_high()
|
||||
|
||||
# Wait for BUSY HIGH then LOW (auth can take up to 1s)
|
||||
self._wait_busy(timeout_s=1.0)
|
||||
|
||||
# Read 1-byte response: 0x00 = success
|
||||
self._cs_low()
|
||||
response = self._spi.xfer2([0xFF])
|
||||
self._cs_high()
|
||||
|
||||
return response[0] == 0x00
|
||||
|
||||
def mfc_read_block(self, block: int) -> bytes | None:
|
||||
"""Read a 16-byte MIFARE Classic block (must be authenticated first).
|
||||
|
||||
Returns 16 bytes of block data, or None on failure.
|
||||
"""
|
||||
# Clear IRQs
|
||||
self.write_reg(0x03, 0xFFFFFFFF)
|
||||
|
||||
# Set transceive mode (Crypto1 stays active from MFC_AUTHENTICATE)
|
||||
self.set_transceive_mode()
|
||||
time.sleep(0.001)
|
||||
|
||||
# Enable TX and RX CRC for encrypted read
|
||||
self.write_reg_or(0x19, 0x01)
|
||||
self.write_reg_or(0x12, 0x01)
|
||||
|
||||
# Send MIFARE READ command: 0x30 + block number
|
||||
self.send_data([0x30, block])
|
||||
time.sleep(0.010)
|
||||
|
||||
# Check RX status
|
||||
rx_status = self.read_reg(0x13)
|
||||
rx_len = rx_status & 0x1FF
|
||||
if rx_len != 16:
|
||||
return None
|
||||
|
||||
return self.read_data(16)
|
||||
|
||||
def ntag_read_pages(self, start_page: int, num_pages: int) -> bytes | None:
|
||||
"""Read NTAG pages (4 bytes each). No authentication required.
|
||||
|
||||
Uses NTAG READ command (0x30) which returns 4 pages (16 bytes) at a time.
|
||||
"""
|
||||
# One-time setup: Crypto1 off, TX CRC on, RX CRC off, IDLE→TRANSCEIVE
|
||||
self.write_reg_and(0x00, 0xFFFFFFBF) # Crypto1 off
|
||||
self.write_reg_or(0x19, 0x01) # TX CRC on
|
||||
self.write_reg_and(0x12, 0xFFFFFFFE) # RX CRC off
|
||||
self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs
|
||||
|
||||
sys_cfg = self.read_reg(0x00)
|
||||
self.write_reg(0x00, sys_cfg & 0xFFFFFFF8) # IDLE
|
||||
time.sleep(0.001)
|
||||
self.write_reg(0x00, (sys_cfg & 0xFFFFFFF8) | 0x03) # TRANSCEIVE
|
||||
time.sleep(0.002)
|
||||
|
||||
result = bytearray()
|
||||
pages_read = 0
|
||||
while pages_read < num_pages:
|
||||
if pages_read > 0:
|
||||
# Subsequent iterations: just clear IRQs and re-enter TRANSCEIVE
|
||||
self.write_reg(0x03, 0xFFFFFFFF)
|
||||
self.set_transceive_mode()
|
||||
time.sleep(0.001)
|
||||
|
||||
# READ command: 0x30 + page number -> returns 16 bytes (4 pages)
|
||||
self.send_data([0x30, start_page + pages_read])
|
||||
time.sleep(0.010)
|
||||
|
||||
rx_status = self.read_reg(0x13)
|
||||
rx_len = rx_status & 0x1FF
|
||||
if rx_len < 16:
|
||||
logger.warning(
|
||||
"NTAG read page %d: rx_len=%d (expected >=16), rx_status=0x%08X",
|
||||
start_page + pages_read,
|
||||
rx_len,
|
||||
rx_status,
|
||||
)
|
||||
return None
|
||||
|
||||
data = self.read_data(16)
|
||||
pages_to_copy = min(4, num_pages - pages_read)
|
||||
result.extend(data[: pages_to_copy * 4])
|
||||
pages_read += 4
|
||||
|
||||
return bytes(result)
|
||||
|
||||
def reactivate_card(self) -> tuple[bytes, int] | None:
|
||||
"""RF cycle and full re-select of the card. Returns (uid, sak) or None."""
|
||||
self.rf_off()
|
||||
time.sleep(0.010)
|
||||
|
||||
self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs
|
||||
self.load_rf_config(0x00, 0x80) # ISO 14443A
|
||||
time.sleep(0.005)
|
||||
|
||||
self.rf_on()
|
||||
time.sleep(0.020)
|
||||
|
||||
return self.activate_type_a()
|
||||
|
||||
def read_bambu_tag(self, uid: bytes) -> dict[int, bytes] | None:
|
||||
"""Read Bambu tag data blocks using HKDF-derived keys.
|
||||
|
||||
Args:
|
||||
uid: 4-byte tag UID (from activate_type_a)
|
||||
Returns:
|
||||
Dict mapping block number -> 16 bytes of data, or None on failure
|
||||
"""
|
||||
# Derive per-sector keys from UID
|
||||
keys = hkdf_derive_keys(uid)
|
||||
|
||||
# Clear Crypto1 state and IRQs
|
||||
self.write_reg_and(0x00, 0xFFFFFFBF) # Clear MFC_CRYPTO1_ON (bit 6)
|
||||
self.write_reg(0x03, 0xFFFFFFFF)
|
||||
|
||||
# Reactivate card (may have timed out)
|
||||
result = self.reactivate_card()
|
||||
if result is None:
|
||||
logger.debug("Failed to reactivate card for Bambu tag read")
|
||||
return None
|
||||
|
||||
uid_check, _ = result
|
||||
if uid_check != uid:
|
||||
logger.debug("UID mismatch after reactivation: %s != %s", uid_check.hex(), uid.hex())
|
||||
return None
|
||||
|
||||
# Read blocks with per-sector authentication
|
||||
blocks = {}
|
||||
current_sector = -1
|
||||
|
||||
for block in BAMBU_BLOCKS:
|
||||
sector = block // 4
|
||||
|
||||
# Authenticate when entering a new sector
|
||||
if sector != current_sector:
|
||||
key = get_sector_key(keys, block)
|
||||
if not self.mfc_authenticate(block, key, uid):
|
||||
logger.debug("Auth failed for block %d (sector %d)", block, sector)
|
||||
return None
|
||||
current_sector = sector
|
||||
|
||||
# Read the block
|
||||
data = self.mfc_read_block(block)
|
||||
if data is None:
|
||||
logger.debug("Read failed for block %d", block)
|
||||
return None
|
||||
blocks[block] = data
|
||||
|
||||
return blocks
|
||||
|
||||
def ntag_write_page(self, page: int, data: bytes) -> bool:
|
||||
"""Write 4 bytes to a single NTAG page.
|
||||
|
||||
NTAG WRITE command: 0xA2 + page_number + 4 bytes data.
|
||||
TX CRC on (tag requires it). Always returns True — the 4-bit ACK
|
||||
cannot be captured by the PN5180, so verification is deferred to
|
||||
ntag_write_pages() which reads back all written data.
|
||||
"""
|
||||
if len(data) != 4:
|
||||
return False
|
||||
|
||||
# Crypto1 off, TX CRC on (tag expects CRC), RX CRC off (ACK is 4-bit, no CRC)
|
||||
self.write_reg_and(0x00, 0xFFFFFFBF) # Crypto1 off
|
||||
self.write_reg_or(0x19, 0x01) # TX CRC on
|
||||
self.write_reg_and(0x12, 0xFFFFFFFE) # RX CRC off
|
||||
self.write_reg(0x03, 0xFFFFFFFF) # Clear IRQs
|
||||
|
||||
# Reset state machine: IDLE then TRANSCEIVE
|
||||
sys_cfg = self.read_reg(0x00)
|
||||
self.write_reg(0x00, sys_cfg & 0xFFFFFFF8) # IDLE
|
||||
time.sleep(0.001)
|
||||
self.write_reg(0x00, (sys_cfg & 0xFFFFFFF8) | 0x03) # TRANSCEIVE
|
||||
time.sleep(0.002)
|
||||
|
||||
# WRITE command: 0xA2 + page + 4 bytes
|
||||
self.send_data([0xA2, page] + list(data))
|
||||
time.sleep(0.010)
|
||||
|
||||
# The NTAG ACK is only 4 bits (0x0A). The PN5180 detects SOF but
|
||||
# cannot capture sub-byte frames — RX_IRQ never fires. Skip ACK
|
||||
# checking; the tag's SOF response confirms it received the command.
|
||||
return True
|
||||
|
||||
def ntag_write_pages(self, start_page: int, data: bytes) -> bool:
|
||||
"""Write data to consecutive NTAG pages starting at start_page.
|
||||
|
||||
Pads last chunk to 4 bytes. Verification is skipped — the PN5180
|
||||
cannot reliably read back NTAG pages after a batch write (the
|
||||
second READ command gets no response). The write itself is reliable:
|
||||
the tag ACKs each page (RX SOF detected on every response).
|
||||
"""
|
||||
# Pad to 4-byte boundary
|
||||
padded = bytearray(data)
|
||||
while len(padded) % 4 != 0:
|
||||
padded.append(0x00)
|
||||
|
||||
# Write page by page
|
||||
num_pages = len(padded) // 4
|
||||
for i in range(0, len(padded), 4):
|
||||
page = start_page + (i // 4)
|
||||
chunk = bytes(padded[i : i + 4])
|
||||
if not self.ntag_write_page(page, chunk):
|
||||
logger.warning("NTAG write failed at page %d (of %d pages)", page, num_pages)
|
||||
return False
|
||||
time.sleep(0.002)
|
||||
|
||||
logger.info("NTAG write complete (%d pages)", num_pages)
|
||||
return True
|
||||
|
||||
def read_ntag(self, uid: bytes) -> bytes | None:
|
||||
"""Read NTAG pages 4-20 (NDEF data area, 68 bytes). No auth needed.
|
||||
|
||||
Used for SpoolEase / OpenPrintTag community tags.
|
||||
"""
|
||||
# Reactivate card
|
||||
result = self.reactivate_card()
|
||||
if result is None:
|
||||
logger.debug("Failed to reactivate card for NTAG read")
|
||||
return None
|
||||
|
||||
return self.ntag_read_pages(start_page=4, num_pages=17)
|
||||
@@ -20,12 +20,18 @@ class ScaleReader:
|
||||
self._last_raw = 0
|
||||
|
||||
try:
|
||||
from scale_diag import NAU7802
|
||||
from .nau7802 import NAU7802
|
||||
|
||||
self._scale = NAU7802()
|
||||
self._scale.init()
|
||||
self._ok = True
|
||||
logger.info("Scale initialized (tare=%d, cal=%.6f)", tare_offset, calibration_factor)
|
||||
bus_num = getattr(self._scale, "_bus_num", "?")
|
||||
logger.info(
|
||||
"Scale initialized on I2C bus %s (tare=%d, cal=%.6f)",
|
||||
bus_num,
|
||||
tare_offset,
|
||||
calibration_factor,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.info("Scale not available: %s", e)
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Collect OS-level system stats from the Raspberry Pi using stdlib only."""
|
||||
|
||||
import os
|
||||
import platform
|
||||
|
||||
|
||||
def _read_file(path: str) -> str | None:
|
||||
try:
|
||||
with open(path) as f:
|
||||
return f.read().strip()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _cpu_temp() -> float | None:
|
||||
raw = _read_file("/sys/class/thermal/thermal_zone0/temp")
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
return round(int(raw) / 1000, 1)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def _memory_info() -> dict | None:
|
||||
raw = _read_file("/proc/meminfo")
|
||||
if raw is None:
|
||||
return None
|
||||
info: dict[str, int] = {}
|
||||
for line in raw.splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) >= 2 and parts[0].endswith(":"):
|
||||
key = parts[0][:-1]
|
||||
try:
|
||||
info[key] = int(parts[1]) # kB
|
||||
except ValueError:
|
||||
continue
|
||||
total = info.get("MemTotal", 0)
|
||||
available = info.get("MemAvailable", 0)
|
||||
if total == 0:
|
||||
return None
|
||||
return {
|
||||
"total_mb": round(total / 1024),
|
||||
"available_mb": round(available / 1024),
|
||||
"used_mb": round((total - available) / 1024),
|
||||
"percent": round((total - available) / total * 100, 1),
|
||||
}
|
||||
|
||||
|
||||
def _disk_info() -> dict | None:
|
||||
try:
|
||||
st = os.statvfs("/")
|
||||
except OSError:
|
||||
return None
|
||||
total = st.f_frsize * st.f_blocks
|
||||
free = st.f_frsize * st.f_bavail
|
||||
used = total - free
|
||||
if total == 0:
|
||||
return None
|
||||
return {
|
||||
"total_gb": round(total / (1024**3), 1),
|
||||
"used_gb": round(used / (1024**3), 1),
|
||||
"free_gb": round(free / (1024**3), 1),
|
||||
"percent": round(used / total * 100, 1),
|
||||
}
|
||||
|
||||
|
||||
def _load_avg() -> list[float] | None:
|
||||
try:
|
||||
load = os.getloadavg()
|
||||
return [round(x, 2) for x in load]
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _cpu_count() -> int | None:
|
||||
return os.cpu_count()
|
||||
|
||||
|
||||
def _os_info() -> dict:
|
||||
uname = platform.uname()
|
||||
os_release = _read_file("/etc/os-release")
|
||||
pretty_name = None
|
||||
if os_release:
|
||||
for line in os_release.splitlines():
|
||||
if line.startswith("PRETTY_NAME="):
|
||||
pretty_name = line.split("=", 1)[1].strip().strip('"')
|
||||
break
|
||||
return {
|
||||
"os": pretty_name or f"{uname.system} {uname.release}",
|
||||
"kernel": uname.release,
|
||||
"arch": uname.machine,
|
||||
"python": platform.python_version(),
|
||||
}
|
||||
|
||||
|
||||
def _system_uptime() -> int | None:
|
||||
raw = _read_file("/proc/uptime")
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
return int(float(raw.split()[0]))
|
||||
except (ValueError, IndexError):
|
||||
return None
|
||||
|
||||
|
||||
def collect() -> dict:
|
||||
"""Collect all system stats. Returns a flat dict safe for JSON serialization."""
|
||||
stats: dict = {}
|
||||
|
||||
stats["os"] = _os_info()
|
||||
|
||||
temp = _cpu_temp()
|
||||
if temp is not None:
|
||||
stats["cpu_temp_c"] = temp
|
||||
|
||||
cpu_count = _cpu_count()
|
||||
if cpu_count is not None:
|
||||
stats["cpu_count"] = cpu_count
|
||||
|
||||
load = _load_avg()
|
||||
if load is not None:
|
||||
stats["load_avg"] = load
|
||||
|
||||
mem = _memory_info()
|
||||
if mem is not None:
|
||||
stats["memory"] = mem
|
||||
|
||||
disk = _disk_info()
|
||||
if disk is not None:
|
||||
stats["disk"] = disk
|
||||
|
||||
uptime = _system_uptime()
|
||||
if uptime is not None:
|
||||
stats["system_uptime_s"] = uptime
|
||||
|
||||
return stats
|
||||
Reference in New Issue
Block a user