#!/usr/bin/python
# Copyright (c) 2014 Adafruit Industries, base code used from Author Ton DiCola

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
import influxdb
import Adafruit_DHT
import time

# open initial DB connections
db_client = influxdb.InfluxDBClient('localhost',8086,'','','sensordata')

def get_sensor_reading():
    # 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(Adafruit_DHT.DHT11, 4)

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

    # validate sensor data received else log false readings
    if humidity is not None and temperature is not None:
        print('Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity))
    else:
        print('Failed to get reading. Try again!')
        temperature = -1
        humidity = -1
    return temperature,humidity


## infinite loop collecting data every XX seconds
while (True):

    temp_data,humidity_data = get_sensor_reading()

    json_body = [
        {
            "measurement": "temperature",
            "fields": {
                "location": "living_room__actual",    
                "temp": temp_data,
                "humidity": humidity_data
            }
        }
    ]

    print("Write points: {0}".format(json_body))
    db_client.write_points(json_body)

    query_all = "select * from temperature"
    print("Querying data: " + query_all)
    result = db_client.query(query_all)
    print("Result: {0}".format(result))
    
    print("Sleeping 15 seconds")
    time.sleep(15)


