Sketch: #1

PI: Temp & Humidity Sensor Reader


Get temp and humidity readings from a location and post the data to rest API. Done by hooking a DHT22 temperature and humidity sensor up to pin 27 for data then power and ground and watching things work! If you change from pin 27 you'll need to pin referance in the do_work() method to reflect the pin you choose for data use. You also need to build and import the AdafruitDHT library from ( https://github.com/benspelledabc/Adafruit_Python_DHT ). Forked from the main project to make sure it doesn't go away.
The output can be seen here via the API: https://benspelledabc.me/content_collection/sensor_readings/

I need to work on the formatting of the code block, but the base is there for now.

                ------------- CODE STARTS BELOW THIS LINE -------------
import sys
import time
import json
import requests
import Adafruit_DHT


def push_data(input_data):
    print("Pushing data")
    try:
        url = 'http://benspelledabc.me/api/sensor_reading/'
        headers = {'Content-Type': "application/json; charset=utf-8", 'Accept': "application/json"}
        data = input_data
        # print(data)
        res = requests.post(url, json=data, headers=headers, auth=('username_redacted', 'pass_redacted'))
        # print(res.status_code)
        # print(res.raise_for_status())
        # print("Done pushing!")
    except requests.exceptions.HTTPError as http_error:
        # print("Error: {0}".format(http_error))
        # print(f"Error: {http_error}")
        sys.exit(1)



def do_work():
    DHT_SENSOR = Adafruit_DHT.DHT22
    DHT_PIN = 27
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
    fahrenheit = 0.0

    if humidity is not None and temperature is not None:
        # juuuuuust a little bit of manual correction to the base temp
        temperature -= 1.6

        fahrenheit = 1.8 * temperature + 32
        # print("Temp={0:0.1f}*C  Humidity={1:0.1f}%".format(temperature, humidity))
        # print("Temp={0:0.1f}*F  Humidity={1:0.1f}%".format(fahrenheit, humidity))

        temperature = format(temperature, '.1f')
        fahrenheit = format(fahrenheit, '.1f')
        humidity = format(humidity, '.1f')

        data = {
            "sensor_location": "Stickers (gun safe)",
            "sensor_model": "DHT22",
            "celsius": temperature,
            "fahrenheit": fahrenheit,
            "humidity": humidity
        }
        push_data(data)
    else:
        # print("Failed to retrieve data from humidity sensor")
        sys.exit(1)


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    do_work()
    time.sleep(23)    # it takes 3-4 seconds to run, sleeping for 23 gives ABOUT 2 per minute
    do_work()