#!/usr/bin/python

#uncomment for debbug purposes
#import logging
#logging.basicConfig(level=logging.DEBUG)

import time
import datetime
import sys
import os

from pymlab import config
from mlabutils import ejson

parser = ejson.Parser()

#### Script Arguments ###############################################

if len(sys.argv) != 3:
    sys.stderr.write("Invalid number of arguments.\n")
    sys.stderr.write("Usage: %s PORT_ADDRESS CONFIG_FILE\n" % (sys.argv[0], ))
    sys.exit(1)


port = eval(sys.argv[1])

value = parser.parse_file(sys.argv[2])
path = value['data_path']
interval = value['raw_sample_interval']
stationName = value['origin']



if (interval<5) or (interval>3600):
    sys.stderr.write("Invalid sample interval arguments.\n")
    sys.stderr.write("The interval has to be in the range from 5 to 3600 seconds\n")
    sys.exit(2)

#### Sensor Configuration ###########################################

cfg = config.Config(
    i2c = {
            "port": port,
    },
    bus = [
        {
            "name":          "current_sensor1",
            "type":        "vcai2c01",
            "address":        0x68,
        },
        {
            "name":          "current_sensor2",
            "type":        "vcai2c01",
            "address":        0x6a,
        },
    ],
)
cfg.initialize()

sys.stdout.write("Current loop sensor example \r\n")
sys.stdout.write("Time, channel #1,  channel #2,  channel #3 ,  channel #4,  channel #5   \r\n")
sensor1 = cfg.get_device("current_sensor1")
sensor2 = cfg.get_device("current_sensor2")
#time.sleep(0.5)

#### Data Logging ###################################################

try:
    before = time.time()-interval
    while True:
        
        filename = path + time.strftime("%Y%m%d%H", time.gmtime()) +"0000_"+ stationName + "_data.csv"        
        now = time.time()
        
        if (now - before >= interval - 2.5):     #   0.5*5 channels= 2.5s
            with open(filename, "a") as f:        

                sensor1.setADC(channel = 1, gain = 1, sample_rate = 3.75);
                time.sleep(0.5)
                channel1 = sensor1.readCurrent();
    
                sensor1.setADC(channel = 2, gain = 1, sample_rate = 3.75);
                time.sleep(0.5)
                channel2 = sensor1.readCurrent();
    
                sensor1.setADC(channel = 3, gain = 1, sample_rate = 3.75);
                time.sleep(0.5)
                channel3 = sensor1.readCurrent();
    
                sensor1.setADC(channel = 4, gain = 1, sample_rate = 3.75);
                time.sleep(0.5)
                channel4 = sensor1.readCurrent();
    
                sensor2.setADC(channel = 1, gain = 1, sample_rate = 3.75);
                time.sleep(0.5)
                channel5 = sensor2.readCurrent();           
            

                sys.stdout.write("%s \t %0.3f \t %0.3f \t %0.3f \t %0.3f \t %0.3f \n" % (datetime.datetime.now().isoformat(), channel1, channel2, channel3, channel4, channel5))

                f.write("%d;%0.3f;%0.3f;%0.3f;%0.3f;%0.3f\n" % (time.time(), channel1, channel2, channel3, channel4, channel5))
                f.flush()

                sys.stdout.flush()
                before = time.time()
        else:
            time.sleep(0.1)

except KeyboardInterrupt:
    f.close()
    sys.exit(0)