#!/usr/bin/python

import sys,time,os
# import portio
import serial
from adc_sample import *

ser0 = serial.Serial('/dev/ttyAM0', 9600, timeout=1)
ser1 = serial.Serial('/dev/ttyAM1', 9600, timeout=1)
id = "MeDON_SubSea"


def archive_file(choice):
        yearname = "%s_%s" %(id, time.strftime("%Y", time.gtime()))
        os.system("mkdir %s" %yearname)
        monthname = "%s_%s" %(id, time.strftime("%B", time.gmtime()))
        os.system("mkdir %s/%s" %(yearname, monthname))
        dayname = "%s_%s" %(id, time.strftime("%Y%m%d", time.gmtime()))
        os.system("mkdir %s/%s/%s" %(yearname, monthname, dayname))

def get_status():
        filename = "%s_%s" %(id, time.strftime("%Y%m%d", time.gmtime()))
	FILE = open(filename, "a")    
        # call comedi demo '.inp' functoion to read A/D channels
	i = 0
        string = ("data")
	ser1.write(string)
        for x in range(0, 10000):
            pass
        reply = ser1.read(16)
        print(reply)
	FILE.write(" \n")
	FILE.close()
        return
	
def get_data():
	print("Acquiring data. Please wait a few seconds...")
	voltages=[]
	offset = find_ts9700()
	#if offset:
		#addr = pc104base+offset
		#for chan in range(0, 8):
			#voltages.append(get_data_value(addr, offset, chan))
	#else:
		#print "Error: ADC interface not found."
		#return "ADC interface not found."
	hostVal = 0
	ser1.write("data\n\r")
	ysiChar = ser1.read(92)
	timeout = 0
	while len(ysiChar) < 80 and timeout < 10:
		ser1.write("data\n\r")
    		ysiChar=ser1.read(94)
		timeout = timeout + 1
	if timeout>9:
		print("Timeout: retries exceeded on ttyAM1")
		return "Timeout: retries exceeded on ttyAM1"
	values = ysiChar.split()
	data = ("%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, " 
		%(values[0], values[1], values[2], values[3], values[4], values[5], 
		values[6], values[7], values[8], values[9], values[10], values[11], values[12]))
	voltage = ""
	for val in voltages:
		voltage = voltage + val + ", "
	data = data + voltage.rstrip(',')
	print(data)
        return data

def auto_sample():
	print("Starting auto sample session.")
	print("Enter number of minutes between samples:")
	interval = raw_input("--->")
	return

def program_upload():
	ser0.write("Uploading file.\n\r")
	#use call to 'sb' command to send ymodem
	return

def handle_choice(choice):
	if (choice == '1'):
		print("Getting system status.\n\r")
		get_status()
	elif (choice == '2'):
		get_data()
	elif (choice == '3'):
		auto_sample()
	elif (choice == '4'):
		program_upload()
        elif (choice == '5'):
                archive_file("status")
        elif (choice == '6'):
		print("Exit session.\n\r")
        else: 
		print("Error. Please enter a valid choice.\n\r")
	return

def main():
	        choice = '0'
	        while (choice != '6'):
		    print("\n\r")
		    print("##############################################")
		    print("#                                            #")
		    print("#  MeDON SubSea Control Program              #")
		    print("#  Version 1.0 16/07/2011                    #")
		    print("#                                            #")
		    print("##############################################")
		    print("\n\r")
		    print("1. Get System Status.")
                    print("2. Get instrument data.")
		    print("4. Upload file.")
                    print("5. Download status file.")
		    print("6. Leave current session.")
		    print("\n\r")
		    print("Enter menu selection:\n\r")
		    while 1:
	                choice = raw_input('--->')
		        if(choice):
		            handle_choice(choice)
                            break
                    if (choice == '6'):
                        ser0.close()
                        os.system("/sbin/getty -L ttyS0 9600 vt100")
			exit
	        ser0.close()

if __name__ == '__main__':
	main()
