Compare commits
2 Commits
b665cb5def
...
binproto
| Author | SHA1 | Date | |
|---|---|---|---|
| f85143d7e5 | |||
| 4f3fbff258 |
@@ -1,217 +0,0 @@
|
||||
# buzzer.py
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Edis Buzzer Host Tool")
|
||||
|
||||
# Globale Argumente (gelten für alle Befehle)
|
||||
parser.add_argument("-p", "--port", type=str, help="Serielle Schnittstelle (z.B. COM15)")
|
||||
parser.add_argument("-b", "--baudrate", type=int, help="Verbindungsgeschwindigkeit")
|
||||
parser.add_argument("-t", "--timeout", type=float, help="Timeout in Sekunden (Standard: 5.0)")
|
||||
parser.add_argument("--no-auto-info", action="store_true", help="Überspringt den automatischen Info-Call beim Start")
|
||||
|
||||
# Subkommandos einrichten
|
||||
subparsers = parser.add_subparsers(dest="command", help="Verfügbare Befehle")
|
||||
|
||||
# Befehl: info (expliziter Aufruf, obwohl es ohnehin immer angezeigt wird)
|
||||
subparsers.add_parser("info", help="Zeigt nur die Systeminformationen an")
|
||||
|
||||
# Befehl: ls
|
||||
ls_parser = subparsers.add_parser("ls", help="Listet Dateien und Verzeichnisse auf")
|
||||
ls_parser.add_argument("path", nargs="?", default="/", help="Zielpfad (Standard: /)")
|
||||
ls_parser.add_argument("-r", "--recursive", action="store_true", help="Rekursiv auflisten")
|
||||
|
||||
# Befehl: put
|
||||
put_parser = subparsers.add_parser("put", help="Lädt eine oder mehrere Dateien auf den Controller hoch")
|
||||
put_parser.add_argument("sources", nargs="+", help="Lokale Quelldatei(en), Verzeichnisse oder Wildcards (z.B. *.raw)")
|
||||
put_parser.add_argument("target", type=str, help="Zielpfad auf dem Controller (Verzeichnis muss mit '/' enden)")
|
||||
put_parser.add_argument("-r", "--recursive", action="store_true", help="Verzeichnisse rekursiv hochladen")
|
||||
|
||||
# Befehl: put_many
|
||||
put_many_parser = subparsers.add_parser("put_many", help="Lädt mehrere Dateien/Verzeichnisse (typisch rekursiv) hoch")
|
||||
put_many_parser.add_argument("sources", nargs="+", help="Lokale Quelldatei(en), Verzeichnisse oder Wildcards")
|
||||
put_many_parser.add_argument("target", type=str, help="Zielpfad auf dem Controller")
|
||||
put_many_parser.add_argument("-r", "--recursive", action="store_true", help="Verzeichnisse rekursiv hochladen (Standard für put_many)")
|
||||
|
||||
# Befehl: fw_put
|
||||
fw_put_parser = subparsers.add_parser("fw_put", help="Lädt eine Firmware in den Secondary Slot (Test-Upgrade)")
|
||||
fw_put_parser.add_argument("source", type=str, help="Lokale Firmware-Datei (.bin)")
|
||||
|
||||
# Befehl: mkdir
|
||||
mkdir_parser = subparsers.add_parser("mkdir", help="Erstellt ein neues Verzeichnis")
|
||||
mkdir_parser.add_argument("path", type=str, help="Pfad des neuen Verzeichnisses (z.B. /lfs/a/neu)")
|
||||
|
||||
# Befehl: rm
|
||||
rm_parser = subparsers.add_parser("rm", help="Löscht eine Datei oder ein Verzeichnis")
|
||||
rm_parser.add_argument("path", type=str, help="Pfad der zu löschenden Datei/Ordner")
|
||||
rm_parser.add_argument("-r", "--recursive", action="store_true", help="Ordnerinhalte rekursiv löschen")
|
||||
|
||||
# Befehl: stat
|
||||
stat_parser = subparsers.add_parser("stat", help="Zeigt Typ und Größe einer Datei/eines Verzeichnisses")
|
||||
stat_parser.add_argument("path", type=str, help="Pfad der Datei/des Verzeichnisses")
|
||||
|
||||
# Befehl: mv
|
||||
mv_parser = subparsers.add_parser("mv", help="Benennt eine Datei/ein Verzeichnis um oder verschiebt es")
|
||||
mv_parser.add_argument("source", type=str, help="Alter Pfad")
|
||||
mv_parser.add_argument("target", type=str, help="Neuer Pfad")
|
||||
|
||||
# Befehl: pull
|
||||
pull_parser = subparsers.add_parser("pull", help="Lädt eine Datei vom Controller herunter")
|
||||
pull_parser.add_argument("source", type=str, help="Quellpfad auf dem Controller")
|
||||
pull_parser.add_argument("target", nargs="?", default=None, help="Optionaler lokaler Zielpfad")
|
||||
|
||||
# Alias: get_file
|
||||
get_file_parser = subparsers.add_parser("get_file", help="Alias für pull")
|
||||
get_file_parser.add_argument("source", type=str, help="Quellpfad auf dem Controller")
|
||||
get_file_parser.add_argument("target", nargs="?", default=None, help="Optionaler lokaler Zielpfad")
|
||||
|
||||
# Befehl: play
|
||||
play_parser = subparsers.add_parser("play", help="Spielt eine Datei auf dem Controller ab")
|
||||
play_parser.add_argument("path", type=str, help="Pfad der abzuspielenden Datei (z.B. /lfs/a/neu)")
|
||||
|
||||
# Befehl: check
|
||||
check_parser = subparsers.add_parser("check", help="Holt die CRC32 einer Datei und zeigt sie an")
|
||||
check_parser.add_argument("path", type=str, help="Pfad der zu prüfenden Datei (z.B. /lfs/a/neu)")
|
||||
|
||||
# Befehl: confirm
|
||||
confirm_parser = subparsers.add_parser("confirm", help="Bestätigt die aktuell laufende Firmware")
|
||||
|
||||
# Befehl: reboot
|
||||
reboot_parser = subparsers.add_parser("reboot", help="Startet den Buzzer neu")
|
||||
|
||||
# Befehl: get_tags (neuer Blob/TLV-Parser)
|
||||
get_tags_parser = subparsers.add_parser("get_tags", help="Holt alle Tags einer Datei als JSON")
|
||||
get_tags_parser.add_argument("path", type=str, help="Pfad der Datei")
|
||||
|
||||
# Befehl: write_tags (merge/replace per JSON)
|
||||
write_tags_parser = subparsers.add_parser("write_tags", help="Fügt Tags ein/ersetzt bestehende Tags per JSON")
|
||||
write_tags_parser.add_argument("path", type=str, help="Pfad der Datei")
|
||||
write_tags_parser.add_argument("json", type=str, help="JSON-Objekt oder @datei.json")
|
||||
|
||||
# Befehl: remove_tag
|
||||
remove_tag_parser = subparsers.add_parser("remove_tag", help="Entfernt einen Tag und schreibt den Rest zurück")
|
||||
remove_tag_parser.add_argument("path", type=str, help="Pfad der Datei")
|
||||
remove_tag_parser.add_argument("key", type=str, choices=["description", "author", "crc32", "fileformat"], help="Zu entfernender Tag-Key")
|
||||
|
||||
# Argumente parsen
|
||||
args = parser.parse_args()
|
||||
from core.config import load_config
|
||||
config = load_config(args)
|
||||
|
||||
print("--- Aktuelle Verbindungsparameter -------------------------------")
|
||||
print(f"Port: {config.get('port', 'Nicht definiert')}")
|
||||
print(f"Baudrate: {config.get('baudrate')}")
|
||||
print(f"Timeout: {config.get('timeout')}s")
|
||||
print("-" * 65)
|
||||
|
||||
if not config.get("port"):
|
||||
print("Abbruch: Es muss ein Port in der config.yaml oder via --port definiert werden.")
|
||||
sys.exit(1)
|
||||
|
||||
from core.connection import BuzzerConnection, BuzzerError
|
||||
|
||||
try:
|
||||
with BuzzerConnection(config) as conn:
|
||||
if not args.no_auto_info:
|
||||
from core.commands import info
|
||||
sys_info = info.execute(conn)
|
||||
|
||||
status = sys_info.get("image_status", "UNKNOWN")
|
||||
status_colors = {
|
||||
"CONFIRMED": "\033[32m",
|
||||
"TESTING": "\033[33m",
|
||||
"PENDING": "\033[36m",
|
||||
}
|
||||
status_color = status_colors.get(status, "\033[37m")
|
||||
|
||||
print(f"Buzzer Firmware: v{sys_info['app_version']} [{status_color}{status}\033[0m] (Protokoll v{sys_info['protocol_version']})")
|
||||
print(f"LittleFS Status: {sys_info['used_kb']:.1f} KB / {sys_info['total_kb']:.1f} KB belegt ({sys_info['percent_used']:.1f}%)")
|
||||
print("-" * 65)
|
||||
|
||||
# 2. Spezifisches Kommando ausführen
|
||||
if args.command == "ls":
|
||||
from core.commands import ls
|
||||
print(f"Inhalt von '{args.path}':\n")
|
||||
tree = ls.get_file_tree(conn, target_path=args.path, recursive=args.recursive)
|
||||
if not tree:
|
||||
print(" (Leer)")
|
||||
else:
|
||||
ls.print_tree(tree, path=args.path )
|
||||
elif args.command == "put":
|
||||
from core.commands import put
|
||||
put.execute(conn, sources=args.sources, target=args.target, recursive=args.recursive)
|
||||
elif args.command == "put_many":
|
||||
from core.commands import put
|
||||
recursive = True if not args.recursive else args.recursive
|
||||
put.execute(conn, sources=args.sources, target=args.target, recursive=recursive)
|
||||
elif args.command == "fw_put":
|
||||
from core.commands import fw_put
|
||||
fw_put.execute(conn, source=args.source)
|
||||
elif args.command == "mkdir":
|
||||
from core.commands import mkdir
|
||||
mkdir.execute(conn, path=args.path)
|
||||
elif args.command == "rm":
|
||||
from core.commands import rm
|
||||
rm.execute(conn, path=args.path, recursive=args.recursive)
|
||||
elif args.command == "stat":
|
||||
from core.commands import stat
|
||||
stat.execute(conn, path=args.path)
|
||||
elif args.command == "mv":
|
||||
from core.commands import mv
|
||||
mv.execute(conn, source=args.source, target=args.target)
|
||||
elif args.command == "pull" or args.command == "get_file":
|
||||
from core.commands import pull
|
||||
pull.execute(conn, source=args.source, target=args.target)
|
||||
elif args.command == "confirm":
|
||||
from core.commands import confirm
|
||||
confirm.execute(conn)
|
||||
elif args.command == "reboot":
|
||||
from core.commands import reboot
|
||||
reboot.execute(conn)
|
||||
elif args.command == "play":
|
||||
from core.commands import play
|
||||
play.execute(conn, path=args.path)
|
||||
elif args.command == "check":
|
||||
from core.commands import check
|
||||
CRC32 = check.execute(conn, path=args.path)
|
||||
if CRC32:
|
||||
size_bytes = CRC32.get("size_bytes")
|
||||
if isinstance(size_bytes, int) and size_bytes >= 0:
|
||||
size_kb = size_bytes / 1024.0
|
||||
print(f"CRC32 von '{args.path}': 0x{CRC32['crc32']:08x} (Größe: {size_bytes} B / {size_kb:.1f} KB)")
|
||||
else:
|
||||
print(f"CRC32 von '{args.path}': 0x{CRC32['crc32']:08x}")
|
||||
else:
|
||||
print(f"Fehler: Keine CRC32-Information für '{args.path}' erhalten.")
|
||||
elif args.command == "get_tags":
|
||||
from core.commands import tags
|
||||
tag_map = tags.get_tags(conn, args.path)
|
||||
print(tag_map)
|
||||
elif args.command == "write_tags":
|
||||
from core.commands import tags
|
||||
updates = tags.parse_tags_json_input(args.json)
|
||||
result = tags.write_tags(conn, args.path, updates)
|
||||
print("Aktuelle Tags:")
|
||||
print(result)
|
||||
elif args.command == "remove_tag":
|
||||
from core.commands import tags
|
||||
result = tags.remove_tag(conn, args.path, args.key)
|
||||
print("Aktuelle Tags:")
|
||||
print(result)
|
||||
elif args.command == "info" or args.command is None:
|
||||
# Wurde kein Befehl oder explizit 'info' angegeben, sind wir hier schon fertig
|
||||
pass
|
||||
|
||||
except TimeoutError as e:
|
||||
print(f"Fehler: {e}")
|
||||
sys.exit(1)
|
||||
except BuzzerError as e:
|
||||
print(f"Buzzer hat die Aktion abgelehnt: {e}")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"Verbindungsfehler auf {config.get('port')}: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +0,0 @@
|
||||
# config.yaml
|
||||
serial:
|
||||
port: "/dev/cu.usbmodem83401"
|
||||
baudrate: 2500000
|
||||
timeout: 1
|
||||
@@ -1,7 +0,0 @@
|
||||
# config.yaml
|
||||
serial:
|
||||
port: "COM17"
|
||||
baudrate: 250000
|
||||
timeout: 20
|
||||
crc_timeout_min_seconds: 2.0
|
||||
crc_timeout_ms_per_100kb: 1.5
|
||||
@@ -1,60 +0,0 @@
|
||||
# core/commands/check.py
|
||||
from core.connection import BuzzerError
|
||||
|
||||
def _split_parent_and_name(path: str) -> tuple[str, str]:
|
||||
normalized = path.rstrip("/")
|
||||
if not normalized or normalized == "/":
|
||||
raise BuzzerError("Für CHECK wird ein Dateipfad benötigt.")
|
||||
|
||||
idx = normalized.rfind("/")
|
||||
if idx <= 0:
|
||||
return "/", normalized
|
||||
|
||||
parent = normalized[:idx]
|
||||
name = normalized[idx + 1:]
|
||||
if not name:
|
||||
raise BuzzerError("Ungültiger Dateipfad für CHECK.")
|
||||
return parent, name
|
||||
|
||||
|
||||
def _lookup_file_size_bytes(conn, path: str) -> int | None:
|
||||
parent, filename = _split_parent_and_name(path)
|
||||
lines = conn.list_directory(parent)
|
||||
|
||||
for line in lines:
|
||||
parts = line.split(",", 2)
|
||||
if len(parts) != 3:
|
||||
continue
|
||||
|
||||
entry_type, entry_size, entry_name = parts
|
||||
if entry_type == "F" and entry_name == filename:
|
||||
try:
|
||||
return int(entry_size)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _estimate_crc_timeout_seconds(conn, size_bytes: int | None) -> float:
|
||||
min_timeout = float(getattr(conn, "crc_timeout_min_seconds", 2.0))
|
||||
ms_per_100kb = float(getattr(conn, "crc_timeout_ms_per_100kb", 1.5))
|
||||
|
||||
base = max(float(conn.timeout), min_timeout)
|
||||
if size_bytes is None or size_bytes <= 0:
|
||||
return base
|
||||
|
||||
blocks_100kb = size_bytes / (100.0 * 1024.0)
|
||||
extra = blocks_100kb * (ms_per_100kb / 1000.0)
|
||||
return base + extra
|
||||
|
||||
def execute(conn, path: str) -> dict:
|
||||
"""Holt die CRC32 nur über Audiodaten und passt Timeout für große Dateien an."""
|
||||
size_bytes = _lookup_file_size_bytes(conn, path)
|
||||
timeout = _estimate_crc_timeout_seconds(conn, size_bytes)
|
||||
crc32 = conn.check_file_crc(path, timeout=timeout)
|
||||
|
||||
return {
|
||||
"crc32": crc32,
|
||||
"size_bytes": size_bytes,
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
# core/commands/confirm.py
|
||||
from core.connection import BuzzerError
|
||||
|
||||
|
||||
def execute(conn):
|
||||
"""Bestätigt die aktuell laufende Firmware per Binary-Protokoll."""
|
||||
try:
|
||||
conn.confirm_firmware()
|
||||
print("✅ Firmware erfolgreich bestätigt.")
|
||||
except BuzzerError as e:
|
||||
print(f"❌ Fehler beim Bestätigen der Firmware: {e}")
|
||||
@@ -1,57 +0,0 @@
|
||||
import os
|
||||
import time
|
||||
import sys
|
||||
|
||||
|
||||
def _estimate_fw_timeout_seconds(conn, total_size: int) -> float:
|
||||
base = float(getattr(conn, "timeout", 5.0))
|
||||
erase_budget = 8.0
|
||||
stream_and_write_budget = total_size / (25.0 * 1024.0)
|
||||
return max(base, erase_budget + stream_and_write_budget)
|
||||
|
||||
|
||||
def execute(conn, source: str):
|
||||
if not os.path.isfile(source):
|
||||
raise FileNotFoundError(f"Firmware-Datei nicht gefunden: {source}")
|
||||
|
||||
with open(source, "rb") as f:
|
||||
data = f.read()
|
||||
|
||||
total_size = len(data)
|
||||
if total_size == 0:
|
||||
raise ValueError("Firmware-Datei ist leer.")
|
||||
|
||||
print(f"Sende 🧩 Firmware ({total_size / 1024:.1f} KB) -> secondary slot")
|
||||
fw_timeout = _estimate_fw_timeout_seconds(conn, total_size)
|
||||
print(f" Timeout fw_put: {fw_timeout:.1f}s")
|
||||
print(" Phase 1/3: Lösche secondary slot und initialisiere Flash...")
|
||||
|
||||
start_time = time.monotonic()
|
||||
last_ui_update = start_time
|
||||
transfer_started = False
|
||||
|
||||
def progress_handler(chunk_len, sent_file, total_file):
|
||||
nonlocal last_ui_update, transfer_started
|
||||
if not transfer_started:
|
||||
transfer_started = True
|
||||
print(" Phase 2/3: Übertrage Firmware...")
|
||||
now = time.monotonic()
|
||||
if now - last_ui_update < 0.2 and sent_file < total_file:
|
||||
return
|
||||
last_ui_update = now
|
||||
|
||||
elapsed = now - start_time
|
||||
speed = (sent_file / 1024.0) / elapsed if elapsed > 0 else 0.0
|
||||
perc = (sent_file / total_file) * 100.0 if total_file > 0 else 100.0
|
||||
eta_sec = ((total_file - sent_file) / (sent_file / elapsed)) if sent_file > 0 and elapsed > 0 else 0.0
|
||||
eta_str = f"{int(eta_sec // 60):02d}:{int(eta_sec % 60):02d}"
|
||||
|
||||
sys.stdout.write(
|
||||
f"\r \033[90mProg: {perc:3.0f}% | {speed:6.1f} KB/s | ETA: {eta_str}\033[0m"
|
||||
)
|
||||
sys.stdout.flush()
|
||||
|
||||
crc32 = conn.fw_put_data(data, timeout=fw_timeout, progress_callback=progress_handler)
|
||||
print("\n Phase 3/3: Finalisiere und warte auf Geräte-ACK...")
|
||||
print(f"\r \033[32mFertig: Firmware übertragen (CRC32: 0x{crc32:08x}).{' ' * 16}\033[0m")
|
||||
print("ℹ️ Nächste Schritte: reboot -> testen -> confirm")
|
||||
@@ -1,37 +0,0 @@
|
||||
# core/commands/info.py
|
||||
from core.connection import BuzzerError
|
||||
|
||||
def execute(conn) -> dict:
|
||||
"""Holt die Systeminformationen und gibt sie als strukturiertes Dictionary zurück."""
|
||||
protocol_version = conn.get_protocol_version()
|
||||
if protocol_version != 1:
|
||||
raise BuzzerError(f"Inkompatibles Protokoll: Gerät nutzt v{protocol_version}, Host erwartet v1.")
|
||||
|
||||
status_code, app_version = conn.get_firmware_status()
|
||||
flash = conn.get_flash_status()
|
||||
|
||||
f_frsize = flash["block_size"]
|
||||
f_blocks = flash["total_blocks"]
|
||||
f_bfree = flash["free_blocks"]
|
||||
|
||||
status_map = {
|
||||
1: "CONFIRMED",
|
||||
2: "TESTING",
|
||||
3: "PENDING",
|
||||
}
|
||||
image_status = status_map.get(status_code, f"UNKNOWN({status_code})")
|
||||
|
||||
total_kb = (f_blocks * f_frsize) / 1024
|
||||
free_kb = (f_bfree * f_frsize) / 1024
|
||||
used_kb = total_kb - free_kb
|
||||
percent_used = (used_kb / total_kb) * 100 if total_kb > 0 else 0
|
||||
|
||||
return {
|
||||
"protocol_version": protocol_version,
|
||||
"app_version": app_version,
|
||||
"total_kb": total_kb,
|
||||
"free_kb": free_kb,
|
||||
"used_kb": used_kb,
|
||||
"percent_used": percent_used,
|
||||
"image_status": image_status
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
# core/commands/ls.py
|
||||
from core.connection import BuzzerError
|
||||
|
||||
def get_file_tree(conn, target_path="/", recursive=False) -> list:
|
||||
"""
|
||||
Liest das Dateisystem aus und gibt eine hierarchische Baumstruktur zurück.
|
||||
"""
|
||||
if not target_path.endswith('/'):
|
||||
target_path += '/'
|
||||
|
||||
cmd_path = target_path.rstrip('/') if target_path != '/' else '/'
|
||||
|
||||
try:
|
||||
lines = conn.list_directory(cmd_path)
|
||||
except BuzzerError as e:
|
||||
return [{"type": "E", "name": f"Fehler beim Lesen: {e}", "path": target_path}]
|
||||
|
||||
nodes = []
|
||||
if not lines:
|
||||
return nodes
|
||||
|
||||
for line in lines:
|
||||
parts = line.split(',', 2)
|
||||
if len(parts) != 3:
|
||||
continue
|
||||
|
||||
entry_type, entry_size, entry_name = parts
|
||||
node = {
|
||||
"type": entry_type,
|
||||
"name": entry_name,
|
||||
"path": f"{target_path}{entry_name}"
|
||||
}
|
||||
|
||||
if entry_type == 'D':
|
||||
if recursive:
|
||||
# Rekursiver Aufruf auf dem Host für Unterverzeichnisse
|
||||
node["children"] = get_file_tree(conn, f"{target_path}{entry_name}/", recursive=True)
|
||||
else:
|
||||
node["children"] = []
|
||||
elif entry_type == 'F':
|
||||
node["size"] = int(entry_size)
|
||||
|
||||
nodes.append(node)
|
||||
|
||||
return nodes
|
||||
|
||||
def print_tree(nodes, prefix="", path=""):
|
||||
"""
|
||||
Gibt die Baumstruktur optisch formatiert auf der Konsole aus.
|
||||
"""
|
||||
if path:
|
||||
if path == "/":
|
||||
display_path = "💾 "+"/ (Root)"
|
||||
else:
|
||||
display_path = "📁 " + path
|
||||
print(f"{prefix}{display_path}")
|
||||
for i, node in enumerate(nodes):
|
||||
is_last = (i == len(nodes) - 1)
|
||||
connector = " └─" if is_last else " ├─"
|
||||
|
||||
if node["type"] == 'D':
|
||||
print(f"{prefix}{connector}📁 {node['name']}")
|
||||
extension = " " if is_last else " │ "
|
||||
if "children" in node and node["children"]:
|
||||
print_tree(node["children"], prefix + extension)
|
||||
elif node["type"] == 'F':
|
||||
size_kb = node["size"] / 1024
|
||||
# \033[90m macht den Text dunkelgrau, \033[0m setzt die Farbe zurück
|
||||
print(f"{prefix}{connector}📄 {node['name']} \033[90m({size_kb:.1f} KB)\033[0m")
|
||||
elif node["type"] == 'E':
|
||||
print(f"{prefix}{connector}❌ \033[31m{node['name']}\033[0m")
|
||||
|
||||
def get_flat_file_list(nodes) -> list:
|
||||
"""
|
||||
Wandelt die Baumstruktur in eine flache Liste von Dateipfaden um.
|
||||
Wird von 'rm -r' benötigt, um nacheinander alle Dateien zu löschen.
|
||||
"""
|
||||
flat_list = []
|
||||
for node in nodes:
|
||||
if node["type"] == 'F':
|
||||
flat_list.append(node)
|
||||
elif node["type"] == 'D' and "children" in node:
|
||||
flat_list.extend(get_flat_file_list(node["children"]))
|
||||
return flat_list
|
||||
@@ -1,10 +0,0 @@
|
||||
# core/commands/mkdir.py
|
||||
from core.connection import BuzzerError
|
||||
|
||||
def execute(conn, path: str):
|
||||
"""Erstellt ein Verzeichnis auf dem Controller."""
|
||||
try:
|
||||
conn.mkdir(path)
|
||||
print(f"📁 Verzeichnis '{path}' erfolgreich erstellt.")
|
||||
except BuzzerError as e:
|
||||
print(f"❌ Fehler beim Erstellen von '{path}': {e}")
|
||||
@@ -1,10 +0,0 @@
|
||||
from core.connection import BuzzerError
|
||||
|
||||
|
||||
def execute(conn, source: str, target: str):
|
||||
try:
|
||||
conn.rename(source, target)
|
||||
print(f"✅ Umbenannt/Verschoben: '{source}' -> '{target}'")
|
||||
except BuzzerError as e:
|
||||
print(f"❌ Fehler beim Umbenennen/Verschieben: {e}")
|
||||
raise
|
||||
@@ -1,10 +0,0 @@
|
||||
# core/commands/mkdir.py
|
||||
from core.connection import BuzzerError
|
||||
|
||||
def execute(conn, path: str):
|
||||
"""Spielt eine Datei auf dem Controller ab."""
|
||||
try:
|
||||
conn.send_command(f"play {path}")
|
||||
print(f"▶️ Datei '{path}' wird abgespielt.")
|
||||
except BuzzerError as e:
|
||||
print(f"❌ Fehler beim Abspielen von '{path}': {e}")
|
||||
@@ -1,62 +0,0 @@
|
||||
import os
|
||||
import posixpath
|
||||
import time
|
||||
|
||||
|
||||
def _resolve_local_target(remote_path: str, target: str | None) -> str:
|
||||
if target:
|
||||
return target
|
||||
|
||||
basename = posixpath.basename(remote_path.rstrip("/"))
|
||||
if not basename:
|
||||
raise ValueError("Kann keinen lokalen Dateinamen aus dem Remote-Pfad ableiten. Bitte Zielpfad angeben.")
|
||||
return basename
|
||||
|
||||
|
||||
def execute(conn, source: str, target: str | None = None):
|
||||
local_path = _resolve_local_target(source, target)
|
||||
|
||||
os.makedirs(os.path.dirname(local_path) or ".", exist_ok=True)
|
||||
|
||||
last_print = 0.0
|
||||
start_time = time.monotonic()
|
||||
|
||||
def _progress(_chunk_len: int, received: int, expected: int | None):
|
||||
nonlocal last_print
|
||||
now = time.monotonic()
|
||||
if now - last_print < 0.2:
|
||||
return
|
||||
last_print = now
|
||||
|
||||
elapsed = max(now - start_time, 1e-6)
|
||||
speed_kb_s = (received / 1024.0) / elapsed
|
||||
|
||||
if expected is not None and expected > 0:
|
||||
percent = (received * 100.0) / expected
|
||||
remaining = max(expected - received, 0)
|
||||
eta_sec = (remaining / 1024.0) / speed_kb_s if speed_kb_s > 0 else 0.0
|
||||
eta_str = f"{int(eta_sec // 60):02d}:{int(eta_sec % 60):02d}"
|
||||
print(
|
||||
f"\r⬇️ {received}/{expected} B ({percent:5.1f}%) | {speed_kb_s:6.1f} KB/s | ETA {eta_str}",
|
||||
end="",
|
||||
flush=True,
|
||||
)
|
||||
else:
|
||||
print(f"\r⬇️ {received} B | {speed_kb_s:6.1f} KB/s", end="", flush=True)
|
||||
|
||||
data = conn.get_file_data(source, progress_callback=_progress)
|
||||
|
||||
if len(data) > 0:
|
||||
print()
|
||||
|
||||
with open(local_path, "wb") as f:
|
||||
f.write(data)
|
||||
|
||||
total_duration = max(time.monotonic() - start_time, 1e-6)
|
||||
avg_speed_kb_s = (len(data) / 1024.0) / total_duration
|
||||
print(f"✅ Heruntergeladen: '{source}' -> '{local_path}' ({len(data)} B, {avg_speed_kb_s:.1f} KB/s)")
|
||||
return {
|
||||
"source": source,
|
||||
"target": local_path,
|
||||
"size": len(data),
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
from core.connection import BuzzerError
|
||||
|
||||
TAG_MAGIC = b"TAG!"
|
||||
TAG_FOOTER_LEN = 7
|
||||
TAG_VERSION_V1 = 0x01
|
||||
TAG_TYPE_CRC32 = 0x10
|
||||
|
||||
|
||||
def _split_audio_and_tag_blob(filepath: str) -> tuple[bytes, bytes | None]:
|
||||
with open(filepath, "rb") as f:
|
||||
data = f.read()
|
||||
|
||||
if len(data) < TAG_FOOTER_LEN:
|
||||
return data, None
|
||||
|
||||
if data[-4:] != TAG_MAGIC:
|
||||
return data, None
|
||||
|
||||
tag_total_len = int.from_bytes(data[-6:-4], byteorder="little", signed=False)
|
||||
tag_version = data[-7]
|
||||
if tag_version != TAG_VERSION_V1:
|
||||
return data, None
|
||||
|
||||
if tag_total_len < TAG_FOOTER_LEN or tag_total_len > len(data):
|
||||
return data, None
|
||||
|
||||
audio_end = len(data) - tag_total_len
|
||||
tag_payload_len = tag_total_len - TAG_FOOTER_LEN
|
||||
tag_payload = data[audio_end:audio_end + tag_payload_len]
|
||||
audio_data = data[:audio_end]
|
||||
return audio_data, tag_payload
|
||||
|
||||
|
||||
def _upsert_crc32_tag(tag_blob: bytes | None, crc32: int) -> tuple[bytes, bool]:
|
||||
crc_payload = int(crc32).to_bytes(4, byteorder="little", signed=False)
|
||||
crc_tlv = bytes([TAG_TYPE_CRC32, 0x04, 0x00]) + crc_payload
|
||||
|
||||
if not tag_blob:
|
||||
return crc_tlv, True
|
||||
|
||||
pos = 0
|
||||
out = bytearray()
|
||||
found_crc = False
|
||||
|
||||
while pos < len(tag_blob):
|
||||
if pos + 3 > len(tag_blob):
|
||||
return crc_tlv, True
|
||||
|
||||
tag_type = tag_blob[pos]
|
||||
tag_len = tag_blob[pos + 1] | (tag_blob[pos + 2] << 8)
|
||||
header = tag_blob[pos:pos + 3]
|
||||
pos += 3
|
||||
|
||||
if pos + tag_len > len(tag_blob):
|
||||
return crc_tlv, True
|
||||
|
||||
value = tag_blob[pos:pos + tag_len]
|
||||
pos += tag_len
|
||||
|
||||
if tag_type == TAG_TYPE_CRC32:
|
||||
if not found_crc:
|
||||
out.extend(crc_tlv)
|
||||
found_crc = True
|
||||
continue
|
||||
|
||||
out.extend(header)
|
||||
out.extend(value)
|
||||
|
||||
if not found_crc:
|
||||
out.extend(crc_tlv)
|
||||
|
||||
return bytes(out), True
|
||||
|
||||
|
||||
def _collect_source_files(sources: list[str], recursive: bool) -> list[dict]:
|
||||
entries = []
|
||||
|
||||
for source in sources:
|
||||
matches = glob.glob(source)
|
||||
if not matches:
|
||||
print(f"⚠️ Keine Treffer für Quelle: {source}")
|
||||
continue
|
||||
|
||||
for match in matches:
|
||||
if os.path.isfile(match):
|
||||
entries.append({"local": match, "relative": os.path.basename(match)})
|
||||
continue
|
||||
|
||||
if os.path.isdir(match):
|
||||
if recursive:
|
||||
for root, _, files in os.walk(match):
|
||||
for name in sorted(files):
|
||||
local_path = os.path.join(root, name)
|
||||
rel = os.path.relpath(local_path, match)
|
||||
entries.append({"local": local_path, "relative": rel.replace("\\", "/")})
|
||||
else:
|
||||
for name in sorted(os.listdir(match)):
|
||||
local_path = os.path.join(match, name)
|
||||
if os.path.isfile(local_path):
|
||||
entries.append({"local": local_path, "relative": name})
|
||||
|
||||
return entries
|
||||
|
||||
|
||||
def _remote_parent(path: str) -> str:
|
||||
idx = path.rfind("/")
|
||||
if idx <= 0:
|
||||
return "/"
|
||||
return path[:idx]
|
||||
|
||||
|
||||
def _ensure_remote_dir(conn, remote_dir: str) -> None:
|
||||
if not remote_dir or remote_dir == "/":
|
||||
return
|
||||
|
||||
current = ""
|
||||
for part in [p for p in remote_dir.split("/") if p]:
|
||||
current = f"{current}/{part}"
|
||||
try:
|
||||
conn.mkdir(current)
|
||||
except BuzzerError as e:
|
||||
msg = str(e)
|
||||
if "0x11" in msg or "existiert bereits" in msg:
|
||||
continue
|
||||
raise
|
||||
|
||||
|
||||
def _build_upload_plan(entries: list[dict], target: str) -> list[dict]:
|
||||
if not entries:
|
||||
return []
|
||||
|
||||
needs_dir_semantics = target.endswith("/") or len(entries) > 1 or any("/" in e["relative"] for e in entries)
|
||||
if not needs_dir_semantics:
|
||||
return [{"local": entries[0]["local"], "remote": target}]
|
||||
|
||||
base = target.rstrip("/")
|
||||
if not base:
|
||||
base = "/"
|
||||
|
||||
plan = []
|
||||
for entry in entries:
|
||||
rel = entry["relative"].lstrip("/")
|
||||
if base == "/":
|
||||
remote = f"/{rel}"
|
||||
else:
|
||||
remote = f"{base}/{rel}"
|
||||
plan.append({"local": entry["local"], "remote": remote})
|
||||
|
||||
return plan
|
||||
|
||||
|
||||
def execute(conn, sources: list[str], target: str, recursive: bool = False):
|
||||
uploads = _build_upload_plan(_collect_source_files(sources, recursive=recursive), target)
|
||||
if not uploads:
|
||||
print("Keine gültigen Dateien gefunden.")
|
||||
return
|
||||
|
||||
total_size_all = sum(os.path.getsize(item["local"]) for item in uploads)
|
||||
sent_all = 0
|
||||
start_time_all = time.monotonic()
|
||||
last_ui_update = start_time_all
|
||||
|
||||
for item in uploads:
|
||||
local_path = item["local"]
|
||||
remote_path = item["remote"]
|
||||
filename = os.path.basename(local_path)
|
||||
|
||||
audio_data, tag_blob = _split_audio_and_tag_blob(local_path)
|
||||
audio_size = len(audio_data)
|
||||
|
||||
_ensure_remote_dir(conn, _remote_parent(remote_path))
|
||||
|
||||
print(f"Sende 📄 {filename} ({audio_size / 1024:.1f} KB Audio) -> {remote_path}")
|
||||
start_time_file = time.monotonic()
|
||||
|
||||
def progress_handler(chunk_len, sent_file, total_file):
|
||||
nonlocal sent_all, last_ui_update
|
||||
sent_all += chunk_len
|
||||
|
||||
now = time.monotonic()
|
||||
if now - last_ui_update < 0.2 and sent_file < total_file:
|
||||
return
|
||||
last_ui_update = now
|
||||
|
||||
elapsed = now - start_time_file
|
||||
speed = (sent_file / 1024.0) / elapsed if elapsed > 0 else 0.0
|
||||
perc_file = (sent_file / total_file) * 100.0 if total_file > 0 else 100.0
|
||||
perc_all = (sent_all / total_size_all) * 100.0 if total_size_all > 0 else 100.0
|
||||
|
||||
elapsed_all = now - start_time_all
|
||||
avg_speed_all = sent_all / elapsed_all if elapsed_all > 0 else 0.0
|
||||
eta_sec = (total_size_all - sent_all) / avg_speed_all if avg_speed_all > 0 else 0.0
|
||||
eta_str = f"{int(eta_sec // 60):02d}:{int(eta_sec % 60):02d}"
|
||||
|
||||
sys.stdout.write(
|
||||
f"\r \033[90mProg: {perc_file:3.0f}% | Gesamt: {perc_all:3.0f}% | "
|
||||
f"{speed:6.1f} KB/s | ETA: {eta_str}\033[0m"
|
||||
)
|
||||
sys.stdout.flush()
|
||||
|
||||
try:
|
||||
audio_crc32 = conn.put_file_data(remote_path, audio_data, progress_callback=progress_handler)
|
||||
|
||||
rewritten_blob, _ = _upsert_crc32_tag(tag_blob, audio_crc32)
|
||||
conn.set_tag_blob(remote_path, rewritten_blob)
|
||||
tag_note = " (CRC32-Tag gesetzt)"
|
||||
|
||||
print(f"\r \033[32mFertig: {filename} übertragen{tag_note}.{' ' * 20}\033[0m")
|
||||
except Exception as e:
|
||||
print(f"\n ❌ \033[31mFehler: {e}\033[0m")
|
||||
|
||||
total_duration = time.monotonic() - start_time_all
|
||||
total_kb = total_size_all / 1024.0
|
||||
avg_speed = total_kb / total_duration if total_duration > 0 else 0.0
|
||||
print(f"\nÜbertragung abgeschlossen: {total_kb:.1f} KB in {total_duration:.1f}s ({avg_speed:.1f} KB/s)")
|
||||
@@ -1,11 +0,0 @@
|
||||
# core/commands/reboot.py
|
||||
from core.connection import BuzzerError
|
||||
|
||||
|
||||
def execute(conn):
|
||||
"""Startet den Buzzer per Binary-Protokoll neu."""
|
||||
try:
|
||||
conn.reboot_device()
|
||||
print("🔄 Buzzer wird neu gestartet.")
|
||||
except BuzzerError as e:
|
||||
print(f"❌ Fehler beim Neustarten des Buzzers: {e}")
|
||||
@@ -1,68 +0,0 @@
|
||||
# core/commands/rm.py
|
||||
import fnmatch
|
||||
import posixpath
|
||||
from core.connection import BuzzerError
|
||||
from core.commands.ls import get_file_tree
|
||||
|
||||
def _delete_recursive(conn, nodes):
|
||||
"""Löscht Knoten Bottom-Up (erst Dateien/Unterordner, dann den Ordner selbst)"""
|
||||
for node in nodes:
|
||||
if node["type"] == 'D':
|
||||
if "children" in node and node["children"]:
|
||||
_delete_recursive(conn, node["children"])
|
||||
_try_rm(conn, node["path"], is_dir=True)
|
||||
elif node["type"] == 'F':
|
||||
_try_rm(conn, node["path"], is_dir=False)
|
||||
|
||||
def _try_rm(conn, path, is_dir=False):
|
||||
icon = "📁" if is_dir else "📄"
|
||||
try:
|
||||
conn.rm(path)
|
||||
print(f" 🗑️ {icon} Gelöscht: {path}")
|
||||
except BuzzerError as e:
|
||||
print(f" ❌ Fehler bei {path}: {e}")
|
||||
|
||||
def execute(conn, path: str, recursive: bool = False):
|
||||
"""Löscht eine Datei, ein Verzeichnis oder löst Wildcards (*) auf."""
|
||||
|
||||
# 1. Wildcard-Behandlung (z.B. /lfs/a/* oder *.wav)
|
||||
if '*' in path or '?' in path:
|
||||
dirname, pattern = posixpath.split(path)
|
||||
if not dirname:
|
||||
dirname = "/"
|
||||
|
||||
print(f"Suche nach Dateien passend zu '{pattern}' in '{dirname}'...")
|
||||
tree = get_file_tree(conn, target_path=dirname, recursive=False)
|
||||
|
||||
# Fehler beim Verzeichnis-Lesen abfangen
|
||||
if len(tree) == 1 and tree[0].get("type") == "E":
|
||||
print(f"❌ Verzeichnis '{dirname}' nicht gefunden.")
|
||||
return
|
||||
|
||||
# Filtern mit fnmatch (funktioniert wie in der Linux-Shell)
|
||||
matches = [node for node in tree if node.get("type") == "F" and fnmatch.fnmatch(node["name"], pattern)]
|
||||
|
||||
if not matches:
|
||||
print(f"Keine passenden Dateien für '{path}' gefunden.")
|
||||
return
|
||||
|
||||
for match in matches:
|
||||
_try_rm(conn, match["path"], is_dir=False)
|
||||
|
||||
return # Fertig mit Wildcard-Löschen
|
||||
|
||||
# 2. Rekursives Löschen (-r)
|
||||
if recursive:
|
||||
try:
|
||||
conn.rm_recursive(path)
|
||||
print(f"🗑️ '{path}' rekursiv gelöscht.")
|
||||
except BuzzerError as e:
|
||||
print(f"❌ Fehler beim rekursiven Löschen von '{path}': {e}")
|
||||
return
|
||||
|
||||
# 3. Standard-Löschen (Einzeldatei oder leeres Verzeichnis)
|
||||
try:
|
||||
conn.rm(path)
|
||||
print(f"🗑️ '{path}' erfolgreich gelöscht.")
|
||||
except BuzzerError as e:
|
||||
print(f"❌ Fehler beim Löschen von '{path}': {e}")
|
||||
@@ -1,5 +0,0 @@
|
||||
def execute(conn, path: str):
|
||||
info = conn.stat(path)
|
||||
entry_type = "Ordner" if info["type"] == "D" else "Datei"
|
||||
print(f"{path}: {entry_type}, Größe: {info['size']} B")
|
||||
return info
|
||||
@@ -1,140 +0,0 @@
|
||||
import json
|
||||
from core.connection import BuzzerError
|
||||
|
||||
TAG_TYPE_TO_KEY = {
|
||||
0x00: "description",
|
||||
0x01: "author",
|
||||
0x10: "crc32",
|
||||
0x20: "fileformat",
|
||||
}
|
||||
|
||||
KEY_TO_TAG_TYPE = {v: k for k, v in TAG_TYPE_TO_KEY.items()}
|
||||
VALID_TAG_KEYS = frozenset(KEY_TO_TAG_TYPE.keys())
|
||||
|
||||
def _u16le(value: int) -> bytes:
|
||||
return bytes((value & 0xFF, (value >> 8) & 0xFF))
|
||||
|
||||
|
||||
def _parse_tlv(blob: bytes) -> dict:
|
||||
tags = {}
|
||||
pos = 0
|
||||
|
||||
while pos < len(blob):
|
||||
if pos + 3 > len(blob):
|
||||
raise BuzzerError("Ungültiger Tag-Blob: TLV-Header abgeschnitten")
|
||||
|
||||
tag_type = blob[pos]
|
||||
tag_len = blob[pos + 1] | (blob[pos + 2] << 8)
|
||||
pos += 3
|
||||
|
||||
if pos + tag_len > len(blob):
|
||||
raise BuzzerError("Ungültiger Tag-Blob: TLV-Wert abgeschnitten")
|
||||
|
||||
value = blob[pos:pos + tag_len]
|
||||
pos += tag_len
|
||||
|
||||
key = TAG_TYPE_TO_KEY.get(tag_type, f"unknown_0x{tag_type:02x}")
|
||||
|
||||
if tag_type in (0x00, 0x01):
|
||||
tags[key] = value.decode("utf-8", errors="replace")
|
||||
elif tag_type == 0x10:
|
||||
if tag_len != 4:
|
||||
raise BuzzerError("Ungültiger crc32-Tag: len muss 4 sein")
|
||||
crc32 = int.from_bytes(value, byteorder="little", signed=False)
|
||||
tags[key] = f"0x{crc32:08x}"
|
||||
elif tag_type == 0x20:
|
||||
if tag_len != 5:
|
||||
raise BuzzerError("Ungültiger fileformat-Tag: len muss 5 sein")
|
||||
bits = value[0]
|
||||
samplerate = int.from_bytes(value[1:5], byteorder="little", signed=False)
|
||||
tags[key] = {"bits_per_sample": bits, "sample_rate": samplerate}
|
||||
else:
|
||||
tags[key] = value.hex()
|
||||
|
||||
return tags
|
||||
|
||||
|
||||
def _build_tlv(tags: dict) -> bytes:
|
||||
entries = []
|
||||
|
||||
if "description" in tags and tags["description"] is not None:
|
||||
data = str(tags["description"]).encode("utf-8")
|
||||
entries.append(bytes([KEY_TO_TAG_TYPE["description"]]) + _u16le(len(data)) + data)
|
||||
|
||||
if "author" in tags and tags["author"] is not None:
|
||||
data = str(tags["author"]).encode("utf-8")
|
||||
entries.append(bytes([KEY_TO_TAG_TYPE["author"]]) + _u16le(len(data)) + data)
|
||||
|
||||
if "crc32" in tags and tags["crc32"] is not None:
|
||||
crc_val = tags["crc32"]
|
||||
if isinstance(crc_val, str):
|
||||
crc_val = int(crc_val, 16) if crc_val.lower().startswith("0x") else int(crc_val)
|
||||
data = int(crc_val).to_bytes(4, byteorder="little", signed=False)
|
||||
entries.append(bytes([KEY_TO_TAG_TYPE["crc32"]]) + _u16le(4) + data)
|
||||
|
||||
if "fileformat" in tags and tags["fileformat"] is not None:
|
||||
ff = tags["fileformat"]
|
||||
if not isinstance(ff, dict):
|
||||
raise BuzzerError("fileformat muss ein Objekt sein: {bits_per_sample, sample_rate}")
|
||||
bits = int(ff.get("bits_per_sample", 16))
|
||||
samplerate = int(ff.get("sample_rate", 16000))
|
||||
data = bytes([bits]) + samplerate.to_bytes(4, byteorder="little", signed=False)
|
||||
entries.append(bytes([KEY_TO_TAG_TYPE["fileformat"]]) + _u16le(5) + data)
|
||||
|
||||
return b"".join(entries)
|
||||
|
||||
|
||||
def get_tags(conn, path: str) -> dict:
|
||||
blob = conn.get_tag_blob(path)
|
||||
if not blob:
|
||||
return {}
|
||||
return _parse_tlv(blob)
|
||||
|
||||
|
||||
def write_tags(conn, path: str, tags_update: dict) -> dict:
|
||||
unknown_keys = [k for k in tags_update.keys() if k not in VALID_TAG_KEYS]
|
||||
if unknown_keys:
|
||||
unknown_str = ", ".join(sorted(str(k) for k in unknown_keys))
|
||||
valid_str = ", ".join(sorted(VALID_TAG_KEYS))
|
||||
raise BuzzerError(
|
||||
f"Unbekannter Tag-Key in write_tags: {unknown_str}. Erlaubte Keys: {valid_str}"
|
||||
)
|
||||
|
||||
current = get_tags(conn, path)
|
||||
merged = dict(current)
|
||||
|
||||
for key, value in tags_update.items():
|
||||
if value is None:
|
||||
merged.pop(key, None)
|
||||
else:
|
||||
merged[key] = value
|
||||
|
||||
blob = _build_tlv(merged)
|
||||
conn.set_tag_blob(path, blob)
|
||||
return merged
|
||||
|
||||
|
||||
def remove_tag(conn, path: str, key: str) -> dict:
|
||||
current = get_tags(conn, path)
|
||||
current.pop(key, None)
|
||||
blob = _build_tlv(current)
|
||||
conn.set_tag_blob(path, blob)
|
||||
return current
|
||||
|
||||
|
||||
def parse_tags_json_input(raw: str) -> dict:
|
||||
text = raw.strip()
|
||||
if text.startswith("@"):
|
||||
file_path = text[1:]
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
text = f.read()
|
||||
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except json.JSONDecodeError as e:
|
||||
raise BuzzerError(f"Ungültiges JSON für write_tags: {e}")
|
||||
|
||||
if not isinstance(data, dict):
|
||||
raise BuzzerError("write_tags erwartet ein JSON-Objekt.")
|
||||
|
||||
return data
|
||||
@@ -1,48 +0,0 @@
|
||||
# core/config.py
|
||||
import os
|
||||
import sys
|
||||
import yaml
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
"port": None,
|
||||
"baudrate": 115200,
|
||||
"timeout": 5.0,
|
||||
"crc_timeout_min_seconds": 2.0,
|
||||
"crc_timeout_ms_per_100kb": 1.5,
|
||||
}
|
||||
|
||||
def load_config(cli_args=None):
|
||||
config = DEFAULT_CONFIG.copy()
|
||||
|
||||
cwd_config = os.path.join(os.getcwd(), "config.yaml")
|
||||
script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
|
||||
script_config = os.path.join(script_dir, "config.yaml")
|
||||
|
||||
yaml_path = cwd_config if os.path.exists(cwd_config) else script_config if os.path.exists(script_config) else None
|
||||
|
||||
if yaml_path:
|
||||
try:
|
||||
with open(yaml_path, "r", encoding="utf-8") as f:
|
||||
yaml_data = yaml.safe_load(f)
|
||||
if yaml_data and "serial" in yaml_data:
|
||||
config["port"] = yaml_data["serial"].get("port", config["port"])
|
||||
config["baudrate"] = yaml_data["serial"].get("baudrate", config["baudrate"])
|
||||
config["timeout"] = yaml_data["serial"].get("timeout", config["timeout"])
|
||||
config["crc_timeout_min_seconds"] = yaml_data["serial"].get(
|
||||
"crc_timeout_min_seconds", config["crc_timeout_min_seconds"]
|
||||
)
|
||||
config["crc_timeout_ms_per_100kb"] = yaml_data["serial"].get(
|
||||
"crc_timeout_ms_per_100kb", config["crc_timeout_ms_per_100kb"]
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Fehler beim Laden der Konfigurationsdatei {yaml_path}: {e}")
|
||||
|
||||
if cli_args:
|
||||
if getattr(cli_args, "port", None) is not None:
|
||||
config["port"] = cli_args.port
|
||||
if getattr(cli_args, "baudrate", None) is not None:
|
||||
config["baudrate"] = cli_args.baudrate
|
||||
if getattr(cli_args, "timeout", None) is not None:
|
||||
config["timeout"] = cli_args.timeout
|
||||
|
||||
return config
|
||||
@@ -1,866 +0,0 @@
|
||||
# core/connection.py
|
||||
import time
|
||||
import os
|
||||
import struct
|
||||
import binascii
|
||||
|
||||
PROTOCOL_ERROR_MESSAGES = {
|
||||
0x01: "Ungültiger Befehl.",
|
||||
0x02: "Ungültige Parameter.",
|
||||
0x03: "Befehl oder Parameter sind zu lang.",
|
||||
0x10: "Datei oder Verzeichnis wurde nicht gefunden.",
|
||||
0x11: "Ziel existiert bereits.",
|
||||
0x12: "Pfad ist kein Verzeichnis.",
|
||||
0x13: "Pfad ist ein Verzeichnis.",
|
||||
0x14: "Zugriff verweigert.",
|
||||
0x15: "Kein freier Speicher mehr vorhanden.",
|
||||
0x16: "Datei ist zu groß.",
|
||||
0x20: "Allgemeiner Ein-/Ausgabefehler auf dem Gerät.",
|
||||
0x21: "Zeitüberschreitung auf dem Gerät.",
|
||||
0x22: "CRC-Prüfung fehlgeschlagen (Daten beschädigt).",
|
||||
0x23: "Übertragung wurde vom Gerät abgebrochen.",
|
||||
0x30: "Befehl wird vom Gerät nicht unterstützt.",
|
||||
0x31: "Gerät ist beschäftigt.",
|
||||
0x32: "Interner Gerätefehler.",
|
||||
}
|
||||
|
||||
SYNC = b"BUZZ"
|
||||
HEADER_SIZE = 14
|
||||
DEFAULT_MAX_PATH_LEN = 32
|
||||
FRAME_REQ = 0x01
|
||||
FRAME_RESP_ACK = 0x10
|
||||
FRAME_RESP_DATA = 0x11
|
||||
FRAME_RESP_STREAM_START = 0x12
|
||||
FRAME_RESP_STREAM_CHUNK = 0x13
|
||||
FRAME_RESP_STREAM_END = 0x14
|
||||
FRAME_RESP_ERROR = 0x7F
|
||||
POLL_SLEEP_SECONDS = 0.002
|
||||
|
||||
CMD_GET_PROTOCOL_VERSION = 0x00
|
||||
CMD_GET_FIRMWARE_STATUS = 0x01
|
||||
CMD_GET_FLASH_STATUS = 0x02
|
||||
CMD_CONFIRM_FIRMWARE = 0x03
|
||||
CMD_REBOOT = 0x04
|
||||
CMD_LIST_DIR = 0x10
|
||||
CMD_CHECK_FILE_CRC = 0x11
|
||||
CMD_MKDIR = 0x12
|
||||
CMD_RM = 0x13
|
||||
CMD_PUT_FILE_START = 0x14
|
||||
CMD_PUT_FILE_CHUNK = 0x15
|
||||
CMD_PUT_FILE_END = 0x16
|
||||
CMD_PUT_FW_START = 0x17
|
||||
CMD_STAT = 0x18
|
||||
CMD_RENAME = 0x19
|
||||
CMD_RM_R = 0x1A
|
||||
CMD_GET_FILE = 0x1B
|
||||
CMD_GET_TAG_BLOB = 0x20
|
||||
CMD_SET_TAG_BLOB_START = 0x21
|
||||
CMD_SET_TAG_BLOB_CHUNK = 0x22
|
||||
CMD_SET_TAG_BLOB_END = 0x23
|
||||
|
||||
class BuzzerError(Exception):
|
||||
pass
|
||||
|
||||
class BuzzerConnection:
|
||||
def __init__(self, config):
|
||||
self.port = config.get("port")
|
||||
self.baudrate = config.get("baudrate", 115200)
|
||||
self.timeout = config.get("timeout", 5.0)
|
||||
self.crc_timeout_min_seconds = float(config.get("crc_timeout_min_seconds", 2.0))
|
||||
self.crc_timeout_ms_per_100kb = float(config.get("crc_timeout_ms_per_100kb", 1.5))
|
||||
self.serial = None
|
||||
self._sequence = 0
|
||||
self._max_path_len = DEFAULT_MAX_PATH_LEN
|
||||
|
||||
def __enter__(self):
|
||||
if not self.port:
|
||||
raise ValueError("Kein serieller Port konfiguriert.")
|
||||
|
||||
try:
|
||||
import serial
|
||||
except ImportError as e:
|
||||
raise BuzzerError("PySerial ist nicht installiert. Bitte 'pip install -r requirements.txt' ausführen.") from e
|
||||
|
||||
# write_timeout verhindert endloses Blockieren auf inaktiven Ports
|
||||
self.serial = serial.Serial(
|
||||
port=self.port,
|
||||
baudrate=self.baudrate,
|
||||
timeout=self.timeout,
|
||||
write_timeout=self.timeout
|
||||
)
|
||||
self.serial.reset_input_buffer()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
if self.serial and self.serial.is_open:
|
||||
self.serial.close()
|
||||
|
||||
def _parse_controller_error(self, line: str) -> str:
|
||||
code_str = line.split(" ", 1)[1].strip() if " " in line else ""
|
||||
try:
|
||||
code = int(code_str, 10)
|
||||
except ValueError:
|
||||
return f"Controller meldet einen unbekannten Fehler: '{line}'"
|
||||
|
||||
message = PROTOCOL_ERROR_MESSAGES.get(code, "Unbekannter Fehlercode vom Gerät.")
|
||||
return f"Controller-Fehler {code} (0x{code:02X}): {message}"
|
||||
|
||||
def _parse_controller_error_code(self, code: int) -> str:
|
||||
message = PROTOCOL_ERROR_MESSAGES.get(code, "Unbekannter Fehlercode vom Gerät.")
|
||||
return f"Controller-Fehler {code} (0x{code:02X}): {message}"
|
||||
|
||||
def _raise_error_from_payload(self, payload: bytes) -> None:
|
||||
error_code = payload[0] if len(payload) >= 1 else 0x32
|
||||
detail = ""
|
||||
if len(payload) >= 2:
|
||||
detail_len = payload[1]
|
||||
if detail_len > 0 and len(payload) >= 2 + detail_len:
|
||||
detail = payload[2:2 + detail_len].decode("utf-8", errors="replace")
|
||||
|
||||
msg = self._parse_controller_error_code(error_code)
|
||||
if detail:
|
||||
msg = f"{msg} Detail: {detail}"
|
||||
raise BuzzerError(msg)
|
||||
|
||||
def _next_sequence(self) -> int:
|
||||
seq = self._sequence
|
||||
self._sequence = (self._sequence + 1) & 0xFFFF
|
||||
return seq
|
||||
|
||||
def _crc16_ccitt_false(self, data: bytes) -> int:
|
||||
crc = 0xFFFF
|
||||
for b in data:
|
||||
crc ^= b
|
||||
for _ in range(8):
|
||||
if crc & 0x0001:
|
||||
crc = ((crc >> 1) ^ 0x8408) & 0xFFFF
|
||||
else:
|
||||
crc = (crc >> 1) & 0xFFFF
|
||||
return crc
|
||||
|
||||
def _read_exact(self, size: int, timeout: float) -> bytes:
|
||||
deadline = time.monotonic() + timeout
|
||||
chunks = bytearray()
|
||||
while len(chunks) < size:
|
||||
remaining_time = deadline - time.monotonic()
|
||||
if remaining_time <= 0:
|
||||
raise TimeoutError(f"Lese-Timeout beim Warten auf {size} Bytes.")
|
||||
old_timeout = self.serial.timeout
|
||||
self.serial.timeout = min(remaining_time, 0.25)
|
||||
try:
|
||||
chunk = self.serial.read(size - len(chunks))
|
||||
finally:
|
||||
self.serial.timeout = old_timeout
|
||||
if chunk:
|
||||
chunks.extend(chunk)
|
||||
return bytes(chunks)
|
||||
|
||||
def _build_frame(self, frame_type: int, command_id: int, sequence: int, payload: bytes) -> bytes:
|
||||
payload = payload or b""
|
||||
payload_len = len(payload)
|
||||
header_no_sync_crc = struct.pack("<BBHI", frame_type, command_id, sequence, payload_len)
|
||||
header_crc = self._crc16_ccitt_false(header_no_sync_crc)
|
||||
header = SYNC + header_no_sync_crc + struct.pack("<H", header_crc)
|
||||
payload_crc = binascii.crc32(payload) & 0xFFFFFFFF
|
||||
return header + payload + struct.pack("<I", payload_crc)
|
||||
|
||||
def _write_frame(self, frame: bytes) -> None:
|
||||
try:
|
||||
self.serial.write(frame)
|
||||
self.serial.flush()
|
||||
except Exception as e:
|
||||
if e.__class__.__name__ == "SerialTimeoutException":
|
||||
raise TimeoutError(f"Schreib-Timeout am Port {self.port}. Ist das Gerät blockiert?") from e
|
||||
raise
|
||||
|
||||
def _send_binary_frame_no_wait(self, command_id: int, payload: bytes = b"") -> int:
|
||||
if self.serial is None:
|
||||
raise BuzzerError("Serielle Verbindung ist nicht geöffnet.")
|
||||
sequence = self._next_sequence()
|
||||
frame = self._build_frame(FRAME_REQ, command_id, sequence, payload)
|
||||
self._write_frame(frame)
|
||||
return sequence
|
||||
|
||||
def _read_frame(self, timeout: float = None) -> dict:
|
||||
eff_timeout = timeout if timeout is not None else self.timeout
|
||||
deadline = time.monotonic() + eff_timeout
|
||||
|
||||
sync_idx = 0
|
||||
while sync_idx < len(SYNC):
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("Timeout beim Warten auf Sync 'BUZZ'.")
|
||||
b = self._read_exact(1, remaining)
|
||||
if b[0] == SYNC[sync_idx]:
|
||||
sync_idx += 1
|
||||
else:
|
||||
sync_idx = 1 if b[0] == SYNC[0] else 0
|
||||
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("Timeout beim Lesen des Frame-Headers.")
|
||||
rest_header = self._read_exact(HEADER_SIZE - len(SYNC), remaining)
|
||||
frame_type, command_id, sequence, payload_len, rx_header_crc = struct.unpack("<BBHIH", rest_header)
|
||||
|
||||
calc_header_crc = self._crc16_ccitt_false(struct.pack("<BBHI", frame_type, command_id, sequence, payload_len))
|
||||
if rx_header_crc != calc_header_crc:
|
||||
raise BuzzerError(
|
||||
f"Ungültige Header-CRC: empfangen 0x{rx_header_crc:04X}, erwartet 0x{calc_header_crc:04X}"
|
||||
)
|
||||
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("Timeout beim Lesen des Payloads.")
|
||||
payload = self._read_exact(payload_len, remaining) if payload_len else b""
|
||||
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("Timeout beim Lesen der Payload-CRC.")
|
||||
rx_payload_crc = struct.unpack("<I", self._read_exact(4, remaining))[0]
|
||||
calc_payload_crc = binascii.crc32(payload) & 0xFFFFFFFF
|
||||
if rx_payload_crc != calc_payload_crc:
|
||||
raise BuzzerError(
|
||||
f"Ungültige Payload-CRC: empfangen 0x{rx_payload_crc:08X}, erwartet 0x{calc_payload_crc:08X}"
|
||||
)
|
||||
|
||||
return {
|
||||
"frame_type": frame_type,
|
||||
"command_id": command_id,
|
||||
"sequence": sequence,
|
||||
"payload": payload,
|
||||
}
|
||||
|
||||
def send_binary_command(self, command_id: int, payload: bytes = b"", timeout: float = None) -> bytes:
|
||||
if self.serial is None:
|
||||
raise BuzzerError("Serielle Verbindung ist nicht geöffnet.")
|
||||
|
||||
eff_timeout = timeout if timeout is not None else self.timeout
|
||||
self.serial.reset_input_buffer()
|
||||
|
||||
sequence = self._next_sequence()
|
||||
frame = self._build_frame(FRAME_REQ, command_id, sequence, payload)
|
||||
|
||||
self._write_frame(frame)
|
||||
|
||||
response = self._read_frame(timeout=eff_timeout)
|
||||
|
||||
if response["sequence"] != sequence:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Sequenz passt nicht: erwartet {sequence}, erhalten {response['sequence']}"
|
||||
)
|
||||
|
||||
if response["command_id"] != command_id:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Kommando passt nicht: erwartet 0x{command_id:02X}, erhalten 0x{response['command_id']:02X}"
|
||||
)
|
||||
|
||||
if response["frame_type"] == FRAME_RESP_ERROR:
|
||||
self._raise_error_from_payload(response["payload"])
|
||||
|
||||
if response["frame_type"] not in (FRAME_RESP_ACK, FRAME_RESP_DATA):
|
||||
raise BuzzerError(f"Unerwarteter Response-Typ: 0x{response['frame_type']:02X}")
|
||||
|
||||
return response["payload"]
|
||||
|
||||
def get_protocol_version(self, timeout: float = None) -> int:
|
||||
payload = self.send_binary_command(CMD_GET_PROTOCOL_VERSION, b"", timeout=timeout)
|
||||
if len(payload) != 2:
|
||||
raise BuzzerError(f"Ungültige Antwortlänge für GET_PROTOCOL_VERSION: {len(payload)}")
|
||||
return struct.unpack("<H", payload)[0]
|
||||
|
||||
def get_firmware_status(self, timeout: float = None) -> tuple[int, str]:
|
||||
payload = self.send_binary_command(CMD_GET_FIRMWARE_STATUS, b"", timeout=timeout)
|
||||
if len(payload) < 2:
|
||||
raise BuzzerError("Ungültige Antwort für GET_FIRMWARE_STATUS: zu kurz")
|
||||
|
||||
status = payload[0]
|
||||
version_len = payload[1]
|
||||
if len(payload) != 2 + version_len:
|
||||
raise BuzzerError(
|
||||
f"Ungültige Antwort für GET_FIRMWARE_STATUS: erwartete Länge {2 + version_len}, erhalten {len(payload)}"
|
||||
)
|
||||
version = payload[2:2 + version_len].decode("utf-8", errors="replace")
|
||||
return status, version
|
||||
|
||||
def get_flash_status(self, timeout: float = None) -> dict:
|
||||
payload = self.send_binary_command(CMD_GET_FLASH_STATUS, b"", timeout=timeout)
|
||||
if len(payload) != 16:
|
||||
raise BuzzerError(f"Ungültige Antwortlänge für GET_FLASH_STATUS: {len(payload)}")
|
||||
|
||||
block_size, total_blocks, free_blocks, path_max_len = struct.unpack("<IIII", payload)
|
||||
if path_max_len > 0:
|
||||
self._max_path_len = int(path_max_len)
|
||||
|
||||
return {
|
||||
"block_size": block_size,
|
||||
"total_blocks": total_blocks,
|
||||
"free_blocks": free_blocks,
|
||||
"path_max_len": path_max_len,
|
||||
}
|
||||
|
||||
def confirm_firmware(self, timeout: float = None) -> None:
|
||||
payload = self.send_binary_command(CMD_CONFIRM_FIRMWARE, b"", timeout=timeout)
|
||||
if len(payload) != 0:
|
||||
raise BuzzerError(f"Unerwartete Payload für CONFIRM_FIRMWARE: {len(payload)} Bytes")
|
||||
|
||||
def reboot_device(self, timeout: float = None) -> None:
|
||||
payload = self.send_binary_command(CMD_REBOOT, b"", timeout=timeout)
|
||||
if len(payload) != 0:
|
||||
raise BuzzerError(f"Unerwartete Payload für REBOOT: {len(payload)} Bytes")
|
||||
|
||||
def _encode_path_payload(self, path: str) -> bytes:
|
||||
path_bytes = path.encode("utf-8")
|
||||
if len(path_bytes) == 0:
|
||||
raise BuzzerError("Pfad darf nicht leer sein.")
|
||||
max_path_len = min(self._max_path_len, 255)
|
||||
if len(path_bytes) > max_path_len:
|
||||
raise BuzzerError(f"Pfad ist zu lang (max. {max_path_len} Bytes).")
|
||||
return bytes([len(path_bytes)]) + path_bytes
|
||||
|
||||
def list_directory(self, path: str, timeout: float = None) -> list[str]:
|
||||
if self.serial is None:
|
||||
raise BuzzerError("Serielle Verbindung ist nicht geöffnet.")
|
||||
|
||||
eff_timeout = timeout if timeout is not None else self.timeout
|
||||
self.serial.reset_input_buffer()
|
||||
|
||||
sequence = self._next_sequence()
|
||||
frame = self._build_frame(FRAME_REQ, CMD_LIST_DIR, sequence, self._encode_path_payload(path))
|
||||
|
||||
try:
|
||||
self.serial.write(frame)
|
||||
self.serial.flush()
|
||||
except Exception as e:
|
||||
if e.__class__.__name__ == "SerialTimeoutException":
|
||||
raise TimeoutError(f"Schreib-Timeout am Port {self.port}. Ist das Gerät blockiert?") from e
|
||||
raise
|
||||
|
||||
lines = []
|
||||
stream_started = False
|
||||
|
||||
while True:
|
||||
response = self._read_frame(timeout=eff_timeout)
|
||||
|
||||
if response["sequence"] != sequence:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Sequenz passt nicht: erwartet {sequence}, erhalten {response['sequence']}"
|
||||
)
|
||||
|
||||
if response["command_id"] != CMD_LIST_DIR:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Kommando passt nicht: erwartet 0x{CMD_LIST_DIR:02X}, erhalten 0x{response['command_id']:02X}"
|
||||
)
|
||||
|
||||
frame_type = response["frame_type"]
|
||||
payload = response["payload"]
|
||||
|
||||
if frame_type == FRAME_RESP_ERROR:
|
||||
error_code = payload[0] if len(payload) >= 1 else 0x32
|
||||
detail = ""
|
||||
if len(payload) >= 2:
|
||||
detail_len = payload[1]
|
||||
if detail_len > 0 and len(payload) >= 2 + detail_len:
|
||||
detail = payload[2:2 + detail_len].decode("utf-8", errors="replace")
|
||||
|
||||
msg = self._parse_controller_error_code(error_code)
|
||||
if detail:
|
||||
msg = f"{msg} Detail: {detail}"
|
||||
raise BuzzerError(msg)
|
||||
|
||||
if frame_type == FRAME_RESP_STREAM_START:
|
||||
stream_started = True
|
||||
continue
|
||||
|
||||
if frame_type == FRAME_RESP_STREAM_CHUNK:
|
||||
if len(payload) < 6:
|
||||
raise BuzzerError("Ungültiger LIST_DIR Chunk: zu kurz")
|
||||
|
||||
entry_type = payload[0]
|
||||
name_len = payload[1]
|
||||
if len(payload) != 6 + name_len:
|
||||
raise BuzzerError("Ungültiger LIST_DIR Chunk: inkonsistente Namenslänge")
|
||||
|
||||
size = struct.unpack("<I", payload[2:6])[0]
|
||||
name = payload[6:6 + name_len].decode("utf-8", errors="replace")
|
||||
|
||||
if entry_type == 0:
|
||||
type_char = "F"
|
||||
elif entry_type == 1:
|
||||
type_char = "D"
|
||||
else:
|
||||
raise BuzzerError(f"Ungültiger LIST_DIR entry_type: {entry_type}")
|
||||
|
||||
lines.append(f"{type_char},{size},{name}")
|
||||
continue
|
||||
|
||||
if frame_type == FRAME_RESP_STREAM_END:
|
||||
return lines
|
||||
|
||||
if not stream_started and frame_type == FRAME_RESP_DATA:
|
||||
text = payload.decode("utf-8", errors="replace")
|
||||
return [line for line in text.splitlines() if line]
|
||||
|
||||
if frame_type == FRAME_RESP_ACK:
|
||||
return lines
|
||||
|
||||
raise BuzzerError(f"Unerwarteter LIST_DIR Response-Typ: 0x{frame_type:02X}")
|
||||
|
||||
def check_file_crc(self, path: str, timeout: float = None) -> int:
|
||||
payload = self.send_binary_command(CMD_CHECK_FILE_CRC, self._encode_path_payload(path), timeout=timeout)
|
||||
if len(payload) != 4:
|
||||
raise BuzzerError(f"Ungültige Antwortlänge für CHECK_FILE_CRC: {len(payload)}")
|
||||
return struct.unpack("<I", payload)[0]
|
||||
|
||||
def mkdir(self, path: str, timeout: float = None) -> None:
|
||||
payload = self.send_binary_command(CMD_MKDIR, self._encode_path_payload(path), timeout=timeout)
|
||||
if len(payload) != 0:
|
||||
raise BuzzerError(f"Unerwartete Payload für MKDIR: {len(payload)} Bytes")
|
||||
|
||||
def rm(self, path: str, timeout: float = None) -> None:
|
||||
payload = self.send_binary_command(CMD_RM, self._encode_path_payload(path), timeout=timeout)
|
||||
if len(payload) != 0:
|
||||
raise BuzzerError(f"Unerwartete Payload für RM: {len(payload)} Bytes")
|
||||
|
||||
def stat(self, path: str, timeout: float = None) -> dict:
|
||||
payload = self.send_binary_command(CMD_STAT, self._encode_path_payload(path), timeout=timeout)
|
||||
if len(payload) != 5:
|
||||
raise BuzzerError(f"Ungültige Antwortlänge für STAT: {len(payload)}")
|
||||
|
||||
entry_type = payload[0]
|
||||
if entry_type == 0:
|
||||
type_char = "F"
|
||||
elif entry_type == 1:
|
||||
type_char = "D"
|
||||
else:
|
||||
raise BuzzerError(f"Ungültiger STAT entry_type: {entry_type}")
|
||||
|
||||
size = struct.unpack("<I", payload[1:5])[0]
|
||||
return {
|
||||
"type": type_char,
|
||||
"size": int(size),
|
||||
}
|
||||
|
||||
def rename(self, old_path: str, new_path: str, timeout: float = None) -> None:
|
||||
old_payload = self._encode_path_payload(old_path)
|
||||
new_payload = self._encode_path_payload(new_path)
|
||||
payload = old_payload + new_payload
|
||||
response = self.send_binary_command(CMD_RENAME, payload, timeout=timeout)
|
||||
if len(response) != 0:
|
||||
raise BuzzerError(f"Unerwartete Payload für RENAME: {len(response)} Bytes")
|
||||
|
||||
def rm_recursive(self, path: str, timeout: float = None) -> None:
|
||||
payload = self.send_binary_command(CMD_RM_R, self._encode_path_payload(path), timeout=timeout)
|
||||
if len(payload) != 0:
|
||||
raise BuzzerError(f"Unerwartete Payload für RM_R: {len(payload)} Bytes")
|
||||
|
||||
def get_file_data(self, path: str, timeout: float = None, progress_callback=None) -> bytes:
|
||||
if self.serial is None:
|
||||
raise BuzzerError("Serielle Verbindung ist nicht geöffnet.")
|
||||
|
||||
eff_timeout = timeout if timeout is not None else self.timeout
|
||||
self.serial.reset_input_buffer()
|
||||
|
||||
sequence = self._next_sequence()
|
||||
frame = self._build_frame(FRAME_REQ, CMD_GET_FILE, sequence, self._encode_path_payload(path))
|
||||
self._write_frame(frame)
|
||||
|
||||
start_response = self._read_frame(timeout=eff_timeout)
|
||||
if start_response["sequence"] != sequence:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Sequenz passt nicht: erwartet {sequence}, erhalten {start_response['sequence']}"
|
||||
)
|
||||
if start_response["command_id"] != CMD_GET_FILE:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Kommando passt nicht: erwartet 0x{CMD_GET_FILE:02X}, erhalten 0x{start_response['command_id']:02X}"
|
||||
)
|
||||
if start_response["frame_type"] == FRAME_RESP_ERROR:
|
||||
self._raise_error_from_payload(start_response["payload"])
|
||||
if start_response["frame_type"] != FRAME_RESP_DATA or len(start_response["payload"]) != 4:
|
||||
raise BuzzerError("Ungültige GET_FILE-Startantwort (erwartet DATA mit 4 Byte Länge)")
|
||||
|
||||
expected_len = struct.unpack("<I", start_response["payload"])[0]
|
||||
received = 0
|
||||
running_crc = 0
|
||||
chunks = bytearray()
|
||||
chunk_size = 4096
|
||||
|
||||
while received < expected_len:
|
||||
to_read = min(chunk_size, expected_len - received)
|
||||
chunk = self._read_exact(to_read, eff_timeout)
|
||||
chunks.extend(chunk)
|
||||
running_crc = binascii.crc32(chunk, running_crc) & 0xFFFFFFFF
|
||||
received += len(chunk)
|
||||
if progress_callback:
|
||||
progress_callback(len(chunk), received, expected_len)
|
||||
|
||||
end_response = self._read_frame(timeout=eff_timeout)
|
||||
if end_response["sequence"] != sequence:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Sequenz passt nicht: erwartet {sequence}, erhalten {end_response['sequence']}"
|
||||
)
|
||||
if end_response["command_id"] != CMD_GET_FILE:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Kommando passt nicht: erwartet 0x{CMD_GET_FILE:02X}, erhalten 0x{end_response['command_id']:02X}"
|
||||
)
|
||||
if end_response["frame_type"] == FRAME_RESP_ERROR:
|
||||
self._raise_error_from_payload(end_response["payload"])
|
||||
if end_response["frame_type"] != FRAME_RESP_DATA or len(end_response["payload"]) != 4:
|
||||
raise BuzzerError("Ungültige GET_FILE-Endantwort (erwartet DATA mit 4 Byte CRC32)")
|
||||
|
||||
expected_crc32 = struct.unpack("<I", end_response["payload"])[0]
|
||||
if running_crc != expected_crc32:
|
||||
raise BuzzerError(
|
||||
f"GET_FILE CRC32-Mismatch: empfangen 0x{running_crc:08X}, erwartet 0x{expected_crc32:08X}"
|
||||
)
|
||||
|
||||
return bytes(chunks)
|
||||
|
||||
def put_file_start(self, path: str, total_len: int, expected_crc32: int, timeout: float = None) -> None:
|
||||
if total_len < 0:
|
||||
raise BuzzerError("Dateigröße darf nicht negativ sein.")
|
||||
payload = self._encode_path_payload(path) + struct.pack("<II", int(total_len), int(expected_crc32) & 0xFFFFFFFF)
|
||||
response = self.send_binary_command(CMD_PUT_FILE_START, payload, timeout=timeout)
|
||||
if len(response) != 0:
|
||||
raise BuzzerError(f"Unerwartete Payload für PUT_FILE_START: {len(response)} Bytes")
|
||||
|
||||
def put_file_chunk(self, chunk: bytes, timeout: float = None) -> None:
|
||||
self._send_binary_frame_no_wait(CMD_PUT_FILE_CHUNK, chunk)
|
||||
|
||||
def put_file_end(self, timeout: float = None) -> None:
|
||||
eff_timeout = timeout if timeout is not None else self.timeout
|
||||
end_sequence = self._send_binary_frame_no_wait(CMD_PUT_FILE_END, b"")
|
||||
|
||||
deadline = time.monotonic() + eff_timeout
|
||||
while True:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("Lese-Timeout beim Warten auf PUT_FILE_END Antwort.")
|
||||
|
||||
response = self._read_frame(timeout=remaining)
|
||||
|
||||
if response["frame_type"] == FRAME_RESP_ERROR and response["command_id"] in (
|
||||
CMD_PUT_FILE_START,
|
||||
CMD_PUT_FILE_CHUNK,
|
||||
CMD_PUT_FILE_END,
|
||||
):
|
||||
self._raise_error_from_payload(response["payload"])
|
||||
|
||||
if response["command_id"] != CMD_PUT_FILE_END or response["sequence"] != end_sequence:
|
||||
continue
|
||||
|
||||
if response["frame_type"] not in (FRAME_RESP_ACK, FRAME_RESP_DATA):
|
||||
raise BuzzerError(f"Unerwarteter Response-Typ für PUT_FILE_END: 0x{response['frame_type']:02X}")
|
||||
|
||||
if len(response["payload"]) != 0:
|
||||
raise BuzzerError(f"Unerwartete Payload für PUT_FILE_END: {len(response['payload'])} Bytes")
|
||||
|
||||
return
|
||||
|
||||
def put_file_data(
|
||||
self,
|
||||
path: str,
|
||||
data: bytes,
|
||||
timeout: float = None,
|
||||
chunk_size: int = 4096,
|
||||
progress_callback=None,
|
||||
) -> int:
|
||||
if data is None:
|
||||
data = b""
|
||||
if chunk_size <= 0:
|
||||
raise BuzzerError("chunk_size muss größer als 0 sein.")
|
||||
|
||||
expected_crc32 = binascii.crc32(data) & 0xFFFFFFFF
|
||||
if self.serial is None:
|
||||
raise BuzzerError("Serielle Verbindung ist nicht geöffnet.")
|
||||
|
||||
eff_timeout = timeout if timeout is not None else self.timeout
|
||||
self.serial.reset_input_buffer()
|
||||
|
||||
sequence = self._next_sequence()
|
||||
start_payload = self._encode_path_payload(path) + struct.pack("<II", len(data), expected_crc32)
|
||||
start_frame = self._build_frame(FRAME_REQ, CMD_PUT_FILE_START, sequence, start_payload)
|
||||
self._write_frame(start_frame)
|
||||
|
||||
sent = 0
|
||||
while sent < len(data):
|
||||
chunk = data[sent:sent + chunk_size]
|
||||
try:
|
||||
self.serial.write(chunk)
|
||||
except Exception as e:
|
||||
if e.__class__.__name__ == "SerialTimeoutException":
|
||||
raise TimeoutError(f"Schreib-Timeout am Port {self.port}. Ist das Gerät blockiert?") from e
|
||||
raise
|
||||
sent += len(chunk)
|
||||
if progress_callback:
|
||||
progress_callback(len(chunk), sent, len(data))
|
||||
|
||||
self.serial.flush()
|
||||
|
||||
response = self._read_frame(timeout=eff_timeout)
|
||||
|
||||
if response["sequence"] != sequence:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Sequenz passt nicht: erwartet {sequence}, erhalten {response['sequence']}"
|
||||
)
|
||||
|
||||
if response["command_id"] != CMD_PUT_FILE_START:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Kommando passt nicht: erwartet 0x{CMD_PUT_FILE_START:02X}, erhalten 0x{response['command_id']:02X}"
|
||||
)
|
||||
|
||||
if response["frame_type"] == FRAME_RESP_ERROR:
|
||||
self._raise_error_from_payload(response["payload"])
|
||||
|
||||
if response["frame_type"] not in (FRAME_RESP_ACK, FRAME_RESP_DATA):
|
||||
raise BuzzerError(f"Unerwarteter Response-Typ für PUT_FILE_START: 0x{response['frame_type']:02X}")
|
||||
|
||||
if len(response["payload"]) != 0:
|
||||
raise BuzzerError(f"Unerwartete Payload für PUT_FILE_START: {len(response['payload'])} Bytes")
|
||||
return expected_crc32
|
||||
|
||||
def fw_put_data(
|
||||
self,
|
||||
data: bytes,
|
||||
timeout: float = None,
|
||||
chunk_size: int = 4096,
|
||||
progress_callback=None,
|
||||
) -> int:
|
||||
if data is None:
|
||||
data = b""
|
||||
if chunk_size <= 0:
|
||||
raise BuzzerError("chunk_size muss größer als 0 sein.")
|
||||
if len(data) == 0:
|
||||
raise BuzzerError("Firmware-Datei ist leer.")
|
||||
|
||||
expected_crc32 = binascii.crc32(data) & 0xFFFFFFFF
|
||||
if self.serial is None:
|
||||
raise BuzzerError("Serielle Verbindung ist nicht geöffnet.")
|
||||
|
||||
eff_timeout = timeout if timeout is not None else self.timeout
|
||||
old_write_timeout = self.serial.write_timeout
|
||||
self.serial.write_timeout = max(float(old_write_timeout or 0.0), float(eff_timeout))
|
||||
self.serial.reset_input_buffer()
|
||||
|
||||
try:
|
||||
sequence = self._next_sequence()
|
||||
start_payload = struct.pack("<II", len(data), expected_crc32)
|
||||
start_frame = self._build_frame(FRAME_REQ, CMD_PUT_FW_START, sequence, start_payload)
|
||||
self._write_frame(start_frame)
|
||||
|
||||
sent = 0
|
||||
while sent < len(data):
|
||||
chunk = data[sent:sent + chunk_size]
|
||||
try:
|
||||
self.serial.write(chunk)
|
||||
except Exception as e:
|
||||
if e.__class__.__name__ == "SerialTimeoutException":
|
||||
raise TimeoutError(f"Schreib-Timeout am Port {self.port}. Ist das Gerät blockiert?") from e
|
||||
raise
|
||||
sent += len(chunk)
|
||||
if progress_callback:
|
||||
progress_callback(len(chunk), sent, len(data))
|
||||
|
||||
self.serial.flush()
|
||||
|
||||
response = self._read_frame(timeout=eff_timeout)
|
||||
finally:
|
||||
self.serial.write_timeout = old_write_timeout
|
||||
|
||||
if response["sequence"] != sequence:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Sequenz passt nicht: erwartet {sequence}, erhalten {response['sequence']}"
|
||||
)
|
||||
|
||||
if response["command_id"] != CMD_PUT_FW_START:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Kommando passt nicht: erwartet 0x{CMD_PUT_FW_START:02X}, erhalten 0x{response['command_id']:02X}"
|
||||
)
|
||||
|
||||
if response["frame_type"] == FRAME_RESP_ERROR:
|
||||
self._raise_error_from_payload(response["payload"])
|
||||
|
||||
if response["frame_type"] not in (FRAME_RESP_ACK, FRAME_RESP_DATA):
|
||||
raise BuzzerError(f"Unerwarteter Response-Typ für PUT_FW_START: 0x{response['frame_type']:02X}")
|
||||
|
||||
if len(response["payload"]) != 0:
|
||||
raise BuzzerError(f"Unerwartete Payload für PUT_FW_START: {len(response['payload'])} Bytes")
|
||||
|
||||
return expected_crc32
|
||||
|
||||
def get_tag_blob(self, path: str, timeout: float = None) -> bytes:
|
||||
if self.serial is None:
|
||||
raise BuzzerError("Serielle Verbindung ist nicht geöffnet.")
|
||||
|
||||
eff_timeout = timeout if timeout is not None else self.timeout
|
||||
self.serial.reset_input_buffer()
|
||||
|
||||
sequence = self._next_sequence()
|
||||
frame = self._build_frame(FRAME_REQ, CMD_GET_TAG_BLOB, sequence, self._encode_path_payload(path))
|
||||
|
||||
try:
|
||||
self.serial.write(frame)
|
||||
self.serial.flush()
|
||||
except Exception as e:
|
||||
if e.__class__.__name__ == "SerialTimeoutException":
|
||||
raise TimeoutError(f"Schreib-Timeout am Port {self.port}. Ist das Gerät blockiert?") from e
|
||||
raise
|
||||
|
||||
expected_len = None
|
||||
chunks = bytearray()
|
||||
|
||||
while True:
|
||||
response = self._read_frame(timeout=eff_timeout)
|
||||
|
||||
if response["sequence"] != sequence:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Sequenz passt nicht: erwartet {sequence}, erhalten {response['sequence']}"
|
||||
)
|
||||
|
||||
if response["command_id"] != CMD_GET_TAG_BLOB:
|
||||
raise BuzzerError(
|
||||
f"Antwort-Kommando passt nicht: erwartet 0x{CMD_GET_TAG_BLOB:02X}, erhalten 0x{response['command_id']:02X}"
|
||||
)
|
||||
|
||||
frame_type = response["frame_type"]
|
||||
payload = response["payload"]
|
||||
|
||||
if frame_type == FRAME_RESP_ERROR:
|
||||
error_code = payload[0] if len(payload) >= 1 else 0x32
|
||||
raise BuzzerError(self._parse_controller_error_code(error_code))
|
||||
|
||||
if frame_type == FRAME_RESP_STREAM_START:
|
||||
if len(payload) != 4:
|
||||
raise BuzzerError("Ungültiger GET_TAG_BLOB START-Frame")
|
||||
expected_len = struct.unpack("<I", payload)[0]
|
||||
continue
|
||||
|
||||
if frame_type == FRAME_RESP_STREAM_CHUNK:
|
||||
chunks.extend(payload)
|
||||
continue
|
||||
|
||||
if frame_type == FRAME_RESP_STREAM_END:
|
||||
if expected_len is not None and len(chunks) != expected_len:
|
||||
raise BuzzerError(
|
||||
f"Tag-Blob-Länge inkonsistent: erwartet {expected_len}, erhalten {len(chunks)}"
|
||||
)
|
||||
return bytes(chunks)
|
||||
|
||||
if frame_type == FRAME_RESP_DATA:
|
||||
return payload
|
||||
|
||||
raise BuzzerError(f"Unerwarteter GET_TAG_BLOB Response-Typ: 0x{frame_type:02X}")
|
||||
|
||||
def set_tag_blob(self, path: str, blob: bytes, timeout: float = None, chunk_size: int = 192) -> None:
|
||||
if blob is None:
|
||||
blob = b""
|
||||
|
||||
if len(blob) > 1024:
|
||||
raise BuzzerError("Tag-Blob ist zu groß (max. 1024 Bytes).")
|
||||
|
||||
path_payload = self._encode_path_payload(path)
|
||||
start_payload = path_payload + struct.pack("<H", len(blob))
|
||||
self.send_binary_command(CMD_SET_TAG_BLOB_START, start_payload, timeout=timeout)
|
||||
|
||||
offset = 0
|
||||
while offset < len(blob):
|
||||
chunk = blob[offset:offset + chunk_size]
|
||||
self.send_binary_command(CMD_SET_TAG_BLOB_CHUNK, chunk, timeout=timeout)
|
||||
offset += len(chunk)
|
||||
|
||||
self.send_binary_command(CMD_SET_TAG_BLOB_END, b"", timeout=timeout)
|
||||
|
||||
def send_command(self, command: str, custom_timeout: float = None) -> list:
|
||||
eff_timeout = custom_timeout if custom_timeout is not None else self.timeout
|
||||
self.serial.reset_input_buffer()
|
||||
|
||||
try:
|
||||
self.serial.write(f"{command}\n".encode('utf-8'))
|
||||
self.serial.flush()
|
||||
except Exception as e:
|
||||
if e.__class__.__name__ == "SerialTimeoutException":
|
||||
raise TimeoutError(f"Schreib-Timeout am Port {self.port}. Ist das Gerät blockiert?") from e
|
||||
raise
|
||||
|
||||
lines = []
|
||||
start_time = time.monotonic()
|
||||
|
||||
while (time.monotonic() - start_time) < eff_timeout:
|
||||
if self.serial.in_waiting > 0:
|
||||
try:
|
||||
line = self.serial.readline().decode('utf-8', errors='ignore').strip()
|
||||
if not line:
|
||||
continue
|
||||
if line == "OK":
|
||||
return lines
|
||||
elif line.startswith("ERR"):
|
||||
raise BuzzerError(self._parse_controller_error(line))
|
||||
else:
|
||||
lines.append(line)
|
||||
except BuzzerError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise BuzzerError(f"Fehler beim Lesen der Antwort: {e}")
|
||||
else:
|
||||
time.sleep(POLL_SLEEP_SECONDS)
|
||||
|
||||
raise TimeoutError(f"Lese-Timeout ({eff_timeout}s) beim Warten auf Antwort für: '{command}'")
|
||||
|
||||
def send_binary(self, filepath: str, chunk_size: int = 4096, timeout: float = 10.0, progress_callback=None):
|
||||
"""
|
||||
Überträgt eine Binärdatei in Chunks, nachdem das READY-Signal empfangen wurde.
|
||||
"""
|
||||
# 1. Warte auf die READY-Bestätigung vom Controller
|
||||
start_time = time.time()
|
||||
ready = False
|
||||
while (time.time() - start_time) < timeout:
|
||||
if self.serial.in_waiting > 0:
|
||||
line = self.serial.readline().decode('utf-8', errors='ignore').strip()
|
||||
if line == "READY":
|
||||
ready = True
|
||||
break
|
||||
elif line.startswith("ERR"):
|
||||
raise BuzzerError(f"Fehler vor Binärtransfer: {self._parse_controller_error(line)}")
|
||||
time.sleep(POLL_SLEEP_SECONDS)
|
||||
|
||||
if not ready:
|
||||
raise TimeoutError("Kein READY-Signal vom Controller empfangen.")
|
||||
|
||||
# 2. Sende die Datei in Blöcken
|
||||
file_size = os.path.getsize(filepath)
|
||||
bytes_sent = 0
|
||||
|
||||
with open(filepath, 'rb') as f:
|
||||
while bytes_sent < file_size:
|
||||
# 1. Nicht blockierende Fehlerprüfung vor jedem Chunk
|
||||
if self.serial.in_waiting > 0:
|
||||
line = self.serial.readline().decode('utf-8', errors='ignore').strip()
|
||||
if line.startswith("ERR"):
|
||||
raise BuzzerError(f"Controller hat Transfer abgebrochen: {self._parse_controller_error(line)}")
|
||||
|
||||
# 2. Chunk lesen und schreiben
|
||||
chunk = f.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
|
||||
self.serial.write(chunk)
|
||||
# WICHTIG: self.serial.flush() hier entfernen.
|
||||
# Dies verhindert den Deadlock mit dem OS-USB-Puffer.
|
||||
|
||||
bytes_sent += len(chunk)
|
||||
|
||||
# 3. Callback für UI
|
||||
if progress_callback:
|
||||
progress_callback(len(chunk))
|
||||
|
||||
# 3. Warte auf das finale OK (oder ERR bei CRC/Schreib-Fehlern)
|
||||
start_time = time.time()
|
||||
while (time.time() - start_time) < timeout:
|
||||
if self.serial.in_waiting > 0:
|
||||
line = self.serial.readline().decode('utf-8', errors='ignore').strip()
|
||||
if line == "OK":
|
||||
return True
|
||||
elif line.startswith("ERR"):
|
||||
raise BuzzerError(f"Fehler beim Speichern der Binärdatei: {self._parse_controller_error(line)}")
|
||||
time.sleep(POLL_SLEEP_SECONDS)
|
||||
|
||||
raise TimeoutError("Zeitüberschreitung nach Binärtransfer (kein OK empfangen).")
|
||||
@@ -1,25 +0,0 @@
|
||||
def hex_to_bytearray(hex_string):
|
||||
"""
|
||||
Wandelt einen Hex-String (z.B. "deadbeef") in ein bytearray um.
|
||||
Entfernt vorher Leerzeichen und prüft auf Gültigkeit.
|
||||
"""
|
||||
try:
|
||||
# Whitespace entfernen (falls vorhanden)
|
||||
clean_hex = hex_string.strip().replace(" ", "")
|
||||
|
||||
# Konvertierung
|
||||
return bytearray.fromhex(clean_hex)
|
||||
|
||||
except ValueError as e:
|
||||
print(f"Fehler bei der Konvertierung: {e}")
|
||||
return None
|
||||
|
||||
def string_to_hexstring(text):
|
||||
"""
|
||||
Wandelt einen String in einen UTF-8-kodierten Hex-String um.
|
||||
"""
|
||||
# 1. String zu UTF-8 Bytes
|
||||
utf8_bytes = text.encode('utf-8')
|
||||
|
||||
# 2. Bytes zu Hex-String
|
||||
return utf8_bytes.hex()
|
||||
@@ -1,2 +0,0 @@
|
||||
pyyaml
|
||||
pyserial
|
||||
@@ -1,165 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ROOT_DIR="$(cd -- "$SCRIPT_DIR/.." && pwd)"
|
||||
CLI="$ROOT_DIR/buzzer_tool/buzzer.py"
|
||||
|
||||
PORT=""
|
||||
BAUDRATE=""
|
||||
TIMEOUT=""
|
||||
REMOTE_BASE="/lfs/smoke"
|
||||
KEEP_TMP=0
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: $(basename "$0") -p <port> [-b baudrate] [-t timeout] [--remote-base /lfs/path] [--keep-tmp]
|
||||
|
||||
Beispiel:
|
||||
$(basename "$0") -p /dev/tty.usbmodem14101 -b 115200 -t 5
|
||||
EOF
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
-p|--port)
|
||||
PORT="$2"
|
||||
shift 2
|
||||
;;
|
||||
-b|--baudrate)
|
||||
BAUDRATE="$2"
|
||||
shift 2
|
||||
;;
|
||||
-t|--timeout)
|
||||
TIMEOUT="$2"
|
||||
shift 2
|
||||
;;
|
||||
--remote-base)
|
||||
REMOTE_BASE="$2"
|
||||
shift 2
|
||||
;;
|
||||
--keep-tmp)
|
||||
KEEP_TMP=1
|
||||
shift
|
||||
;;
|
||||
-h|--help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unbekanntes Argument: $1" >&2
|
||||
usage
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ -z "$PORT" ]]; then
|
||||
echo "Fehler: --port ist erforderlich" >&2
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
COMMON_ARGS=("-p" "$PORT" "--no-auto-info")
|
||||
if [[ -n "$BAUDRATE" ]]; then
|
||||
COMMON_ARGS+=("-b" "$BAUDRATE")
|
||||
fi
|
||||
if [[ -n "$TIMEOUT" ]]; then
|
||||
COMMON_ARGS+=("-t" "$TIMEOUT")
|
||||
fi
|
||||
|
||||
run_cli() {
|
||||
python3 "$CLI" "${COMMON_ARGS[@]}" "$@"
|
||||
}
|
||||
|
||||
TMP_DIR="$(mktemp -d -t buzzer-smoke-XXXXXX)"
|
||||
cleanup() {
|
||||
if [[ "$KEEP_TMP" -eq 0 ]]; then
|
||||
rm -rf "$TMP_DIR"
|
||||
else
|
||||
echo "Temporärer Ordner bleibt erhalten: $TMP_DIR"
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
echo "[1/9] Erzeuge sehr kleine Testdateien mit Nullen in $TMP_DIR"
|
||||
python3 - "$TMP_DIR" <<'PY'
|
||||
import os
|
||||
import sys
|
||||
base = sys.argv[1]
|
||||
files = {
|
||||
"z0.bin": 0,
|
||||
"z1.bin": 1,
|
||||
"z8.bin": 8,
|
||||
"z16.bin": 16,
|
||||
"z64.bin": 64,
|
||||
"z100k.bin": 102400,
|
||||
}
|
||||
for name, size in files.items():
|
||||
with open(os.path.join(base, name), "wb") as f:
|
||||
f.write(b"\x00" * size)
|
||||
print("Created:", ", ".join(f"{k}:{v}B" for k,v in files.items()))
|
||||
PY
|
||||
|
||||
echo "[2/9] Bereinige altes Remote-Testverzeichnis (falls vorhanden)"
|
||||
run_cli rm -r "$REMOTE_BASE" >/dev/null 2>&1 || true
|
||||
|
||||
echo "[3/9] Lege Remote-Verzeichnis an"
|
||||
run_cli mkdir "$REMOTE_BASE"
|
||||
|
||||
echo "[4/9] Upload der kleinen Null-Dateien"
|
||||
run_cli put "$TMP_DIR"/*.bin "$REMOTE_BASE/"
|
||||
|
||||
echo "[5/9] Prüfe remote stat"
|
||||
run_cli stat "$REMOTE_BASE/z0.bin"
|
||||
run_cli stat "$REMOTE_BASE/z64.bin"
|
||||
|
||||
echo "[6/9] Teste rename/mv"
|
||||
run_cli mv "$REMOTE_BASE/z16.bin" "$REMOTE_BASE/z16_renamed.bin"
|
||||
run_cli stat "$REMOTE_BASE/z16_renamed.bin"
|
||||
|
||||
echo "[7/9] Pull + get_file (Alias)"
|
||||
run_cli pull "$REMOTE_BASE/z1.bin" "$TMP_DIR/pull_z1.bin"
|
||||
run_cli get_file "$REMOTE_BASE/z100k.bin" "$TMP_DIR/get_file_z100k.bin"
|
||||
|
||||
echo "[8/9] Vergleiche heruntergeladene Dateien"
|
||||
python3 - "$TMP_DIR" <<'PY'
|
||||
import os
|
||||
import sys
|
||||
|
||||
TAG_MAGIC = b"TAG!"
|
||||
TAG_FOOTER_LEN = 7
|
||||
|
||||
base = sys.argv[1]
|
||||
|
||||
checks = [
|
||||
("z1.bin", "pull_z1.bin"),
|
||||
("z8.bin", "get_file_z8.bin"),
|
||||
]
|
||||
|
||||
for original_name, pulled_name in checks:
|
||||
original_path = os.path.join(base, original_name)
|
||||
pulled_path = os.path.join(base, pulled_name)
|
||||
|
||||
with open(original_path, "rb") as f:
|
||||
original = f.read()
|
||||
with open(pulled_path, "rb") as f:
|
||||
pulled = f.read()
|
||||
|
||||
if len(pulled) < len(original) + TAG_FOOTER_LEN:
|
||||
raise SystemExit(f"Pulled file zu kurz: {pulled_name}")
|
||||
|
||||
if pulled[:len(original)] != original:
|
||||
raise SystemExit(f"Audio-Präfix stimmt nicht: {pulled_name}")
|
||||
|
||||
if pulled[-4:] != TAG_MAGIC:
|
||||
raise SystemExit(f"TAG-Footer fehlt: {pulled_name}")
|
||||
|
||||
print("Vergleich OK (audio + tags)")
|
||||
PY
|
||||
|
||||
echo "[9/9] Rekursives Löschen + Abschlussliste"
|
||||
run_cli rm -r "$REMOTE_BASE"
|
||||
run_cli ls /lfs
|
||||
|
||||
echo "✅ Smoke-Test erfolgreich abgeschlossen"
|
||||
@@ -9,9 +9,12 @@ target_sources(app PRIVATE
|
||||
src/io.c
|
||||
src/audio.c
|
||||
src/usb.c
|
||||
src/uart.c
|
||||
src/protocol.c
|
||||
src/utils.c
|
||||
src/settings.c
|
||||
)
|
||||
zephyr_include_directories(src)
|
||||
|
||||
zephyr_include_directories(include)
|
||||
|
||||
|
||||
|
||||
195
firmware/Tags.md
195
firmware/Tags.md
@@ -1,133 +1,122 @@
|
||||
# Audio-Tags Format
|
||||
# Edi's Buzzer - Metadata Tags Format
|
||||
|
||||
Dieses Dokument beschreibt das aktuelle Tag-Format für Audiodateien.
|
||||
## Architektur-Übersicht
|
||||
Die Metadaten werden transparent an das Ende der rohen Audio-Daten angehängt. Das Format basiert auf einer strikten **Little-Endian** Byte-Reihenfolge und nutzt eine erweiterbare **TLV-Struktur** (Type-Length-Value) für die eigentlichen Datenblöcke.
|
||||
|
||||
## 1) Position in der Datei
|
||||
Das physische Layout einer Datei im Flash-Speicher sieht wie folgt aus:
|
||||
`[Audio-Rohdaten] [TLV-Block 1] ... [TLV-Block N] [Footer (8 Bytes)]`
|
||||
|
||||
Die Tags stehen am Dateiende:
|
||||
---
|
||||
|
||||
`[audio_data][metadata][tag_version_u8][footer_len_le16]["TAG!"]`
|
||||
## 1. Footer-Struktur
|
||||
Der Footer liegt exakt auf den letzten 8 Bytes der Datei (EOF - 8). Er dient als Ankerpunkt für den Parser, um die Metadaten rückwärts aus der Datei zu extrahieren. Das 8-Byte-Alignment stellt speichersichere Casts auf 32-Bit-ARM-Architekturen sicher.
|
||||
|
||||
- `audio_data`: eigentliche Audiodaten
|
||||
- `metadata`: Folge von Tag-Einträgen
|
||||
- `tag_version_u8`: 1 Byte Versionsnummer des Tag-Formats
|
||||
- `footer_len_le16`: 2 Byte, Little Endian
|
||||
- `"TAG!"`: 4 Byte Magic (`0x54 0x41 0x47 0x21`)
|
||||
| Offset | Feld | Typ | Beschreibung |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| 0 | `total_size` | `uint16_t` | Gesamtgröße in Bytes (Summe aller TLV-Blöcke + 8 Bytes Footer). |
|
||||
| 2 | `version` | `uint16_t` | Format-Version. Aktuell `0x0001`. |
|
||||
| 4 | `magic` | `char[4]` | Fixe Signatur: `"TAG!"` (Hex: `54 41 47 21`). |
|
||||
|
||||
## 2) Bedeutung von `footer_len_le16`
|
||||
---
|
||||
|
||||
`footer_len_le16` ist die **Gesamtlänge des Footers**, also:
|
||||
## 2. TLV-Header (Type-Length-Value)
|
||||
Jeder Metadaten-Block beginnt mit einem exakt 4 Bytes großen Header. Unbekannte Typen können vom Controller durch einen relativen Sprung (`fs_seek` um `length` Bytes) übersprungen werden.
|
||||
|
||||
`footer_len = metadata_len + 1 + 2 + 4`
|
||||
| Offset | Feld | Typ | Beschreibung |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| 0 | `type` | `uint8_t` | Definiert den Inhalt des Blocks (siehe Typen-Definitionen). |
|
||||
| 1 | `index` | `uint8_t` | Erlaubt die Fragmentierung großer Datensätze (z.B. bei JSON > 64 KB). Standard: `0x00`. |
|
||||
| 2 | `length` | `uint16_t` | Größe der folgenden Payload in Bytes (ohne diesen Header). |
|
||||
|
||||
Damit beginnt `metadata` bei:
|
||||
---
|
||||
|
||||
`metadata_start = file_size - footer_len`
|
||||
## 3. Typen-Definitionen
|
||||
|
||||
Das passt zur aktuellen Implementierung in der Firmware.
|
||||
### Type `0x00`: Binary System Metadata
|
||||
Dieser Typ gruppiert maschinenlesbare, binäre Systeminformationen. Die Unterscheidung erfolgt über das `Index`-Feld.
|
||||
|
||||
### Tag-Version
|
||||
#### Index `0x00`: Audio Format
|
||||
Dieser Block konfiguriert den I2S-Treiber vor der Wiedergabe.
|
||||
* **Typ:** `0x00`
|
||||
* **Index:** `0x00`
|
||||
* **Länge:** `0x0008` (8 Bytes)
|
||||
* **Payload:** `[codec: 1 Byte] [bit_depth: 1 Byte] [reserved: 2 Bytes] [samplerate: 4 Bytes]`
|
||||
|
||||
- `tag_version` ist aktuell `0x01`.
|
||||
- Der Host darf nur bekannte Versionen interpretieren.
|
||||
- Bei unbekannter Version: Tag-Block ignorieren oder als "nicht unterstützt" melden.
|
||||
#### Index `0x01`: Audio CRC32
|
||||
Speichert die CRC32-Prüfsumme (IEEE) der reinen Audiodaten (vom Dateianfang bis zum Beginn des ersten TLV-Blocks). Dient Synchronisations-Tools für einen schnellen Integritäts- und Abgleich-Check, ohne die gesamte Datei neu hashen zu müssen.
|
||||
* **Typ:** `0x00`
|
||||
* **Index:** `0x01`
|
||||
* **Länge:** `0x0004` (4 Bytes)
|
||||
* **Payload:** `uint32_t` (Little-Endian)
|
||||
|
||||
## 3) Endianness und Typen
|
||||
### Type `0x10`: JSON Metadata
|
||||
Dieser Block enthält Metadaten, die primär für das Host-System (z. B. das Python-Tool) zur Verwaltung, Kategorisierung und Anzeige bestimmt sind. Der Mikrocontroller ignoriert und überspringt diesen Block während der Audiowiedergabe.
|
||||
|
||||
- Alle Multi-Byte-Werte sind **Little Endian**.
|
||||
- Tag-Einträge sind TLV-basiert:
|
||||
- `type`: `uint8_t`
|
||||
- `len`: `uint16_t`
|
||||
- `value`: `byte[len]`
|
||||
* **Typ:** `0x10`
|
||||
* **Länge:** Variabel
|
||||
* **Payload:** UTF-8-kodierter JSON-String (ohne Null-Terminator).
|
||||
|
||||
Dadurch können auch unbekannte Typen sauber übersprungen werden.
|
||||
#### Standardisierte JSON-Schlüssel
|
||||
Die nachfolgenden Schlüssel (Keys) sind im Basis-Standard definiert. Die Integration weiterer, proprietärer Schlüssel ist technisch möglich. Es wird jedoch empfohlen, dies mit Vorsicht zu handhaben, da zukünftige Standardisierungen diese Schlüsselnamen belegen könnten (Namenskollision).
|
||||
|
||||
## 4) Unterstützte Tag-Typen
|
||||
| Schlüssel | Datentyp | Beschreibung |
|
||||
| :--- | :--- | :--- |
|
||||
| `t` | String | Titel der Audiodatei |
|
||||
| `a` | String | Autor oder Ersteller |
|
||||
| `r` | String | Bemerkungen (Remarks) oder Beschreibung |
|
||||
| `c` | Array of Strings | Kategorien zur Gruppierung |
|
||||
| `dc` | String | Erstellungsdatum (Date Created), idealerweise nach ISO 8601 |
|
||||
| `ds` | String | Speicher- oder Änderungsdatum (Date Saved), idealerweise nach ISO 8601 |
|
||||
|
||||
Aktuell definierte Typen:
|
||||
**Beispiel-Payload:**
|
||||
Ein vollständiger JSON-Datensatz gemäß dieser Spezifikation hat folgendes Format:
|
||||
|
||||
- `0x00`: `DESCRIPTION` (Beschreibung des Samples)
|
||||
- `0x01`: `AUTHOR`
|
||||
- `0x10`: `CRC32_RAW`
|
||||
- `0x20`: `FILE_FORMAT` (Info für Host, Player wertet derzeit nicht aus)
|
||||
```json
|
||||
{
|
||||
"t": "Testaufnahme System A",
|
||||
"a": "Entwickler-Team",
|
||||
"r": "Überprüfung der Mikrofon-Aussteuerung.",
|
||||
"c": ["Test", "Audio", "V1"],
|
||||
"dc": "2026-03-05T13:00:00Z",
|
||||
"ds": "2026-03-05T13:10:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
## 5) Value-Format pro Tag
|
||||
*(Hinweis zur Skalierbarkeit: Für zukünftige Erweiterungen können dedizierte TLV-Typen definiert werden, wie beispielsweise 0x11 für GZIP-komprimierte JSON-Daten oder 0x20 für binäre Bilddaten wie PNG-Cover).*
|
||||
|
||||
### 5.1 `0x00` DESCRIPTION
|
||||
---
|
||||
|
||||
- `value`: UTF-8-Text
|
||||
- `len`: Anzahl Bytes des UTF-8-Texts
|
||||
## 4. Lese-Algorithmus (Parser-Logik)
|
||||
|
||||
### 5.2 `0x01` AUTHOR
|
||||
Der Controller extrahiert die Hardware-Parameter nach folgendem Ablauf:
|
||||
|
||||
- `value`: UTF-8-Text
|
||||
- `len`: Anzahl Bytes des UTF-8-Texts
|
||||
1. **Footer lokalisieren:** * Gehe zu `EOF - 8`. Lese 8 Bytes in das `tag_footer_t` Struct.
|
||||
* Validiere `magic == "TAG!"` und `version == 0x0001` (unter Berücksichtigung von Little-Endian Konvertierung via `sys_le16_to_cpu`).
|
||||
2. **Grenzen berechnen:**
|
||||
* Lese `total_size`.
|
||||
* Die reinen Audiodaten enden bei `audio_limit = EOF - total_size`.
|
||||
* Gehe zur Position `audio_limit`.
|
||||
3. **TLV-Blöcke iterieren:**
|
||||
* Solange die aktuelle Leseposition kleiner als `EOF - 8` ist:
|
||||
* Lese 4 Bytes in den `tlv_header_t`.
|
||||
* Wenn `type == 0x00`: Lese die nächsten 8 Bytes in das `tlv_audio_format_t` Struct.
|
||||
* Wenn `type != 0x00`: Führe `fs_seek(header.length, FS_SEEK_CUR)` aus.
|
||||
|
||||
### 5.3 `0x10` CRC32_RAW
|
||||
---
|
||||
|
||||
- `value`: `uint32_t crc32` (4 Byte, Little Endian)
|
||||
- `len`: **muss 4** sein
|
||||
## 5. Hex-Beispiel
|
||||
|
||||
### 5.4 `0x20` FILE_FORMAT
|
||||
Eine fiktive Datei enthält Audio-Daten. Es soll ein PCM-Mono Format (16 Bit, 16 kHz) sowie ein kurzes JSON `{"t":"A"}` (9 Bytes) angehängt werden.
|
||||
|
||||
- `value`:
|
||||
- `bits_per_sample`: `uint8_t`
|
||||
- `sample_rate`: `uint32_t` (Little Endian)
|
||||
- `len`: **muss 5** sein
|
||||
**1. TLV 0x00 (Audio Format):**
|
||||
* Header: `00 00 08 00` (Type 0, Index 0, Length 8)
|
||||
* Payload: `00 10 00 00 80 3E 00 00` (Mono, 16-Bit, Reserved, 16000 Hz)
|
||||
|
||||
Beispielwerte aktuell oft: `bits_per_sample = 16`, `sample_rate = 16000`.
|
||||
**2. TLV 0x10 (JSON):**
|
||||
* Header: `10 00 09 00` (Type 16, Index 0, Length 9)
|
||||
* Payload: `7B 22 74 22 3A 22 41 22 7D` (`{"t":"A"}`)
|
||||
|
||||
## 6) Vorkommen je Typ
|
||||
|
||||
Aktueller Stand: **jeder Tag-Typ darf maximal 1x vorkommen**.
|
||||
|
||||
Empfohlene Host-Regel:
|
||||
|
||||
- Falls ein Typ mehrfach vorkommt, letzte Instanz gewinnt (`last-wins`) und ein Warnhinweis wird geloggt.
|
||||
|
||||
## 7) Validierungsregeln (Host)
|
||||
|
||||
Beim Lesen:
|
||||
|
||||
1. Prüfen, ob Datei mindestens 7 Byte hat.
|
||||
2. Letzte 6 Byte prüfen: `footer_len_le16` + `TAG!`.
|
||||
3. `footer_len` gegen Dateigröße validieren (`6 <= footer_len <= file_size`).
|
||||
4. `tag_version` an Position `file_size - 6 - 1` lesen und validieren.
|
||||
5. Im Metadatenbereich TLV-Einträge lesen, bis Ende erreicht.
|
||||
6. Für bekannte Typen feste Längen prüfen (`CRC32_RAW=4`, `FILE_FORMAT=5`).
|
||||
7. Unbekannte Typen über `len` überspringen.
|
||||
|
||||
Beim Schreiben:
|
||||
|
||||
1. Vorhandene Tags entfernen/ersetzen (audio-Ende bestimmen).
|
||||
2. Neue TLV-Metadaten schreiben.
|
||||
3. `tag_version_u8` schreiben (`0x01`).
|
||||
4. `footer_len_le16` schreiben (inkl. 1+2+4).
|
||||
5. `TAG!` schreiben.
|
||||
5. Datei auf neue Länge truncaten.
|
||||
|
||||
## 8) Beispiel (hex)
|
||||
|
||||
Beispiel mit:
|
||||
|
||||
- DESCRIPTION = "Kick"
|
||||
- AUTHOR = "Edi"
|
||||
- CRC32_RAW = `0x12345678`
|
||||
|
||||
TLV-Daten:
|
||||
|
||||
- `00 04 00 4B 69 63 6B`
|
||||
- `01 03 00 45 64 69`
|
||||
- `10 04 00 78 56 34 12`
|
||||
|
||||
`metadata_len = 7 + 6 + 7 = 20 (0x0014)`
|
||||
|
||||
`footer_len = 20 + 1 + 2 + 4 = 27 (0x001B)`
|
||||
|
||||
Footer-Ende:
|
||||
|
||||
- `01 1B 00 54 41 47 21`
|
||||
|
||||
## 9) Hinweis zur aktuellen Firmware
|
||||
|
||||
Die Firmware verarbeitet Tag-Payload direkt binär (Chunk-Streaming über das Protokoll). Das dateiinterne Format entspricht direkt diesem Dokument.
|
||||
**3. Footer:**
|
||||
* Total Size: `2D 00` (45 Bytes = 12 Bytes Audio-TLV + 13 Bytes JSON-TLV + 12 Bytes Padding/Zusatz + 8 Bytes Footer) -> *Hinweis: Size ist in diesem Konstrukt abhängig vom genauen Payload.*
|
||||
* Version: `01 00`
|
||||
* Magic: `54 41 47 21` (`TAG!`)
|
||||
@@ -1,6 +1,6 @@
|
||||
VERSION_MAJOR = 0
|
||||
VERSION_MINOR = 2
|
||||
PATCHLEVEL = 19
|
||||
VERSION_MINOR = 3
|
||||
PATCHLEVEL = 5
|
||||
VERSION_TWEAK = 0
|
||||
#if (IS_ENABLED(CONFIG_LOG))
|
||||
EXTRAVERSION = debug
|
||||
|
||||
@@ -3,11 +3,44 @@
|
||||
|
||||
#include <zephyr/fs/fs.h>
|
||||
|
||||
#define MAX_PATH_LEN 32U
|
||||
|
||||
typedef struct slot_info_t {
|
||||
size_t start_addr;
|
||||
size_t size;
|
||||
} slot_info_t;
|
||||
|
||||
typedef enum {
|
||||
FS_MSG_START,
|
||||
FS_MSG_CHUNK,
|
||||
FS_MSG_EOF,
|
||||
FS_MSG_ABORT
|
||||
} fs_msg_type_t;
|
||||
|
||||
typedef struct {
|
||||
fs_msg_type_t type;
|
||||
|
||||
/* Die Union spart RAM, da Start- und Chunk-Parameter
|
||||
nie gleichzeitig im selben Message-Paket benötigt werden. */
|
||||
union {
|
||||
/* Payload für FS_MSG_START */
|
||||
struct {
|
||||
/* Der String wird sicher in die Queue kopiert */
|
||||
char filename[MAX_PATH_LEN];
|
||||
uint32_t expected_size;
|
||||
uint32_t start_position;
|
||||
} start;
|
||||
|
||||
/* Payload für FS_MSG_CHUNK */
|
||||
struct {
|
||||
void *slab_ptr;
|
||||
uint32_t chunk_size;
|
||||
} chunk;
|
||||
};
|
||||
} fs_msg_t;
|
||||
|
||||
extern struct k_msgq fs_msgq;
|
||||
|
||||
/**
|
||||
* @brief Initializes the filesystem by mounting it
|
||||
*/
|
||||
@@ -100,6 +133,21 @@ int fs_pm_mkdir(const char *path);
|
||||
*/
|
||||
int fs_pm_rename(const char *old_path, const char *new_path);
|
||||
|
||||
/**
|
||||
* @brief Recursively creates directories for the given path, ensuring the flash is active during the operation
|
||||
* @param path Path to the directory to create (can include multiple levels, e.g. "/dir1/dir2/dir3")
|
||||
* @return 0 on success, negative error code on failure
|
||||
*/
|
||||
int fs_pm_mkdir_recursive(char *path);
|
||||
|
||||
/**
|
||||
* @brief Recursively removes a directory and all its contents, ensuring the flash is active during the operation
|
||||
* @param path Path to the directory to remove
|
||||
* @param max_len Maximum length of the path buffer
|
||||
* @return 0 on success, negative error code on failure
|
||||
*/
|
||||
int fs_pm_rm_recursive(char *path, size_t max_len);
|
||||
|
||||
/**
|
||||
* @brief Gets the length of the audio data in a file, accounting for any metadata tags
|
||||
* @param fp Pointer to an open fs_file_t structure representing the audio file
|
||||
@@ -136,29 +184,15 @@ int fs_tag_open_read(struct fs_file_t *fp, uint8_t *version, size_t *payload_len
|
||||
ssize_t fs_tag_read_chunk(struct fs_file_t *fp, void *buffer, size_t len);
|
||||
|
||||
/**
|
||||
* @brief Positions file pointer for tag payload overwrite at end of audio data.
|
||||
* @param fp Pointer to an open fs_file_t structure representing the audio file
|
||||
* @return 0 on success, negative error code on failure
|
||||
* @brief Setzt die Synchronisation für einen neuen Dateitransfer zurück.
|
||||
*/
|
||||
int fs_tag_open_write(struct fs_file_t *fp);
|
||||
void fs_reset_transfer_sync(void);
|
||||
|
||||
/**
|
||||
* @brief Writes a raw tag payload chunk.
|
||||
* @param fp Pointer to an open fs_file_t positioned for tag payload write
|
||||
* @param buffer Source buffer
|
||||
* @param len Number of bytes to write
|
||||
* @return Number of bytes written, negative error code on failure
|
||||
* @brief Blockiert den aufrufenden Thread, bis der FS-Thread den Transfer
|
||||
* (EOF oder ABORT) vollständig auf dem Flash abgeschlossen hat.
|
||||
*/
|
||||
ssize_t fs_tag_write_chunk(struct fs_file_t *fp, const void *buffer, size_t len);
|
||||
|
||||
/**
|
||||
* @brief Finalizes tags by appending version + footer and truncating file.
|
||||
* @param fp Pointer to an open fs_file_t structure representing the audio file
|
||||
* @param version Tag format version to write
|
||||
* @param payload_len Tag payload length in bytes
|
||||
* @return 0 on success, negative error code on failure
|
||||
*/
|
||||
int fs_tag_finish_write(struct fs_file_t *fp, uint8_t version, size_t payload_len);
|
||||
void fs_wait_for_transfer_complete(void);
|
||||
|
||||
/**
|
||||
* @brief Retrieves information about the firmware slot, such as start address and size
|
||||
@@ -182,4 +216,21 @@ int flash_init_firmware_upload(void);
|
||||
*/
|
||||
int flash_write_firmware_block(const uint8_t *buffer, size_t length, bool is_last_block);
|
||||
|
||||
/**
|
||||
* @brief Gets the page size of the internal flash, which is needed for proper write operations
|
||||
* @return Page size in bytes
|
||||
*/
|
||||
size_t fs_get_internal_flash_page_size(void);
|
||||
|
||||
/**
|
||||
* @brief Gets the size of the firmware slot, which is needed for proper write operations
|
||||
* @return Size in bytes
|
||||
*/
|
||||
size_t fs_get_fw_slot_size(void);
|
||||
|
||||
/**
|
||||
* @brief Gets the page size of the external flash, which is needed for proper write operations
|
||||
* @return Page size in bytes
|
||||
*/
|
||||
size_t fs_get_external_flash_page_size(void);
|
||||
#endif // FS_H
|
||||
@@ -8,44 +8,50 @@
|
||||
|
||||
typedef enum {
|
||||
PS_WAIT_SYNC = 0,
|
||||
PS_READ_HEADER,
|
||||
PS_READ_PAYLOAD,
|
||||
PS_READ_PAYLOAD_CRC,
|
||||
PS_READ_FRAME_TYPE,
|
||||
PS_READ_REQ,
|
||||
PS_READ_REQ_DATA,
|
||||
} protocol_state_t;
|
||||
|
||||
typedef enum {
|
||||
CMD_INVALID = 0,
|
||||
CMD_GET_PROTOCOL_VERSION = 0x00,
|
||||
CMD_GET_FIRMWARE_STATUS = 0x01,
|
||||
CMD_GET_FLASH_STATUS = 0x02,
|
||||
CMD_CONFIRM_FIRMWARE = 0x03,
|
||||
CMD_REBOOT = 0x04,
|
||||
|
||||
CMD_LIST_DIR = 0x10,
|
||||
CMD_CHECK_FILE_CRC = 0x11,
|
||||
CMD_MKDIR = 0x12,
|
||||
CMD_RM = 0x13,
|
||||
CMD_PUT_FILE_START = 0x14,
|
||||
CMD_PUT_FILE_CHUNK = 0x15,
|
||||
CMD_PUT_FILE_END = 0x16,
|
||||
CMD_PUT_FW_START = 0x17,
|
||||
CMD_STAT = 0x18,
|
||||
CMD_RENAME = 0x19,
|
||||
CMD_RM_R = 0x1A,
|
||||
CMD_GET_FILE = 0x1B,
|
||||
CMD_GET_TAG_BLOB = 0x20,
|
||||
CMD_SET_TAG_BLOB_START = 0x21,
|
||||
CMD_SET_TAG_BLOB_CHUNK = 0x22,
|
||||
CMD_SET_TAG_BLOB_END = 0x23,
|
||||
|
||||
CMD_PUT_FILE = 0x20,
|
||||
CMD_PUT_FW = 0x21,
|
||||
CMD_GET_FILE = 0x22,
|
||||
CMD_PUT_TAGS = 0x24,
|
||||
CMD_GET_TAGS = 0x25,
|
||||
|
||||
CMD_PLAY = 0x30,
|
||||
CMD_STOP = 0x31,
|
||||
|
||||
CMD_SET_SETTING = 0x40,
|
||||
CMD_GET_SETTING = 0x41,
|
||||
} protocol_cmd_t;
|
||||
|
||||
typedef enum {
|
||||
FRAME_REQ = 0x01,
|
||||
FRAME_REQ_DATA = 0x02,
|
||||
FRAME_RESP_ACK = 0x10,
|
||||
FRAME_RESP_DATA = 0x11,
|
||||
FRAME_RESP_STREAM_START = 0x12,
|
||||
FRAME_RESP_STREAM_CHUNK = 0x13,
|
||||
// FRAME_RESP_STREAM_CHUNK = 0x13,
|
||||
FRAME_RESP_STREAM_END = 0x14,
|
||||
FRAME_RESP_ERROR = 0x7F,
|
||||
FRAME_RESP_LIST_START = 0x15,
|
||||
FRAME_RESP_LIST_CHUNK = 0x16,
|
||||
FRAME_RESP_LIST_END = 0x17,
|
||||
FRAME_RESP_ERROR = 0xFF,
|
||||
} protocol_frame_type_t;
|
||||
|
||||
typedef enum {
|
||||
@@ -72,6 +78,13 @@ typedef enum {
|
||||
P_ERR_INTERNAL = 0x32,
|
||||
} protocol_error_t;
|
||||
|
||||
typedef enum
|
||||
{
|
||||
FW_STATUS_CONFIRMED = 0x00,
|
||||
FW_STATUS_PENDING = 0x01,
|
||||
FW_STATUS_TESTING = 0x02,
|
||||
} firmware_status_t;
|
||||
|
||||
void protocol_thread_entry(void *p1, void *p2, void *p3);
|
||||
|
||||
#endif // PROTOCOL_H
|
||||
28
firmware/include/settings.h
Normal file
28
firmware/include/settings.h
Normal file
@@ -0,0 +1,28 @@
|
||||
#ifndef BUZZER_SETTINGS_H
|
||||
#define BUZZER_SETTINGS_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
/* Struktur für den direkten Lesezugriff aus dem RAM (Zero-Latency) */
|
||||
typedef struct {
|
||||
uint8_t audio_vol; /* 0..100 */
|
||||
bool play_norepeat; /* true = 1, false = 0 */
|
||||
uint32_t storage_interval_s; /* 0..7200 Sekunden */
|
||||
} app_settings_t;
|
||||
|
||||
/* Globale Instanz für den direkten Lesezugriff */
|
||||
extern app_settings_t app_settings;
|
||||
|
||||
/* Initialisiert das Settings-Subsystem, NVS und lädt die gespeicherten Werte */
|
||||
int app_settings_init(void);
|
||||
|
||||
/* Setter: Aktualisieren den RAM-Wert und starten/verlängern den Speichern-Timer */
|
||||
void app_settings_set_audio_vol(uint8_t vol);
|
||||
void app_settings_set_play_norepeat(bool norepeat);
|
||||
void app_settings_set_storage_interval(uint32_t interval_s);
|
||||
|
||||
/* Forciert sofortiges Speichern aller anstehenden Werte (Aufruf z.B. vor CMD_REBOOT) */
|
||||
void app_settings_save_pending_now(void);
|
||||
|
||||
#endif /* BUZZER_SETTINGS_H */
|
||||
8
firmware/include/uart.h
Normal file
8
firmware/include/uart.h
Normal file
@@ -0,0 +1,8 @@
|
||||
#ifndef _UART_H_
|
||||
#define _UART_H_
|
||||
|
||||
int uart_init(void);
|
||||
int uart_write(const uint8_t *data, size_t len, k_timeout_t timeout);
|
||||
int uart_write_string(const char *str, k_timeout_t timeout);
|
||||
int uart_read(uint8_t *buffer, size_t max_len, k_timeout_t timeout);
|
||||
#endif /* _UART_H_ */
|
||||
8
firmware/include/usb.h
Normal file
8
firmware/include/usb.h
Normal file
@@ -0,0 +1,8 @@
|
||||
#ifndef USB_H_
|
||||
#define USB_H_
|
||||
|
||||
int usb_init(void);
|
||||
void usb_wait_for_dtr(void);
|
||||
bool usb_dtr_active(void);
|
||||
|
||||
#endif /* USB_H_ */
|
||||
@@ -3,7 +3,7 @@ mcuboot:
|
||||
size: 0xC000
|
||||
region: flash_primary
|
||||
|
||||
# Primary Slot: Start bleibt 0xC000, Größe jetzt 200KB (0x32000)
|
||||
# Primary Slot: Start bleibt 0xC000, Größe 200KB (0x32000)
|
||||
mcuboot_primary:
|
||||
address: 0xC000
|
||||
size: 0x32000
|
||||
@@ -26,7 +26,13 @@ mcuboot_secondary:
|
||||
size: 0x32000
|
||||
region: flash_primary
|
||||
|
||||
# External Flash bleibt unverändert
|
||||
# NVS storage am Ende des Flashs, 16KB (0x4000)
|
||||
settings_storage:
|
||||
address: 0xFC000
|
||||
size: 0x4000
|
||||
region: flash_primary
|
||||
|
||||
# External Flash
|
||||
littlefs_storage:
|
||||
address: 0x0
|
||||
size: 0x800000
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# --- GPIO & Logging ---
|
||||
CONFIG_GPIO=y
|
||||
CONFIG_LOG=y
|
||||
CONFIG_POLL=y
|
||||
CONFIG_POLL=n
|
||||
|
||||
# --- Power Management (Fix für HAS_PM & Policy) ---
|
||||
# CONFIG_PM=y
|
||||
@@ -13,25 +13,25 @@ CONFIG_FLASH_MAP=y
|
||||
CONFIG_FILE_SYSTEM=y
|
||||
CONFIG_FILE_SYSTEM_LITTLEFS=y
|
||||
CONFIG_FILE_SYSTEM_MKFS=y
|
||||
CONFIG_CRC=y
|
||||
CONFIG_FS_LITTLEFS_READ_SIZE=64
|
||||
CONFIG_FS_LITTLEFS_READ_SIZE=256
|
||||
CONFIG_FS_LITTLEFS_PROG_SIZE=256
|
||||
CONFIG_FS_LITTLEFS_CACHE_SIZE=512
|
||||
CONFIG_FS_LITTLEFS_LOOKAHEAD_SIZE=128
|
||||
CONFIG_FS_LITTLEFS_CACHE_SIZE=4096
|
||||
CONFIG_FS_LITTLEFS_LOOKAHEAD_SIZE=256
|
||||
CONFIG_FS_LITTLEFS_BLOCK_CYCLES=512
|
||||
CONFIG_MAIN_STACK_SIZE=2048
|
||||
|
||||
# --- NVS & Settings (für die Speicherung von Konfigurationen) ---
|
||||
CONFIG_NVS=y
|
||||
CONFIG_SETTINGS=y
|
||||
CONFIG_SETTINGS_NVS=y
|
||||
|
||||
# --- USB Device & CDC ACM ---
|
||||
CONFIG_USB_DEVICE_STACK=y
|
||||
CONFIG_DEPRECATION_TEST=y
|
||||
CONFIG_USB_DEVICE_MANUFACTURER="Eduard Iten"
|
||||
CONFIG_USB_DEVICE_PRODUCT="Edi's Buzzer"
|
||||
CONFIG_USB_DEVICE_PID=0x0001
|
||||
CONFIG_USB_DRIVER_LOG_LEVEL_ERR=y
|
||||
CONFIG_USB_DEVICE_LOG_LEVEL_ERR=y
|
||||
CONFIG_USB_DEVICE_LOG_LEVEL_OFF=y
|
||||
CONFIG_USB_DEVICE_INITIALIZE_AT_BOOT=n
|
||||
CONFIG_USB_DEVICE_STACK_NEXT=n
|
||||
CONFIG_USB_DEVICE_STACK_NEXT=y
|
||||
CONFIG_USBD_CDC_ACM_CLASS=y
|
||||
CONFIG_CDC_ACM_SERIAL_INITIALIZE_AT_BOOT=n
|
||||
CONFIG_USBD_LOG_LEVEL_ERR=y
|
||||
CONFIG_UDC_DRIVER_LOG_LEVEL_ERR=y
|
||||
CONFIG_USBD_CDC_ACM_LOG_LEVEL_OFF=y
|
||||
|
||||
# --- UART (für USB-CDC) ---
|
||||
CONFIG_SERIAL=y
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include <audio.h>
|
||||
#include <fs.h>
|
||||
#include <io.h>
|
||||
#include <settings.h>
|
||||
|
||||
#define AUDIO_THREAD_STACK_SIZE 2048
|
||||
#define AUDIO_THREAD_PRIORITY 5
|
||||
@@ -47,7 +48,6 @@ K_SEM_DEFINE(audio_ready_sem, 0, 1);
|
||||
static const struct device *const i2s_dev = DEVICE_DT_GET(I2S_NODE);
|
||||
static const struct gpio_dt_spec amp_en_dev = GPIO_DT_SPEC_GET(AUDIO_AMP_ENABLE_NODE, gpios);
|
||||
|
||||
static volatile int current_volume = 8;
|
||||
static volatile bool abort_playback = false;
|
||||
static char next_random_filename[64] = {0};
|
||||
|
||||
@@ -57,6 +57,8 @@ static char cached_404_path[] = "/lfs/sys/404";
|
||||
static struct k_mutex i2s_lock;
|
||||
static struct k_work audio_stop_work;
|
||||
|
||||
static uint32_t last_played_index = 0xFFFFFFFF;
|
||||
|
||||
static void audio_stop_work_handler(struct k_work *work)
|
||||
{
|
||||
ARG_UNUSED(work);
|
||||
@@ -89,6 +91,52 @@ void i2s_resume(void)
|
||||
k_mutex_unlock(&i2s_lock);
|
||||
}
|
||||
|
||||
int get_random_file(char *out_filename, size_t max_len)
|
||||
{
|
||||
if (audio_file_count == 0)
|
||||
{
|
||||
/* Fallback auf System-Sound, wenn Ordner leer */
|
||||
strncpy(out_filename, cached_404_path, max_len);
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint32_t target_index;
|
||||
|
||||
/* Random-Index generieren mit optionalem No-Repeat-Schutz */
|
||||
if (app_settings.play_norepeat && audio_file_count > 1) {
|
||||
do {
|
||||
target_index = k_cycle_get_32() % audio_file_count;
|
||||
} while (target_index == last_played_index);
|
||||
} else {
|
||||
target_index = k_cycle_get_32() % audio_file_count;
|
||||
}
|
||||
|
||||
last_played_index = target_index;
|
||||
|
||||
struct fs_dir_t dirp;
|
||||
struct fs_dirent entry;
|
||||
uint32_t current_index = 0;
|
||||
|
||||
fs_dir_t_init(&dirp);
|
||||
if (fs_pm_opendir(&dirp, AUDIO_PATH) < 0)
|
||||
return -ENOENT;
|
||||
|
||||
while (fs_readdir(&dirp, &entry) == 0 && entry.name[0] != '\0')
|
||||
{
|
||||
if (entry.type == FS_DIR_ENTRY_FILE)
|
||||
{
|
||||
if (current_index == target_index)
|
||||
{
|
||||
snprintf(out_filename, max_len, "%s/%s", AUDIO_PATH, entry.name);
|
||||
break;
|
||||
}
|
||||
current_index++;
|
||||
}
|
||||
}
|
||||
fs_pm_closedir(&dirp);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void audio_refresh_file_count(void)
|
||||
{
|
||||
static struct fs_dir_t dirp;
|
||||
@@ -112,6 +160,7 @@ void audio_refresh_file_count(void)
|
||||
fs_pm_closedir(&dirp);
|
||||
audio_file_count = count;
|
||||
LOG_INF("Audio cache refreshed: %u files found in %s", count, AUDIO_PATH);
|
||||
get_random_file(next_random_filename, sizeof(next_random_filename));
|
||||
}
|
||||
|
||||
static void wait_for_i2s_drain(void)
|
||||
@@ -130,40 +179,6 @@ static void wait_for_i2s_drain(void)
|
||||
}
|
||||
}
|
||||
|
||||
int get_random_file(char *out_filename, size_t max_len)
|
||||
{
|
||||
if (audio_file_count == 0)
|
||||
{
|
||||
/* Fallback auf System-Sound, wenn Ordner leer */
|
||||
strncpy(out_filename, cached_404_path, max_len);
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct fs_dir_t dirp;
|
||||
struct fs_dirent entry;
|
||||
uint32_t target_index = k_cycle_get_32() % audio_file_count;
|
||||
uint32_t current_index = 0;
|
||||
|
||||
fs_dir_t_init(&dirp);
|
||||
if (fs_pm_opendir(&dirp, AUDIO_PATH) < 0)
|
||||
return -ENOENT;
|
||||
|
||||
while (fs_readdir(&dirp, &entry) == 0 && entry.name[0] != '\0')
|
||||
{
|
||||
if (entry.type == FS_DIR_ENTRY_FILE)
|
||||
{
|
||||
if (current_index == target_index)
|
||||
{
|
||||
snprintf(out_filename, max_len, "%s/%s", AUDIO_PATH, entry.name);
|
||||
break;
|
||||
}
|
||||
current_index++;
|
||||
}
|
||||
}
|
||||
fs_pm_closedir(&dirp);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void audio_system_ready(void)
|
||||
{
|
||||
k_sem_give(&audio_ready_sem);
|
||||
@@ -250,8 +265,8 @@ void audio_thread(void *arg1, void *arg2, void *arg3)
|
||||
|
||||
bool trigger_started = false;
|
||||
int queued_blocks = 0;
|
||||
uint8_t factor = MIN(255, current_volume * 0xFF / 100);
|
||||
LOG_INF("Volume factor: %u (for volume %d%%)", factor, current_volume);
|
||||
uint8_t factor = MIN(255, app_settings.audio_vol * 0xFF / 100);
|
||||
LOG_INF("Volume factor: %u (for volume %d%%)", factor, app_settings.audio_vol);
|
||||
|
||||
while (!abort_playback)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#include <zephyr/fs/littlefs.h>
|
||||
#include <zephyr/sys/byteorder.h>
|
||||
#include <zephyr/drivers/flash.h>
|
||||
#include <zephyr/storage/flash_map.h>
|
||||
#include <zephyr/dfu/flash_img.h>
|
||||
#include <zephyr/dfu/mcuboot.h>
|
||||
#include <zephyr/pm/device.h>
|
||||
@@ -8,18 +10,23 @@
|
||||
|
||||
LOG_MODULE_REGISTER(buzz_fs, LOG_LEVEL_INF);
|
||||
|
||||
#define FS_THREAD_STACK_SIZE 2048
|
||||
#define FS_THREAD_PRIORITY 6
|
||||
|
||||
#define FS_MSGQ_MAX_ITEMS 4
|
||||
#define FS_SLAB_BUF_SIZE 4096
|
||||
#define TAG_FORMAT_VERSION 0x0001
|
||||
#define TAG_MAGIC "TAG!"
|
||||
#define TAG_MAGIC_LEN 4U
|
||||
#define TAG_LEN_FIELD_LEN 2U
|
||||
#define TAG_VERSION_LEN 1U
|
||||
#define TAG_FOOTER_V1_LEN (TAG_VERSION_LEN + TAG_LEN_FIELD_LEN + TAG_MAGIC_LEN)
|
||||
#define TAG_FORMAT_VERSION 0x01
|
||||
|
||||
#define STORAGE_PARTITION_ID FIXED_PARTITION_ID(littlefs_storage)
|
||||
#define SLOT1_ID FIXED_PARTITION_ID(slot1_partition)
|
||||
|
||||
FS_LITTLEFS_DECLARE_DEFAULT_CONFIG(fs_storage_data);
|
||||
|
||||
K_MEM_SLAB_DEFINE(file_buffer_slab, FS_SLAB_BUF_SIZE, FS_MSGQ_MAX_ITEMS, 4);
|
||||
K_MSGQ_DEFINE(fs_msgq, sizeof(fs_msg_t), FS_MSGQ_MAX_ITEMS, 4);
|
||||
K_SEM_DEFINE(fs_transfer_done_sem, 0, 1);
|
||||
|
||||
#define QSPI_FLASH_NODE DT_ALIAS(qspi_flash)
|
||||
#if !DT_NODE_EXISTS(QSPI_FLASH_NODE)
|
||||
#error "QSPI Flash alias not defined in devicetree"
|
||||
@@ -32,6 +39,8 @@ static struct k_mutex flash_pm_lock;
|
||||
static struct slot_info_t slot1_info;
|
||||
static struct flash_img_context flash_ctx;
|
||||
|
||||
extern struct k_mem_slab file_buffer_slab;
|
||||
|
||||
static struct fs_mount_t fs_storage_mnt = {
|
||||
.type = FS_LITTLEFS,
|
||||
.fs_data = &fs_storage_data,
|
||||
@@ -39,6 +48,17 @@ static struct fs_mount_t fs_storage_mnt = {
|
||||
.mnt_point = "/lfs",
|
||||
};
|
||||
|
||||
typedef enum {
|
||||
FS_STATE_IDLE,
|
||||
FS_STATE_RECEIVING
|
||||
} fs_thread_state_t;
|
||||
|
||||
typedef struct __attribute__((packed)) {
|
||||
uint16_t total_size;
|
||||
uint16_t version;
|
||||
uint8_t magic[4];
|
||||
} tag_footer_t;
|
||||
|
||||
int fs_init(void) {
|
||||
int rc = fs_mount(&fs_storage_mnt);
|
||||
if (rc < 0) {
|
||||
@@ -120,10 +140,7 @@ int fs_pm_close(struct fs_file_t *file)
|
||||
{
|
||||
LOG_DBG("PM Closing file");
|
||||
int rc = fs_close(file);
|
||||
if (rc == 0)
|
||||
{
|
||||
fs_pm_flash_suspend();
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
@@ -143,10 +160,7 @@ int fs_pm_closedir(struct fs_dir_t *dirp)
|
||||
{
|
||||
LOG_DBG("PM Closing directory");
|
||||
int rc = fs_closedir(dirp);
|
||||
if (rc == 0)
|
||||
{
|
||||
fs_pm_flash_suspend();
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
@@ -195,11 +209,159 @@ int fs_pm_rename(const char *old_path, const char *new_path)
|
||||
return rc;
|
||||
}
|
||||
|
||||
int fs_pm_rm_recursive(char *path_buf, size_t max_len)
|
||||
{
|
||||
struct fs_dirent entry;
|
||||
struct fs_dir_t dir;
|
||||
int rc;
|
||||
|
||||
fs_pm_flash_resume();
|
||||
|
||||
/* 1. Stat prüfen: Ist es eine Datei? */
|
||||
rc = fs_stat(path_buf, &entry);
|
||||
if (rc != 0) {
|
||||
fs_pm_flash_suspend();
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* Wenn es eine Datei ist, direkt löschen und beenden */
|
||||
if (entry.type == FS_DIR_ENTRY_FILE) {
|
||||
rc = fs_unlink(path_buf);
|
||||
fs_pm_flash_suspend();
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* 2. Es ist ein Verzeichnis. Schleife bis es leer ist. */
|
||||
size_t orig_len = strlen(path_buf);
|
||||
|
||||
while (1) {
|
||||
fs_dir_t_init(&dir);
|
||||
rc = fs_opendir(&dir, path_buf);
|
||||
if (rc != 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
bool found_something = false;
|
||||
|
||||
/* Genau EINEN löschbaren Eintrag suchen */
|
||||
while (1) {
|
||||
rc = fs_readdir(&dir, &entry);
|
||||
if (rc != 0 || entry.name[0] == '\0') {
|
||||
break; /* Ende oder Fehler */
|
||||
}
|
||||
if (strcmp(entry.name, ".") == 0 || strcmp(entry.name, "..") == 0) {
|
||||
continue; /* Ignorieren */
|
||||
}
|
||||
|
||||
found_something = true;
|
||||
break; /* Treffer! Schleife abbrechen. */
|
||||
}
|
||||
|
||||
/* WICHTIG: Das Verzeichnis SOFORT schließen, BEVOR wir rekurieren!
|
||||
* Damit geben wir das File-Handle (NUM_DIRS) an Zephyr zurück. */
|
||||
fs_closedir(&dir);
|
||||
|
||||
if (!found_something || rc != 0) {
|
||||
break; /* Verzeichnis ist nun restlos leer */
|
||||
}
|
||||
|
||||
size_t name_len = strlen(entry.name);
|
||||
if (orig_len + 1 + name_len >= max_len) {
|
||||
rc = -ENAMETOOLONG;
|
||||
break;
|
||||
}
|
||||
|
||||
/* Pfad für das gefundene Kindelement bauen */
|
||||
path_buf[orig_len] = '/';
|
||||
strcpy(&path_buf[orig_len + 1], entry.name);
|
||||
|
||||
/* Rekursiver Aufruf für das Kind */
|
||||
rc = fs_pm_rm_recursive(path_buf, max_len);
|
||||
|
||||
/* Puffer sofort wieder auf unser Verzeichnis zurückschneiden */
|
||||
path_buf[orig_len] = '\0';
|
||||
|
||||
if (rc != 0) {
|
||||
break; /* Abbruch, falls beim Löschen des Kindes ein Fehler auftrat */
|
||||
}
|
||||
}
|
||||
|
||||
/* 3. Das nun restlos leere Verzeichnis selbst löschen */
|
||||
if (rc == 0) {
|
||||
rc = fs_unlink(path_buf);
|
||||
}
|
||||
|
||||
fs_pm_flash_suspend();
|
||||
return rc;
|
||||
}
|
||||
|
||||
int fs_pm_mkdir_recursive(char *path)
|
||||
{
|
||||
int rc = 0;
|
||||
struct fs_dirent entry;
|
||||
char *p = path;
|
||||
|
||||
/* Führenden Slash überspringen, falls vorhanden (z. B. bei "/lfs") */
|
||||
if (*p == '/') {
|
||||
p++;
|
||||
}
|
||||
|
||||
/* Flash für den gesamten Durchlauf aktivieren */
|
||||
fs_pm_flash_resume();
|
||||
|
||||
while (*p != '\0') {
|
||||
if (*p == '/') {
|
||||
*p = '\0'; /* String temporär am aktuellen Slash terminieren */
|
||||
|
||||
/* Prüfen, ob dieser Pfadabschnitt bereits existiert */
|
||||
rc = fs_stat(path, &entry);
|
||||
|
||||
if (rc == -ENOENT) {
|
||||
/* Existiert nicht -> anlegen */
|
||||
rc = fs_mkdir(path);
|
||||
if (rc != 0) {
|
||||
*p = '/'; /* Bei Fehler Slash wiederherstellen und abbrechen */
|
||||
break;
|
||||
}
|
||||
} else if (rc == 0) {
|
||||
/* Existiert -> prüfen, ob es ein Verzeichnis ist */
|
||||
if (entry.type != FS_DIR_ENTRY_DIR) {
|
||||
rc = -ENOTDIR;
|
||||
*p = '/';
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
/* Anderer Dateisystemfehler */
|
||||
*p = '/';
|
||||
break;
|
||||
}
|
||||
|
||||
*p = '/'; /* Slash für den nächsten Schleifendurchlauf wiederherstellen */
|
||||
}
|
||||
p++;
|
||||
}
|
||||
|
||||
/* Letztes Element verarbeiten, falls der Pfad nicht mit '/' endet */
|
||||
if (rc == 0 && p > path && *(p - 1) != '/') {
|
||||
rc = fs_stat(path, &entry);
|
||||
if (rc == -ENOENT) {
|
||||
rc = fs_mkdir(path);
|
||||
} else if (rc == 0) {
|
||||
if (entry.type != FS_DIR_ENTRY_DIR) {
|
||||
rc = -ENOTDIR;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Flash am Ende wieder in den Suspend schicken */
|
||||
fs_pm_flash_suspend();
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int fs_get_tag_bounds(struct fs_file_t *fp, off_t file_size,
|
||||
size_t *audio_limit, size_t *payload_len, bool *has_tag)
|
||||
{
|
||||
uint8_t footer[6];
|
||||
uint16_t tag_len;
|
||||
tag_footer_t footer;
|
||||
|
||||
if (audio_limit == NULL || payload_len == NULL || has_tag == NULL) {
|
||||
return -EINVAL;
|
||||
@@ -209,42 +371,41 @@ static int fs_get_tag_bounds(struct fs_file_t *fp, off_t file_size,
|
||||
*audio_limit = (size_t)file_size;
|
||||
*payload_len = 0U;
|
||||
|
||||
if (file_size < (off_t)TAG_FOOTER_V1_LEN) {
|
||||
if (file_size < (off_t)sizeof(tag_footer_t)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
fs_seek(fp, -(off_t)(TAG_LEN_FIELD_LEN + TAG_MAGIC_LEN), FS_SEEK_END);
|
||||
if (fs_read(fp, footer, sizeof(footer)) != sizeof(footer)) {
|
||||
/* Den 8-Byte-Footer direkt in das Struct einlesen */
|
||||
fs_seek(fp, -(off_t)sizeof(tag_footer_t), FS_SEEK_END);
|
||||
if (fs_read(fp, &footer, sizeof(tag_footer_t)) != sizeof(tag_footer_t)) {
|
||||
fs_seek(fp, 0, FS_SEEK_SET);
|
||||
return -EIO;
|
||||
}
|
||||
|
||||
if (memcmp(&footer[2], TAG_MAGIC, TAG_MAGIC_LEN) != 0) {
|
||||
/* 1. Signatur prüfen */
|
||||
if (memcmp(footer.magic, TAG_MAGIC, 4) != 0) {
|
||||
fs_seek(fp, 0, FS_SEEK_SET);
|
||||
return 0;
|
||||
}
|
||||
|
||||
tag_len = (uint16_t)footer[0] | ((uint16_t)footer[1] << 8);
|
||||
if (tag_len > (uint16_t)file_size || tag_len < TAG_FOOTER_V1_LEN) {
|
||||
fs_seek(fp, 0, FS_SEEK_SET);
|
||||
return -EBADMSG;
|
||||
}
|
||||
|
||||
uint8_t tag_version = 0;
|
||||
fs_seek(fp, -(off_t)TAG_FOOTER_V1_LEN, FS_SEEK_END);
|
||||
if (fs_read(fp, &tag_version, 1) != 1) {
|
||||
fs_seek(fp, 0, FS_SEEK_SET);
|
||||
return -EIO;
|
||||
}
|
||||
/* 2. Endianness konvertieren */
|
||||
uint16_t tag_version = sys_le16_to_cpu(footer.version);
|
||||
uint16_t tag_len = sys_le16_to_cpu(footer.total_size);
|
||||
|
||||
/* 3. Version und Größe validieren */
|
||||
if (tag_version != TAG_FORMAT_VERSION) {
|
||||
fs_seek(fp, 0, FS_SEEK_SET);
|
||||
return -ENOTSUP;
|
||||
}
|
||||
|
||||
if (tag_len > (uint16_t)file_size || tag_len < sizeof(tag_footer_t)) {
|
||||
fs_seek(fp, 0, FS_SEEK_SET);
|
||||
return -EBADMSG;
|
||||
}
|
||||
|
||||
*has_tag = true;
|
||||
*audio_limit = (size_t)file_size - tag_len;
|
||||
*payload_len = tag_len - TAG_FOOTER_V1_LEN;
|
||||
*payload_len = tag_len - sizeof(tag_footer_t);
|
||||
|
||||
fs_seek(fp, 0, FS_SEEK_SET);
|
||||
return 0;
|
||||
@@ -320,51 +481,6 @@ ssize_t fs_tag_read_chunk(struct fs_file_t *fp, void *buffer, size_t len)
|
||||
return fs_read(fp, buffer, len);
|
||||
}
|
||||
|
||||
int fs_tag_open_write(struct fs_file_t *fp)
|
||||
{
|
||||
ssize_t audio_limit = fs_get_audio_data_len(fp);
|
||||
if (audio_limit < 0) {
|
||||
return (int)audio_limit;
|
||||
}
|
||||
fs_seek(fp, audio_limit, FS_SEEK_SET);
|
||||
return 0;
|
||||
}
|
||||
|
||||
ssize_t fs_tag_write_chunk(struct fs_file_t *fp, const void *buffer, size_t len)
|
||||
{
|
||||
return fs_write(fp, buffer, len);
|
||||
}
|
||||
|
||||
int fs_tag_finish_write(struct fs_file_t *fp, uint8_t version, size_t payload_len)
|
||||
{
|
||||
if (version != TAG_FORMAT_VERSION) {
|
||||
return -ENOTSUP;
|
||||
}
|
||||
|
||||
size_t total_footer_len = payload_len + TAG_FOOTER_V1_LEN;
|
||||
if (total_footer_len > UINT16_MAX) {
|
||||
return -EFBIG;
|
||||
}
|
||||
|
||||
if (fs_write(fp, &version, 1) != 1) {
|
||||
return -EIO;
|
||||
}
|
||||
|
||||
uint8_t len_bytes[2];
|
||||
len_bytes[0] = (uint8_t)(total_footer_len & 0xFFU);
|
||||
len_bytes[1] = (uint8_t)((total_footer_len >> 8) & 0xFFU);
|
||||
if (fs_write(fp, len_bytes, sizeof(len_bytes)) != sizeof(len_bytes)) {
|
||||
return -EIO;
|
||||
}
|
||||
|
||||
if (fs_write(fp, TAG_MAGIC, TAG_MAGIC_LEN) != TAG_MAGIC_LEN) {
|
||||
return -EIO;
|
||||
}
|
||||
|
||||
off_t current_pos = fs_tell(fp);
|
||||
return fs_truncate(fp, current_pos);
|
||||
}
|
||||
|
||||
int flash_get_slot_info(slot_info_t *info) {
|
||||
if (slot1_info.size != 0) {
|
||||
*info = slot1_info;
|
||||
@@ -417,3 +533,187 @@ int flash_write_firmware_block(const uint8_t *buffer, size_t length, bool is_las
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
size_t fs_get_external_flash_page_size(void) {
|
||||
const struct flash_area *fa;
|
||||
const struct device *dev;
|
||||
struct flash_pages_info info;
|
||||
int rc;
|
||||
|
||||
rc = flash_area_open(STORAGE_PARTITION_ID, &fa);
|
||||
if (rc != 0) {
|
||||
LOG_ERR("Failed to open flash area for page size retrieval");
|
||||
return 256; // Fallback to a common page size
|
||||
}
|
||||
|
||||
dev = flash_area_get_device(fa);
|
||||
if (dev == NULL) {
|
||||
flash_area_close(fa);
|
||||
LOG_ERR("Failed to get flash device for page size retrieval");
|
||||
return 256; // Fallback to a common page size
|
||||
}
|
||||
|
||||
rc = flash_get_page_info_by_offs(dev, fa->fa_off, &info);
|
||||
flash_area_close(fa);
|
||||
|
||||
if (rc != 0) {
|
||||
LOG_ERR("Failed to get flash page info: %d", rc);
|
||||
return 256; // Fallback to a common page size
|
||||
}
|
||||
|
||||
return info.size;
|
||||
}
|
||||
|
||||
size_t fs_get_fw_slot_size(void) {
|
||||
const struct flash_area *fa;
|
||||
int rc;
|
||||
|
||||
rc = flash_area_open(SLOT1_ID, &fa);
|
||||
if (rc != 0) {
|
||||
LOG_ERR("Failed to open flash area for slot size retrieval");
|
||||
return 0;
|
||||
}
|
||||
|
||||
size_t slot_size = fa->fa_size;
|
||||
flash_area_close(fa);
|
||||
return slot_size;
|
||||
}
|
||||
|
||||
size_t fs_get_internal_flash_page_size(void) {
|
||||
const struct flash_area *fa;
|
||||
const struct device *dev;
|
||||
struct flash_pages_info info;
|
||||
int rc;
|
||||
|
||||
rc = flash_area_open(SLOT1_ID, &fa);
|
||||
if (rc != 0) {
|
||||
LOG_ERR("Failed to open flash area for page size retrieval");
|
||||
return 256; // Fallback to a common page size
|
||||
}
|
||||
|
||||
dev = flash_area_get_device(fa);
|
||||
if (dev == NULL) {
|
||||
flash_area_close(fa);
|
||||
LOG_ERR("Failed to get flash device for page size retrieval");
|
||||
return 256; // Fallback to a common page size
|
||||
}
|
||||
|
||||
rc = flash_get_page_info_by_offs(dev, fa->fa_off, &info);
|
||||
flash_area_close(fa);
|
||||
|
||||
if (rc != 0) {
|
||||
LOG_ERR("Failed to get flash page info: %d", rc);
|
||||
return 256; // Fallback to a common page size
|
||||
}
|
||||
|
||||
return info.size;
|
||||
}
|
||||
|
||||
void fs_reset_transfer_sync(void)
|
||||
{
|
||||
k_sem_reset(&fs_transfer_done_sem);
|
||||
}
|
||||
|
||||
void fs_wait_for_transfer_complete(void)
|
||||
{
|
||||
k_sem_take(&fs_transfer_done_sem, K_FOREVER);
|
||||
}
|
||||
|
||||
static void fs_thread_entry(void *p1, void *p2, void *p3)
|
||||
{
|
||||
ARG_UNUSED(p1);
|
||||
ARG_UNUSED(p2);
|
||||
ARG_UNUSED(p3);
|
||||
|
||||
LOG_INF("Filesystem thread started");
|
||||
fs_thread_state_t state = FS_STATE_IDLE;
|
||||
fs_msg_t msg;
|
||||
struct fs_file_t current_file;
|
||||
fs_file_t_init(¤t_file);
|
||||
char current_filename[MAX_PATH_LEN] = {0};
|
||||
|
||||
while (1)
|
||||
{
|
||||
k_timeout_t wait_time = (state == FS_STATE_IDLE) ? K_FOREVER : K_SECONDS(1);
|
||||
int rc = k_msgq_get(&fs_msgq, &msg, wait_time);
|
||||
|
||||
if (rc == -EAGAIN)
|
||||
{
|
||||
if (state == FS_STATE_RECEIVING)
|
||||
{
|
||||
LOG_WRN("FS Transfer Timeout. Aborting and dropping file.");
|
||||
fs_pm_close(¤t_file);
|
||||
fs_pm_unlink(current_filename);
|
||||
state = FS_STATE_IDLE;
|
||||
k_sem_give(&fs_transfer_done_sem);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (state)
|
||||
{
|
||||
case FS_STATE_IDLE:
|
||||
if (msg.type == FS_MSG_START)
|
||||
{
|
||||
strncpy(current_filename, msg.start.filename, MAX_PATH_LEN - 1);
|
||||
current_filename[MAX_PATH_LEN - 1] = '\0';
|
||||
|
||||
/* Bei Position 0 (Neuer Datei-Upload) die alte Datei restlos löschen */
|
||||
if (msg.start.start_position == 0) {
|
||||
fs_pm_unlink(current_filename);
|
||||
}
|
||||
|
||||
rc = fs_pm_open(¤t_file, current_filename, FS_O_CREATE | FS_O_WRITE);
|
||||
if (rc == 0) {
|
||||
if (msg.start.start_position > 0) {
|
||||
fs_seek(¤t_file, msg.start.start_position, FS_SEEK_SET);
|
||||
}
|
||||
state = FS_STATE_RECEIVING;
|
||||
} else {
|
||||
LOG_ERR("Failed to open %s: %d", current_filename, rc);
|
||||
}
|
||||
}
|
||||
else if (msg.type == FS_MSG_CHUNK)
|
||||
{
|
||||
/* Chunks im IDLE-Status (z.B. nach Fehler) direkt verwerfen */
|
||||
if (msg.chunk.slab_ptr != NULL)
|
||||
{
|
||||
k_mem_slab_free(&file_buffer_slab, msg.chunk.slab_ptr);
|
||||
}
|
||||
}
|
||||
else if (msg.type == FS_MSG_EOF || msg.type == FS_MSG_ABORT)
|
||||
{
|
||||
/* Verhindert Deadlocks, falls das Öffnen fehlgeschlagen war */
|
||||
k_sem_give(&fs_transfer_done_sem);
|
||||
}
|
||||
break;
|
||||
|
||||
case FS_STATE_RECEIVING:
|
||||
if (msg.type == FS_MSG_CHUNK)
|
||||
{
|
||||
if (msg.chunk.slab_ptr != NULL)
|
||||
{
|
||||
fs_write(¤t_file, msg.chunk.slab_ptr, msg.chunk.chunk_size);
|
||||
k_mem_slab_free(&file_buffer_slab, msg.chunk.slab_ptr);
|
||||
}
|
||||
}
|
||||
else if (msg.type == FS_MSG_EOF)
|
||||
{
|
||||
fs_pm_close(¤t_file);
|
||||
state = FS_STATE_IDLE;
|
||||
k_sem_give(&fs_transfer_done_sem);
|
||||
}
|
||||
else if (msg.type == FS_MSG_ABORT)
|
||||
{
|
||||
fs_pm_close(¤t_file);
|
||||
fs_pm_unlink(current_filename);
|
||||
state = FS_STATE_IDLE;
|
||||
k_sem_give(&fs_transfer_done_sem);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
K_THREAD_DEFINE(fs, FS_THREAD_STACK_SIZE, fs_thread_entry,
|
||||
NULL, NULL, NULL, FS_THREAD_PRIORITY, 0, 0);
|
||||
@@ -15,6 +15,8 @@
|
||||
#include <io.h>
|
||||
#include <usb.h>
|
||||
#include <utils.h>
|
||||
#include <uart.h>
|
||||
#include <settings.h>
|
||||
|
||||
LOG_MODULE_REGISTER(main, LOG_LEVEL_INF);
|
||||
|
||||
@@ -38,6 +40,13 @@ int main(void)
|
||||
|
||||
int rc;
|
||||
|
||||
rc = app_settings_init();
|
||||
if (rc < 0)
|
||||
{
|
||||
LOG_ERR("Settings initialization failed: %d", rc);
|
||||
return rc;
|
||||
}
|
||||
|
||||
rc = fs_init();
|
||||
if (rc < 0)
|
||||
{
|
||||
@@ -52,13 +61,21 @@ int main(void)
|
||||
return rc;
|
||||
}
|
||||
|
||||
rc = usb_cdc_acm_init();
|
||||
rc = usb_init();
|
||||
if (rc < 0)
|
||||
{
|
||||
LOG_ERR("USB initialization failed: %d", rc);
|
||||
return rc;
|
||||
}
|
||||
|
||||
rc = uart_init();
|
||||
if (rc < 0)
|
||||
{
|
||||
LOG_ERR("UART initialization failed: %d", rc);
|
||||
return rc;
|
||||
}
|
||||
|
||||
|
||||
rc = io_init();
|
||||
if (rc < 0)
|
||||
{
|
||||
@@ -81,6 +98,7 @@ int main(void)
|
||||
{
|
||||
LOG_INF("Firmware image already confirmed. No need to confirm again.");
|
||||
}
|
||||
|
||||
while (1)
|
||||
{
|
||||
k_sleep(K_FOREVER);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
1195
firmware/src/protocol_old.c
Normal file
1195
firmware/src/protocol_old.c
Normal file
File diff suppressed because it is too large
Load Diff
166
firmware/src/settings.c
Normal file
166
firmware/src/settings.c
Normal file
@@ -0,0 +1,166 @@
|
||||
#include "settings.h"
|
||||
#include <zephyr/kernel.h>
|
||||
#include <zephyr/settings/settings.h>
|
||||
#include <zephyr/logging/log.h>
|
||||
|
||||
LOG_MODULE_REGISTER(app_settings, LOG_LEVEL_DBG);
|
||||
|
||||
/* Initialisierung mit Standardwerten als Fallback */
|
||||
app_settings_t app_settings = {
|
||||
.audio_vol = 50,
|
||||
.play_norepeat = false,
|
||||
.storage_interval_s = 3600
|
||||
};
|
||||
|
||||
/* Flags zur Markierung ungespeicherter Änderungen */
|
||||
static bool dirty_audio_vol = false;
|
||||
static bool dirty_play_norepeat = false;
|
||||
static bool dirty_storage_interval = false;
|
||||
|
||||
/* Workqueue-Objekt für das asynchrone Speichern */
|
||||
static struct k_work_delayable save_work;
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Lese-Handler für Zephyr (Aufruf beim Booten durch settings_load) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
static int audio_settings_set(const char *name, size_t len, settings_read_cb read_cb, void *cb_arg)
|
||||
{
|
||||
if (settings_name_steq(name, "vol", NULL)) {
|
||||
return read_cb(cb_arg, &app_settings.audio_vol, sizeof(app_settings.audio_vol));
|
||||
}
|
||||
return -ENOENT;
|
||||
}
|
||||
|
||||
static int play_settings_set(const char *name, size_t len, settings_read_cb read_cb, void *cb_arg)
|
||||
{
|
||||
if (settings_name_steq(name, "norepeat", NULL)) {
|
||||
uint8_t val = 0;
|
||||
int rc = read_cb(cb_arg, &val, sizeof(val));
|
||||
if (rc >= 0) {
|
||||
app_settings.play_norepeat = (val > 0);
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
return -ENOENT;
|
||||
}
|
||||
|
||||
static int sys_settings_set(const char *name, size_t len, settings_read_cb read_cb, void *cb_arg)
|
||||
{
|
||||
if (settings_name_steq(name, "storage_interval", NULL)) {
|
||||
return read_cb(cb_arg, &app_settings.storage_interval_s, sizeof(app_settings.storage_interval_s));
|
||||
}
|
||||
return -ENOENT;
|
||||
}
|
||||
|
||||
/* Registrierung der Namespaces für das automatische Laden */
|
||||
SETTINGS_STATIC_HANDLER_DEFINE(audio, "audio", NULL, audio_settings_set, NULL, NULL);
|
||||
SETTINGS_STATIC_HANDLER_DEFINE(play, "play", NULL, play_settings_set, NULL, NULL);
|
||||
SETTINGS_STATIC_HANDLER_DEFINE(sys, "settings", NULL, sys_settings_set, NULL, NULL);
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Schreib-Logik (Asynchron über System Workqueue) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
static void save_work_handler(struct k_work *work)
|
||||
{
|
||||
if (dirty_audio_vol) {
|
||||
settings_save_one("audio/vol", &app_settings.audio_vol, sizeof(app_settings.audio_vol));
|
||||
dirty_audio_vol = false;
|
||||
LOG_DBG("NVS Write: audio/vol = %d", app_settings.audio_vol);
|
||||
}
|
||||
if (dirty_play_norepeat) {
|
||||
uint8_t val = app_settings.play_norepeat ? 1 : 0;
|
||||
settings_save_one("play/norepeat", &val, sizeof(val));
|
||||
dirty_play_norepeat = false;
|
||||
LOG_DBG("NVS Write: play/norepeat = %d", val);
|
||||
}
|
||||
if (dirty_storage_interval) {
|
||||
settings_save_one("settings/storage_interval", &app_settings.storage_interval_s, sizeof(app_settings.storage_interval_s));
|
||||
dirty_storage_interval = false;
|
||||
LOG_DBG("NVS Write: settings/storage_interval = %d", app_settings.storage_interval_s);
|
||||
}
|
||||
}
|
||||
|
||||
static void schedule_save(void)
|
||||
{
|
||||
if (app_settings.storage_interval_s == 0) {
|
||||
/* Direkter Schreibvorgang, Work sofort einreihen */
|
||||
k_work_cancel_delayable(&save_work);
|
||||
k_work_submit(&save_work.work);
|
||||
} else {
|
||||
/* Timer neustarten (überschreibt laufenden Countdown) */
|
||||
k_work_reschedule(&save_work, K_SECONDS(app_settings.storage_interval_s));
|
||||
}
|
||||
}
|
||||
|
||||
void app_settings_save_pending_now(void)
|
||||
{
|
||||
struct k_work_sync sync;
|
||||
k_work_cancel_delayable_sync(&save_work, &sync);
|
||||
save_work_handler(&save_work.work);
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Setter (API für das Protokoll) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
void app_settings_set_audio_vol(uint8_t vol)
|
||||
{
|
||||
if (vol > 100) vol = 100;
|
||||
|
||||
if (app_settings.audio_vol != vol) {
|
||||
app_settings.audio_vol = vol;
|
||||
dirty_audio_vol = true;
|
||||
schedule_save();
|
||||
}
|
||||
}
|
||||
|
||||
void app_settings_set_play_norepeat(bool norepeat)
|
||||
{
|
||||
if (app_settings.play_norepeat != norepeat) {
|
||||
app_settings.play_norepeat = norepeat;
|
||||
dirty_play_norepeat = true;
|
||||
schedule_save();
|
||||
}
|
||||
}
|
||||
|
||||
void app_settings_set_storage_interval(uint32_t interval_s)
|
||||
{
|
||||
if (interval_s > 7200) interval_s = 7200;
|
||||
|
||||
if (app_settings.storage_interval_s != interval_s) {
|
||||
app_settings.storage_interval_s = interval_s;
|
||||
dirty_storage_interval = true;
|
||||
schedule_save();
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Initialisierung */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
int app_settings_init(void)
|
||||
{
|
||||
int err;
|
||||
|
||||
k_work_init_delayable(&save_work, save_work_handler);
|
||||
|
||||
err = settings_subsys_init();
|
||||
if (err) {
|
||||
LOG_ERR("settings_subsys_init failed (err %d)", err);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* Lädt alle Werte aus dem NVS in den RAM */
|
||||
err = settings_load();
|
||||
if (err) {
|
||||
LOG_ERR("settings_load failed (err %d)", err);
|
||||
return err;
|
||||
}
|
||||
|
||||
LOG_INF("Settings init ok. Vol=%d, NoRepeat=%d, Interval=%d",
|
||||
app_settings.audio_vol, app_settings.play_norepeat, app_settings.storage_interval_s);
|
||||
|
||||
return 0;
|
||||
}
|
||||
135
firmware/src/uart.c
Normal file
135
firmware/src/uart.c
Normal file
@@ -0,0 +1,135 @@
|
||||
// uart.c
|
||||
#include <zephyr/kernel.h>
|
||||
#include <zephyr/logging/log.h>
|
||||
#include <zephyr/drivers/uart.h>
|
||||
#include <zephyr/sys/ring_buffer.h>
|
||||
|
||||
LOG_MODULE_REGISTER(uart, LOG_LEVEL_INF);
|
||||
|
||||
#define RX_RING_BUF_SIZE 1024
|
||||
#define TX_RING_BUF_SIZE 1024
|
||||
|
||||
const struct device *const uart_dev = DEVICE_DT_GET_ONE(zephyr_cdc_acm_uart);
|
||||
|
||||
RING_BUF_ITEM_DECLARE(rx_ringbuf, RX_RING_BUF_SIZE);
|
||||
RING_BUF_ITEM_DECLARE(tx_ringbuf, TX_RING_BUF_SIZE);
|
||||
K_SEM_DEFINE(tx_done_sem, 0, 1);
|
||||
K_SEM_DEFINE(rx_ready_sem, 0, 1);
|
||||
|
||||
static void uart_isr(const struct device *dev, void *user_data)
|
||||
{
|
||||
ARG_UNUSED(user_data);
|
||||
|
||||
if (!uart_irq_update(dev))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (uart_irq_rx_ready(dev))
|
||||
{
|
||||
uint8_t *data_ptr;
|
||||
uint32_t claimed_len;
|
||||
int recv_len;
|
||||
|
||||
claimed_len = ring_buf_put_claim(&rx_ringbuf, &data_ptr, RX_RING_BUF_SIZE);
|
||||
|
||||
if (claimed_len > 0)
|
||||
{
|
||||
recv_len = uart_fifo_read(dev, data_ptr, claimed_len);
|
||||
ring_buf_put_finish(&rx_ringbuf, recv_len);
|
||||
if (recv_len > 0)
|
||||
{
|
||||
k_sem_give(&rx_ready_sem);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
uart_irq_rx_disable(dev);
|
||||
}
|
||||
}
|
||||
if (uart_irq_tx_ready(dev))
|
||||
{
|
||||
uint8_t *data_ptr;
|
||||
uint32_t claim_len;
|
||||
int written;
|
||||
|
||||
claim_len = ring_buf_get_claim(&tx_ringbuf, &data_ptr, ring_buf_size_get(&tx_ringbuf));
|
||||
|
||||
if (claim_len > 0)
|
||||
{
|
||||
written = uart_fifo_fill(dev, data_ptr, claim_len);
|
||||
ring_buf_get_finish(&tx_ringbuf, written);
|
||||
}
|
||||
else
|
||||
{
|
||||
uart_irq_tx_disable(dev);
|
||||
}
|
||||
k_sem_give(&tx_done_sem);
|
||||
}
|
||||
}
|
||||
|
||||
int uart_init(void)
|
||||
{
|
||||
if (!device_is_ready(uart_dev))
|
||||
{
|
||||
LOG_ERR("UART device not ready");
|
||||
return -ENODEV;
|
||||
}
|
||||
|
||||
uart_irq_callback_set(uart_dev, uart_isr);
|
||||
uart_irq_rx_enable(uart_dev);
|
||||
|
||||
LOG_INF("UART device initialized");
|
||||
return 0;
|
||||
}
|
||||
|
||||
int uart_write(const uint8_t *data, size_t len, k_timeout_t timeout)
|
||||
{
|
||||
size_t written_total = 0;
|
||||
k_sem_reset(&tx_done_sem);
|
||||
|
||||
while (written_total < len)
|
||||
{
|
||||
uint32_t written = ring_buf_put(&tx_ringbuf, &data[written_total], len - written_total);
|
||||
written_total += written;
|
||||
|
||||
if (written > 0)
|
||||
{
|
||||
uart_irq_tx_enable(uart_dev);
|
||||
}
|
||||
|
||||
if (written_total < len)
|
||||
{
|
||||
int ret = k_sem_take(&tx_done_sem, timeout);
|
||||
if (ret != 0)
|
||||
{
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
}
|
||||
return written_total;
|
||||
}
|
||||
|
||||
int uart_write_string(const char *str, k_timeout_t timeout)
|
||||
{
|
||||
return uart_write((const uint8_t *)str, strlen(str), timeout);
|
||||
}
|
||||
|
||||
int uart_read(uint8_t *data, size_t len, k_timeout_t timeout)
|
||||
{
|
||||
uint32_t read_len = ring_buf_get(&rx_ringbuf, data, len);
|
||||
|
||||
if (read_len == 0 && !K_TIMEOUT_EQ(timeout, K_NO_WAIT)) {
|
||||
k_sem_reset(&rx_ready_sem);
|
||||
if (ring_buf_is_empty(&rx_ringbuf)) {
|
||||
if (k_sem_take(&rx_ready_sem, timeout) != 0) {
|
||||
return -ETIMEDOUT;
|
||||
}
|
||||
}
|
||||
read_len = ring_buf_get(&rx_ringbuf, data, len);
|
||||
}
|
||||
if (read_len > 0) {
|
||||
uart_irq_rx_enable(uart_dev);
|
||||
}
|
||||
return read_len;
|
||||
}
|
||||
@@ -1,209 +1,181 @@
|
||||
#include <zephyr/kernel.h>
|
||||
#include <zephyr/logging/log.h>
|
||||
#include <zephyr/usb/usb_device.h>
|
||||
#include <zephyr/device.h>
|
||||
#include <zephyr/drivers/uart.h>
|
||||
#include <zephyr/sys/ring_buffer.h> /* NEU */
|
||||
#include <errno.h>
|
||||
#include <zephyr/logging/log.h>
|
||||
#include <zephyr/usb/usbd.h>
|
||||
|
||||
#include <io.h>
|
||||
#include "usb.h"
|
||||
|
||||
#define USB_MANUFACTURER_STRING "Iten Engineering"
|
||||
#define USB_PRODUCT_STRING "Edis Buzzer"
|
||||
#define USB_DEVICE_VID 0x1209
|
||||
#define USB_DEVICE_PID 0xEDED
|
||||
|
||||
LOG_MODULE_REGISTER(usb, LOG_LEVEL_INF);
|
||||
|
||||
K_SEM_DEFINE(usb_rx_sem, 0, 1);
|
||||
K_SEM_DEFINE(usb_tx_sem, 0, 1);
|
||||
K_SEM_DEFINE(dtr_active_sem, 0, 1);
|
||||
static uint32_t dtr_active = 0U;
|
||||
|
||||
#define UART_NODE DT_ALIAS(usb_uart)
|
||||
const struct device *cdc_dev = DEVICE_DT_GET(UART_NODE);
|
||||
USBD_DEVICE_DEFINE(cdc_acm_serial,
|
||||
DEVICE_DT_GET(DT_NODELABEL(zephyr_udc0)),
|
||||
USB_DEVICE_VID, USB_DEVICE_PID);
|
||||
|
||||
/* NEU: Ringbuffer für stabilen asynchronen USB-Empfang */
|
||||
#define RX_RING_BUF_SIZE 5*1024 /* 8 KB Ringpuffer für eingehende USB-Daten */
|
||||
RING_BUF_DECLARE(rx_ringbuf, RX_RING_BUF_SIZE);
|
||||
USBD_DESC_LANG_DEFINE(cdc_acm_lang);
|
||||
USBD_DESC_MANUFACTURER_DEFINE(cdc_acm_mfr, USB_MANUFACTURER_STRING);
|
||||
USBD_DESC_PRODUCT_DEFINE(cdc_acm_product, USB_PRODUCT_STRING);
|
||||
IF_ENABLED(CONFIG_HWINFO, (USBD_DESC_SERIAL_NUMBER_DEFINE(cdc_acm_sn)));
|
||||
|
||||
static void cdc_acm_irq_cb(const struct device *dev, void *user_data)
|
||||
USBD_DESC_CONFIG_DEFINE(fs_cfg_desc, "FS Configuration");
|
||||
USBD_DESC_CONFIG_DEFINE(hs_cfg_desc, "HS Configuration");
|
||||
|
||||
USBD_CONFIGURATION_DEFINE(fs_config, 0U, 125U, &fs_cfg_desc);
|
||||
USBD_CONFIGURATION_DEFINE(hs_config, 0U, 125U, &hs_cfg_desc);
|
||||
|
||||
static void fix_code_triple(struct usbd_context *uds_ctx, enum usbd_speed speed)
|
||||
{
|
||||
ARG_UNUSED(user_data);
|
||||
|
||||
if (!uart_irq_update(dev)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (uart_irq_rx_ready(dev)) {
|
||||
uint8_t buffer[64];
|
||||
uint32_t space = ring_buf_space_get(&rx_ringbuf);
|
||||
|
||||
if (space == 0) {
|
||||
/* Backpressure anwenden: Ringpuffer ist voll.
|
||||
Interrupt deaktivieren, damit Daten im HW-FIFO bleiben
|
||||
und der USB-Stack den Host drosselt (NAK). */
|
||||
uart_irq_rx_disable(dev);
|
||||
if (IS_ENABLED(CONFIG_USBD_CDC_ACM_CLASS) ||
|
||||
IS_ENABLED(CONFIG_USBD_CDC_ECM_CLASS) ||
|
||||
IS_ENABLED(CONFIG_USBD_CDC_NCM_CLASS) ||
|
||||
IS_ENABLED(CONFIG_USBD_MIDI2_CLASS) ||
|
||||
IS_ENABLED(CONFIG_USBD_AUDIO2_CLASS) ||
|
||||
IS_ENABLED(CONFIG_USBD_VIDEO_CLASS)) {
|
||||
usbd_device_set_code_triple(uds_ctx, speed,
|
||||
USB_BCC_MISCELLANEOUS, 0x02, 0x01);
|
||||
} else {
|
||||
/* Nur so viele Daten lesen, wie Platz im Ringpuffer ist */
|
||||
int to_read = MIN(sizeof(buffer), space);
|
||||
int len = uart_fifo_read(dev, buffer, to_read);
|
||||
|
||||
if (len > 0) {
|
||||
ring_buf_put(&rx_ringbuf, buffer, len);
|
||||
k_sem_give(&usb_rx_sem);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (uart_irq_tx_ready(dev)) {
|
||||
uart_irq_tx_disable(dev);
|
||||
k_sem_give(&usb_tx_sem);
|
||||
usbd_device_set_code_triple(uds_ctx, speed, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
bool usb_wait_for_data(k_timeout_t timeout)
|
||||
static void usbd_msg_cb(struct usbd_context *const ctx, const struct usbd_msg *const msg)
|
||||
{
|
||||
if (!ring_buf_is_empty(&rx_ringbuf)) {
|
||||
return true;
|
||||
int err;
|
||||
|
||||
LOG_DBG("USBD message: %s", usbd_msg_type_string(msg->type));
|
||||
|
||||
if (usbd_can_detect_vbus(ctx)) {
|
||||
if (msg->type == USBD_MSG_VBUS_READY) {
|
||||
err = usbd_enable(ctx);
|
||||
if (err) {
|
||||
LOG_ERR("Failed to enable USB device (%d)", err);
|
||||
}
|
||||
}
|
||||
|
||||
/* Wenn der Puffer leer ist, sicherstellen, dass der RX-Interrupt
|
||||
aktiviert ist, da sonst keine neuen Daten empfangen werden können. */
|
||||
if (device_is_ready(cdc_dev)) {
|
||||
uart_irq_rx_enable(cdc_dev);
|
||||
if (msg->type == USBD_MSG_VBUS_REMOVED) {
|
||||
err = usbd_disable(ctx);
|
||||
if (err) {
|
||||
LOG_ERR("Failed to disable USB device (%d)", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (k_sem_take(&usb_rx_sem, timeout) == 0);
|
||||
}
|
||||
if (msg->type == USBD_MSG_CDC_ACM_CONTROL_LINE_STATE) {
|
||||
uint32_t rts = 0U;
|
||||
uint32_t dcd = 0U;
|
||||
uint32_t dsr = 0U;
|
||||
|
||||
int usb_read_char(uint8_t *c)
|
||||
{
|
||||
int ret = ring_buf_get(&rx_ringbuf, c, 1);
|
||||
if (ret > 0 && device_is_ready(cdc_dev)) {
|
||||
/* Platz geschaffen -> Empfang wieder aktivieren */
|
||||
uart_irq_rx_enable(cdc_dev);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
int usb_read_buffer(uint8_t *buf, size_t max_len)
|
||||
{
|
||||
int ret = ring_buf_get(&rx_ringbuf, buf, max_len);
|
||||
if (ret > 0 && device_is_ready(cdc_dev)) {
|
||||
/* Platz geschaffen -> Empfang wieder aktivieren */
|
||||
uart_irq_rx_enable(cdc_dev);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
void usb_resume_rx(void)
|
||||
{
|
||||
if (device_is_ready(cdc_dev)) {
|
||||
uart_irq_rx_enable(cdc_dev);
|
||||
}
|
||||
}
|
||||
|
||||
void usb_write_char(uint8_t c)
|
||||
{
|
||||
if (!device_is_ready(cdc_dev)) {
|
||||
return;
|
||||
}
|
||||
uart_poll_out(cdc_dev, c);
|
||||
}
|
||||
|
||||
void usb_write_buffer(const uint8_t *buf, size_t len)
|
||||
{
|
||||
if (!device_is_ready(cdc_dev))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
size_t written;
|
||||
while (len > 0)
|
||||
{
|
||||
written = uart_fifo_fill(cdc_dev, buf, len);
|
||||
|
||||
len -= written;
|
||||
buf += written;
|
||||
|
||||
uart_irq_tx_enable(cdc_dev);
|
||||
|
||||
if (len > 0)
|
||||
{
|
||||
|
||||
if (k_sem_take(&usb_tx_sem, K_MSEC(100)) != 0)
|
||||
{
|
||||
LOG_WRN("USB TX timeout - consumer not reading?");
|
||||
return;
|
||||
if (msg->dev != NULL) {
|
||||
(void)uart_line_ctrl_get(msg->dev, UART_LINE_CTRL_RTS, &rts);
|
||||
(void)uart_line_ctrl_get(msg->dev, UART_LINE_CTRL_DTR, &dtr_active);
|
||||
(void)uart_line_ctrl_get(msg->dev, UART_LINE_CTRL_DCD, &dcd);
|
||||
(void)uart_line_ctrl_get(msg->dev, UART_LINE_CTRL_DSR, &dsr);
|
||||
LOG_DBG("CDC ACM RTS: %u, DTR: %u, DCD: %u, DSR: %u", rts, dtr_active, dcd, dsr);
|
||||
if (dtr_active) {
|
||||
k_sem_give(&dtr_active_sem);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void usb_flush_rx(void)
|
||||
int usb_init(void)
|
||||
{
|
||||
uint8_t dummy;
|
||||
if (!device_is_ready(cdc_dev)) return;
|
||||
int err;
|
||||
|
||||
/* Hardware-FIFO leeren, falls Reste vorhanden */
|
||||
while (uart_fifo_read(cdc_dev, &dummy, 1) > 0);
|
||||
|
||||
/* Ringpuffer und Semaphore zurücksetzen */
|
||||
ring_buf_reset(&rx_ringbuf);
|
||||
k_sem_reset(&usb_rx_sem);
|
||||
}
|
||||
|
||||
static void usb_status_cb(enum usb_dc_status_code cb_status, const uint8_t *param)
|
||||
{
|
||||
switch (cb_status) {
|
||||
case USB_DC_CONNECTED:
|
||||
/* VBUS wurde vom Zephyr-Stack erkannt */
|
||||
LOG_DBG("VBUS detected, USB device connected");
|
||||
break;
|
||||
case USB_DC_CONFIGURED:
|
||||
LOG_DBG("USB device configured by host");
|
||||
io_usb_status(true);
|
||||
if (device_is_ready(cdc_dev)) {
|
||||
(void)uart_line_ctrl_set(cdc_dev, UART_LINE_CTRL_DCD, 1);
|
||||
(void)uart_line_ctrl_set(cdc_dev, UART_LINE_CTRL_DSR, 1);
|
||||
|
||||
/* Interrupt-Handler binden und initial aktivieren */
|
||||
uart_irq_callback_set(cdc_dev, cdc_acm_irq_cb);
|
||||
uart_irq_rx_enable(cdc_dev);
|
||||
}
|
||||
break;
|
||||
case USB_DC_DISCONNECTED:
|
||||
/* Kabel wurde gezogen */
|
||||
LOG_DBG("VBUS removed, USB device disconnected");
|
||||
if (device_is_ready(cdc_dev)) {
|
||||
uart_irq_rx_disable(cdc_dev);
|
||||
}
|
||||
io_usb_status(false);
|
||||
break;
|
||||
case USB_DC_RESET:
|
||||
LOG_DBG("USB bus reset");
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int usb_cdc_acm_init(void)
|
||||
{
|
||||
LOG_DBG("Initializing USB Stack...");
|
||||
|
||||
/* Zephyr-Treiber registrieren. Verbraucht keinen Strom ohne VBUS. */
|
||||
int ret = usb_enable(usb_status_cb);
|
||||
if (ret != 0) {
|
||||
LOG_ERR("Failed to enable USB (%d)", ret);
|
||||
return ret;
|
||||
err = usbd_add_descriptor(&cdc_acm_serial, &cdc_acm_lang);
|
||||
if (err) {
|
||||
LOG_ERR("Failed to add language descriptor (%d)", err);
|
||||
return err;
|
||||
}
|
||||
|
||||
#if DT_NODE_HAS_STATUS(DT_NODELABEL(cdc_acm_uart0), okay)
|
||||
const struct device *cdc_dev = DEVICE_DT_GET(DT_NODELABEL(cdc_acm_uart0));
|
||||
|
||||
if (!device_is_ready(cdc_dev)) {
|
||||
LOG_ERR("CDC ACM device not ready");
|
||||
return -ENODEV;
|
||||
err = usbd_add_descriptor(&cdc_acm_serial, &cdc_acm_mfr);
|
||||
if (err) {
|
||||
LOG_ERR("Failed to add manufacturer descriptor (%d)", err);
|
||||
return err;
|
||||
}
|
||||
|
||||
#else
|
||||
LOG_ERR("CDC ACM UART device not found in devicetree");
|
||||
return -ENODEV;
|
||||
#endif
|
||||
err = usbd_add_descriptor(&cdc_acm_serial, &cdc_acm_product);
|
||||
if (err) {
|
||||
LOG_ERR("Failed to add product descriptor (%d)", err);
|
||||
return err;
|
||||
}
|
||||
|
||||
LOG_DBG("USB Stack enabled and waiting for VBUS in hardware");
|
||||
IF_ENABLED(CONFIG_HWINFO, (
|
||||
err = usbd_add_descriptor(&cdc_acm_serial, &cdc_acm_sn);
|
||||
))
|
||||
if (err) {
|
||||
LOG_ERR("Failed to add serial-number descriptor (%d)", err);
|
||||
return err;
|
||||
}
|
||||
|
||||
if (USBD_SUPPORTS_HIGH_SPEED && usbd_caps_speed(&cdc_acm_serial) == USBD_SPEED_HS) {
|
||||
err = usbd_add_configuration(&cdc_acm_serial, USBD_SPEED_HS, &hs_config);
|
||||
if (err) {
|
||||
LOG_ERR("Failed to add HS configuration (%d)", err);
|
||||
return err;
|
||||
}
|
||||
|
||||
err = usbd_register_class(&cdc_acm_serial, "cdc_acm_0", USBD_SPEED_HS, 1);
|
||||
if (err) {
|
||||
LOG_ERR("Failed to register HS CDC ACM class (%d)", err);
|
||||
return err;
|
||||
}
|
||||
|
||||
fix_code_triple(&cdc_acm_serial, USBD_SPEED_HS);
|
||||
}
|
||||
|
||||
err = usbd_add_configuration(&cdc_acm_serial, USBD_SPEED_FS, &fs_config);
|
||||
if (err) {
|
||||
LOG_ERR("Failed to add FS configuration (%d)", err);
|
||||
return err;
|
||||
}
|
||||
|
||||
err = usbd_register_class(&cdc_acm_serial, "cdc_acm_0", USBD_SPEED_FS, 1);
|
||||
if (err) {
|
||||
LOG_ERR("Failed to register FS CDC ACM class (%d)", err);
|
||||
return err;
|
||||
}
|
||||
|
||||
fix_code_triple(&cdc_acm_serial, USBD_SPEED_FS);
|
||||
|
||||
err = usbd_msg_register_cb(&cdc_acm_serial, usbd_msg_cb);
|
||||
if (err) {
|
||||
LOG_ERR("Failed to register USBD callback (%d)", err);
|
||||
return err;
|
||||
}
|
||||
|
||||
err = usbd_init(&cdc_acm_serial);
|
||||
if (err) {
|
||||
LOG_ERR("Failed to initialize USBD (%d)", err);
|
||||
return err;
|
||||
}
|
||||
|
||||
if (!usbd_can_detect_vbus(&cdc_acm_serial)) {
|
||||
err = usbd_enable(&cdc_acm_serial);
|
||||
if (err) {
|
||||
LOG_ERR("Failed to enable USBD (%d)", err);
|
||||
return err;
|
||||
}
|
||||
}
|
||||
|
||||
LOG_INF("USBD CDC ACM initialized");
|
||||
return 0;
|
||||
}
|
||||
|
||||
void usb_wait_for_dtr(void)
|
||||
{
|
||||
k_sem_take(&dtr_active_sem, K_FOREVER);
|
||||
}
|
||||
|
||||
bool usb_dtr_active(void)
|
||||
{
|
||||
return dtr_active != 0U;
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
#ifndef USB_CDC_ACM_H
|
||||
#define USB_CDC_ACM_H
|
||||
|
||||
/**
|
||||
* @brief Initializes the USB CDC ACM device
|
||||
* @return 0 on success, negative error code on failure
|
||||
*/
|
||||
int usb_cdc_acm_init(void);
|
||||
|
||||
/**
|
||||
* @brief Waits until data is available in the USB RX FIFO or the timeout expires
|
||||
* @param timeout Maximum time to wait for data. Use K_FOREVER for infinite wait.
|
||||
* @return true if data is available, false if timeout occurred
|
||||
*/
|
||||
bool usb_wait_for_data(k_timeout_t timeout);
|
||||
|
||||
/**
|
||||
* @brief Reads a single character from the USB RX FIFO
|
||||
* @param c Pointer to store the read character
|
||||
* @return 1 if a character was read, 0 if no data was available
|
||||
*/
|
||||
int usb_read_char(uint8_t *c);
|
||||
|
||||
/**
|
||||
* @brief Reads a block of data from the USB RX FIFO
|
||||
* @param buf Buffer to store the read data
|
||||
* @param max_len Maximum number of bytes to read
|
||||
* @return Number of bytes read
|
||||
*/
|
||||
int usb_read_buffer(uint8_t *buf, size_t max_len);
|
||||
|
||||
/**
|
||||
* @brief Resumes the USB RX interrupt when all data has been read
|
||||
*/
|
||||
void usb_resume_rx(void);
|
||||
|
||||
/**
|
||||
* @brief Writes a single character to the USB TX FIFO
|
||||
* @param c Character to write
|
||||
*/
|
||||
void usb_write_char(uint8_t c);
|
||||
|
||||
/**
|
||||
* @brief Writes a block of data to the USB TX FIFO
|
||||
* @param buf Buffer containing the data to write
|
||||
* @param len Number of bytes to write
|
||||
*/
|
||||
void usb_write_buffer(const uint8_t *buf, size_t len);
|
||||
|
||||
/**
|
||||
* @brief Flushes the USB RX FIFO
|
||||
*/
|
||||
void usb_flush_rx(void);
|
||||
|
||||
#endif // USB_CDC_ACM_H
|
||||
@@ -4,6 +4,8 @@
|
||||
#include <zephyr/logging/log_ctrl.h>
|
||||
#include <zephyr/sys/reboot.h>
|
||||
|
||||
#include <settings.h>
|
||||
|
||||
#if IS_ENABLED(CONFIG_SOC_SERIES_NRF52X)
|
||||
#include <hal/nrf_power.h>
|
||||
#elif IS_ENABLED(CONFIG_SOC_SERIES_STM32G0X)
|
||||
@@ -17,6 +19,7 @@ LOG_MODULE_REGISTER(utils, LOG_LEVEL_DBG);
|
||||
|
||||
void reboot_with_status(uint8_t status)
|
||||
{
|
||||
app_settings_save_pending_now();
|
||||
#if IS_ENABLED(CONFIG_SOC_SERIES_NRF52X)
|
||||
/* Korrigierter Aufruf mit Register-Index 0 */
|
||||
nrf_power_gpregret_set(NRF_POWER, REBOOT_STATUS_REG_IDX, (uint32_t)status);
|
||||
|
||||
BIN
sounds/sys/404
Normal file
BIN
sounds/sys/404
Normal file
Binary file not shown.
BIN
sounds/sys/confirm
Normal file
BIN
sounds/sys/confirm
Normal file
Binary file not shown.
BIN
sounds/sys/update
Normal file
BIN
sounds/sys/update
Normal file
Binary file not shown.
BIN
sounds/sys/voltest
Normal file
BIN
sounds/sys/voltest
Normal file
Binary file not shown.
274
tool/buzz.py
Normal file
274
tool/buzz.py
Normal file
@@ -0,0 +1,274 @@
|
||||
import sys
|
||||
import os
|
||||
import argparse
|
||||
|
||||
# # Falls buzz.py tief in Unterordnern liegt, stellen wir sicher,
|
||||
# # dass das Hauptverzeichnis im Pfad ist:
|
||||
# sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def main():
|
||||
try:
|
||||
parser = argparse.ArgumentParser(description="Buzzer Serial Comm Tool")
|
||||
|
||||
# Allgemeine Parameter
|
||||
parser.add_argument("-c", "--config", help="Pfad zur config.yaml (optional)", type=str)
|
||||
parser.add_argument("-d", "--debug", help="Aktiviert detaillierte Hex-Logs", action="store_true")
|
||||
|
||||
# Verbindungsparameter (können auch in config.yaml definiert werden)
|
||||
parser.add_argument("-p", "--port", help="Serieller Port", type=str)
|
||||
parser.add_argument("-b", "--baud", help="Baudrate", type=int)
|
||||
parser.add_argument("-t", "--timeout", help="Timeout in Sekunden", type=float)
|
||||
|
||||
# Subparser für Befehle
|
||||
subparsers = parser.add_subparsers(dest="command", help="Verfügbare Befehle")
|
||||
|
||||
# Befehl: crc32
|
||||
crc32_parser = subparsers.add_parser("crc32", help="CRC32-Checksumme einer Datei oder eines Verzeichnisses berechnen")
|
||||
crc32_parser.add_argument("path", help="Pfad der Datei auf dem Zielsystem")
|
||||
|
||||
# Befehl: flash_info
|
||||
flash_info_parser = subparsers.add_parser("flash_info", help="Informationen über den Flash-Speicher des Controllers abfragen")
|
||||
|
||||
# Befehl: fw_status
|
||||
fw_status_parser = subparsers.add_parser("fw_status", help="Firmware- und Kernel-Status des Controllers abfragen")
|
||||
|
||||
# Befehl: get_file
|
||||
get_file_parser = subparsers.add_parser("get_file", help="Datei vom Zielsystem herunterladen")
|
||||
get_file_parser.add_argument("source_path", help="Pfad der Datei auf dem Zielsystem")
|
||||
get_file_parser.add_argument("dest_path", help="Zielpfad auf dem lokalen System")
|
||||
|
||||
# Befehl: ls
|
||||
ls_parser = subparsers.add_parser("ls", help="Listet Dateien/Ordner in einem Verzeichnis auf")
|
||||
ls_parser.add_argument("path", help="Pfad auf dem Zielsystem")
|
||||
ls_parser.add_argument("-r", "--recursive", help="Rekursiv durch die Verzeichnisse durchsuchen", action="store_true")
|
||||
|
||||
# Befehl: proto
|
||||
proto_parser = subparsers.add_parser("proto", help="Protokollversion des Controllers abfragen")
|
||||
|
||||
# Befehl: put_file
|
||||
put_file_parser = subparsers.add_parser("put_file", help="Datei auf das Zielsystem hochladen")
|
||||
put_file_parser.add_argument("source_path", help="Pfad der Datei auf dem lokalen System")
|
||||
put_file_parser.add_argument("dest_path", help="Zielpfad auf dem Zielsystem")
|
||||
put_file_parser.add_argument("-t", "--tags", help="Optionale JSON Tags für den Upload", type=str)
|
||||
|
||||
# Befehl: get_tags
|
||||
get_tags_parser = subparsers.add_parser("get_tags", help="Tags einer Datei anzeigen")
|
||||
get_tags_parser.add_argument("path", help="Pfad der Datei auf dem Zielsystem")
|
||||
|
||||
# Befehl: put_tags
|
||||
put_tags_parser = subparsers.add_parser("put_tags", help="Tags schreiben")
|
||||
put_tags_parser.add_argument("path", help="Pfad der Datei auf dem Zielsystem")
|
||||
put_tags_parser.add_argument("json", help="JSON String (z.B. '{\"json\": {\"t\": \"Titel\"}}')")
|
||||
put_tags_parser.add_argument("-o", "--overwrite", help="Alle bestehenden JSON-Tags vorher löschen", action="store_true")
|
||||
# Befehl: rename
|
||||
rename_parser = subparsers.add_parser("rename", help="Benennen Sie eine Datei oder einen Ordner auf dem Zielsystem um")
|
||||
rename_parser.add_argument("source_path", help="Aktueller Pfad der Datei/des Ordners auf dem Zielsystem")
|
||||
rename_parser.add_argument("dest_path", help="Neuer Pfad der Datei/des Ordners auf dem Zielsystem")
|
||||
|
||||
# Befehl: rm
|
||||
rm_parser = subparsers.add_parser("rm", help="Entfernt eine Datei oder einen Ordner auf dem Zielsystem")
|
||||
rm_parser.add_argument("path", help="Pfad auf dem Zielsystem")
|
||||
|
||||
# Befehl: stat
|
||||
stat_parser = subparsers.add_parser("stat", help="Informationen zu einer Datei/Ordner")
|
||||
stat_parser.add_argument("path", help="Pfad auf dem Zielsystem")
|
||||
|
||||
# Befehl: put_fw
|
||||
put_fw_parser = subparsers.add_parser("put_fw", help="Firmware-Image auf den Controller hochladen")
|
||||
put_fw_parser.add_argument("file_path", help="Pfad zur Firmware-Datei auf dem lokalen System")
|
||||
|
||||
# Befehl: confirm_fw
|
||||
confirm_fw_parser = subparsers.add_parser("confirm_fw", help="Bestätigt ein als 'Testing' markiertes Firmware-Image, damit es beim permanent wird")
|
||||
|
||||
# Befehl: reboot
|
||||
reboot_parser = subparsers.add_parser("reboot", help="Neustart des Controllers")
|
||||
|
||||
# Befehl: play
|
||||
play_parser = subparsers.add_parser("play", help="Startet die Wiedergabe einer Datei")
|
||||
play_parser.add_argument("path", help="Pfad der Datei auf dem Zielsystem")
|
||||
play_parser.add_argument("-i", "--interrupt", help="Sofortige Wiedergabe (Interrupt)", action="store_true")
|
||||
|
||||
# Befehl: stop
|
||||
stop_parser = subparsers.add_parser("stop", help="Stoppt die aktuelle Wiedergabe")
|
||||
|
||||
# Befehl: set
|
||||
set_parser = subparsers.add_parser("set", help="System-Einstellung setzen")
|
||||
set_parser.add_argument("key", help="Schlüssel (z.B. audio/vol)")
|
||||
set_parser.add_argument("value", help="Wert")
|
||||
|
||||
# Befehl: get
|
||||
get_parser = subparsers.add_parser("get", help="System-Einstellung auslesen")
|
||||
get_parser.add_argument("key", help="Schlüssel (z.B. audio/vol)")
|
||||
args = parser.parse_args()
|
||||
|
||||
if not args.command:
|
||||
parser.print_help()
|
||||
sys.exit(0)
|
||||
|
||||
from core.config import cfg
|
||||
from core.utils import console, console_err
|
||||
|
||||
if args.config:
|
||||
cfg.custom_path = args.config
|
||||
|
||||
if args.debug:
|
||||
cfg.debug = True
|
||||
|
||||
console.print("[bold blue]Buzzer Tool v1.0[/bold blue]", justify="left")
|
||||
|
||||
settings = cfg.serial_settings
|
||||
|
||||
settings['debug'] = args.debug
|
||||
|
||||
# Überschreibe Einstellungen mit Kommandozeilenparametern, falls vorhanden
|
||||
if args.port:
|
||||
settings['port'] = args.port
|
||||
if args.baud:
|
||||
settings['baudrate'] = args.baud
|
||||
if args.timeout:
|
||||
settings['timeout'] = args.timeout
|
||||
|
||||
# Ausgabe der aktuellen Einstellungen
|
||||
port = settings.get('port')
|
||||
baud = settings.get('baudrate', 'N/A')
|
||||
timeout = settings.get('timeout', 'N/A')
|
||||
|
||||
if not port:
|
||||
console_err.print("[error]Fehler: Kein serieller Port angegeben.[/error]")
|
||||
sys.exit(1)
|
||||
|
||||
if args.debug:
|
||||
console.print(f" • Port: [info]{port}[/info]")
|
||||
console.print(f" • Baud: [info]{baud}[/info]")
|
||||
console.print(f" • Timeout: [info]{timeout:1.2f}s[/info]")
|
||||
console.print("-" * 78)
|
||||
|
||||
from core.serial_conn import SerialBus
|
||||
bus = SerialBus(settings)
|
||||
|
||||
try:
|
||||
bus.open()
|
||||
if args.command == "crc32":
|
||||
from core.cmd.crc32 import crc32
|
||||
cmd = crc32(bus)
|
||||
result = cmd.get(args.path)
|
||||
cmd.print(result, args.path)
|
||||
elif args.command == "get_file":
|
||||
from core.cmd.get_file import get_file
|
||||
cmd = get_file(bus)
|
||||
result = cmd.get(args.source_path, args.dest_path)
|
||||
cmd.print(result)
|
||||
elif args.command == "flash_info":
|
||||
from core.cmd.flash_info import flash_info
|
||||
cmd = flash_info(bus)
|
||||
result = cmd.get()
|
||||
cmd.print(result)
|
||||
elif args.command == "fw_status":
|
||||
from core.cmd.fw_status import fw_status
|
||||
cmd = fw_status(bus)
|
||||
result = cmd.get()
|
||||
cmd.print(result)
|
||||
elif args.command == "ls":
|
||||
from core.cmd.list_dir import list_dir
|
||||
cmd = list_dir(bus)
|
||||
result = cmd.get(args.path, recursive=args.recursive)
|
||||
cmd.print(result, args.path)
|
||||
elif args.command == "proto":
|
||||
from core.cmd.proto import proto
|
||||
cmd = proto(bus)
|
||||
result = cmd.get()
|
||||
cmd.print(result)
|
||||
elif args.command == "put_file":
|
||||
from core.cmd.put_file import put_file
|
||||
cmd = put_file(bus)
|
||||
result = cmd.get(args.source_path, args.dest_path)
|
||||
cmd.print(result)
|
||||
elif args.command == "rename":
|
||||
from core.cmd.rename import rename
|
||||
cmd = rename(bus)
|
||||
result = cmd.get(args.source_path, args.dest_path)
|
||||
cmd.print(result)
|
||||
elif args.command == "rm":
|
||||
from core.cmd.rm import rm
|
||||
cmd = rm(bus)
|
||||
result = cmd.get(args.path)
|
||||
cmd.print(result, args.path)
|
||||
elif args.command == "stat":
|
||||
from core.cmd.stat import stat
|
||||
cmd = stat(bus)
|
||||
result = cmd.get(args.path)
|
||||
cmd.print(result, args.path)
|
||||
elif args.command == "put_file":
|
||||
from core.cmd.put_file import put_file
|
||||
cmd = put_file(bus)
|
||||
result = cmd.get(args.source_path, args.dest_path, cli_tags_json=args.tags)
|
||||
cmd.print(result)
|
||||
elif args.command == "get_tags":
|
||||
from core.cmd.get_tags import get_tags
|
||||
cmd = get_tags(bus)
|
||||
result = cmd.get(args.path)
|
||||
cmd.print(result, args.path)
|
||||
elif args.command == "put_tags":
|
||||
from core.cmd.put_tags import put_tags
|
||||
cmd = put_tags(bus)
|
||||
result = cmd.get(args.path, args.json, overwrite=args.overwrite)
|
||||
cmd.print(result, args.path)
|
||||
elif args.command == "confirm_fw":
|
||||
from core.cmd.fw_confirm import fw_confirm
|
||||
cmd = fw_confirm(bus)
|
||||
result = cmd.get()
|
||||
cmd.print(result)
|
||||
elif args.command == "put_fw":
|
||||
from core.cmd.put_fw import put_fw
|
||||
cmd = put_fw(bus)
|
||||
result = cmd.get(args.file_path)
|
||||
cmd.print(result)
|
||||
elif args.command == "reboot":
|
||||
from core.cmd.reboot import reboot
|
||||
cmd = reboot(bus)
|
||||
result = cmd.get()
|
||||
cmd.print(result)
|
||||
elif args.command == "play":
|
||||
from core.cmd.play import play
|
||||
cmd = play(bus)
|
||||
result = cmd.get(args.path, interrupt=args.interrupt)
|
||||
cmd.print(result, args.path, interrupt=args.interrupt)
|
||||
elif args.command == "stop":
|
||||
from core.cmd.stop import stop
|
||||
cmd = stop(bus)
|
||||
result = cmd.get()
|
||||
cmd.print(result)
|
||||
elif args.command == "set":
|
||||
from core.cmd.set_setting import set_setting
|
||||
cmd = set_setting(bus)
|
||||
result = cmd.get(args.key, args.value)
|
||||
cmd.print(result, args.key, args.value)
|
||||
elif args.command == "get":
|
||||
from core.cmd.get_setting import get_setting
|
||||
cmd = get_setting(bus)
|
||||
result = cmd.get(args.key)
|
||||
cmd.print(result, args.key)
|
||||
finally:
|
||||
bus.close()
|
||||
|
||||
except FileNotFoundError as e:
|
||||
console_err.print(f"[error]Fehler: {e}[/error]")
|
||||
sys.exit(1)
|
||||
except (TimeoutError, IOError, ValueError) as e:
|
||||
console_err.print(f"[bold red]KOMMUNIKATIONSFEHLER:[/bold red] [error_msg]{e}[/error_msg]")
|
||||
sys.exit(1) # Beendet das Script mit Fehlercode 1 für Tests
|
||||
except Exception as e:
|
||||
# Hier fangen wir auch deinen neuen ControllerError ab
|
||||
from core.serial_conn import ControllerError
|
||||
if isinstance(e, ControllerError):
|
||||
console_err.print(f"[bold red]CONTROLLER FEHLER:[/bold red] [error_msg]{e}[/error_msg]")
|
||||
else:
|
||||
console_err.print(f"[bold red]UNERWARTETER FEHLER:[/bold red] [error_msg]{e}[/error_msg]")
|
||||
|
||||
if args.debug:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
4
tool/config.yaml
Normal file
4
tool/config.yaml
Normal file
@@ -0,0 +1,4 @@
|
||||
serial:
|
||||
port: "/dev/cu.usbmodem83401"
|
||||
baudrate: 115200
|
||||
timeout: 1.0
|
||||
36
tool/core/cmd/crc32.py
Normal file
36
tool/core/cmd/crc32.py
Normal file
@@ -0,0 +1,36 @@
|
||||
# tool/core/cmd/crc32.py
|
||||
import struct
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS, ERRORS
|
||||
|
||||
class crc32:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self, path: str):
|
||||
path_bytes = path.encode('utf-8')
|
||||
payload = struct.pack('B', len(path_bytes)) + path_bytes
|
||||
self.bus.send_request(COMMANDS['crc_32'], payload)
|
||||
|
||||
# 1 Byte Type + 4 Byte Size = 5
|
||||
data = self.bus.receive_response(length=8, timeout=5)
|
||||
|
||||
if not data or data.get('type') == 'error':
|
||||
return None
|
||||
|
||||
payload = data['data']
|
||||
crc_value = struct.unpack('<I', payload[0:4])[0]
|
||||
audio_crc_value = struct.unpack('<I', payload[4:8])[0]
|
||||
result = {
|
||||
'crc32': crc_value,
|
||||
'audio_crc32': audio_crc_value
|
||||
}
|
||||
return result
|
||||
|
||||
def print(self, result, path: str):
|
||||
if not result:
|
||||
return
|
||||
|
||||
console.print(f"[info_title]CRC32[/info_title] für [info]{path}[/info]:")
|
||||
console.print(f" • CRC32 Datei: [info]{result['crc32']:08X}[/info]")
|
||||
console.print(f" • CRC32 Audio: [info]{result['audio_crc32']:08X}[/info]")
|
||||
53
tool/core/cmd/flash_info.py
Normal file
53
tool/core/cmd/flash_info.py
Normal file
@@ -0,0 +1,53 @@
|
||||
# tool/core/cmd/flash_info.py
|
||||
import struct
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS, ERRORS
|
||||
|
||||
class flash_info:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
|
||||
def get(self):
|
||||
import struct
|
||||
self.bus.send_request(COMMANDS['get_flash_info'])
|
||||
|
||||
data = self.bus.receive_response(length=21)
|
||||
if not data or data.get('type') == 'error':
|
||||
return None
|
||||
|
||||
payload = data['data']
|
||||
ext_block_size = struct.unpack('<I', payload[0:4])[0]
|
||||
ext_total_blocks = struct.unpack('<I', payload[4:8])[0]
|
||||
ext_free_blocks = struct.unpack('<I', payload[8:12])[0]
|
||||
int_slot_size = struct.unpack('<I', payload[12:16])[0]
|
||||
ext_page_size = struct.unpack('<H', payload[16:18])[0]
|
||||
int_page_size = struct.unpack('<H', payload[18:20])[0]
|
||||
max_path_len = payload[20]
|
||||
|
||||
result = {
|
||||
'ext_block_size': ext_block_size,
|
||||
'ext_total_blocks': ext_total_blocks,
|
||||
'ext_free_blocks': ext_free_blocks,
|
||||
'int_slot_size': int_slot_size,
|
||||
'ext_page_size': ext_page_size,
|
||||
'int_page_size': int_page_size,
|
||||
'max_path_len': max_path_len,
|
||||
'ext_total_size': ext_block_size * ext_total_blocks,
|
||||
'ext_free_size': ext_block_size * ext_free_blocks,
|
||||
'ext_used_size': ext_block_size * (ext_total_blocks - ext_free_blocks)
|
||||
}
|
||||
return result
|
||||
|
||||
def print(self, result):
|
||||
if not result:
|
||||
return
|
||||
|
||||
console.print(f"[info]Flash-Informationen:[/info]")
|
||||
console.print(f" • [info]Externer Flash:[/info] {result['ext_total_size']/1024/1024:.2f} MB ({result['ext_total_blocks']} Blöcke à {result['ext_block_size']} Bytes)")
|
||||
console.print(f" - Belegt: {result['ext_used_size']/1024/1024:.2f} MB ({result['ext_total_blocks'] - result['ext_free_blocks']} Blöcke)")
|
||||
console.print(f" - Frei: {result['ext_free_size']/1024/1024:.2f} MB ({result['ext_free_blocks']} Blöcke)")
|
||||
console.print(f" • [info]FW Flash Slot:[/info] {result['int_slot_size']/1024:.2f} KB")
|
||||
console.print(f" • [info]EXTFLASH Seitengröße:[/info] {result['ext_page_size']} Bytes")
|
||||
console.print(f" • [info]INTFLASH Seitengröße:[/info] {result['int_page_size']} Bytes")
|
||||
console.print(f" • [info]Maximale Pfadlänge:[/info] {result['max_path_len']} Zeichen")
|
||||
23
tool/core/cmd/fw_confirm.py
Normal file
23
tool/core/cmd/fw_confirm.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS
|
||||
|
||||
class fw_confirm:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self):
|
||||
# Fehler 1: Der Key in COMMANDS heißt 'confirm_fw'
|
||||
self.bus.send_request(COMMANDS['confirm_fw'])
|
||||
|
||||
# Fehler 2: Try-Except entfernt, damit der ControllerError (z.B. bei nicht-pending Image)
|
||||
# sauber nach buzz.py durchschlägt.
|
||||
data = self.bus.receive_ack()
|
||||
return data is not None and data.get('type') == 'ack'
|
||||
|
||||
def print(self, result):
|
||||
if result:
|
||||
console.print("✓ Laufende Firmware wurde [info]erfolgreich bestätigt[/info] (Permanent).")
|
||||
else:
|
||||
# Wird im Fehlerfall eigentlich nicht mehr erreicht, da buzz.py abbricht,
|
||||
# bleibt aber als Fallback für leere Antworten.
|
||||
console_err.print("❌ Fehler beim Bestätigen der Firmware.")
|
||||
53
tool/core/cmd/fw_status.py
Normal file
53
tool/core/cmd/fw_status.py
Normal file
@@ -0,0 +1,53 @@
|
||||
# tool/core/cmd/fw_status.py
|
||||
import struct
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS, ERRORS
|
||||
|
||||
class fw_status:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
|
||||
def get(self):
|
||||
import struct
|
||||
self.bus.send_request(COMMANDS['get_firmware_status'])
|
||||
|
||||
data = self.bus.receive_response(length=10)
|
||||
if not data or data.get('type') == 'error':
|
||||
return None
|
||||
|
||||
header = data['data']
|
||||
status = header[0]
|
||||
app_version_raw = struct.unpack('<I', header[1:5])[0]
|
||||
ker_version_raw = struct.unpack('<I', header[5:9])[0]
|
||||
str_len = header[9]
|
||||
|
||||
fw_string_bytes = self.bus.connection.read(str_len)
|
||||
fw_string = fw_string_bytes.decode('utf-8')
|
||||
|
||||
result = {
|
||||
'status': status,
|
||||
'fw_version_raw': hex(app_version_raw),
|
||||
'kernel_version_raw': hex(ker_version_raw),
|
||||
'fw_major': (app_version_raw >> 24) & 0xFF,
|
||||
'fw_minor': (app_version_raw >> 16) & 0xFF,
|
||||
'fw_patch': (app_version_raw >> 8)& 0xFF,
|
||||
'kernel_major': (ker_version_raw >> 16) & 0xFF,
|
||||
'kernel_minor': (ker_version_raw >> 8) & 0xFF,
|
||||
'kernel_patch': ker_version_raw & 0xFF,
|
||||
'fw_string': fw_string,
|
||||
'kernel_string': f"{(ker_version_raw >> 16) & 0xFF}.{(ker_version_raw >> 8) & 0xFF}.{ker_version_raw & 0xFF}"
|
||||
}
|
||||
return result
|
||||
|
||||
def print(self, result):
|
||||
if not result:
|
||||
return
|
||||
|
||||
status = "UNKNOWN"
|
||||
if result['status'] == 0x00: status = "CONFIRMED"
|
||||
elif result['status'] == 0x01: status = "PENDING"
|
||||
elif result['status'] == 0x02: status = "TESTING"
|
||||
console.print(f"[info]Firmware Status[/info] des Controllers ist [info]{status}[/info]:")
|
||||
console.print(f" • Firmware: [info]{result['fw_string']}[/info] ({result['fw_major']}.{result['fw_minor']}.{result['fw_patch']})")
|
||||
console.print(f" • Kernel: [info]{result['kernel_string']}[/info] ({result['kernel_major']}.{result['kernel_minor']}.{result['kernel_patch']})")
|
||||
89
tool/core/cmd/get_file.py
Normal file
89
tool/core/cmd/get_file.py
Normal file
@@ -0,0 +1,89 @@
|
||||
# tool/core/cmd/get_file.py
|
||||
import struct
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, DownloadColumn, TransferSpeedColumn, TimeRemainingColumn
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS
|
||||
|
||||
class get_file:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self, source_path: str, dest_path: str):
|
||||
try:
|
||||
p = Path(dest_path)
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(p, 'wb') as f:
|
||||
pass
|
||||
except Exception as e:
|
||||
console_err.print(f"Fehler: Kann Zieldatei nicht anlegen: {e}")
|
||||
return None
|
||||
|
||||
source_path_bytes = source_path.encode('utf-8')
|
||||
payload = struct.pack('B', len(source_path_bytes)) + source_path_bytes
|
||||
self.bus.send_request(COMMANDS['get_file'], payload)
|
||||
|
||||
# Fortschrittsbalken Setup
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn("[progress.description]{task.description}"),
|
||||
BarColumn(),
|
||||
DownloadColumn(),
|
||||
TransferSpeedColumn(),
|
||||
"•",
|
||||
TimeRemainingColumn(),
|
||||
console=console,
|
||||
transient=False
|
||||
) as progress:
|
||||
|
||||
task = progress.add_task(f"Lade {source_path}...", total=None)
|
||||
|
||||
def update_bar(received, total):
|
||||
progress.update(task, total=total, completed=received)
|
||||
|
||||
stream_res = self.bus.receive_stream(progress_callback=update_bar)
|
||||
|
||||
if not stream_res or stream_res.get('type') == 'error':
|
||||
return None
|
||||
file_data = stream_res['data']
|
||||
remote_crc = stream_res.get('crc32')
|
||||
local_crc = zlib.crc32(file_data) & 0xFFFFFFFF
|
||||
duratuion = stream_res.get('duration')
|
||||
|
||||
if local_crc == remote_crc:
|
||||
with open(p, 'wb') as f:
|
||||
f.write(file_data)
|
||||
success = True
|
||||
else:
|
||||
with open(p, 'wb') as f:
|
||||
f.write(file_data)
|
||||
success = False
|
||||
|
||||
return {
|
||||
'success': success,
|
||||
'source_path': source_path,
|
||||
'dest_path': dest_path,
|
||||
'crc32_remote': remote_crc,
|
||||
'crc32_local': local_crc,
|
||||
'size': len(file_data),
|
||||
'duration': duratuion
|
||||
}
|
||||
|
||||
def print(self, result):
|
||||
if not result:
|
||||
return
|
||||
|
||||
if result['success']:
|
||||
console.print(f"✓ Datei [info]{result['source_path']}[/info] erfolgreich heruntergeladen.")
|
||||
console.print(f" • Größe: [info]{result['size'] / 1024:.2f} KB[/info]")
|
||||
else:
|
||||
console_err.print(f"❌ CRC-FEHLER: Datei [error]{result['source_path']}[/error] wurde nicht korrekt empfangen!")
|
||||
|
||||
console.print(f" • Remote CRC: [info]{result['crc32_remote']:08X}[/info]")
|
||||
console.print(f" • Local CRC: [info]{result['crc32_local']:08X}[/info]")
|
||||
if result.get('crc32_device_file') is not None:
|
||||
console.print(f" • Device CRC: [info]{result['crc32_device_file']:08X}[/info]")
|
||||
console.print(f" • Zielpfad: [info]{result['dest_path']}[/info]")
|
||||
if result.get('duration') is not None and result.get('duration') > 0:
|
||||
console.print(f" • Dauer: [info]{result['duration']:.2f} s[/info]")
|
||||
37
tool/core/cmd/get_setting.py
Normal file
37
tool/core/cmd/get_setting.py
Normal file
@@ -0,0 +1,37 @@
|
||||
import struct
|
||||
from core.utils import console
|
||||
from core.protocol import COMMANDS
|
||||
|
||||
class get_setting:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self, key: str):
|
||||
key_bytes = key.encode('utf-8')
|
||||
payload = struct.pack('B', len(key_bytes)) + key_bytes
|
||||
|
||||
self.bus.send_request(COMMANDS['get_setting'], payload)
|
||||
|
||||
# varlen_params=1 liest exakt 1 Byte Länge + entsprechend viele Datenbytes
|
||||
data = self.bus.receive_response(length=0, varlen_params=1)
|
||||
|
||||
if not data or data.get('type') == 'error':
|
||||
return None
|
||||
|
||||
raw = data['data']
|
||||
val_len = raw[0]
|
||||
val_buf = raw[1:1+val_len]
|
||||
|
||||
# Binärdaten zurück in Python-Typen parsen
|
||||
if key == "audio/vol" and val_len == 1:
|
||||
return struct.unpack('<B', val_buf)[0]
|
||||
elif key == "play/norepeat" and val_len == 1:
|
||||
return bool(struct.unpack('<B', val_buf)[0])
|
||||
elif key == "settings/storage_interval" and val_len == 2:
|
||||
return struct.unpack('<H', val_buf)[0]
|
||||
else:
|
||||
return None
|
||||
|
||||
def print(self, result, key: str):
|
||||
if result is not None:
|
||||
console.print(f"⚙️ [info]{key}[/info] = [info]{result}[/info]")
|
||||
43
tool/core/cmd/get_tags.py
Normal file
43
tool/core/cmd/get_tags.py
Normal file
@@ -0,0 +1,43 @@
|
||||
# tool/core/cmd/get_tags.py
|
||||
import struct
|
||||
import json
|
||||
from core.utils import console
|
||||
from core.protocol import COMMANDS
|
||||
from core.tag import TagManager
|
||||
|
||||
class get_tags:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get_raw_tlvs(self, path: str):
|
||||
"""Holt die rohen TLVs vom Gerät."""
|
||||
path_bytes = path.encode('utf-8')
|
||||
payload = struct.pack('B', len(path_bytes)) + path_bytes
|
||||
self.bus.send_request(COMMANDS['get_tags'], payload)
|
||||
|
||||
stream_res = self.bus.receive_stream()
|
||||
if not stream_res or stream_res.get('type') == 'error': return []
|
||||
|
||||
return TagManager.parse_tlvs(stream_res['data'])
|
||||
|
||||
def get(self, path: str):
|
||||
tlvs = self.get_raw_tlvs(path)
|
||||
result = {"system": {}, "json": {}}
|
||||
|
||||
for tlv in tlvs:
|
||||
if tlv['type'] == 0x00:
|
||||
if tlv['index'] == 0x00 and len(tlv['value']) == 8:
|
||||
codec, bit_depth, _, samplerate = struct.unpack('<BBHI', tlv['value'])
|
||||
result["system"]["format"] = {"codec": codec, "bit_depth": bit_depth, "samplerate": samplerate}
|
||||
elif tlv['index'] == 0x01 and len(tlv['value']) == 4:
|
||||
result["system"]["crc32"] = f"0x{struct.unpack('<I', tlv['value'])[0]:08X}"
|
||||
elif tlv['type'] == 0x10:
|
||||
try:
|
||||
result["json"].update(json.loads(tlv['value'].decode('utf-8')))
|
||||
except:
|
||||
pass
|
||||
return result
|
||||
|
||||
def print(self, result, path: str):
|
||||
console.print(f"[info]Metadaten[/info] für [info]{path}[/info]:")
|
||||
console.print(json.dumps(result, indent=2, ensure_ascii=False))
|
||||
71
tool/core/cmd/list_dir.py
Normal file
71
tool/core/cmd/list_dir.py
Normal file
@@ -0,0 +1,71 @@
|
||||
# tool/core/cmd/list_dir.py
|
||||
import struct
|
||||
from core.utils import console
|
||||
from core.protocol import COMMANDS
|
||||
|
||||
class list_dir:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self, path: str, recursive: bool = False):
|
||||
# Wir stellen sicher, dass der Pfad nicht leer ist und normalisieren ihn leicht
|
||||
clean_path = path if path == "/" else path.rstrip('/')
|
||||
path_bytes = clean_path.encode('utf-8')
|
||||
|
||||
payload = struct.pack('B', len(path_bytes)) + path_bytes
|
||||
self.bus.send_request(COMMANDS['list_dir'], payload)
|
||||
|
||||
chunks = self.bus.receive_list()
|
||||
if chunks is None:
|
||||
return None
|
||||
|
||||
entries = []
|
||||
for chunk in chunks:
|
||||
if len(chunk) < 6: # Typ(1) + Size(4) + min 1 char Name
|
||||
continue
|
||||
|
||||
is_dir = chunk[0] == 1
|
||||
size = struct.unpack('<I', chunk[1:5])[0] if not is_dir else None
|
||||
name = chunk[5:].decode('utf-8').rstrip('\x00')
|
||||
|
||||
entry = {
|
||||
'name': name,
|
||||
'is_dir': is_dir,
|
||||
'size': size
|
||||
}
|
||||
|
||||
if recursive and is_dir:
|
||||
# Rekursiver Aufruf: Pfad sauber zusammenfügen
|
||||
sub_path = f"{clean_path}/{name}"
|
||||
entry['children'] = self.get(sub_path, recursive=True)
|
||||
|
||||
entries.append(entry)
|
||||
|
||||
return entries
|
||||
|
||||
def print(self, entries, path: str, prefix: str = ""):
|
||||
if prefix == "":
|
||||
console.print(f"Inhalt von [info]{path}[/info]:")
|
||||
|
||||
if not entries:
|
||||
return
|
||||
|
||||
# Sortierung: Verzeichnisse zuerst
|
||||
entries.sort(key=lambda x: (not x['is_dir'], x['name'].lower()))
|
||||
|
||||
for i, entry in enumerate(entries):
|
||||
# Prüfen, ob es das letzte Element auf dieser Ebene ist
|
||||
is_last = (i == len(entries) - 1)
|
||||
connector = "└" if is_last else "├"
|
||||
|
||||
icon = "📁" if entry['is_dir'] else "📄"
|
||||
size_str = f" ({entry['size']/1024:.2f} KB)" if entry['size'] is not None else ""
|
||||
|
||||
# Ausgabe der aktuellen Zeile
|
||||
console.print(f"{prefix}{connector}{icon} [info]{entry['name']}[/info]{size_str}")
|
||||
|
||||
# Wenn Kinder vorhanden sind, rekursiv weiter
|
||||
if 'children' in entry and entry['children']:
|
||||
# Für die Kinder-Ebene das Prefix anpassen
|
||||
extension = " " if is_last else "│ "
|
||||
self.print(entry['children'], "", prefix=prefix + extension)
|
||||
23
tool/core/cmd/play.py
Normal file
23
tool/core/cmd/play.py
Normal file
@@ -0,0 +1,23 @@
|
||||
import struct
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS
|
||||
|
||||
class play:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self, path: str, interrupt: bool):
|
||||
flags = 0x01 if interrupt else 0x00
|
||||
path_bytes = path.encode('utf-8')
|
||||
|
||||
# Payload: [1 Byte Flags] + [1 Byte Path Length] + [Path String]
|
||||
payload = struct.pack('B', flags) + struct.pack('B', len(path_bytes)) + path_bytes
|
||||
|
||||
self.bus.send_request(COMMANDS['play'], payload)
|
||||
data = self.bus.receive_ack()
|
||||
return data is not None and data.get('type') == 'ack'
|
||||
|
||||
def print(self, result, path: str, interrupt: bool):
|
||||
if result:
|
||||
mode = "sofort (Interrupt)" if interrupt else "in die Warteschlange (Queue)"
|
||||
console.print(f"▶ Wiedergabe von [info]{path}[/info] {mode} eingereiht.")
|
||||
28
tool/core/cmd/proto.py
Normal file
28
tool/core/cmd/proto.py
Normal file
@@ -0,0 +1,28 @@
|
||||
# tool/core/cmd/proto.py
|
||||
import struct
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS, ERRORS
|
||||
|
||||
class proto:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self):
|
||||
self.bus.send_request(COMMANDS['get_protocol_version'], None)
|
||||
|
||||
data = self.bus.receive_response(length=1)
|
||||
if not data or data.get('type') == 'error':
|
||||
return None
|
||||
|
||||
payload = data['data']
|
||||
result = {
|
||||
'protocol_version': payload[0]
|
||||
}
|
||||
return result
|
||||
|
||||
def print(self, result):
|
||||
if not result:
|
||||
return
|
||||
|
||||
protocol_version = result['protocol_version']
|
||||
console.print(f"[title]Protokoll Version[/info] des Controllers ist [info]{protocol_version}[/info]:")
|
||||
100
tool/core/cmd/put_file.py
Normal file
100
tool/core/cmd/put_file.py
Normal file
@@ -0,0 +1,100 @@
|
||||
# tool/core/cmd/put_file.py
|
||||
import struct
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, DownloadColumn, TransferSpeedColumn, TimeRemainingColumn
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS
|
||||
from core.tag import TagManager
|
||||
from core.cmd.put_tags import put_tags
|
||||
|
||||
class put_file:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self, source_path: str, dest_path: str, cli_tags_json: str = None):
|
||||
try:
|
||||
p = Path(source_path)
|
||||
if not p.exists() or not p.is_file():
|
||||
console_err.print(f"Fehler: Quelldatei existiert nicht: {source_path}")
|
||||
return None
|
||||
with open(p, 'rb') as f:
|
||||
file_data = f.read()
|
||||
except Exception as e:
|
||||
console_err.print(f"Fehler beim Lesen: {e}")
|
||||
return None
|
||||
|
||||
# 1. Lokale Tags abtrennen
|
||||
audio_data, local_tlvs = TagManager.split_file(file_data)
|
||||
audio_size = len(audio_data)
|
||||
|
||||
# 2. Upload der REINEN Audiodaten
|
||||
dest_path_bytes = dest_path.encode('utf-8')
|
||||
payload = struct.pack('B', len(dest_path_bytes)) + dest_path_bytes + struct.pack('<I', audio_size)
|
||||
|
||||
self.bus.send_request(COMMANDS['put_file'], payload)
|
||||
self.bus.receive_ack(timeout=5.0)
|
||||
|
||||
with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), BarColumn(), DownloadColumn(), TransferSpeedColumn(), "•", TimeRemainingColumn(), console=console, transient=False) as progress:
|
||||
task = progress.add_task(f"Sende {source_path}...", total=audio_size)
|
||||
stream_res = self.bus.send_stream(audio_data, progress_callback=lambda sent, total: progress.update(task, total=total, completed=sent))
|
||||
|
||||
if not stream_res: return None
|
||||
|
||||
remote_crc = stream_res.get('crc32')
|
||||
local_crc = zlib.crc32(audio_data) & 0xFFFFFFFF
|
||||
|
||||
if local_crc != remote_crc:
|
||||
return {'success': False, 'source_path': source_path, 'crc32_remote': remote_crc, 'crc32_local': local_crc}
|
||||
|
||||
# 3. Tags aktualisieren (CRC32 + evtl. CLI-Tags)
|
||||
# Alten CRC-Tag entfernen, neuen einsetzen
|
||||
final_tlvs = [t for t in local_tlvs if not (t['type'] == 0x00 and t['index'] == 0x01)]
|
||||
final_tlvs.append({'type': 0x00, 'index': 0x01, 'value': struct.pack('<I', local_crc)})
|
||||
|
||||
# Falls CLI-Tags übergeben wurden (-t), diese priorisiert anwenden
|
||||
if cli_tags_json:
|
||||
try:
|
||||
cli_tlvs = TagManager.parse_cli_json(cli_tags_json)
|
||||
# Bestehendes JSON löschen, wenn neues im CLI-Input definiert ist
|
||||
if any(t['type'] == 0x10 for t in cli_tlvs):
|
||||
final_tlvs = [t for t in final_tlvs if t['type'] != 0x10]
|
||||
final_tlvs.extend(cli_tlvs)
|
||||
except ValueError as e:
|
||||
console_err.print(f"[warning]Warnung: Tags konnten nicht geparst werden ({e}). Datei wurde ohne extra Tags hochgeladen.[/warning]")
|
||||
|
||||
# 4. Tags via separatem Befehl anhängen
|
||||
tag_cmd = put_tags(self.bus)
|
||||
tag_blob = TagManager.build_blob(final_tlvs)
|
||||
tag_cmd.send_blob(dest_path, tag_blob)
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'source_path': source_path,
|
||||
'dest_path': dest_path,
|
||||
'crc32_remote': remote_crc,
|
||||
'crc32_local': local_crc,
|
||||
'size': audio_size,
|
||||
'duration': stream_res.get('duration')
|
||||
}
|
||||
|
||||
def print(self, result):
|
||||
if not result:
|
||||
return
|
||||
|
||||
if result.get('success'):
|
||||
console.print(f"✓ Datei [info]{result['source_path']}[/info] erfolgreich hochgeladen und Tags generiert.")
|
||||
console.print(f" • Größe: [info]{result['size'] / 1024:.2f} KB[/info]")
|
||||
else:
|
||||
console_err.print(f"❌ CRC-FEHLER: Datei [error]{result['source_path']}[/error] wurde auf dem Gerät korrumpiert!")
|
||||
|
||||
if 'crc32_remote' in result:
|
||||
console.print(f" • Remote CRC: [info]{result['crc32_remote']:08X}[/info]")
|
||||
if 'crc32_local' in result:
|
||||
console.print(f" • Local CRC: [info]{result['crc32_local']:08X}[/info]")
|
||||
|
||||
if 'dest_path' in result:
|
||||
console.print(f" • Zielpfad: [info]{result['dest_path']}[/info]")
|
||||
|
||||
if result.get('duration') is not None and result.get('duration') > 0:
|
||||
console.print(f" • Dauer: [info]{result['duration']:.2f} s[/info]")
|
||||
89
tool/core/cmd/put_fw.py
Normal file
89
tool/core/cmd/put_fw.py
Normal file
@@ -0,0 +1,89 @@
|
||||
import struct
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, DownloadColumn, TransferSpeedColumn, TimeRemainingColumn
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS
|
||||
|
||||
class put_fw:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self, file_path: str):
|
||||
try:
|
||||
p = Path(file_path)
|
||||
if not p.exists() or not p.is_file():
|
||||
console_err.print(f"Fehler: Firmware-Datei existiert nicht: {file_path}")
|
||||
return None
|
||||
|
||||
file_size = p.stat().st_size
|
||||
with open(p, 'rb') as f:
|
||||
file_data = f.read()
|
||||
except Exception as e:
|
||||
console_err.print(f"Lese-Fehler: {e}")
|
||||
return None
|
||||
|
||||
# 1. Schritt: Löschvorgang mit minimalem Feedback
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn("[progress.description]{task.description}"),
|
||||
BarColumn(),
|
||||
console=console,
|
||||
transient=True
|
||||
) as progress:
|
||||
erase_task = progress.add_task("Lösche Firmware Slot...", total=None)
|
||||
|
||||
payload = struct.pack('<I', file_size)
|
||||
self.bus.send_request(COMMANDS['put_fw'], payload)
|
||||
|
||||
# Warten auf ACK (Balken pulsiert ohne Byte-Anzeige)
|
||||
self.bus.receive_ack(timeout=10.0)
|
||||
progress.update(erase_task, description="✓ Slot gelöscht", completed=100, total=100)
|
||||
|
||||
# 2. Schritt: Eigentlicher Transfer mit allen Metriken (Bytes, Speed, Time)
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn("[progress.description]{task.description}"),
|
||||
BarColumn(),
|
||||
DownloadColumn(),
|
||||
TransferSpeedColumn(),
|
||||
"•",
|
||||
TimeRemainingColumn(),
|
||||
console=console,
|
||||
transient=False
|
||||
) as progress:
|
||||
transfer_task = progress.add_task("Sende Firmware...", total=file_size)
|
||||
|
||||
stream_res = self.bus.send_stream(
|
||||
file_data,
|
||||
progress_callback=lambda sent, total: progress.update(transfer_task, total=total, completed=sent)
|
||||
)
|
||||
|
||||
if not stream_res:
|
||||
return None
|
||||
|
||||
remote_crc = stream_res.get('crc32')
|
||||
local_crc = zlib.crc32(file_data) & 0xFFFFFFFF
|
||||
|
||||
return {
|
||||
'success': local_crc == remote_crc,
|
||||
'source_path': file_path,
|
||||
'crc32_remote': remote_crc,
|
||||
'crc32_local': local_crc,
|
||||
'size': file_size,
|
||||
'duration': stream_res.get('duration')
|
||||
}
|
||||
|
||||
def print(self, result):
|
||||
if not result:
|
||||
return
|
||||
|
||||
if result['success']:
|
||||
console.print(f"✓ Firmware [info]{result['source_path']}[/info] erfolgreich in Slot 1 geschrieben.")
|
||||
console.print(" [warning]Achtung:[/warning] Das Image ist als 'Pending' markiert. Führe 'reboot' aus, um das Update zu installieren.")
|
||||
else:
|
||||
console_err.print(f"❌ CRC-FEHLER: Die Firmware wurde korrumpiert übertragen!")
|
||||
|
||||
console.print(f" • Größe: [info]{result['size'] / 1024:.2f} KB[/info]")
|
||||
console.print(f" • Remote CRC: [info]{result['crc32_remote']:08X}[/info]")
|
||||
console.print(f" • Local CRC: [info]{result['crc32_local']:08X}[/info]")
|
||||
68
tool/core/cmd/put_tags.py
Normal file
68
tool/core/cmd/put_tags.py
Normal file
@@ -0,0 +1,68 @@
|
||||
# tool/core/cmd/put_tags.py
|
||||
import struct
|
||||
import json
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS
|
||||
from core.tag import TagManager
|
||||
from core.cmd.get_tags import get_tags
|
||||
|
||||
class put_tags:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self, path: str, json_str: str, overwrite: bool):
|
||||
try:
|
||||
new_tlvs = TagManager.parse_cli_json(json_str)
|
||||
except ValueError as e:
|
||||
console_err.print(f"[error]{e}[/error]")
|
||||
return False
|
||||
|
||||
getter = get_tags(self.bus)
|
||||
existing_tlvs = getter.get_raw_tlvs(path)
|
||||
|
||||
if overwrite:
|
||||
# Bei Overwrite: Alle alten JSON-Tags löschen
|
||||
existing_tlvs = [t for t in existing_tlvs if t['type'] != 0x10]
|
||||
else:
|
||||
# Ohne Overwrite: Bestehende JSON-Werte mit neuen mischen
|
||||
existing_json = {}
|
||||
for t in existing_tlvs:
|
||||
if t['type'] == 0x10:
|
||||
try: existing_json.update(json.loads(t['value'].decode('utf-8')))
|
||||
except: pass
|
||||
|
||||
# Neues JSON einmischen
|
||||
for nt in new_tlvs:
|
||||
if nt['type'] == 0x10:
|
||||
try: existing_json.update(json.loads(nt['value'].decode('utf-8')))
|
||||
except: pass
|
||||
|
||||
existing_tlvs = [t for t in existing_tlvs if t['type'] != 0x10]
|
||||
if existing_json:
|
||||
existing_tlvs.append({'type': 0x10, 'index': 0x00, 'value': json.dumps(existing_json, ensure_ascii=False).encode('utf-8')})
|
||||
|
||||
# System-Tags (0x00) überschreiben alte direkt
|
||||
new_sys_tlvs = [t for t in new_tlvs if t['type'] == 0x00]
|
||||
for nt in new_sys_tlvs:
|
||||
existing_tlvs = [t for t in existing_tlvs if not (t['type'] == nt['type'] and t['index'] == nt['index'])]
|
||||
existing_tlvs.append(nt)
|
||||
|
||||
new_tlvs = existing_tlvs
|
||||
|
||||
blob = TagManager.build_blob(new_tlvs)
|
||||
return self.send_blob(path, blob)
|
||||
|
||||
def send_blob(self, path: str, blob: bytes):
|
||||
path_bytes = path.encode('utf-8')
|
||||
req_payload = struct.pack('B', len(path_bytes)) + path_bytes + struct.pack('<I', len(blob))
|
||||
|
||||
self.bus.send_request(COMMANDS['put_tags'], req_payload)
|
||||
self.bus.receive_ack(timeout=2.0)
|
||||
|
||||
if self.bus.send_stream(blob):
|
||||
return True
|
||||
return False
|
||||
|
||||
def print(self, result, path: str):
|
||||
if result:
|
||||
console.print(f"✓ Metadaten erfolgreich auf [info]{path}[/info] geschrieben.")
|
||||
23
tool/core/cmd/reboot.py
Normal file
23
tool/core/cmd/reboot.py
Normal file
@@ -0,0 +1,23 @@
|
||||
import serial
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS
|
||||
|
||||
class reboot:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self):
|
||||
self.bus.send_request(COMMANDS['reboot'])
|
||||
try:
|
||||
data = self.bus.receive_ack()
|
||||
return data is not None and data.get('type') == 'ack'
|
||||
except serial.SerialException:
|
||||
# SerialException MUSS hier ignoriert werden, da der Controller
|
||||
# den USB-Port beim Reboot hart schließt
|
||||
return True
|
||||
|
||||
def print(self, result):
|
||||
if result:
|
||||
console.print("🔄 Neustart-Befehl erfolgreich gesendet. Controller [info]bootet neu...[/info]")
|
||||
else:
|
||||
console_err.print("❌ Fehler beim Senden des Neustart-Befehls.")
|
||||
37
tool/core/cmd/rename.py
Normal file
37
tool/core/cmd/rename.py
Normal file
@@ -0,0 +1,37 @@
|
||||
# tool/core/cmd/rename.py
|
||||
import struct
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS, ERRORS
|
||||
|
||||
class rename:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self, source_path: str, dest_path: str):
|
||||
source_path_bytes = source_path.encode('utf-8')
|
||||
dest_path_bytes = dest_path.encode('utf-8')
|
||||
|
||||
payload = struct.pack('B', len(source_path_bytes)) + source_path_bytes
|
||||
payload += struct.pack('B', len(dest_path_bytes)) + dest_path_bytes
|
||||
|
||||
self.bus.send_request(COMMANDS['rename'], payload)
|
||||
|
||||
data = self.bus.receive_ack()
|
||||
|
||||
if not data or data.get('type') == 'error':
|
||||
return None
|
||||
|
||||
return {
|
||||
'success': data.get('type') == 'ack',
|
||||
'source_path': source_path,
|
||||
'dest_path': dest_path
|
||||
}
|
||||
|
||||
def print(self, result):
|
||||
if not result or not result.get('success'):
|
||||
return
|
||||
|
||||
console.print(
|
||||
f"Pfad [info]{result['source_path']}[/info] wurde erfolgreich in "
|
||||
f"[info]{result['dest_path']}[/info] umbenannt."
|
||||
)
|
||||
32
tool/core/cmd/rm.py
Normal file
32
tool/core/cmd/rm.py
Normal file
@@ -0,0 +1,32 @@
|
||||
# tool/core/cmd/rm.py
|
||||
import struct
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS, ERRORS
|
||||
|
||||
class rm:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self, path: str):
|
||||
path_bytes = path.encode('utf-8')
|
||||
payload = struct.pack('B', len(path_bytes)) + path_bytes
|
||||
self.bus.send_request(COMMANDS['rm'], payload)
|
||||
|
||||
# 1 Byte Type + 4 Byte Size = 5
|
||||
data = self.bus.receive_ack()
|
||||
|
||||
if not data or data.get('type') == 'error':
|
||||
return None
|
||||
|
||||
if data.get('type') == 'ack':
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def print(self, result, path: str):
|
||||
if result is None:
|
||||
console_err.print(f"Fehler: Pfad [error]{path}[/error] konnte nicht entfernt werden.")
|
||||
elif result is False:
|
||||
console_err.print(f"Fehler: Pfad [error]{path}[/error] existiert nicht oder konnte nicht entfernt werden.")
|
||||
else:
|
||||
console.print(f"Pfad [info]{path}[/info] wurde erfolgreich entfernt.")
|
||||
38
tool/core/cmd/set_setting.py
Normal file
38
tool/core/cmd/set_setting.py
Normal file
@@ -0,0 +1,38 @@
|
||||
import struct
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS
|
||||
|
||||
class set_setting:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self, key: str, value: str):
|
||||
key_bytes = key.encode('utf-8')
|
||||
val_bytes = b''
|
||||
|
||||
# Typen-Konvertierung basierend auf dem Key
|
||||
try:
|
||||
if key == "audio/vol":
|
||||
val_bytes = struct.pack('<B', int(value))
|
||||
elif key == "play/norepeat":
|
||||
val_int = 1 if str(value).lower() in ['1', 'true', 'on', 'yes'] else 0
|
||||
val_bytes = struct.pack('<B', val_int)
|
||||
elif key == "settings/storage_interval":
|
||||
val_bytes = struct.pack('<H', int(value))
|
||||
else:
|
||||
console_err.print(f"[error]Unbekannter Key: {key}[/error]")
|
||||
return False
|
||||
except ValueError:
|
||||
console_err.print(f"[error]Ungültiger Wert für {key}: {value}[/error]")
|
||||
return False
|
||||
|
||||
# Payload: [Key Len] [Key] [Val Len] [Val Bytes]
|
||||
payload = struct.pack('B', len(key_bytes)) + key_bytes + struct.pack('B', len(val_bytes)) + val_bytes
|
||||
self.bus.send_request(COMMANDS['set_setting'], payload)
|
||||
|
||||
data = self.bus.receive_ack()
|
||||
return data is not None and data.get('type') == 'ack'
|
||||
|
||||
def print(self, result, key: str, value: str):
|
||||
if result:
|
||||
console.print(f"✓ Setting [info]{key}[/info] wurde auf [info]{value}[/info] gesetzt.")
|
||||
36
tool/core/cmd/stat.py
Normal file
36
tool/core/cmd/stat.py
Normal file
@@ -0,0 +1,36 @@
|
||||
# tool/core/cmd/stat.py
|
||||
import struct
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS, ERRORS
|
||||
|
||||
class stat:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self, path: str):
|
||||
path_bytes = path.encode('utf-8')
|
||||
payload = struct.pack('B', len(path_bytes)) + path_bytes
|
||||
self.bus.send_request(COMMANDS['stat'], payload)
|
||||
|
||||
# 1 Byte Type + 4 Byte Size = 5
|
||||
data = self.bus.receive_response(length=5)
|
||||
|
||||
if not data or data.get('type') == 'error':
|
||||
return None
|
||||
|
||||
payload = data['data']
|
||||
result = {
|
||||
'is_directory': payload[0] == 1,
|
||||
'size': struct.unpack('<I', payload[1:5])[0]
|
||||
}
|
||||
return result
|
||||
|
||||
def print(self, result, path: str):
|
||||
if not result:
|
||||
return
|
||||
|
||||
t_name = "📁 Verzeichnis" if result['is_directory'] else "📄 Datei"
|
||||
console.print(f"[info_title]Stat[/info_title] für [info]{path}[/info]:")
|
||||
console.print(f" • Typ: [info]{t_name}[/info]")
|
||||
if not result['is_directory']:
|
||||
console.print(f" • Grösse: [info]{result['size']/1024:.2f} KB[/info] ({result['size']} Bytes)")
|
||||
15
tool/core/cmd/stop.py
Normal file
15
tool/core/cmd/stop.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import COMMANDS
|
||||
|
||||
class stop:
|
||||
def __init__(self, bus):
|
||||
self.bus = bus
|
||||
|
||||
def get(self):
|
||||
self.bus.send_request(COMMANDS['stop'])
|
||||
data = self.bus.receive_ack()
|
||||
return data is not None and data.get('type') == 'ack'
|
||||
|
||||
def print(self, result):
|
||||
if result:
|
||||
console.print("⏹ Wiedergabe gestoppt und Warteschlange geleert.")
|
||||
48
tool/core/config.py
Normal file
48
tool/core/config.py
Normal file
@@ -0,0 +1,48 @@
|
||||
# tool/core/config.py
|
||||
import os
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
|
||||
class Config:
|
||||
def __init__(self):
|
||||
self._config = None
|
||||
self.config_name = "config.yaml"
|
||||
self.custom_path = None # Speicher für den Parameter-Pfad
|
||||
self.debug = False
|
||||
|
||||
def _load(self):
|
||||
if self._config is not None:
|
||||
return
|
||||
|
||||
from core.utils import console
|
||||
|
||||
search_paths = []
|
||||
if self.custom_path:
|
||||
search_paths.append(Path(self.custom_path))
|
||||
|
||||
search_paths.append(Path(os.getcwd()) / self.config_name)
|
||||
search_paths.append(Path(__file__).parent.parent / self.config_name)
|
||||
|
||||
config_path = None
|
||||
for p in search_paths:
|
||||
if p.exists():
|
||||
config_path = p
|
||||
break
|
||||
|
||||
if not config_path:
|
||||
raise FileNotFoundError(f"Konfiguration konnte an keinem Ort gefunden werden.")
|
||||
|
||||
if not config_path.exists():
|
||||
raise FileNotFoundError(f"Konfiguration nicht gefunden: {self.config_name}")
|
||||
else:
|
||||
if self.debug: console.print(f"[bold green]✓[/bold green] Konfiguration geladen: [info]{config_path}[/info]")
|
||||
|
||||
with open(config_path, 'r') as f:
|
||||
self._config = yaml.safe_load(f)
|
||||
|
||||
@property
|
||||
def serial_settings(self):
|
||||
self._load()
|
||||
return self._config.get('serial', {})
|
||||
|
||||
cfg = Config()
|
||||
77
tool/core/protocol.py
Normal file
77
tool/core/protocol.py
Normal file
@@ -0,0 +1,77 @@
|
||||
# tool/core/protocol.py
|
||||
VERSION = {
|
||||
"min_protocol_version": 1,
|
||||
"max_protocol_version": 1,
|
||||
"current_protocol_version": None,
|
||||
}
|
||||
|
||||
SYNC_SEQ = b'BUZZ'
|
||||
|
||||
ERRORS = {
|
||||
0x00: "NONE",
|
||||
0x01: "INVALID_COMMAND",
|
||||
0x02: "INVALID_PARAMETERS",
|
||||
0x03: "MISSING_PARAMETERS",
|
||||
|
||||
0x10: "FILE_NOT_FOUND",
|
||||
0x11: "ALREADY_EXISTS",
|
||||
0x12: "NOT_A_DIRECTORY",
|
||||
0x13: "IS_A_DIRECTORY",
|
||||
0x14: "ACCESS_DENIED",
|
||||
0x15: "NO_SPACE",
|
||||
0x16: "FILE_TOO_LARGE",
|
||||
|
||||
0x20: "IO_ERROR",
|
||||
0x21: "TIMEOUT",
|
||||
0x22: "CRC_MISMATCH",
|
||||
0x23: "TRANSFER_ABORTED",
|
||||
|
||||
0x30: "NOT_SUPPORTED",
|
||||
0x31: "BUSY",
|
||||
0x32: "INTERNAL_ERROR",
|
||||
|
||||
0x40: "NOT_IMPLEMENTED",
|
||||
}
|
||||
|
||||
FRAME_TYPES = {
|
||||
'request': 0x01,
|
||||
|
||||
'ack': 0x10,
|
||||
|
||||
'response': 0x11,
|
||||
'stream_start': 0x12,
|
||||
'stream_chunk': 0x13,
|
||||
'stream_end': 0x14,
|
||||
'list_start': 0x15,
|
||||
'list_chunk': 0x16,
|
||||
'list_end': 0x17,
|
||||
|
||||
'error': 0xFF,
|
||||
}
|
||||
|
||||
COMMANDS = {
|
||||
'get_protocol_version': 0x00,
|
||||
'get_firmware_status': 0x01,
|
||||
'get_flash_info': 0x02,
|
||||
'confirm_fw': 0x03,
|
||||
'reboot': 0x04,
|
||||
|
||||
'list_dir': 0x10,
|
||||
'crc_32': 0x11,
|
||||
'mkdir': 0x12,
|
||||
'rm': 0x13,
|
||||
'stat': 0x18,
|
||||
'rename': 0x19,
|
||||
|
||||
'put_file': 0x20,
|
||||
'put_fw': 0x21,
|
||||
'get_file': 0x22,
|
||||
'put_tags': 0x24,
|
||||
'get_tags': 0x25,
|
||||
|
||||
'play': 0x30,
|
||||
'stop': 0x31,
|
||||
|
||||
'set_setting': 0x40,
|
||||
'get_setting': 0x41,
|
||||
}
|
||||
317
tool/core/serial_conn.py
Normal file
317
tool/core/serial_conn.py
Normal file
@@ -0,0 +1,317 @@
|
||||
# tool/core/serial_conn.py
|
||||
import struct
|
||||
import serial
|
||||
import time
|
||||
from core.utils import console, console_err
|
||||
from core.protocol import SYNC_SEQ, ERRORS, FRAME_TYPES, VERSION
|
||||
|
||||
class SerialBus:
|
||||
def __init__(self, settings: dict):
|
||||
"""
|
||||
Initialisiert den Bus mit den (ggf. übersteuerten) Settings.
|
||||
"""
|
||||
self.port = settings.get('port')
|
||||
self.baudrate = settings.get('baudrate', 115200)
|
||||
self.timeout = settings.get('timeout', 1.0)
|
||||
self.debug = settings.get('debug', False)
|
||||
self.connection = None
|
||||
|
||||
def open(self):
|
||||
"""Öffnet die serielle Schnittstelle."""
|
||||
try:
|
||||
self.connection = serial.Serial(
|
||||
port=self.port,
|
||||
baudrate=self.baudrate,
|
||||
timeout=self.timeout
|
||||
)
|
||||
self.flush_input()
|
||||
if self.debug: console.print(f"[bold green]✓[/bold green] Port [info]{self.port}[/info] erfolgreich geöffnet.")
|
||||
from core.cmd.proto import proto
|
||||
cmd = proto(self)
|
||||
data = cmd.get()
|
||||
VERSION["current_protocol_version"] = data['protocol_version'] if data else None
|
||||
if data:
|
||||
if self.debug: console.print(f" • Protokoll Version: [info]{data['protocol_version']}[/info]")
|
||||
if data['protocol_version'] < VERSION["min_protocol_version"] or data['protocol_version'] > VERSION["max_protocol_version"]:
|
||||
if VERSION["min_protocol_version"] == VERSION["max_protocol_version"]:
|
||||
expected = f"Version {VERSION['min_protocol_version']}"
|
||||
else:
|
||||
expected = f"Version {VERSION['min_protocol_version']} bis {VERSION['max_protocol_version']}"
|
||||
raise ValueError(f"Inkompatibles Protokoll. Controller spricht {data['protocol_version']}, erwartet wird {expected}.")
|
||||
else:
|
||||
raise ValueError("Keine gültige Antwort auf Protokollversion erhalten.")
|
||||
except serial.SerialException as e:
|
||||
console_err.print(f"[bold red]Serieller Fehler:[/bold red] [error_msg]{e}[/error_msg]")
|
||||
raise
|
||||
except Exception as e:
|
||||
console_err.print(f"[bold red]Unerwarteter Fehler beim Öffnen:[/bold red] [error_msg]{e}[/error_msg]")
|
||||
raise
|
||||
|
||||
def flush_input(self):
|
||||
"""Leert den Empfangspuffer der seriellen Schnittstelle."""
|
||||
if self.connection and self.connection.is_open:
|
||||
self.connection.reset_input_buffer()
|
||||
|
||||
def close(self):
|
||||
"""Schließt die Verbindung sauber."""
|
||||
if self.connection and self.connection.is_open:
|
||||
self.connection.close()
|
||||
if self.debug: console.print(f"Verbindung zu [info]{self.port}[/info] geschlossen.")
|
||||
|
||||
def send_binary(self, data: bytes):
|
||||
"""Sendet Rohdaten und loggt sie im Hex-Format."""
|
||||
if not self.connection or not self.connection.is_open:
|
||||
raise ConnectionError("Port ist nicht geöffnet.")
|
||||
|
||||
self.connection.write(data)
|
||||
|
||||
if self.debug:
|
||||
hex_data = data.hex(' ').upper()
|
||||
console.print(f"TX -> [grey62]{hex_data}[/grey62]")
|
||||
|
||||
def _read_exact(self, length: int, context: str = "Daten") -> bytes:
|
||||
data = bytearray()
|
||||
while len(data) < length:
|
||||
try:
|
||||
chunk = self.connection.read(length - len(data))
|
||||
except serial.SerialException as e:
|
||||
raise IOError(f"Serielle Verbindung verloren beim Lesen von {context}: {e}") from e
|
||||
if not chunk:
|
||||
raise TimeoutError(f"Timeout beim Lesen von {context}: {len(data)}/{length} Bytes.")
|
||||
data.extend(chunk)
|
||||
return bytes(data)
|
||||
|
||||
def wait_for_sync(self, sync_seq: bytes, max_time: float = 2.0):
|
||||
"""Wartet maximal max_time Sekunden auf die Sync-Sequenz."""
|
||||
buffer = b""
|
||||
start_time = time.time()
|
||||
|
||||
if self.debug:
|
||||
console.print(f"[bold cyan]Warte auf SYNC-Sequenz:[/bold cyan] [grey62]{sync_seq.hex(' ').upper()}[/grey62]")
|
||||
|
||||
# Kurzer interner Timeout für reaktive Schleife
|
||||
original_timeout = self.connection.timeout
|
||||
self.connection.timeout = 0.1
|
||||
|
||||
try:
|
||||
while (time.time() - start_time) < max_time:
|
||||
char = self.connection.read(1)
|
||||
if not char:
|
||||
continue
|
||||
|
||||
buffer += char
|
||||
if len(buffer) > len(sync_seq):
|
||||
buffer = buffer[1:]
|
||||
|
||||
if buffer == sync_seq:
|
||||
if self.debug: console.print("[bold cyan]RX <- SYNC OK[/bold cyan]")
|
||||
return True
|
||||
return False
|
||||
finally:
|
||||
self.connection.timeout = original_timeout
|
||||
|
||||
def send_request(self, cmd_id: int, payload: bytes = b''):
|
||||
self.flush_input()
|
||||
frame_type = struct.pack('B', FRAME_TYPES['request'])
|
||||
cmd_byte = struct.pack('B', cmd_id)
|
||||
|
||||
full_frame = SYNC_SEQ + frame_type + cmd_byte
|
||||
if payload:
|
||||
full_frame += payload
|
||||
self.send_binary(full_frame)
|
||||
|
||||
def send_stream(self, data: bytes, chunk_size: int = 4096, progress_callback=None):
|
||||
"""Sendet einen Datenstrom in Chunks und wartet auf die Bestätigung (CRC)."""
|
||||
start_time = time.time()
|
||||
size = len(data)
|
||||
sent_size = 0
|
||||
|
||||
while sent_size < size:
|
||||
chunk = data[sent_size:sent_size+chunk_size]
|
||||
self.connection.write(chunk)
|
||||
sent_size += len(chunk)
|
||||
|
||||
if progress_callback:
|
||||
progress_callback(sent_size, size)
|
||||
|
||||
if not self.wait_for_sync(SYNC_SEQ, max_time=self.timeout + 5.0):
|
||||
raise TimeoutError("Timeout beim Warten auf Stream-Ende (Flash ist evtl. noch beschäftigt).")
|
||||
|
||||
ftype = self._read_exact(1, "Frame-Typ")[0]
|
||||
|
||||
if ftype == FRAME_TYPES['stream_end']:
|
||||
end_time = time.time()
|
||||
crc32 = struct.unpack('<I', self._read_exact(4, "CRC32"))[0]
|
||||
return {
|
||||
'crc32': crc32,
|
||||
'duration': end_time - start_time
|
||||
}
|
||||
elif ftype == FRAME_TYPES['error']:
|
||||
err_code_raw = self.connection.read(1)
|
||||
err_code = err_code_raw[0] if err_code_raw else 0xFF
|
||||
err_name = ERRORS.get(err_code, "UNKNOWN")
|
||||
raise ControllerError(err_code, err_name)
|
||||
else:
|
||||
raise ValueError(f"Unerwarteter Frame-Typ nach Stream-Upload: 0x{ftype:02X}")
|
||||
|
||||
def receive_ack(self, timeout: float = None):
|
||||
wait_time = timeout if timeout is not None else self.timeout
|
||||
|
||||
if not self.wait_for_sync(SYNC_SEQ, max_time=wait_time):
|
||||
raise TimeoutError(f"SYNC-Sequenz nicht innerhalb von {wait_time}s gefunden.")
|
||||
|
||||
ftype_raw = self.connection.read(1)
|
||||
if not ftype_raw:
|
||||
raise TimeoutError("Timeout beim Lesen des Frame-Typs.")
|
||||
ftype = ftype_raw[0]
|
||||
|
||||
if ftype == FRAME_TYPES['error']:
|
||||
err_code_raw = self.connection.read(1)
|
||||
err_code = err_code_raw[0] if err_code_raw else 0xFF
|
||||
err_name = ERRORS.get(err_code, "UNKNOWN")
|
||||
raise ControllerError(err_code, err_name)
|
||||
|
||||
elif ftype == FRAME_TYPES['ack']:
|
||||
if self.debug:
|
||||
console.print(f"[green]ACK empfangen[/green]")
|
||||
return {"type": "ack"}
|
||||
raise ValueError(f"Unerwarteter Frame-Typ (0x{FRAME_TYPES['ack']:02X} (ACK) erwartet): 0x{ftype:02X}")
|
||||
|
||||
def receive_response(self, length: int, timeout: float = None, varlen_params: int = 0):
|
||||
wait_time = timeout if timeout is not None else self.timeout
|
||||
|
||||
if not self.wait_for_sync(SYNC_SEQ, max_time=wait_time):
|
||||
raise TimeoutError(f"SYNC-Sequenz nicht innerhalb von {wait_time}s gefunden.")
|
||||
|
||||
ftype_raw = self.connection.read(1)
|
||||
if not ftype_raw:
|
||||
raise TimeoutError("Timeout beim Lesen des Frame-Typs.")
|
||||
ftype = ftype_raw[0]
|
||||
|
||||
if ftype == FRAME_TYPES['error']:
|
||||
err_code_raw = self.connection.read(1)
|
||||
err_code = err_code_raw[0] if err_code_raw else 0xFF
|
||||
err_name = ERRORS.get(err_code, "UNKNOWN")
|
||||
raise ControllerError(err_code, err_name)
|
||||
|
||||
elif ftype == FRAME_TYPES['response']:
|
||||
data = self.connection.read(length)
|
||||
for varlen_param in range(varlen_params):
|
||||
length_byte = self.connection.read(1)
|
||||
if not length_byte:
|
||||
raise TimeoutError("Timeout beim Lesen der Länge eines variablen Parameters.")
|
||||
param_length = length_byte[0]
|
||||
param_data = self.connection.read(param_length)
|
||||
if not param_data:
|
||||
raise TimeoutError("Timeout beim Lesen eines variablen Parameters.")
|
||||
data += length_byte + param_data
|
||||
if self.debug:
|
||||
console.print(f"RX <- [grey62]{data.hex(' ').upper()}[/grey62]")
|
||||
if len(data) < length:
|
||||
raise IOError(f"Unvollständiges Paket: {len(data)}/{length} Bytes.")
|
||||
return {"type": "response", "data": data}
|
||||
|
||||
raise ValueError(f"Unerwarteter Frame-Typ: 0x{ftype:02X}")
|
||||
|
||||
def receive_list(self):
|
||||
"""Liest eine Liste von Einträgen, bis list_end kommt."""
|
||||
is_list = False
|
||||
list_items = []
|
||||
|
||||
while True:
|
||||
if not self.wait_for_sync(SYNC_SEQ):
|
||||
raise TimeoutError("Timeout beim Warten auf Sync im List-Modus.")
|
||||
|
||||
ftype = self.connection.read(1)[0]
|
||||
|
||||
if ftype == FRAME_TYPES['list_start']:
|
||||
is_list = True
|
||||
list_items = []
|
||||
elif ftype == FRAME_TYPES['list_chunk']:
|
||||
if not is_list: raise ValueError("Chunk ohne Start.")
|
||||
length = struct.unpack('<H', self.connection.read(2))[0]
|
||||
if self.debug: console.print(f"Erwarte List-Chunk mit Länge: {length} Bytes")
|
||||
data = self.connection.read(length)
|
||||
if self.debug: console.print(f"Rohdaten List-Chunk: [grey62]{data.hex(' ').upper()}[/grey62]") # Debug-Ausgabe des rohen Chunks
|
||||
list_items.append(data)
|
||||
elif ftype == FRAME_TYPES['list_end']:
|
||||
if not is_list: raise ValueError("Ende ohne Start.")
|
||||
num_entries = struct.unpack('<H', self.connection.read(2))[0]
|
||||
if len(list_items) != num_entries:
|
||||
console_err.print(f"[warning]Warnung: Erwartete {num_entries} Items, bekam {len(list_items)}[/warning]")
|
||||
return list_items
|
||||
elif ftype == FRAME_TYPES['error']:
|
||||
err_code_raw = self.connection.read(1)
|
||||
err_code = err_code_raw[0] if err_code_raw else 0xFF
|
||||
err_name = ERRORS.get(err_code, "UNKNOWN")
|
||||
raise ControllerError(err_code, err_name)
|
||||
|
||||
def receive_stream(self, chunk_size: int = 1024, progress_callback=None):
|
||||
"""Liest einen Datenstrom in Chunks, bis ein Fehler oder Ende-Signal kommt."""
|
||||
is_stream = False
|
||||
data_chunks = []
|
||||
start_time = None
|
||||
|
||||
while True:
|
||||
if not self.wait_for_sync(SYNC_SEQ):
|
||||
raise TimeoutError("Timeout beim Warten auf Sync im Stream-Modus.")
|
||||
|
||||
ftype = self._read_exact(1, "Frame-Typ")[0]
|
||||
|
||||
if ftype == FRAME_TYPES['stream_start']:
|
||||
is_stream = True
|
||||
data_chunks = []
|
||||
size = struct.unpack('<I', self._read_exact(4, "Stream-Größe"))[0]
|
||||
start_time = time.time()
|
||||
|
||||
received_size = 0
|
||||
while received_size < size:
|
||||
chunk_length = min(chunk_size, size - received_size)
|
||||
chunk_data = self._read_exact(chunk_length, f"Daten-Chunk @ {received_size}/{size}")
|
||||
data_chunks.append(chunk_data)
|
||||
received_size += len(chunk_data)
|
||||
|
||||
# Callback für UI-Update (z.B. Progress Bar)
|
||||
if progress_callback:
|
||||
progress_callback(received_size, size)
|
||||
|
||||
if self.debug: console.print("Stream vollständig empfangen.")
|
||||
|
||||
elif ftype == FRAME_TYPES['stream_end']:
|
||||
end_time = time.time()
|
||||
if not is_stream: raise ValueError("Ende ohne Start.")
|
||||
crc32 = struct.unpack('<I', self._read_exact(4, "CRC32"))[0]
|
||||
return {
|
||||
'data': b''.join(data_chunks),
|
||||
'crc32': crc32,
|
||||
'duration': end_time - start_time if start_time and end_time else None
|
||||
}
|
||||
|
||||
# elif ftype == FRAME_TYPES['list_chunk']:
|
||||
# if not is_list: raise ValueError("Chunk ohne Start.")
|
||||
# length = struct.unpack('<H', self.connection.read(2))[0]
|
||||
# if self.debug: console.print(f"Erwarte List-Chunk mit Länge: {length} Bytes")
|
||||
# data = self.connection.read(length)
|
||||
# if self.debug: console.print(f"Rohdaten List-Chunk: [grey62]{data.hex(' ').upper()}[/grey62]") # Debug-Ausgabe des rohen Chunks
|
||||
# list_items.append(data)
|
||||
# elif ftype == FRAME_TYPES['list_end']:
|
||||
# if not is_list: raise ValueError("Ende ohne Start.")
|
||||
# num_entries = struct.unpack('<H', self.connection.read(2))[0]
|
||||
# if len(list_items) != num_entries:
|
||||
# console_err.print(f"[warning]Warnung: Erwartete {num_entries} Items, bekam {len(list_items)}[/warning]")
|
||||
# return list_items
|
||||
elif ftype == FRAME_TYPES['error']:
|
||||
err_code_raw = self.connection.read(1)
|
||||
err_code = err_code_raw[0] if err_code_raw else 0xFF
|
||||
err_name = ERRORS.get(err_code, "UNKNOWN")
|
||||
raise ControllerError(err_code, err_name)
|
||||
|
||||
else:
|
||||
raise ValueError(f"Unerwarteter Frame-Typ: 0x{ftype:02X}")
|
||||
|
||||
class ControllerError(Exception):
|
||||
"""Wird ausgelöst, wenn der Controller einen Error-Frame (0xFF) sendet."""
|
||||
def __init__(self, code, name):
|
||||
self.code = code
|
||||
self.name = name
|
||||
super().__init__(f"Controller Error 0x{code:02X} ({name})")
|
||||
95
tool/core/tag.py
Normal file
95
tool/core/tag.py
Normal file
@@ -0,0 +1,95 @@
|
||||
# tool/core/tag.py
|
||||
import struct
|
||||
import json
|
||||
|
||||
class TagManager:
|
||||
FOOTER_MAGIC = b'TAG!'
|
||||
FOOTER_SIZE = 8
|
||||
FORMAT_VERSION = 1
|
||||
|
||||
@classmethod
|
||||
def split_file(cls, file_data: bytes):
|
||||
"""Trennt eine Datei in reine Audiodaten und eine Liste von TLVs auf."""
|
||||
if len(file_data) < cls.FOOTER_SIZE:
|
||||
return file_data, []
|
||||
|
||||
footer = file_data[-cls.FOOTER_SIZE:]
|
||||
total_size, version, magic = struct.unpack('<HH4s', footer)
|
||||
|
||||
if magic != cls.FOOTER_MAGIC or version != cls.FORMAT_VERSION:
|
||||
return file_data, []
|
||||
|
||||
if total_size > len(file_data) or total_size < cls.FOOTER_SIZE:
|
||||
return file_data, []
|
||||
|
||||
audio_limit = len(file_data) - total_size
|
||||
audio_data = file_data[:audio_limit]
|
||||
tag_data = file_data[audio_limit:-cls.FOOTER_SIZE]
|
||||
|
||||
tlvs = cls.parse_tlvs(tag_data)
|
||||
return audio_data, tlvs
|
||||
|
||||
@classmethod
|
||||
def parse_tlvs(cls, tag_data: bytes):
|
||||
"""Parst einen rohen TLV-Byteblock in eine Liste von Dictionaries."""
|
||||
tlvs = []
|
||||
pos = 0
|
||||
while pos + 4 <= len(tag_data):
|
||||
t, i, length = struct.unpack('<BBH', tag_data[pos:pos+4])
|
||||
pos += 4
|
||||
if pos + length > len(tag_data):
|
||||
break # Korrupt
|
||||
val = tag_data[pos:pos+length]
|
||||
tlvs.append({'type': t, 'index': i, 'value': val})
|
||||
pos += length
|
||||
return tlvs
|
||||
|
||||
@classmethod
|
||||
def build_blob(cls, tlvs: list):
|
||||
"""Baut aus einer TLV-Liste den fertigen Byte-Blob inklusive Footer."""
|
||||
# Sortierung: Type 0x00 (System) zwingend nach vorne
|
||||
tlvs = sorted(tlvs, key=lambda x: x['type'])
|
||||
|
||||
payload = b""
|
||||
for tlv in tlvs:
|
||||
payload += struct.pack('<BBH', tlv['type'], tlv['index'], len(tlv['value']))
|
||||
payload += tlv['value']
|
||||
|
||||
total_size = len(payload) + cls.FOOTER_SIZE
|
||||
footer = struct.pack('<HH4s', total_size, cls.FORMAT_VERSION, cls.FOOTER_MAGIC)
|
||||
return payload + footer
|
||||
|
||||
@classmethod
|
||||
def parse_cli_json(cls, json_str: str):
|
||||
"""Konvertiert den Kommandozeilen-JSON-String in neue TLVs."""
|
||||
try:
|
||||
data = json.loads(json_str)
|
||||
except json.JSONDecodeError as e:
|
||||
raise ValueError(f"Ungültiges JSON-Format: {e}")
|
||||
|
||||
new_tlvs = []
|
||||
|
||||
# 1. System Tags (0x00)
|
||||
if "system" in data:
|
||||
sys_data = data["system"]
|
||||
if "format" in sys_data:
|
||||
fmt = sys_data["format"]
|
||||
if isinstance(fmt, str) and fmt.startswith("0x"):
|
||||
val = bytes.fromhex(fmt[2:])
|
||||
else:
|
||||
val = struct.pack('<BBHI', fmt.get("codec", 0), fmt.get("bit_depth", 16), 0, fmt.get("samplerate", 16000))
|
||||
new_tlvs.append({'type': 0x00, 'index': 0x00, 'value': val})
|
||||
|
||||
if "crc32" in sys_data:
|
||||
crc_str = sys_data["crc32"]
|
||||
crc_val = int(crc_str, 16) if isinstance(crc_str, str) else crc_str
|
||||
new_tlvs.append({'type': 0x00, 'index': 0x01, 'value': struct.pack('<I', crc_val)})
|
||||
|
||||
# 2. JSON Tags (0x10)
|
||||
if "json" in data:
|
||||
# Bei leerem JSON-Objekt ("{}") wird kein 0x10 TLV erstellt
|
||||
if data["json"]:
|
||||
json_bytes = json.dumps(data["json"], ensure_ascii=False).encode('utf-8')
|
||||
new_tlvs.append({'type': 0x10, 'index': 0x00, 'value': json_bytes})
|
||||
|
||||
return new_tlvs
|
||||
14
tool/core/utils.py
Normal file
14
tool/core/utils.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from rich.console import Console
|
||||
from rich.theme import Theme
|
||||
|
||||
custom_theme = Theme({
|
||||
"info": "bold blue",
|
||||
"warning": "yellow",
|
||||
"error": "bold red",
|
||||
"error_msg": "red",
|
||||
"sync": "bold magenta",
|
||||
"wait": "italic grey50"
|
||||
})
|
||||
|
||||
console = Console(theme=custom_theme, highlight=False)
|
||||
console_err = Console(theme=custom_theme, stderr=True, highlight=False)
|
||||
3
tool/requirements.txt
Normal file
3
tool/requirements.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
PyYAML
|
||||
pyserial
|
||||
rich
|
||||
@@ -1,50 +1,143 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { bus } from '../lib/bus/SerialBus';
|
||||
import { buzzer } from '../lib/buzzerStore';
|
||||
import { connectToPort, disconnectBuzzer,initSerialListeners } from '../lib/buzzerActions';
|
||||
import { PlugsIcon, PlugsConnectedIcon } from 'phosphor-svelte';
|
||||
import { GetProtocolCommand } from '../lib/protocol/commands/GetProtocol';
|
||||
import { addToast } from '../lib/toastStore';
|
||||
import {
|
||||
PlugsIcon,
|
||||
PlugsConnectedIcon,
|
||||
CaretDownIcon,
|
||||
BluetoothIcon,
|
||||
TrashIcon,
|
||||
PlusCircleIcon
|
||||
} from 'phosphor-svelte';
|
||||
import { slide } from 'svelte/transition';
|
||||
import { initializeBuzzer } from '../lib/buzzerActions';
|
||||
|
||||
const BUZZER_FILTER = [
|
||||
{ usbVendorId: 0x2fe3, usbProductId: 0x0001 },
|
||||
];
|
||||
onMount(() => {
|
||||
initSerialListeners();
|
||||
});
|
||||
const BUZZER_FILTER = [{ usbVendorId: 0x1209, usbProductId: 0xEDED }];
|
||||
|
||||
async function handleConnectClick() {
|
||||
try {
|
||||
if ($buzzer.connected) {
|
||||
console.log("Trenne verbindung zum aktuellen Buzzer...");
|
||||
await disconnectBuzzer();
|
||||
console.log("Verbindung getrennt");
|
||||
let showMenu = false;
|
||||
let menuElement: HTMLElement;
|
||||
|
||||
// Schließt das Menü bei Klick außerhalb
|
||||
function handleOutsideClick(event: MouseEvent) {
|
||||
if (showMenu && menuElement && !menuElement.contains(event.target as Node)) {
|
||||
showMenu = false;
|
||||
}
|
||||
}
|
||||
|
||||
const port = await navigator.serial.requestPort({ filters: BUZZER_FILTER });
|
||||
console.log("Port ausgewählt, versuche Verbindung.", port.getInfo());
|
||||
await connectToPort(port);
|
||||
} catch (e) {
|
||||
// Verhindert das Error-Logging, wenn der User einfach nur "Abbrechen" klickt
|
||||
if (e instanceof Error && e.name === 'NotFoundError') {
|
||||
console.log("Keine Verbindung ausgewählt, Abbruch durch Nutzer.");
|
||||
async function connectTo(port: SerialPort) {
|
||||
try {
|
||||
await bus.connect(port);
|
||||
// Kurze Pause für die Hardware-Bereitschaft
|
||||
await new Promise(r => setTimeout(r, 100));
|
||||
|
||||
// Logische Initialisierung starten
|
||||
await initializeBuzzer();
|
||||
|
||||
} catch (e: any) {
|
||||
console.error("Port-Fehler:", e);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMainAction() {
|
||||
if ($buzzer.connected) {
|
||||
await bus.disconnect();
|
||||
buzzer.update(s => ({ ...s, connected: false }));
|
||||
return;
|
||||
}
|
||||
console.error("Verbindung abgebrochen", e);
|
||||
|
||||
const ports = await navigator.serial.getPorts();
|
||||
if (ports.length > 0) {
|
||||
await connectTo(ports[0]);
|
||||
} else {
|
||||
await pairNewDevice();
|
||||
}
|
||||
}
|
||||
|
||||
async function pairNewDevice() {
|
||||
showMenu = false;
|
||||
try {
|
||||
const port = await navigator.serial.requestPort({ filters: BUZZER_FILTER });
|
||||
await connectTo(port);
|
||||
} catch (e) {
|
||||
console.log("Pairing abgebrochen");
|
||||
}
|
||||
}
|
||||
|
||||
async function forgetDevice() {
|
||||
showMenu = false;
|
||||
const ports = await navigator.serial.getPorts();
|
||||
for (const port of ports) {
|
||||
if ('forget' in port) {
|
||||
await (port as any).forget();
|
||||
}
|
||||
}
|
||||
if ($buzzer.connected) {
|
||||
await bus.disconnect();
|
||||
buzzer.update(s => ({ ...s, connected: false }));
|
||||
}
|
||||
addToast("Geräte entkoppelt", "info");
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
window.addEventListener('click', handleOutsideClick);
|
||||
return () => window.removeEventListener('click', handleOutsideClick);
|
||||
});
|
||||
</script>
|
||||
|
||||
<button
|
||||
on:click={handleConnectClick}
|
||||
class="flex items-center gap-2 px-4 py-2 rounded-xl transition-all
|
||||
<div class="relative inline-flex shadow-lg" bind:this={menuElement}>
|
||||
<button
|
||||
on:click={handleMainAction}
|
||||
class="flex items-center gap-3 px-5 py-2.5 rounded-l-xl transition-all border-r border-white/10
|
||||
{$buzzer.connected
|
||||
? 'bg-emerald-500/20 text-emerald-400 border border-emerald-500/50'
|
||||
: 'bg-slate-700 hover:bg-slate-600 text-slate-200 border border-slate-600'}"
|
||||
>
|
||||
? 'bg-emerald-600 hover:bg-emerald-500 text-white'
|
||||
: 'bg-slate-700 hover:bg-slate-600 text-slate-200'}"
|
||||
>
|
||||
{#if $buzzer.connected}
|
||||
<PlugsConnectedIcon size={18} weight="fill" />
|
||||
<span class="text-xs font-bold uppercase tracking-wider text-emerald-300">Verbunden</span>
|
||||
<PlugsConnectedIcon size={20} weight="fill" />
|
||||
<span class="text-sm font-bold uppercase tracking-wide">Trennen</span>
|
||||
{:else}
|
||||
<PlugsIcon size={18} weight="bold" />
|
||||
<span class="text-xs font-bold uppercase tracking-wider">Verbinden</span>
|
||||
<PlugsIcon size={20} weight="bold" />
|
||||
<span class="text-sm font-bold uppercase tracking-wide">Verbinden</span>
|
||||
{/if}
|
||||
</button>
|
||||
</button>
|
||||
|
||||
<button
|
||||
on:click={() => showMenu = !showMenu}
|
||||
class="px-3 py-2.5 rounded-r-xl transition-all
|
||||
{$buzzer.connected
|
||||
? 'bg-emerald-600 hover:bg-emerald-500 text-white'
|
||||
: 'bg-slate-700 hover:bg-slate-600 text-slate-200'}"
|
||||
>
|
||||
<CaretDownIcon size={16} weight="bold" class="transition-transform {showMenu ? 'rotate-180' : ''}" />
|
||||
</button>
|
||||
|
||||
{#if showMenu}
|
||||
<div
|
||||
transition:slide={{ duration: 150 }}
|
||||
class="absolute top-full right-0 mt-2 w-56 bg-slate-800 border border-slate-700 rounded-xl overflow-hidden z-50 shadow-2xl"
|
||||
>
|
||||
<div class="p-2 flex flex-col gap-1">
|
||||
<button
|
||||
on:click={pairNewDevice}
|
||||
class="flex items-center gap-3 w-full px-3 py-2 text-sm text-slate-300 hover:bg-slate-700 rounded-lg transition-colors"
|
||||
>
|
||||
<PlusCircleIcon size={18} class="text-emerald-400" />
|
||||
Neuen Buzzer koppeln
|
||||
</button>
|
||||
|
||||
<div class="h-px bg-slate-700 my-1"></div>
|
||||
|
||||
<button
|
||||
on:click={forgetDevice}
|
||||
class="flex items-center gap-3 w-full px-3 py-2 text-sm text-rose-400 hover:bg-rose-500/10 rounded-lg transition-colors"
|
||||
>
|
||||
<TrashIcon size={18} />
|
||||
Buzzer entkoppeln
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,8 +1,15 @@
|
||||
<script>
|
||||
import { buzzer } from '../lib/buzzerStore';
|
||||
import { CpuIcon } from 'phosphor-svelte';
|
||||
</script>
|
||||
|
||||
<div class="text-[11px] font-mono text-slate-400 space-y-1 relative z-10">
|
||||
<div class="h-48 bg-indigo-950/20 border border-indigo-500/20 rounded-[2rem] p-6 relative overflow-hidden shrink-0">
|
||||
<div class="absolute top-6 right-6 text-indigo-500 opacity-20">
|
||||
<CpuIcon class="w-12 h-12" weight="fill" />
|
||||
</div>
|
||||
<h3 class="text-indigo-400 text-[10px] font-black uppercase tracking-[0.2em] mb-4">
|
||||
Device Info
|
||||
</h3>
|
||||
<div class="text-[11px] font-mono text-slate-400 space-y-1 relative z-10 transition-all duration-300 {!$buzzer.connected ? 'blur-[1px] opacity-30 grayscale pointer-events-none' : ''}">
|
||||
<p>
|
||||
Firmware: <span class="text-indigo-300">{$buzzer.version}</span>
|
||||
</p>
|
||||
@@ -14,4 +21,5 @@
|
||||
{$buzzer.connected ? 'Confirmed' : 'Disconnected'}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -14,7 +14,7 @@
|
||||
$: isDisconnected = !$buzzer.connected;
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-1.5 w-96 transition-all duration-700 {isDisconnected ? 'blur-sm opacity-30 grayscale pointer-events-none' : ''}">
|
||||
<div class="flex flex-col gap-1.5 w-96 transition-all duration-300 {isDisconnected ? 'blur-[1px] opacity-30 grayscale pointer-events-none' : ''}">
|
||||
|
||||
<div class="h-3.5 w-full bg-slate-800 rounded-full overflow-hidden flex border border-slate-700 shadow-inner">
|
||||
<div class="h-full bg-slate-300 transition-all duration-500" style="width: {pMeta}%"></div>
|
||||
|
||||
@@ -1,10 +1,31 @@
|
||||
<script lang="ts">
|
||||
import { buzzer } from '../lib/buzzerStore';
|
||||
import { playFile, deleteFile } from '../lib/buzzerActions';
|
||||
import { MusicNotesIcon, WrenchIcon, PlayIcon, TrashIcon, ArrowsLeftRightIcon, QuestionMarkIcon } from "phosphor-svelte";
|
||||
import { InfoIcon, MusicNotesIcon, WrenchIcon, PlayIcon, TrashIcon, ArrowsLeftRightIcon, QuestionMarkIcon } from "phosphor-svelte";
|
||||
import { PlayFileCommand } from '../lib/protocol/commands/PlayFile';
|
||||
|
||||
export let file: { name: string, size: string, isSystem: boolean, crc32?: number};
|
||||
export let selected = false;
|
||||
|
||||
async function handlePlay() {
|
||||
try {
|
||||
const cmd = new PlayFileCommand();
|
||||
|
||||
// 1. WICHTIG: Der Buzzer braucht den absoluten Pfad!
|
||||
const fullPath = `/lfs/a/${file.name}`;
|
||||
|
||||
console.log("Sende Play-Befehl für:", fullPath);
|
||||
const success = await cmd.execute(fullPath);
|
||||
|
||||
if (success) {
|
||||
// Optional: Erfolg kurz im Log zeigen
|
||||
console.log("Wiedergabe läuft...");
|
||||
} else {
|
||||
addToast(`Buzzer konnte ${file.name} nicht abspielen.`, "error");
|
||||
}
|
||||
} catch (e: any) {
|
||||
addToast(`Fehler: ${e.message}`, "error");
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div
|
||||
@@ -48,17 +69,24 @@
|
||||
|
||||
<div class="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0 ml-4">
|
||||
<button
|
||||
on:click|stopPropagation={() => playFile(file.name)}
|
||||
class="p-2 hover:bg-gray-500/20 rounded-lg text-white-400 transition-colors"
|
||||
title="Datei-Infos"
|
||||
>
|
||||
<InfoIcon size={16} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
on:click|stopPropagation={handlePlay}
|
||||
class="p-2 hover:bg-blue-500/20 rounded-lg text-blue-400 transition-colors"
|
||||
title="Play Sound"
|
||||
title="Auf dem Buzzer abspielen"
|
||||
>
|
||||
<PlayIcon size={16} weight="fill" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
on:click|stopPropagation={() => deleteFile(file.name)}
|
||||
// on:click|stopPropagation={() => deleteFile(file.name)}
|
||||
class="p-2 hover:bg-red-500/20 rounded-lg text-red-400 transition-colors"
|
||||
title="Delete File"
|
||||
title="Datei vom Buzzer löschen"
|
||||
>
|
||||
<TrashIcon size={16} weight="fill" />
|
||||
</button>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
<script lang="ts">
|
||||
import { buzzer } from '../lib/buzzerStore';
|
||||
import { refreshFileList } from '../lib/buzzerActions';
|
||||
import FileRow from './FileRow.svelte';
|
||||
import { ArrowsCounterClockwiseIcon } from 'phosphor-svelte';
|
||||
import { refreshFileList } from '../lib/buzzerActions';
|
||||
|
||||
async function handleRefresh() {
|
||||
console.log("Aktualisiere Dateiliste...");
|
||||
await refreshFileList();
|
||||
}
|
||||
</script>
|
||||
|
||||
134
webpage/src/lib/bus/SerialBus.ts
Normal file
134
webpage/src/lib/bus/SerialBus.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
import { SYNC_SEQ, FrameType } from '../protocol/constants';
|
||||
import { buzzer } from '../buzzerStore';
|
||||
|
||||
class SerialBus {
|
||||
public port: SerialPort | null = null;
|
||||
private reader: ReadableStreamDefaultReader<Uint8Array> | null = null;
|
||||
private internalBuffer: Uint8Array = new Uint8Array(0);
|
||||
|
||||
async connect(port: SerialPort) {
|
||||
if (this.port) await this.disconnect();
|
||||
await port.open({ baudRate: 115200 });
|
||||
this.port = port;
|
||||
this.internalBuffer = new Uint8Array(0);
|
||||
this.reader = null;
|
||||
port.addEventListener('disconnect', () => {
|
||||
console.warn("Hardware-Verbindung verloren!");
|
||||
this.disconnect();
|
||||
buzzer.update(s => ({ ...s, connected: false }));
|
||||
});
|
||||
(window as any).buzzerBus = this;
|
||||
}
|
||||
|
||||
// Hilfsmethode: Stellt sicher, dass wir einen aktiven Reader haben ohne zu crashen
|
||||
private async ensureReader() {
|
||||
if (!this.port?.readable) throw new Error("Port nicht lesbar");
|
||||
if (!this.reader) {
|
||||
this.reader = this.port.readable.getReader();
|
||||
}
|
||||
}
|
||||
|
||||
async sendRequest(cmd: number, payload: Uint8Array = new Uint8Array(0)) {
|
||||
if (!this.port?.writable) throw new Error("Port nicht bereit");
|
||||
const writer = this.port.writable.getWriter();
|
||||
const header = new Uint8Array([FrameType.REQUEST, cmd]);
|
||||
const frame = new Uint8Array(SYNC_SEQ.length + header.length + payload.length);
|
||||
frame.set(SYNC_SEQ, 0);
|
||||
frame.set(header, SYNC_SEQ.length);
|
||||
frame.set(payload, SYNC_SEQ.length + header.length);
|
||||
await writer.write(frame);
|
||||
writer.releaseLock();
|
||||
}
|
||||
|
||||
async waitForSync(timeoutMs = 2000): Promise<boolean> {
|
||||
await this.ensureReader();
|
||||
const startTime = Date.now();
|
||||
|
||||
while (Date.now() - startTime < timeoutMs) {
|
||||
// 1. Zuerst im Puffer schauen (verhindert Datenverlust zwischen Frames!)
|
||||
for (let i = 0; i <= this.internalBuffer.length - SYNC_SEQ.length; i++) {
|
||||
if (this.internalBuffer[i] === SYNC_SEQ[0] && this.internalBuffer[i+1] === SYNC_SEQ[1] &&
|
||||
this.internalBuffer[i+2] === SYNC_SEQ[2] && this.internalBuffer[i+3] === SYNC_SEQ[3]) {
|
||||
this.internalBuffer = this.internalBuffer.subarray(i + SYNC_SEQ.length);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Neue Daten lesen
|
||||
const { value, done } = await this.reader!.read();
|
||||
if (done) break;
|
||||
if (value) {
|
||||
const next = new Uint8Array(this.internalBuffer.length + value.length);
|
||||
next.set(this.internalBuffer);
|
||||
next.set(value, this.internalBuffer.length);
|
||||
this.internalBuffer = next;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async readExact(len: number): Promise<Uint8Array> {
|
||||
await this.ensureReader();
|
||||
while (this.internalBuffer.length < len) {
|
||||
const { value, done } = await this.reader!.read();
|
||||
if (done || !value) throw new Error("Stream closed");
|
||||
const next = new Uint8Array(this.internalBuffer.length + value.length);
|
||||
next.set(this.internalBuffer);
|
||||
next.set(value, this.internalBuffer.length);
|
||||
this.internalBuffer = next;
|
||||
}
|
||||
const res = this.internalBuffer.subarray(0, len);
|
||||
this.internalBuffer = this.internalBuffer.subarray(len);
|
||||
return res;
|
||||
}
|
||||
|
||||
public releaseReadLock() {
|
||||
if (this.reader) {
|
||||
this.reader.releaseLock();
|
||||
this.reader = null;
|
||||
}
|
||||
}
|
||||
|
||||
async disconnect() {
|
||||
this.releaseReadLock();
|
||||
if (this.port) {
|
||||
try { await this.port.close(); } catch (e) {}
|
||||
this.port = null;
|
||||
}
|
||||
this.internalBuffer = new Uint8Array(0);
|
||||
}
|
||||
}
|
||||
|
||||
const existingBus = typeof window !== 'undefined' ? (window as any).buzzerBus : null;
|
||||
|
||||
export const bus: SerialBus = existingBus || new SerialBus();
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
(window as any).buzzerBus = bus;
|
||||
|
||||
(window as any).initDebug = async () => {
|
||||
console.log("🚀 Lade Debug-Kommandos...");
|
||||
|
||||
// Nutze hier am besten absolute Pfade ab /src/
|
||||
const [proto, settings, list, play, flash] = await Promise.all([
|
||||
import('../protocol/commands/GetProtocol.ts'),
|
||||
import('../protocol/commands/GetSettings.ts'),
|
||||
import('../protocol/commands/ListDir.ts'),
|
||||
import('../protocol/commands/PlayFile.ts'), // Pfad prüfen!
|
||||
import('../protocol/commands/GetFlashInfo.ts') // Pfad prüfen!
|
||||
]);
|
||||
|
||||
(window as any).GetProtocolCommand = proto.GetProtocolCommand;
|
||||
(window as any).GetSettingCommand = settings.GetSettingCommand;
|
||||
(window as any).ListDirCommand = list.ListDirCommand;
|
||||
(window as any).PlayFileCommand = play.PlayFileCommand;
|
||||
(window as any).GetFlashInfoCommand = flash.GetFlashInfoCommand;
|
||||
|
||||
console.log("✅ Alle Commands geladen und an window gebunden.");
|
||||
};
|
||||
|
||||
(window as any).run = async (CommandClass: any, ...args: any[]) => {
|
||||
const cmd = new CommandClass();
|
||||
return await cmd.execute(...args);
|
||||
};
|
||||
}
|
||||
@@ -1,362 +1,46 @@
|
||||
import { buzzer } from './buzzerStore';
|
||||
import { get } from 'svelte/store';
|
||||
import { addToast } from './toastStore';
|
||||
|
||||
let isConnecting = false;
|
||||
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
type Task = {
|
||||
command: string;
|
||||
priority: number; // 0 = Hintergrund, 1 = User-Aktion
|
||||
resolve: (lines: string[]) => void;
|
||||
key?: string;
|
||||
};
|
||||
|
||||
class SerialQueue {
|
||||
private queue: Task[] = [];
|
||||
private isProcessing = false;
|
||||
private port: SerialPort | null = null;
|
||||
|
||||
private reader: ReadableStreamDefaultReader<Uint8Array> | null = null;
|
||||
private writer: WritableStreamDefaultWriter<Uint8Array> | null = null;
|
||||
|
||||
setPort(port: SerialPort | null) { this.port = port; }
|
||||
|
||||
async add(command: string, priority = 1, key?: string): Promise<string[]> {
|
||||
if (key) {
|
||||
this.queue = this.queue.filter(t => t.key !== key);
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const task = { command, priority, resolve, key };
|
||||
if (priority === 1) {
|
||||
const lastUserTaskIndex = this.queue.findLastIndex(t => t.priority === 1);
|
||||
this.queue.splice(lastUserTaskIndex + 1, 0, task);
|
||||
} else {
|
||||
this.queue.push(task);
|
||||
}
|
||||
this.process();
|
||||
});
|
||||
}
|
||||
|
||||
private async process() {
|
||||
if (this.isProcessing || !this.port || this.queue.length === 0) return;
|
||||
this.isProcessing = true;
|
||||
|
||||
const task = this.queue.shift()!;
|
||||
try {
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
// Reader und Writer in der Instanz speichern
|
||||
this.writer = this.port.writable.getWriter();
|
||||
this.reader = this.port.readable.getReader();
|
||||
|
||||
await this.writer.write(encoder.encode(task.command + "\n"));
|
||||
|
||||
// Writer sofort wieder freigeben nach dem Senden
|
||||
this.writer.releaseLock();
|
||||
this.writer = null;
|
||||
|
||||
let raw = "";
|
||||
while (true) {
|
||||
// Hier könnte die Queue hängen bleiben, wenn das Gerät nicht antwortet
|
||||
const { value, done } = await this.reader.read();
|
||||
if (done) break;
|
||||
raw += decoder.decode(value);
|
||||
if (raw.includes("OK") || raw.includes("ERR")) break;
|
||||
}
|
||||
|
||||
this.reader.releaseLock();
|
||||
this.reader = null;
|
||||
|
||||
const lines = raw.split('\n').map(l => l.trim()).filter(l => l);
|
||||
const errorLine = lines.find(l => l.startsWith("ERR"));
|
||||
if (errorLine) addToast(`Gerätefehler: ${errorLine}`, 'error', 5000);
|
||||
|
||||
task.resolve(lines.filter(l => l !== "OK" && !l.startsWith("ERR") && !l.startsWith(task.command)));
|
||||
} catch (e) {
|
||||
// Im Fehlerfall Locks sicher aufheben
|
||||
this.cleanupLocks();
|
||||
if (e instanceof Error && e.name !== 'AbortError') {
|
||||
console.error("Queue Error:", e);
|
||||
}
|
||||
} finally {
|
||||
this.isProcessing = false;
|
||||
this.process();
|
||||
}
|
||||
}
|
||||
|
||||
// Hilfsmethode zum Aufräumen der Sperren
|
||||
private cleanupLocks() {
|
||||
if (this.reader) {
|
||||
try { this.reader.releaseLock(); } catch { }
|
||||
this.reader = null;
|
||||
}
|
||||
if (this.writer) {
|
||||
try { this.writer.releaseLock(); } catch { }
|
||||
this.writer = null;
|
||||
}
|
||||
}
|
||||
|
||||
async close() {
|
||||
this.queue = [];
|
||||
if (this.port) {
|
||||
try {
|
||||
// Erst die Streams abbrechen, um laufende Reads zu beenden
|
||||
if (this.reader) {
|
||||
await this.reader.cancel();
|
||||
}
|
||||
if (this.writer) {
|
||||
await this.writer.abort();
|
||||
}
|
||||
// Dann die Locks freigeben
|
||||
this.cleanupLocks();
|
||||
await this.port.close();
|
||||
// console.log("Port erfolgreich geschlossen");
|
||||
} catch (e) {
|
||||
console.error("Port-Fehler beim Schließen:", e);
|
||||
this.cleanupLocks();
|
||||
}
|
||||
this.port = null;
|
||||
}
|
||||
this.isProcessing = false;
|
||||
}
|
||||
}
|
||||
|
||||
const queue = new SerialQueue();
|
||||
|
||||
/**
|
||||
* Initialisiert die globalen Serial-Listener (aufgerufen beim Start der App)
|
||||
* Initialisiert den Buzzer nach dem physikalischen Verbindungsaufbau.
|
||||
*/
|
||||
export function initSerialListeners() {
|
||||
if (typeof navigator === 'undefined' || !navigator.serial) return;
|
||||
|
||||
// 1. Wenn ein bereits gekoppeltes Gerät eingesteckt wird
|
||||
navigator.serial.addEventListener('connect', (event) => {
|
||||
// console.log('Neues Gerät erkannt, starte Auto-Connect...');
|
||||
autoConnect();
|
||||
});
|
||||
|
||||
// Beim Laden der Seite prüfen, ob wir bereits Zugriff auf Geräte haben
|
||||
autoConnect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Versucht eine Verbindung zu bereits gekoppelten Geräten herzustellen
|
||||
*/
|
||||
export async function autoConnect() {
|
||||
if (typeof navigator === 'undefined' || !navigator.serial) return;
|
||||
|
||||
const ports = await navigator.serial.getPorts();
|
||||
if (ports.length > 0) {
|
||||
const port = ports[0];
|
||||
const retryDelays = [100, 500];
|
||||
|
||||
// Erster Versuch + 2 Retries = max 3 Versuche
|
||||
for (let i = 0; i <= retryDelays.length; i++) {
|
||||
export async function initializeBuzzer() {
|
||||
try {
|
||||
// console.log("Auto-Connect Versuch mit Port:", port.getInfo());
|
||||
await connectToPort(port);
|
||||
return; // Erfolg!
|
||||
} catch (e) {
|
||||
if (i < retryDelays.length) {
|
||||
// console.log(`Reconnect Versuch ${i + 1} fehlgeschlagen, warte ${retryDelays[i]}ms...`);
|
||||
await delay(retryDelays[i]);
|
||||
} else {
|
||||
console.error('Auto-Connect nach Retries endgültig fehlgeschlagen.');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const version = await new GetProtocolCommand().execute();
|
||||
|
||||
/**
|
||||
* Kernfunktion für den Verbindungsaufbau
|
||||
*/
|
||||
export async function connectToPort(port: SerialPort) {
|
||||
if (isConnecting || get(buzzer).connected) return;
|
||||
isConnecting = true;
|
||||
|
||||
try {
|
||||
// console.log("Versuche Verbindung mit Port:", port.getInfo());
|
||||
await port.open({ baudRate: 115200 });
|
||||
await delay(100);
|
||||
setActivePort(port);
|
||||
|
||||
try {
|
||||
// Validierung: Antwortet das Teil auf "info"?
|
||||
const success = await Promise.race([
|
||||
updateDeviceInfo(port),
|
||||
new Promise<boolean>((_, reject) => setTimeout(() => reject(new Error("Timeout")), 1500))
|
||||
]);
|
||||
|
||||
if (!success) throw new Error("Kein Buzzer");
|
||||
|
||||
port.addEventListener('disconnect', () => {
|
||||
addToast("Buzzer-Verbindung verloren!", "warning");
|
||||
handleDisconnect();
|
||||
});
|
||||
|
||||
buzzer.update(s => ({ ...s, connected: true }));
|
||||
addToast("Buzzer erfolgreich verbunden", "success");
|
||||
if (version !== null) {
|
||||
buzzer.update(s => ({ ...s, connected: true, protocol: version }));
|
||||
|
||||
// FIX 1: Flash-Info muss auch beim Start geladen werden!
|
||||
await refreshFileList();
|
||||
} catch (validationError) {
|
||||
addToast("Buzzer-Validierung fehlgeschlagen!", "error");
|
||||
await disconnectBuzzer();
|
||||
await refreshFlashInfo();
|
||||
|
||||
addToast(`Buzzer bereit (v${version})`, 'success');
|
||||
return true;
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.error("Initialisierung fehlgeschlagen:", e);
|
||||
addToast(`Fehler: ${e.message}`, "error");
|
||||
await bus.disconnect();
|
||||
buzzer.update(s => ({ ...s, connected: false }));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function refreshFlashInfo() {
|
||||
try {
|
||||
if ('forget' in port) { // Check für Browser-Support
|
||||
await (port as any).forget();
|
||||
console.log("Gerät wurde erfolgreich entkoppelt.");
|
||||
}
|
||||
} catch (forgetError) {
|
||||
console.error("Entkoppeln fehlgeschlagen:", forgetError);
|
||||
}
|
||||
|
||||
throw new Error("Device ist kein gültiger Buzzer");
|
||||
throw validationError; // Fehler an den äußeren Block weitergeben
|
||||
}
|
||||
} catch (e) {
|
||||
setActivePort(null);
|
||||
// Hier landen wir, wenn der User den Port-Dialog abbricht oder die Validierung fehlschlägt
|
||||
throw e;
|
||||
} finally {
|
||||
isConnecting = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleDisconnect() {
|
||||
setActivePort(null);
|
||||
buzzer.update(s => ({
|
||||
...s,
|
||||
connected: false,
|
||||
files: [] // Liste leeren, da Gerät weg
|
||||
}));
|
||||
}
|
||||
|
||||
// --- EXPORTE ---
|
||||
|
||||
export function setActivePort(port: SerialPort | null) {
|
||||
queue.setPort(port);
|
||||
}
|
||||
|
||||
export async function disconnectBuzzer() {
|
||||
await queue.close();
|
||||
handleDisconnect();
|
||||
}
|
||||
|
||||
export async function updateDeviceInfo(port: SerialPort): Promise<boolean> {
|
||||
const lines = await queue.add("info", 1);
|
||||
if (lines.length > 0) {
|
||||
const parts = lines[0].split(';');
|
||||
if (parts.length >= 6) {
|
||||
const pageSize = parseInt(parts[2]);
|
||||
const totalPages = parseInt(parts[3]);
|
||||
const availablePages = parseInt(parts[4]);
|
||||
|
||||
// MB Berechnung mit dem korrekten Divisor (1024 * 1024)
|
||||
const totalMB = (totalPages * pageSize) / 1048576;
|
||||
const availableMB = (availablePages * pageSize) / 1048576;
|
||||
const flashInfo = await new GetFlashInfoCommand().execute();
|
||||
if (flashInfo) {
|
||||
const totalSize = (flashInfo.total_size / (1024 * 1024));
|
||||
const freeSize = (flashInfo.free_size / (1024 * 1024));
|
||||
const fwSlotSize = (flashInfo.fw_slot_size / 1024);
|
||||
const maxPathLength = flashInfo.max_path_length;
|
||||
|
||||
buzzer.update(s => ({
|
||||
...s,
|
||||
version: parts[1],
|
||||
protocol: parseInt(parts[0]),
|
||||
storage: { ...s.storage, total: totalMB, available: availableMB }
|
||||
storage: { total: totalSize, available: freeSize }, // FIX 2: "storage" korrekt geschrieben
|
||||
fw_slot_size: fwSlotSize,
|
||||
max_path_length: maxPathLength
|
||||
}));
|
||||
return true; // Validierung erfolgreich
|
||||
}
|
||||
} catch (e) { // FIX 3: try/catch Block sauber schließen
|
||||
console.error("Fehler beim Abrufen der Flash-Info:", e);
|
||||
}
|
||||
return false; // Keine gültigen Daten erhalten
|
||||
}
|
||||
|
||||
export async function refreshFileList() {
|
||||
let totalSystemBytes = 0;
|
||||
let totalAudioBytes = 0;
|
||||
|
||||
// 1. System-Größe abfragen (nur Summieren, keine Liste speichern)
|
||||
const syslines = await queue.add("ls /lfs/sys", 1, 'ls');
|
||||
syslines.forEach(line => {
|
||||
const parts = line.split(',');
|
||||
if (parts.length >= 2) {
|
||||
totalSystemBytes += parseInt(parts[1]);
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Audio-Files abfragen und Liste für das UI erstellen
|
||||
const lines = await queue.add("ls /lfs/a", 1, 'ls');
|
||||
const audioFiles = lines.map(line => {
|
||||
const parts = line.split(',');
|
||||
if (parts.length < 3) return null;
|
||||
const size = parseInt(parts[1]);
|
||||
totalAudioBytes += size;
|
||||
|
||||
return {
|
||||
name: parts[2],
|
||||
size: (size / 1024).toFixed(1) + " KB",
|
||||
crc32: 0,
|
||||
isSystem: false
|
||||
};
|
||||
}).filter(f => f !== null) as any[];
|
||||
|
||||
// 3. Den Store mit MB-Werten aktualisieren
|
||||
buzzer.update(s => {
|
||||
// Konvertierung in MB (1024 * 1024 = 1048576)
|
||||
const audioMB = totalAudioBytes / 1048576;
|
||||
const sysMB = totalSystemBytes / 1048576;
|
||||
const usedTotalMB = s.storage.total - s.storage.available;
|
||||
const unknownMB = Math.max(0, usedTotalMB - audioMB - sysMB);
|
||||
console.log(`Storage: Total ${s.storage.total} MB, Used ${usedTotalMB.toFixed(2)} MB, Audio ${audioMB.toFixed(2)} MB, System ${sysMB.toFixed(2)} MB, Unknown ${unknownMB.toFixed(2)} MB`);
|
||||
return {
|
||||
...s,
|
||||
files: audioFiles,
|
||||
storage: {
|
||||
...s.storage,
|
||||
usedSys: sysMB,
|
||||
usedAudio: audioMB,
|
||||
unknown: unknownMB
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
startBackgroundCrcCheck();
|
||||
}
|
||||
|
||||
async function startBackgroundCrcCheck() {
|
||||
const currentFiles = get(buzzer).files;
|
||||
for (const file of currentFiles) {
|
||||
if (true) {//(!file.crc32) {
|
||||
const tagresponse = await queue.add(`gett /lfs/a/${file.name}`, 0);
|
||||
if (tagresponse.length > 0) {
|
||||
console.log(`Tag für ${file.name}:`, tagresponse[0]);
|
||||
}
|
||||
const response = await queue.add(`check /lfs/a/${file.name}`, 0);
|
||||
if (response.length > 0) {
|
||||
const match = response[0].match(/0x([0-9a-fA-F]+)/);
|
||||
if (match) {
|
||||
const crc = parseInt(match[1], 16);
|
||||
updateFileCrc(file.name, crc);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateFileCrc(name: string, crc: number) {
|
||||
buzzer.update(s => ({
|
||||
...s,
|
||||
files: s.files.map(f => f.name === name ? { ...f, crc32: crc } : f)
|
||||
}));
|
||||
}
|
||||
|
||||
export async function playFile(filename: string) {
|
||||
return queue.add(`play /lfs/a/${filename}`, 1, 'play');
|
||||
}
|
||||
|
||||
export async function deleteFile(filename: string) {
|
||||
if (!confirm(`Datei ${filename} wirklich löschen?`)) return;
|
||||
await queue.add(`rm /lfs/a/${filename}`, 1);
|
||||
await refreshFileList();
|
||||
}
|
||||
} // Funktion schließen
|
||||
@@ -2,15 +2,18 @@ import { writable } from 'svelte/store';
|
||||
|
||||
export const buzzer = writable({
|
||||
connected: false,
|
||||
version: 'v0.0.0',
|
||||
protocol: 0,
|
||||
build: 'unknown',
|
||||
version: 'v0.0.0',
|
||||
kernel_version: 'v0.0.0',
|
||||
storage: {
|
||||
total: 8.0, // 8 MB Flash laut Spezifikation
|
||||
total: 8.0,
|
||||
available: 0.0,
|
||||
unknown: 8.0,
|
||||
usedSys: 0.0,
|
||||
usedAudio: 0.0
|
||||
usedAudio: 0.0,
|
||||
unknown: 0.0
|
||||
},
|
||||
files: [] as {name: string, size: string, crc32: number, isSystem: boolean, isSynced: boolean}[]
|
||||
max_path_length: 15,
|
||||
fw_slot_size: 0,
|
||||
|
||||
files: [] as {name: string, size: string, crc32: number | null, isSystem: boolean}[]
|
||||
});
|
||||
49
webpage/src/lib/protocol/commands/GetFlashInfo.ts
Normal file
49
webpage/src/lib/protocol/commands/GetFlashInfo.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { bus } from '../../bus/SerialBus';
|
||||
import { Command, FrameType } from '../constants';
|
||||
import { BinaryUtils } from '../../utils/BinaryUtils';
|
||||
|
||||
export interface FlashInfo {
|
||||
total_size: number; // in Bytes
|
||||
free_size: number; // in Bytes
|
||||
fw_slot_size: number; // in Bytes
|
||||
ext_flash_erase_size: number; // in Bytes
|
||||
int_flash_erase_size: number; // in Bytes
|
||||
max_path_length: number;
|
||||
}
|
||||
|
||||
export class GetFlashInfoCommand {
|
||||
async execute(): Promise<FlashInfo | null> {
|
||||
try {
|
||||
await bus.sendRequest(Command.GET_FLASH_INFO);
|
||||
|
||||
if (await bus.waitForSync()) {
|
||||
const typeArr = await bus.readExact(1);
|
||||
if (typeArr[0] === FrameType.RESPONSE) {
|
||||
// Wir lesen exakt 21 Bytes für die Flash-Info
|
||||
const data = await bus.readExact(21);
|
||||
const pageSize = BinaryUtils.readUint32LE(data.subarray(0, 4));
|
||||
const totalSize = BinaryUtils.readUint32LE(data.subarray(4, 8)) * pageSize;
|
||||
const freeSize = BinaryUtils.readUint32LE(data.subarray(8, 12)) * pageSize; // Aktuell haben wir keine Info über belegten Speicher, also annehmen, dass alles frei ist
|
||||
const fwSlotSize = BinaryUtils.readUint32LE(data.subarray(12, 16));
|
||||
const extEraseSize = BinaryUtils.readUint16LE(data.subarray(16, 18));
|
||||
const intEraseSize = BinaryUtils.readUint16LE(data.subarray(18, 20));
|
||||
const maxPathLength = data[20];
|
||||
console.log("Flash Info:", { pageSize, totalSize, freeSize, fwSlotSize, extEraseSize, intEraseSize, maxPathLength });
|
||||
return {
|
||||
total_size: totalSize,
|
||||
free_size: totalSize, // Aktuell haben wir keine Info über belegten Speicher, also annehmen, dass alles frei ist
|
||||
fw_slot_size: fwSlotSize,
|
||||
ext_flash_erase_size: extEraseSize,
|
||||
int_flash_erase_size: intEraseSize,
|
||||
max_path_length: maxPathLength
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("GetFlashInfoCommand failed:", e);
|
||||
} finally {
|
||||
bus.releaseReadLock();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
26
webpage/src/lib/protocol/commands/GetProtocol.ts
Normal file
26
webpage/src/lib/protocol/commands/GetProtocol.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { bus } from '../../bus/SerialBus';
|
||||
import { Command, FrameType } from '../constants';
|
||||
import { BinaryUtils } from '../../utils/BinaryUtils';
|
||||
|
||||
export class GetProtocolCommand {
|
||||
async execute(): Promise<number | null> {
|
||||
try {
|
||||
await bus.sendRequest(Command.GET_PROTOCOL_VERSION);
|
||||
|
||||
if (await bus.waitForSync()) {
|
||||
const typeArr = await bus.readExact(1);
|
||||
if (typeArr[0] === FrameType.RESPONSE) {
|
||||
// Wir lesen exakt 2 Bytes für die Version
|
||||
const data = await bus.readExact(2);
|
||||
// Nutze die neue Hilfsfunktion
|
||||
return BinaryUtils.readUint16LE(data);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("GetProtocolCommand failed:", e);
|
||||
} finally {
|
||||
bus.releaseReadLock();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
37
webpage/src/lib/protocol/commands/GetSettings.ts
Normal file
37
webpage/src/lib/protocol/commands/GetSettings.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { bus } from '../../bus/SerialBus';
|
||||
import { Command, FrameType } from '../constants';
|
||||
import { BinaryUtils } from '../../utils/BinaryUtils';
|
||||
|
||||
export class GetSettingCommand {
|
||||
async execute(key: string): Promise<number | boolean | null> {
|
||||
try {
|
||||
const keyBuf = new TextEncoder().encode(key);
|
||||
const payload = new Uint8Array(1 + keyBuf.length);
|
||||
payload[0] = keyBuf.length;
|
||||
payload.set(keyBuf, 1);
|
||||
|
||||
await bus.sendRequest(Command.GET_SETTING, payload);
|
||||
|
||||
if (await bus.waitForSync()) {
|
||||
const typeArr = await bus.readExact(1);
|
||||
if (typeArr[0] === FrameType.RESPONSE) {
|
||||
const lenArr = await bus.readExact(1);
|
||||
const valLen = lenArr[0];
|
||||
const data = await bus.readExact(valLen);
|
||||
|
||||
// Typ-Konvertierung analog zu C/Python
|
||||
if (key === "audio/vol" || key === "play/norepeat") {
|
||||
return data[0] === 1 ? true : (key === "audio/vol" ? data[0] : false);
|
||||
} else if (key === "settings/storage_interval") {
|
||||
return BinaryUtils.readUint16LE(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("GetSetting failed:", e);
|
||||
} finally {
|
||||
bus.releaseReadLock();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
43
webpage/src/lib/protocol/commands/ListDir.ts
Normal file
43
webpage/src/lib/protocol/commands/ListDir.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
// src/lib/protocol/commands/ListDir.ts
|
||||
import { bus } from '../../bus/SerialBus';
|
||||
import { Command, FrameType } from '../constants';
|
||||
import { BinaryUtils } from '../../utils/BinaryUtils';
|
||||
|
||||
export class ListDirCommand {
|
||||
async execute(path: string) {
|
||||
try {
|
||||
const p = new TextEncoder().encode(path);
|
||||
const req = new Uint8Array(p.length + 1);
|
||||
req[0] = p.length; req.set(p, 1);
|
||||
|
||||
await bus.sendRequest(Command.LIST_DIR, req);
|
||||
const entries = [];
|
||||
|
||||
while (true) {
|
||||
// Wichtig: Wir rufen waitForSync ohne releaseReadLock zwischendurch auf!
|
||||
if (!(await bus.waitForSync())) break;
|
||||
|
||||
const type = (await bus.readExact(1))[0];
|
||||
if (type === FrameType.LIST_START) continue;
|
||||
if (type === FrameType.LIST_END) {
|
||||
const expected = BinaryUtils.readUint16LE(await bus.readExact(2));
|
||||
console.log(`Erwartet: ${expected}, Erhalten: ${entries.length}`);
|
||||
return entries;
|
||||
}
|
||||
if (type === FrameType.LIST_CHUNK) {
|
||||
const len = BinaryUtils.readUint16LE(await bus.readExact(2));
|
||||
const data = await bus.readExact(len);
|
||||
entries.push({
|
||||
isDir: data[0] === 1,
|
||||
size: data[0] === 1 ? null : BinaryUtils.readUint32LE(data.subarray(1, 5)),
|
||||
name: new TextDecoder().decode(data.subarray(5)).replace(/\0/g, '')
|
||||
});
|
||||
}
|
||||
if (type === FrameType.ERROR) break;
|
||||
}
|
||||
} finally {
|
||||
bus.releaseReadLock(); // ERST HIER LOCK LÖSEN!
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
31
webpage/src/lib/protocol/commands/PlayFile.ts
Normal file
31
webpage/src/lib/protocol/commands/PlayFile.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { bus } from '../../bus/SerialBus';
|
||||
import { Command, FrameType } from '../constants';
|
||||
|
||||
export class PlayFileCommand {
|
||||
async execute(path: string): Promise<boolean | null> {
|
||||
try {
|
||||
const p = new TextEncoder().encode(path);
|
||||
// Wir brauchen: 1 Byte Flags + 1 Byte Länge + Pfad
|
||||
const req = new Uint8Array(p.length + 2);
|
||||
|
||||
req[0] = 0x01; // 1. Byte: Flags (LSB: 1 = sofort abspielen)
|
||||
req[1] = p.length; // 2. Byte: Länge für get_path() im C-Code
|
||||
req.set(p, 2); // Ab 3. Byte: Der Pfad-String
|
||||
|
||||
await bus.sendRequest(Command.PLAY, req);
|
||||
|
||||
// Warten auf das ACK vom Board
|
||||
if (await bus.waitForSync()) {
|
||||
const typeArr = await bus.readExact(1);
|
||||
if (typeArr[0] === FrameType.ACK) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("PlayFileCommand failed:", e);
|
||||
} finally {
|
||||
bus.releaseReadLock();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
91
webpage/src/lib/protocol/constants.ts
Normal file
91
webpage/src/lib/protocol/constants.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
export const SYNC_SEQ = new TextEncoder().encode('BUZZ');
|
||||
|
||||
export enum FrameType {
|
||||
REQUEST = 0x01,
|
||||
|
||||
ACK = 0x10,
|
||||
RESPONSE = 0x11,
|
||||
STREAM_START = 0x12,
|
||||
STREAM_CHUNK = 0x13,
|
||||
STREAM_END = 0x14,
|
||||
LIST_START = 0x15,
|
||||
LIST_CHUNK = 0x16,
|
||||
LIST_END = 0x17,
|
||||
|
||||
ERROR = 0xFF,
|
||||
}
|
||||
|
||||
export enum Command {
|
||||
GET_PROTOCOL_VERSION = 0x00,
|
||||
GET_FIRMWARE_STATUS = 0x01,
|
||||
GET_FLASH_INFO = 0x02,
|
||||
CONFIRM_FIRMWARE = 0x03,
|
||||
REBOOT = 0x04,
|
||||
|
||||
LIST_DIR = 0x10,
|
||||
CRC32 = 0x11,
|
||||
MKDIR = 0x12,
|
||||
RM = 0x13,
|
||||
STAT = 0x18,
|
||||
RENAME = 0x19,
|
||||
|
||||
PUT_FILE = 0x20,
|
||||
PUT_FW = 0x21,
|
||||
GET_FILE = 0x22,
|
||||
PUT_TAGS = 0x24,
|
||||
GET_TAGS = 0x25,
|
||||
|
||||
PLAY = 0x30,
|
||||
STOP = 0x31,
|
||||
|
||||
SET_SETTING = 0x40,
|
||||
GET_SETTING = 0x41,
|
||||
}
|
||||
|
||||
export const ERRORS: Record<number, string> = {
|
||||
0x00: "NONE",
|
||||
0x01: "INVALID_COMMAND",
|
||||
0x02: "INVALID_PARAMETERS",
|
||||
0x03: "COMMAND_TOO_LONG",
|
||||
|
||||
0x10: "FILE_NOT_FOUND",
|
||||
0x11: "ALREADY_EXISTS",
|
||||
0x12: "NOT_A_DIRECTORY",
|
||||
0x13: "IS_A_DIRECTORY",
|
||||
0x14: "ACCESS_DENIED",
|
||||
0x15: "NO_SPACE",
|
||||
0x16: "FILE_TOO_LARGE",
|
||||
|
||||
0x20: "IO_ERROR",
|
||||
0x21: "TIMEOUT",
|
||||
0x22: "CRC_MISMATCH",
|
||||
0x23: "TRANSFER_ABORTED",
|
||||
|
||||
0x30: "NOT_SUPPORTED",
|
||||
0x31: "BUSY",
|
||||
0x32: "INTERNAL_ERROR",
|
||||
};
|
||||
|
||||
export enum ErrorCode {
|
||||
P_ERR_NONE = 0x00,
|
||||
P_ERR_INVALID_COMMAND = 0x01,
|
||||
P_ERR_INVALID_PARAMETERS = 0x02,
|
||||
P_ERR_COMMAND_TOO_LONG = 0x03,
|
||||
|
||||
P_ERR_FILE_NOT_FOUND = 0x10,
|
||||
P_ERR_ALREADY_EXISTS = 0x11,
|
||||
P_ERR_NOT_A_DIRECTORY = 0x12,
|
||||
P_ERR_IS_A_DIRECTORY = 0x13,
|
||||
P_ERR_ACCESS_DENIED = 0x14,
|
||||
P_ERR_NO_SPACE = 0x15,
|
||||
P_ERR_FILE_TOO_LARGE = 0x16,
|
||||
|
||||
P_ERR_IO = 0x20,
|
||||
P_ERR_TIMEOUT = 0x21,
|
||||
P_ERR_CRC_MISMATCH = 0x22,
|
||||
P_ERR_TRANSFER_ABORTED = 0x23,
|
||||
|
||||
P_ERR_NOT_SUPPORTED = 0x30,
|
||||
P_ERR_BUSY = 0x31,
|
||||
P_ERR_INTERNAL = 0x32,
|
||||
};
|
||||
34
webpage/src/lib/utils/BinaryUtils.ts
Normal file
34
webpage/src/lib/utils/BinaryUtils.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
export class BinaryUtils {
|
||||
/**
|
||||
* Konvertiert 2 Bytes (Little Endian) in eine Zahl (uint16)
|
||||
*/
|
||||
static readUint16LE(data: Uint8Array, offset = 0): number {
|
||||
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
||||
return view.getUint16(offset, true); // true = Little Endian
|
||||
}
|
||||
|
||||
/**
|
||||
* Konvertiert 4 Bytes (Little Endian) in eine Zahl (uint32)
|
||||
*/
|
||||
static readUint32LE(data: Uint8Array, offset = 0): number {
|
||||
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
||||
return view.getUint32(offset, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Erstellt ein Uint8Array aus einer Zahl (uint16 LE)
|
||||
*/
|
||||
static writeUint16LE(value: number): Uint8Array {
|
||||
const buf = new Uint8Array(2);
|
||||
const view = new DataView(buf.buffer);
|
||||
view.setUint16(0, value, true);
|
||||
return buf;
|
||||
}
|
||||
|
||||
static writeUint32LE(value: number): Uint8Array {
|
||||
const buf = new Uint8Array(4);
|
||||
const view = new DataView(buf.buffer);
|
||||
view.setUint32(0, value, true);
|
||||
return buf;
|
||||
}
|
||||
}
|
||||
@@ -67,17 +67,7 @@ import type { loadRenderers } from "astro:container";
|
||||
</section>
|
||||
|
||||
<section class="flex-1 flex flex-col gap-6 min-h-0">
|
||||
<div
|
||||
class="h-48 bg-indigo-950/20 border border-indigo-500/20 rounded-[2rem] p-6 relative overflow-hidden shrink-0">
|
||||
<div class="absolute top-6 right-6 text-indigo-500 opacity-20">
|
||||
<Icon name="ph:cpu-fill" class="w-12 h-12" />
|
||||
</div>
|
||||
<h3 class="text-indigo-400 text-[10px] font-black uppercase tracking-[0.2em] mb-4">
|
||||
Device Info
|
||||
</h3>
|
||||
<DeviceInfo client:load />
|
||||
</div>
|
||||
|
||||
<div class="flex-1 flex flex-col overflow-hidden">
|
||||
<FileStorage client:load />
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user