# crontab -e
# 1 * * * * python3 /path/to/flipper-scheduled.py

from glob import glob
from zoneinfo import ZoneInfo
from datetime import datetime
import serial, sys

now = datetime.now(tz=ZoneInfo("Europe/Copenhagen"))
SIGNAL_TO_SEND = {
    # hour : (subghz-)signal
    7 : 'Up.sub',
    20: 'Down.sub',
}.get(now.hour)

if SIGNAL_TO_SEND is None:
    print(f'Nothing to send at hour {now.hour}')
    exit(0)

flippers = glob("/dev/serial/by-id/usb-Flipper_Devices_Inc._Flipper_*-if00")
if len(flippers) != 1:
    print(f"Found {len(flippers)} flippers. Using first found", file=sys.stderr)

flipper_port = flippers[0]

port = serial.Serial(port=flipper_port, baudrate=9600, bytesize=8, timeout=10, stopbits=serial.STOPBITS_ONE)
port.read_until(b'>: ') # skip welcome banner

def send_cmd(cmd: str):
    cmd = f'{cmd}\r'.encode()
    port.write(cmd)
    assert port.readline() == cmd + b'\n'
    return port.read_until(b'>: ').decode().rstrip('\r\n')

# Tjek at filen findes:
files = send_cmd('storage list /ext/subghz')
assert SIGNAL_TO_SEND in files, f'Could not find {SIGNAL_TO_SEND=} in {files=}'

# Tjek at der ikke kører noget i fg
opened_apps = send_cmd('loader info')
assert 'No application is running' in opened_apps

# Send signalet
ans = send_cmd(f"subghz tx_from_file /ext/subghz/{SIGNAL_TO_SEND} 1 0")
print(ans)

port.close()

