#!/usr/bin/python
import sys
import requests
import Adafruit_DHT
import config
import RPi.GPIO as GPIO

# Try to read the state of GPIO_PIN_TANKFULL
GPIO.setmode(GPIO.BCM)
GPIO.setup(config.GPIO_PIN_TANKFULL, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# tank sensor has inverse logic - 0 when it is full 1 when it is not
# so we are inverting its value here
tankFull = (not GPIO.input(config.GPIO_PIN_TANKFULL))
GPIO.cleanup()
print 'Bacva puna: {}'.format(tankFull)

# Go on to DHT
SENSOR_TYPE = Adafruit_DHT.DHT11
controller_id = config.CONTROLLER_ID
owner = "Controller: %s" % controller_id

# Try to grab a sensor reading.  Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(SENSOR_TYPE, config.GPIO_PIN_DHT)

# Un-comment the line below to convert the temperature to Fahrenheit.
# temperature = temperature * 9/5.0 + 32

# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if temperature is not None and humidity is not None:
    response = requests.post(config.SENSORDATA_URL, json={"owner": owner, "temperatureValue": temperature, "humidityValue":humidity, "tankFull":tankFull,
    "controllerId": controller_id
    })
    print 'Temp={0:0.1f}*C'.format(temperature)
    print 'Humidity={0:0.1f}%'.format(humidity)
    if response.status_code != 200:
        print 'Failed to send temperature!'

else:
    print 'Failed to get reading. Try again!'
