
import serial
import sys
import threading
import time

T = None
paka_on = False
stop_event = threading.Event()
tmr = None

def iras(fn):
    global ser
    with open(fn, 'w') as o:
        while not stop_event.is_set():
            line = ser.readline()
            try:
                o.write(line.decode())
                o.flush()
            except:
                print ("junk line")

def billen():
    global T
    global paka_on
    global tmr
    if paka_on:
        ser.write(b'p65535\n')
        print ('sold off')
        paka_on = False
    else:
        ser.write(b'p36322\n')
        print ('sold on')
        paka_on = True
    tmr = threading.Timer(T, billen)
    tmr.start()

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("-D", '--device', type = str, default = '/dev/ttyUSB0',
                        help = "the serial line device")
    parser.add_argument("output", metavar = 'output', nargs = 1,
                        help = "the output file")
    parser.add_argument("-p", "--program", type = int, choices = [0, 1, 2, 3], default = 0,
            help = "what to do. 0: nothing, 1: cool only, 2: cool and heat the edges, 3: cool and heat on-off")
    parser.add_argument("-t", "--period", type = float, default = 0,
                        help = "only when program = 3, how long to heat / cool")
    args = parser.parse_args()
    ser = serial.Serial(args.device)

    wt = threading.Thread(target = iras, args = args.output)
    wt.start()

    # first reset microcode, and make sure not to heat
    ser.write(b'r\n')
    print ('reset')
    time.sleep(.5)
    ser.write(b'p65535\n')
    print ('sold off')
    time.sleep(.5)

    if args.program == 0:
        pass
    elif args.program == 1:
        ser.write(b'h38941\n')
        print ("peltier cool")
        time.sleep(.5)
    elif args.program == 2:
        ser.write(b'h38941\n')
        print ("peltier cool")
        time.sleep(.5)
        ser.write(b'p36322\n')
        print ('sold on')
        time.sleep(.5)
    elif args.program == 3:
        T = args.period
        tmr = threading.Timer(T, billen)
        tmr.start()

    print ("looping")
    try:
        h = 0
        while True:
            time.sleep(60)
            print("t", h)
            h += 1
    except KeyboardInterrupt:
        stop_event.set()
        wt.join()
        if tmr:
            tmr.cancel()
