#!/usr/bin/python

import sys,time,os
import serial

f = open('/root/databuoy/scripts/buoy_parameters.txt','r')
i = 0
for line in f.read().split('\n'):
   if i == 0:
      id = line
   if i == 1:
      SERIALPORT = line
   i = i + 1
f.close()

ser0 = serial.Serial('/dev/ttyS0', 4800, timeout=1)
ser1 = serial.Serial(SERIALPORT, 57600, timeout=1)

def close_down():
        ser0.close()
        #os.system("/sbin/agetty -L ttyS0 4800 vt100")
        os.system("reset")
        exit

def archive_file(choice):
        os.system("ls *.sta > /tmp/files.txt")
        data_dir = "%s_%s/" %(id, time.strftime("%Y%m%d", time.localtime()))
        os.system("mkdir %s" %data_dir)
        f = open('/tmp/files.txt', 'r')
        for line in f.readlines():
            #Insert download code here
            print("Moving %s to %s\n" %(line, data_dir))
            cmd = "mv %s %s" %(line, data_dir)
            os.system(cmd)
        os.system("rm /tmp/files.txt")

def get_video(hour):
    filename = "%s_%s_%s.vid" %(id, time.strftime("%Y%m%d", time.localtime()), hour)
    try:
        os.system("/root/databuoy/jpegdemo 1")
    except:
        close_down()
    cmd = "mv snapshot.jpg %s" %filename
    os.system(cmd)

def get_battery():
    filename = "%s_%s.sta" %(id, time.strftime("%Y%m%d", time.localtime()))
    FILE = open(filename, "a")
    # call comedi demo 'inp' function to read A/D channels
    #os.system("rm voltage.txt");
    try:
        os.system("/root/databuoy/inp -s 0 -c 0 -r 4 >> /dev/null")
        os.system("/root/databuoy/inp -s 0 -c 0 -r 4 > voltage.txt")
        os.system("/root/databuoy/inp -s 0 -c 1 -r 4 >> /dev/null")
        os.system("/root/databuoy/inp -s 0 -c 1 -r 4 >> voltage.txt")
        os.system("/root/databuoy/inp -s 0 -c 2 -r 4 >> /dev/null")
        os.system("/root/databuoy/inp -s 0 -c 2 -r 4 >> voltage.txt")
        os.system("/root/databuoy/inp -s 0 -c 3 -r 4 >> /dev/null")
        os.system("/root/databuoy/inp -s 0 -c 3 -r 4 >> voltage.txt")
        os.system("/root/databuoy/inp -s 0 -c 4 -r 4 >> /dev/null")
        os.system("/root/databuoy/inp -s 0 -c 4 -r 4 >> voltage.txt")
        os.system("/root/databuoy/inp -s 0 -c 7 -r 4 >> /dev//null")
	os.system("/root/databuoy/inp -s 0 -c 7 -r 4 >> voltage.txt")
    except :
        FILE.close()
        close_down()
    i = 0
    string = ("%s %s  " %( id, time.strftime("%d/%m/%Y %H:%M%:%S", time.localtime())))
    ser0.write(string)
    FILE.write(string)
    for line in file("voltage.txt").readlines():
        V = float(line)
        voltage = (V-1.014)/279.1
	if (voltage<0.1):
            voltage = 0.0
	string = ("%5.2f " %voltage)
	ser0.write(string)
	FILE.write(string)
	i=i+1
	for x in range(0, 1000):
	    pass
    ser0.write("\r\n")
    FILE.write(" \n")
    FILE.close()
    return
	
def storx_mode():
	ser0.write("Switching to Stor-X mode.\n\r")
	ser0.write("Press 'ESC' key to exit.\n\r")
	ser1.write("\n\r\n\r")		# wake up!
	hostVal = 0
	while (hostVal!=27):
		storxChar = ser1.read(1)
		while(storxChar):
			ser0.write(storxChar)
			storxChar = ser1.read(1)
		hostChar = ser0.read(1)
		while(hostChar) and (hostVal != 27): 
			ser1.write(hostChar)
			hostChar = ser0.read(1)
			if(hostChar): hostVal = ord(hostChar)
	return


def handle_choice(choice):
	if (choice == '1'):
		ser0.write("Getting system status.\n\r")
		get_battery()
	elif (choice == '2'):
		storx_mode()
	elif (choice == '3'):
                get_video("usr")
	elif (choice == '4'):
		program_upload()
        elif (choice == '5'):
                archive_file("status")
        elif (choice == '6'):
                archive_file("video")
	elif (choice == '7'):
		ser0.write("Exit session.\n\r")
	elif (choice == '8'):
                ser0.write("Terminating Program.\n\r")
        else: 
		ser0.write("Error. Please enter a valid choice.\n\r")
	return

def main():
	lasttime=0
	choice=0
        while(choice!='8'):
	    currtime = time.time()
	    if (currtime - lasttime > 60*60):
		#get_battery()
	        lasttime = currtime
                currtime = time.localtime()
                hour = currtime[3]
                #if(hour == 10) or (hour == 12) or (hour == 3):
                #    get_video(hour)
	    cmd = ser0.read(2)
	    if(cmd == id):
	        choice = ser0.read(1)
	        while (choice != '7') and (choice!='8'):
		    ser0.write("\n")
		    ser0.write("##############################################\n\r")
		    ser0.write("#                                            #\n\r")
		    ser0.write("#  Plymouth Marine Databuoy Control Program  #\n\r")
		    ser0.write("#  Version 1.0 24/05/2008                    #\n\r")
		    ser0.write("#                                            #\n\r")
		    ser0.write("#  %s DATABUOY User Menu Options:            #\n\r" %id)
		    ser0.write("#                                            #\n\r")
		    ser0.write("##############################################\n\r")
		    ser0.write("\n\r")
		    ser0.write("1. Get System Status.\n\r")
		    ser0.write("2. Set Stor-X Mode.\n\r")
		    ser0.write("3. Get Video Image.\n\r")
		    ser0.write("4. Upload file.\n\r")
                    ser0.write("5. Download status file.\n\r")
                    ser0.write("6. Download video file.\n\r")
		    ser0.write("7. Leave current session.\n\r")
                    ser0.write("8. Terminate program.\n\r")
		    ser0.write("\n\r")
		    ser0.write("Enter menu selection:\n\r\n\r")
		    while 1:
	                choice = ser0.read(1)
		        if(choice):
		            handle_choice(choice)
                            break
                    if (choice == '8'):
                        close_down()
	close_down()

if __name__ == '__main__':
	main()
