#!/usr/bin/python

import os, logging
import logging.handlers
import time
from alin import *

from datetime import datetime


dev = alinDevice('ADC_CORE')

try:
	try:
		n_cycles = int(input('\nNumero de ciclos: '))
	except:
		n_cyckles = 1
	try:
		delay = int(input("\nIntervalo entre ciclos en segundos: "))
	except:
		delay = 1
	Log_file = raw_input ("\nNombre fichero salida sin extension:")

	if n_cycles < 0: n_cycles = 1
	if delay < 0: delay = 1
	LOGS_FOLDER = '/home/projects/alba-em/logs/'
	if len(Log_file)<=0:
		data = time.strftime("%Y%m%d_%H%M%S")
		LOG_FILENAME = LOGS_FOLDER+'Current_'+data+'.csv'
	else:
		LOG_FILENAME = LOGS_FOLDER+Log_file+'.csv'
		
	if not os.path.exists(LOGS_FOLDER):
		os.makedirs(LOGS_FOLDER)		

	my_logger = logging.getLogger('Alba Em#')
	my_logger.setLevel(logging.DEBUG)

	handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=5000000, backupCount=5)
	handler.setLevel(logging.INFO)

	formatter = logging.Formatter('%(asctime)s,%(message)s')
	handler.setFormatter(formatter)

	my_logger.addHandler(handler)

	# Enable ADC 
	dev.writeAttribute('CTL_FSM_CMD',0x01)
	dev.writeAttribute('CTL_ADC_OS',0x06)

	ch1 = ch2 = ch3 = ch3 = ch4 = ch5 = ch6 = ch7 = ch8 = samples_counter = 0

	msg = " Ch1, Ch2, Ch3, Ch4, Ch5, Ch6, Ch7, Ch8, Samples Counter"
	my_logger.info(msg)
	print msg

	counter = 0
	while counter<n_cycles:
		
		def getChannel(ch):
			#readch = s.SDB_readAddress(ch)
			readch = dev.readAttribute(ch)
			if readch is not None:
				if readch>0x7fffffff:
					readch-=0x100000000
				readch = (readch*10)/131072.
				return readch
			return 0

		ch1 = getChannel('ADC_CH1')
		ch2 = getChannel('ADC_CH2')
		ch3 = getChannel('ADC_CH3')
		ch4 = getChannel('ADC_CH4')
		ch5 = getChannel('ADC_CH5')
		ch6 = getChannel('ADC_CH6')
		ch7 = getChannel('ADC_CH7')
		ch8 = getChannel('ADC_CH8')
		samples_counter = dev.readAttribute('SAMPLES_CNT')
		
		msg = " " +str(ch1)+", "+str(ch2)+", "+str(ch3)+", "+str(ch4)+", "
		msg += str(ch5)+", "+str(ch6)+", "+str(ch7)+", "+str(ch8)+", "+str(samples_counter)
		print msg
		my_logger.info(msg)

		counter +=1
		time.sleep(delay)

	print "\nSEQUENCE COMPLETED!!!!"
	print "\nGenerate output file:",LOG_FILENAME+"\n"
except Exception, e:
	print "\nSEQUENCE ABORTED"
	print str(e)
