#!/usr/bin/python
 
import spidev
import time
import os
import signal
import RPi.GPIO as GPIO
from twython import Twython
from auth import (
  consumer_key,
  consumer_secret,
  access_token,
  access_token_secret
)

twitter = Twython(
  consumer_key,
  consumer_secret,
  access_token,
  access_token_secret
)

send = True
message = "It's too close!! " 
# Crear instancia de bus SPI
spi = spidev.SpiDev()

#Intentar abrir bus SPI
try:
  spi.open(0,0)
except:
  print "Error al abrir SPI"
  exit()
#Manejador de signal
def signal_handler(signum, frame):
  global send
  send = True

#Funcion para lectura de un canal SPI
def ReadChannel(channel):
  adc = spi.xfer2([1,(8+channel)<<4,0])
  data = ((adc[1]&3) << 8) + adc[2]
  return data
#Asignar manejador
signal.signal(signal.SIGALRM, signal_handler)

#Utilizar el GPIO en modo bcm
GPIO.setmode(GPIO.BCM)

#Definir los pines a utilizar
pines=[2,3,4,17,27,22]

#Configurar los pines como salidas
for p in pines:
  GPIO.setup(p, GPIO.OUT)

#Loop principal
while True:

#Leer dato del ADC
  level = ReadChannel(0)
#Encender los LEDs dependiendo del dato
  if level > 5:
    GPIO.output(pines[0], True)
  if level > 170:
    GPIO.output(pines[1], True)
  if level > 340:
    GPIO.output(pines[2], True)
  if level > 510:
    GPIO.output(pines[3], True)
  if level > 680:
    GPIO.output(pines[4], True)
#Enviar tweet si level > 850
  if level > 850:
    GPIO.output(pines[5], True)
    if send:
      try:
        twitter.update_status(status=message+time.strftime("%c"))  
        send = False
#Esperar 10 segundos para enviar otro tweet
        signal.alarm(10)
      except Exception, e:
        print "Imposible enviar tweet: ", str(e)

#Delay
  time.sleep(0.1)
#Apagar los LEDs
  for p in pines:
    GPIO.output(p, False)





