# devroom.py  26/08/2014  D.J.Whale

import piduino
from Copro import *
import RPi.GPIO as GPIO
import time
import datetime
import urllib2 #TODO deprecate
# import IoticLabs.IOTConnector as IOT


# CONFIGURATION ----------------------------------------------------------

LED  = 11 # same pin as piduino D13, which is the LED
DOOR = 9  # same pin as piduino D12, wired to a button

POLL_TIME   = 0.25  # how long to wait for an ADC reading
REPORT_TIME = 1.0   # fastest to report to web page that data has changed

DOOR_OPEN = True
#TODO deprecate
UPDATE_URL = "http://www.thinkingbinaries.com/test/door/doorupdate.php"

def ui(msg):
  print(str(msg))


# INIT -------------------------------------------------------------------

piduino.firmware("copro.hex")
piduino.connect(baud=9600)

GPIO.setmode(GPIO.BCM)
GPIO.setup(LED, GPIO.OUT)
GPIO.setup(DOOR, GPIO.IN)


# IOT.joinAs("com.iotic-labs/devroom")
# entryDoor    = IOT.advertise("door/entry")
# ambientLight = IOT.advertise("light/ambient")
# ambientTemp  = IOT.advertuse("temp/ambient")


# BACK-END ---------------------------------------------------------------

#TODO deprecate
def send(t, s):
  try:
    urllib2.urlopen(UPDATE_URL + "?time=" + t + "&status=" + s)
  except:
    ui("Failed to send to internet, ignoring")

#TODO deprecate
def reportState(t, s):
  dstr = "STATE:"
  if s:
    dstr += "OPEN"
    GPIO.output(LED, True)
  else:
    dstr += "CLOSED"
    GPIO.output(LED, False)

  ui(t + "," + dstr)
  send(t, dstr)

#TODO deprecate
def reportChange(t, d):
  dstr = "CHANGE:"
  if d:
    dstr += "OPENED"
    GPIO.output(LED, True)
  else:
    dstr += "CLOSED"
    GPIO.output(LED, False)

  ui(t + "," + dstr) 
  send(t, dstr)


#TODO deprecate? time in default message?
def timestamp():
  return datetime.datetime.now().strftime("%Y-%m-%d-%H:%M:%S")


# FRONT-END ------------------------------------------------------------

def main():
  lasttime = time.time()

  ui("starting...")
  door_state = GPIO.input(DOOR)
  reportState(timestamp(), door_state)

  while True:
    # ACQUIRE DATA (fast)

    #TODO still knitting in ADC readings
    adcvals = readNextAdcValues(timeout=POLL_TIME)
    if adcvals != None:
      #fix the order (which is a left over from the neopixel demo)
      #we re-ordered adcs because sk wired rgb as gbr!
      a2, a0, a1 = adcvals
      print("A0=" + str(a0) + " A1=" + str(a1) + " A2=" + str(a2))    

    door = GPIO.input(DOOR)


    # if ambient light reading has changed in last 5 seconds
    # might want some averaging and stats here (min/max/N)
    # ambientLight.share(a0)

    # if temp has changed in last 5 seconds
    # might want some averaging and stats here (min/max/N)
    # ambientTemp.share(a1)


    # REPORT DATA (slower)
    newtime = time.time()
    if newtime > (lasttime + REPORT_TIME):
      if door != door_state:
        reportChange(timestamp(), door) # deprecate
        # entryDoor.share(door_state)
        lasttime = newtime
        door_state = door


# MAIN PROGRAM ---------------------------------------------------------

try:
  main()
finally:
  GPIO.cleanup()
  #IOT.cleanup()

# END



