#!/usr/bin/env python3
from time import sleep
from sys import exit, argv
import minimalmodbus
import serial
from sensor import Sensor

def print_usage():
    print(
f'''
USAGE:
\t{argv[0]} [ -a [{{FIRST_ADDR-LAST_ADDR | ADDR}} ...] ] [ -b [BAUD ...]]
EXAMPLES:
Complete search (slow!):
\t{argv[0]}
Look for devices 123,10,56 at baudrates 19200,115200:
\t{argv[0]} -a 123 10 56 -b 19200 115200
Look for devices 10-55 at baudrate 19200:
\t{argv[0]} -a 10-55 -b 19200
Look for device 1-10 and 55 at baudrate 115200:
\t{argv[0]} -a 1-10 55 -b 115200
Look for device 1-10 at all possible baudrates:
\t{argv[0]} -a 1-10 55
'''
            )

# Parse arguments. And no, I won't use argparse.
processing_address = 0
processing_baud = 0
addr = []
baud = []
for arg in argv[1:]:
    if arg == '-a' or arg == '--address':
        processing_address = 1
        processing_baud = 0
    elif arg == '-b' or arg == '--baudrate':
        processing_address = 0
        processing_baud = 1
    elif processing_address:
        if arg.count('-') == 1:
            # range in form START_ADDR-STOP_ADDR
            start_addr, stop_addr = arg.split('-')
            for a in range(int(start_addr), int(stop_addr) + 1):
                addr.append(a)
        else:
            addr.append(int(arg))
    elif processing_baud:
        baud.append(int(arg))
    elif arg == '-h' or arg == '--help':
        print_usage()
        exit(0)
    else:
        print(f'Unknown argument {arg}')
        print_usage()
        exit(-1)
# if empty, use all possible values
if not baud:
    baud = Sensor.baudrates
if not addr:
    addr = [a for a in range(1,248)]
    addr.reverse() # we usually use high addresses for test devices
# print
print('---- Searchspace ----')
print(f'Addresses: {addr}')
print(f'Baudrates: {baud}')
# search for device
print('---- Looking for device ----')
total_devices = 0
tried_devices = 0
for a in addr:
    for b in baud:
        print(f'Address {a : >3} baud {b : >6}: ', end='')
        try:
            s = Sensor(address=a, baudrate=b)
            reg_number = Sensor.input_registers['CO2']
            s.read_register(reg_number, retries=1)
            print('DEVICE RESPONDED')
            total_devices += 1
        except minimalmodbus.NoResponseError:
            print('no response')
        tried_devices += 1
        sleep(0.1)
print(f'Found {total_devices} devices (tried {tried_devices})')
print('---- DONE ----')
exit(0)
