#!/usr/bin/env python

DEBUG = False

import argparse
import time, glob
from lora_gateway import LoRaGateway
import json

parser = argparse.ArgumentParser(description='Repeatedly read in analog value from remote node analog pin, and print json-formatted text to std_out.  Sleep in between reads for sleep_seconds*sleep_iterations seconds.  Also logs output to outfilename.json')
parser.add_argument('-d', '--device', default=glob.glob("/dev/ttyACM*")[0], help='path to serial device')
parser.add_argument('-r', '--rate', default=115200, help='rate of serial communication',type=int)
parser.add_argument('-o', '--outfilename', default='output.csv', help='output file')
parser.add_argument('-p', '--pin', default=0, help='the analog pin we want to measure',type=int)
parser.add_argument('-s', '--sleep_seconds', default=5, help='number of seconds to sleep',type=int)
parser.add_argument('-i', '--sleep_iterations', default=1, help='number of times to repeat sleep_seconds sleep interval before waking',type=int)

args = parser.parse_args()

port = args.device
rate = args.rate
PIN=args.pin
outfilename=str(args.outfilename)
sleep_seconds=int(args.sleep_seconds)
repeats=int(args.sleep_iterations)
delay_time=int(sleep_seconds*repeats)

# create a lora gateway object
LG = LoRaGateway(port,rate)

while True:
    try:

        outfile = open(outfilename,"w")
        
        # read the value of a digital pin
        LG.analog_read(PIN)
        
        # get the response (in 'dict' format)
        pkt = LG.pkt
        
        if not pkt is None:
            
            # print json to the command line
            print json.dumps(pkt)
           
            # write to a local output file
            outfile.write(json.dumps(pkt))
            outfile.flush()
            
        else:
            print 'ERROR'
            
        # put remote node to sleep
        LG.set_sleep(sleep_seconds,repeats)
        
        if (DEBUG):
            print "# sleeping for "+str(delay_time)+" seconds ..."
        
        time.sleep(delay_time+2) # give a 2 second buffer 
        
    except Exception as exc:
        print "# WARNING caught exception: %s" % exc
    finally:
        outfile.close()
        
       
    
    

