#!/usr/bin/env python3 -u
#
# Launch a HMTL command server

from optparse import OptionParser
from hmtl.server import *
import hmtl.portscan as portscan
from hmtl.SerialBuffer import SerialBuffer
from hmtl.SocketBuffer import SocketBuffer


def handle_args():
    global options

    parser = OptionParser()

    parser.add_option("-d", "--device", dest="device",
                      help="Arduino USB device")
    parser.add_option("-b", "--baud", dest="baud", type="int",
                      help="Serial port baud (9600, 19200, 57600, [115200])",
                      default=115200)
    parser.add_option("-I", "--ip", dest="ip",
                      help="IP of device to connect to")
    parser.add_option("-P", "--deviceport", dest="deviceport", default=23,
                      help="Port on IP device [default=%(default)s]")

    parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                      help="Verbose output", default=False)
    parser.add_option("-p", "--port", dest="port", type="int",
                      help="Port to bind to", default=6000)
    parser.add_option("-a", "--address", dest="address",
                      help="Address to bind to", default="0.0.0.0")

    parser.add_option("-s", "--devicescan", dest="devicescan", action="store_true",
                      help="Scan for devices in the background", default=False)

    (options, args) = parser.parse_args()
    print("options:" + str(options) + " args:" + str(args))

    if options.device is None and options.ip is None:
        options.device = portscan.choose_port()

        if options.device == None:
            parser.print_help()
            exit("Must specify device")
    
    return (options, args)
 
def main():

    handle_args()

    if options.device:
        buff = SerialBuffer(options.device, options.baud)
    elif options.ip:
        buff = SocketBuffer(options.ip, options.deviceport)
    else:
        exit("No device or address specified")
    ser = HMTLSerial(buff, verbose=options.verbose)

    server = HMTLServer(ser, (options.address, options.port),
                        options.devicescan)
    server.listen()
    server.close()

    print("Done.")
    exit(0)

main()

