#!/usr/bin/python

import time
import datetime
import sys
from pymlab import config

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

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

port    = eval(sys.argv[1])
#### Sensor Configuration ###########################################

cfg = config.Config(
    port = port,
    bus = [
        {
            "name":          "counter",
            "type":        "acount02",
        },
    ],
)
cfg.initialize()

print "Frequency counter readout example \r\n"
fcount = cfg.get_device("counter")
time.sleep(0.5)
frequency = fcount.get_freq()

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

try:
    with open("temperature.log", "a") as f:
        while True:
            now = datetime.datetime.now()
            if (now.second == 15) or (now.second == 35) or (now.second == 55):
                frequency = fcount.get_freq()
                now = datetime.datetime.now()

            sys.stdout.write("frequency: " + str(frequency) + " Hz  Time: " + str(now.second) + "\r")
            f.write("%d\t%s\t%.3f\n" % (time.time(), datetime.datetime.now().isoformat(), frequency))

            sys.stdout.flush()
            time.sleep(1)
except KeyboardInterrupt:
    sys.stdout.write("\r\n")
    sys.exit(0)
    f.close()