#!/usr/bin/env python

import argparse
import socket

parser = argparse.ArgumentParser(description='Send a VBAN command')
parser.add_argument(
    '--host', type=str, default='localhost', help='The host to send the command to'
)
parser.add_argument(
    '--port', type=int, default=6980, help='The port to send the command to'
)
parser.add_argument(
    '--streamname',
    type=str,
    default='Command1',
    help='The name of the stream to send the command to',
)
parser.add_argument('command', type=str, help='The command to send')
args = parser.parse_args()

# fmt: off
BPS_OPTS: list[int] = [
    0, 110, 150, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 31250,
    38400, 57600, 115200, 128000, 230400, 250000, 256000, 460800, 921600,
    1000000, 1500000, 2000000, 3000000
]
# fmt: on
SUBPROTOCOL_TXT = 0x40
CHANNEL = 0
STREAMTYPE_UTF8 = 0x10

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
    header = bytearray(b'VBAN')
    header.extend((BPS_OPTS.index(256000) | SUBPROTOCOL_TXT).to_bytes(1, 'little'))
    header.extend((0).to_bytes(1, 'little'))
    header.extend((CHANNEL).to_bytes(1, 'little'))
    header.extend((STREAMTYPE_UTF8).to_bytes(1, 'little'))
    header.extend(args.streamname.encode('utf-8').ljust(16, b'\0'))
    header.extend(
        (0).to_bytes(4, 'little')
    )  # 4 byte frame counter, set to 0 for commands

    sock.sendto(header + args.command.encode('utf-8'), (args.host, args.port))