#!/usr/bin/env python3

# This source code by DJ3EI is marked CC0 1.0.
# To view a copy of this mark, visit
# https://creativecommons.org/publicdomain/zero/1.0/

from socket import create_connection, socket
from time import sleep


def send_command(s: socket, command: str) -> None:
    s.sendall(command.encode())
    ans = str(s.recv(1024), encoding="UTF-8", errors="strict")
    if ans != "RPRT 0\n":
        raise RuntimeError(f'Asking {command.rstrip()}, received "{ans}"')


with create_connection(("localhost", 4532)) as s:

    s.settimeout(2)
    try:
        # for f in range(28010000, 29210001, 100000):
        for f in (f_khz * 1000 for f_khz in (1850, 3650, 5360, 7100, 10125, 14175, 18100, 21225, 24945, 28850)):
            send_command(s, f"F {f}\n")  # QSY
            sleep(0.1)  # Being a bit paranoid here.

            send_command(s, "T 3\n")  # PTT
            sleep(0.1)  # Being a bit paranoid here, too.

            s.sendall(b"l SWR\n")  # read SWR
            ans_swr = str(s.recv(1024), encoding="UTF-8", errors="strict")
            if "RPRT" in ans_swr:
                raise RuntimeError(f'Asking for SWR, received "{ans_swr.rstrip()}"')
            swr = float(ans_swr)

            send_command(s, "T 0\n")  # PTT release

            print(f"{round(f / 1000)} | {swr}")
            sleep(1)  # My dummy load is not the best, so let it cool
            # (if that's what I'm measuring).

    finally:
        send_command(s, "T 0\n")  # Just to make sure: PTT release
