#! /usr/bin/python

"""
started with dispatch_async.py
Original code derived from Paul Malmsten, 2010, pmalmsten@gmail.com

This example continuously reads the serial port and dispatches packets
which arrive to appropriate methods for processing in a separate thread.

Sends data to node-red socket.
"""
from xbee import XBee
from xbee.helpers.dispatch import Dispatch
import time
import serial
from datetime import datetime
import binascii
import socket
import sys, os
import simplejson
import syslog
import ConfigParser
import threading


# check that the config file exists
configfile = "/etc/tinaja/tinaja.conf"

if not os.path.isfile("/etc/passwd"):
    print "cannot locate config file: " + configfile
    sys.exit(1)

# get the config file info
try:
    config = ConfigParser.ConfigParser()
    config.read(configfile)

    PORT = config.get('tinaja', 'serialport')
    BAUD_RATE = config.getint('tinaja', 'baudrate')
    TIMEOUT = config.getint('tinaja', 'timeout')
    LOCALLOGPATH = config.get('tinaja', 'locallogpath')

    COLLECT_INTERVAL = config.getfloat('tinaja', 'collection_interval')

    # node-red socket info
    SOCKET_SERVER = config.get('tinaja', 'nr_server')
    SOCKET_PORT_SNSR = config.getint('tinaja', 'snsr_socketport')
    SOCKET_PORT_CNTR = config.getint('tinaja', 'cntr_socketport')

    # local socket server info
    HOST_SERVER = config.get('tinaja', 'hostserver')
    HOST_PORT = config.getint('tinaja', 'hostport')
    HOST_BACKLOG = config.getint('tinaja', 'hostbacklog')
    HOST_SIZE = config.getint('tinaja', 'hostsize')
except Exception, e:
    print "TLSM: Configuration error: ", e.message
    syslog.syslog("TLSM: Configuration error: " + e.message)

# starting up...
print ""
print "------------------- starting: " + os.path.basename(sys.argv[0])
syslog.syslog("TLSM - Tinaja Labs Sensor Manager: "+os.path.basename(sys.argv[0])+" started")

keepGoing = True

# counters for reporting data through-put
inBoundCount = 0
outBoundCount = 0
countSeconds = 15

# Open serial port
# ser = serial.Serial(PORT, BAUD_RATE,timeout=TIMEOUT)
ser = serial.Serial(PORT, BAUD_RATE)
syslog.syslog("Serial port opened: "+ str(ser))


##############################################################
def clamp(n, minn, maxn):
    if n < minn:
        return minn
    elif n > maxn:
        return maxn
    else:
        return n

##############################################################
def inADCRange(n):
    minn=0
    maxn=1024