#!/usr/bin/env python3
# Play a single shutdown beep via the RP2350 JSON serial interface.
# Replaces the old smbus/I2C MCP23008 GPIO toggle.

import serial
import json
import sys
import time

SERIAL_PORT = "/dev/ttyACM0"
BAUD_RATE   = 115200
TIMEOUT_S   = 2.0

# Tone IDs must match BuzzerController::Tone in buzzer_controller.h
TONE_CRITICAL = 4   # Single descending beep — used to signal shutdown

def main():
    try:
        ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=TIMEOUT_S)
    except serial.SerialException as e:
        print(f"[smpro_shutdown_buzzer] Cannot open {SERIAL_PORT}: {e}", file=sys.stderr)
        sys.exit(1)

    # Brief pause to let the RP2350 USB-CDC stack settle after open
    time.sleep(0.1)

    cmd = {
        "subsystem": "buzzer",
        "command":   "play_tone",
        "payload":   {"tone": TONE_CRITICAL}
    }

    try:
        ser.write((json.dumps(cmd) + "\n").encode("utf-8"))
        response_line = ser.readline().decode("utf-8").strip()
        if response_line:
            response = json.loads(response_line)
            if response.get("status") != "ok":
                print(f"[smpro_shutdown_buzzer] RP2350 error: {response.get('error', 'unknown')}",
                      file=sys.stderr)
    except Exception as e:
        print(f"[smpro_shutdown_buzzer] Communication error: {e}", file=sys.stderr)
    finally:
        ser.close()

if __name__ == "__main__":
    main()
