import datetime
import getpass
import sys
import telnetlib
import time
import csv
import numpy as np
import shutil
import sys
import atexit, os
    
sys.stdout.write('whatever')

from collections import defaultdict
from xml.etree import cElementTree as ET

def etree_to_dict(t):
    d = {t.tag: {} if t.attrib else None}
    children = list(t)
    if children:
        dd = defaultdict(list)
        for dc in map(etree_to_dict, children):
            for k, v in dc.iteritems():
                dd[k].append(v)
        d = {t.tag: {k:v[0] if len(v) == 1 else v for k, v in dd.iteritems()}}
    if t.attrib:
        d[t.tag].update(('@' + k, v) for k, v in t.attrib.iteritems())
    if t.text:
        text = t.text.strip()
        if children or t.attrib:
            if text:
                d[t.tag]['#text'] = text
        else:
            d[t.tag] = text
    return d
    
def Scan_Params():
    print params['PAR']["HOST"]
    print params['PAR']["HOSTIP"]
    print 'DATANAME',params['PAR']["DATANAME"]
    print 'DATANAMEAUTO',params['PAR']["DATANAMEAUTO"]
    print 'PERIODE:', params['PAR']["PERIODE"]
    print 'LENGTH:', params['PAR']["LENGTH"]
    print 'BUFLENGTH:', params['PAR']["BUFLENGTH"]
    print 'TEMPCHANNELS',params['PAR']["TEMPCHANNELS"]
    print 'VOLTAGECHANNELS',params['PAR']["VOLTAGECHANNELS"]
    print datetime.datetime.today()
    
def Scan_Params_Str():
    buf=''
    buf+=KTMODEL+"\r"
    buf+=str(params['PAR']["HOST"])+"\r"
    buf+=str( params['PAR']["HOSTIP"])+"\r"
    buf+= 'DATANAME:,'+str(params['PAR']["DATANAME"])+"\r"
    buf+= 'DATANAMEAUTO:,'+str(params['PAR']["DATANAMEAUTO"])+"\r"
    buf+= 'PERIODE:,'+str( params['PAR']["PERIODE"])+"\r"
    buf+= 'LENGTH:,'+str( params['PAR']["LENGTH"])+"\r"
    buf+= 'BUFLENGTH:,'+str( params['PAR']["BUFLENGTH"])+"\r"
    buf+= 'TEMPCHANNELS:,'+str(params['PAR']["TEMPCHANNELS"])+"\r"
    buf+= 'VOLTAGECHANNELS:,'+str(params['PAR']["VOLTAGECHANNELS"])+"\r"
    buf+= str(datetime.datetime.today())+"\r"
    buf+= "\r"
    buf+= str(params['PAR']["COMMENTS"])+"\r"
    buf+= "\r"
    buf+= str(params['PAR']["NAMECHANNELS"]).replace(',', ",,")+"\r"
    return buf
    
def ASK(cmd):
    buf={}
    tn.write(cmd+"\n")
    time.sleep(0.5)
    buf = tn.read_very_eager()
    return buf

f = open(os.path.join(os.pardir,"Config.xml"),"r")
#f = open("Config.xml","r")
xml_config = ET.XML(f.read())
f.close()
params=etree_to_dict(xml_config)

Scan_Params()

try:
    tn=telnetlib.Telnet(params['PAR']["HOST"],23,20)
except:
    try:
        tn=telnetlib.Telnet(params['PAR']["HOSTIP"],23,20)
    except:
        print "NO CONNECTION!!!"
        #tn.close()
        sys.exit("NO CONNECTION!!!")
#terminal close
def Close_Terminal_Exception():
    tn.close()
    print "CLOSING..."
atexit.register(Close_Terminal_Exception)
#terminal close

KTMODEL=ASK('*IDN?')
if KTMODEL.find('KEITHLEY INSTRUMENTS')!=0:
    print "NO CONNECTION!!!"
    tn.close()
    sys.exit("NO CONNECTION!!!")
       
print KTMODEL

f = open('KT_Script.txt')
Script = f.read()
f.close()

#Script=Script.replace("CHANNELS","\"1001:"+str(1000+int(params['PAR']["CHANNELS"]))+"\"")
#Script=Script.replace("PERIODE",params['PAR']["PERIODE"])
Script=Script.replace("SCANCOUNT",params['PAR']["LENGTH"])
Script=Script.replace("BUFFER",params['PAR']["BUFLENGTH"])
if params['PAR']["TEMPCHANNELS"]=='0':
    Script=Script.replace("dmm.setconfig(\"TEMPCHANNELS\"","--dmm.setconfig(\"TEMPCHANNELS\"")
else:
    Script=Script.replace("TEMPCHANNELS",params['PAR']["TEMPCHANNELS"])

if params['PAR']["VOLTAGECHANNELS"]=='0':
    Script=Script.replace("dmm.setconfig(\"VOLTAGECHANNELS\"","--dmm.setconfig(\"VOLTAGECHANNELS\"")
else:
    Script=Script.replace("VOLTAGECHANNELS",params['PAR']["VOLTAGECHANNELS"])

if params['PAR']["DATANAMEAUTO"]=='YES':
    Script=Script.replace("DATANAME",params['PAR']["DATANAME"]+str(datetime.datetime.today()).replace(" ","_").replace(":","x").replace(".","x").replace("-","_"))
    script_name=params['PAR']["DATANAME"]+str(datetime.datetime.today()).replace(" ","_").replace(":","x").replace(".","x").replace("-","_")
else:
    Script=Script.replace("DATANAME",params['PAR']["DATANAME"])
    script_name=params['PAR']["DATANAME"]

if params['PAR']["TEMPCHANNELS"]=='0':
    CHANNELS=params['PAR']["VOLTAGECHANNELS"]
elif params['PAR']["VOLTAGECHANNELS"]=='0':
    CHANNELS=params['PAR']["TEMPCHANNELS"]
else:
    CHANNELS=params['PAR']["TEMPCHANNELS"]+':'+params['PAR']["VOLTAGECHANNELS"]
CHANNELS_TAB=CHANNELS.split(':')
CHANNELS=min(CHANNELS_TAB)+':'+max(CHANNELS_TAB)
Script=Script.replace("MINCHANNEL,PERIODE", "\""+str(min(CHANNELS_TAB))+"\""+","+params['PAR']["PERIODE"])
Script=Script.replace("CHANNELS",CHANNELS)
print 'CHANNELS:',CHANNELS
CHANNEL_NUM=int(max(CHANNELS_TAB))-int(min(CHANNELS_TAB))+1
print 'CHANNEL NUMBER:', CHANNEL_NUM
if (int(max(CHANNELS_TAB))-1000)*int(params['PAR']["LENGTH"])>int(params['PAR']["BUFLENGTH"]):
    print "SCAN TOO LONG!!!"
    sys.exit("SCAN TOO LONG!!!")

#Update time from laptop to Keithley
at=str(datetime.datetime.today()).replace(" ",",").replace(":",",").replace(".",",").replace("-",",")
at=at.split(',')
time_string= "settime(os.time{year=%s,month=%s,day=%s,hour=%s,min=%s,sec=%s})\n"%(at[0],at[1],at[2],at[3],at[4],at[5])
#Set updated time in Keithley
tn.write(time_string)
#Write the workscript
tn.write(Script)

data_dir="..\\data\\"
start_time = time.time()
f = open(data_dir+script_name+".csv", "w")
f.write(Scan_Params_Str())
f.close()

time.sleep(2)
data=""
status_flag=2
sample_counter=0
print str(params['PAR']["COMMENTS"])
print str(params['PAR']["NAMECHANNELS"])
while status_flag!=6:
    data=tn.read_very_eager()
    data=data.replace("\r\n", ",")
#    print len(data)
    if data.find("<6>")!=-1:
        status_flag=6
        
    data=data.replace("<2>,", '')
    data=data.replace("<6>,", '')
    
    length=len(data)
    if length==0 or data=='' or data==',':
        time.sleep(2)
        continue
        
    data2=data.split(',')
    del data2[-1]
    
    for i in np.arange(1,len(data2),2):
        sample_counter+=1
        if sample_counter % CHANNEL_NUM == 0:
            data2[i]+="\r"
        try:
            if ((sample_counter-1)%CHANNEL_NUM)+1==1:
                print ''
            print "%.2E|"  % (float(data2[i-1])),
        except:
            pass
            
    data3=','.join(data2)
    data3=data3.replace("\r,", ",\r")
    
    if data3[len(data3)-1]!='\r':
        data3+=','
        
    f = open(data_dir+script_name+".csv", "a")
    f.write(data3)
    f.close()
    try:
        shutil.copy2(data_dir+script_name+".csv", "..\\TEMP_FILE.csv")
    except:
        pass
        
    time.sleep(2)

end_time = time.time()
#Scan_Params()
print ''
print "Time elapsed[s]:",end_time-start_time
tn.close()
#raw_input("Press any key to continue...")
exit(0)
#choice='a'
#print "Press 'Y' to close the terminal"
#while choice!= 'Y' and choice != 'y':
#   choice = raw_input()
