Created
November 19, 2019 09:25
-
-
Save Fieel/7338078166ffb9bfeb8c02a3528a3ed9 to your computer and use it in GitHub Desktop.
Python script to read sensor data from the Enviro+ hat installed in a Raspberry Pi. Using the python libraries to read the raw data, requests library for posting the jsonified data with POST requests and the ST7735 library to update the small LED display whenever a request is done.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# Utility di base | |
import os | |
import time | |
import datetime | |
# Loggare su file | |
import logging | |
logging.basicConfig( | |
level=logging.INFO, | |
filename='/home/fieel/sensorStation.log', | |
filemode='a', | |
format='%(asctime)s :: %(name)s %(process)d-%(levelname)s - %(message)s') | |
# Per fare le richieste POST | |
import requests | |
## Per interagire con i sensori tramite l'Enviro+ hat | |
# Temp, humidity and pressure | |
from bme280 import BME280 | |
try: | |
from smbus2 import SMBus | |
except ImportError: | |
from smbus import SMBus | |
bus = SMBus(1) | |
bme280 = BME280(i2c_dev=bus) | |
# Lux & Proximity | |
try: | |
# Transitional fix for breaking change in LTR559 | |
from ltr559 import LTR559 | |
ltr559 = LTR559() | |
except ImportError: | |
import ltr559 | |
# Gas | |
from enviroplus import gas | |
# Particulate | |
#from pms5003 import PMS5003 | |
#pms5003 = PMS5003() | |
# Costanti | |
API_ENDPOINT = 'http://web.server/iot/enviro/' | |
# Per manipolare il minidisplay LED 160 x 80 | |
import ST7735 | |
from PIL import Image, ImageDraw, ImageFont | |
disp = ST7735.ST7735( # Setup display | |
port=0, | |
cs=1, | |
dc=9, | |
backlight=12, | |
rotation=270, | |
spi_speed_hz=10000000 | |
) | |
disp.begin() | |
WIDTH = disp.width | |
HEIGHT = disp.height | |
# LCD reset e scritta loading | |
img = Image.new('RGB', (WIDTH, HEIGHT), color=(0,0,0)) | |
draw = ImageDraw.Draw(img) | |
font_size = 12 | |
font = ImageFont.truetype("/usr/share/fonts/truetype/lato/Lato-Bold.ttf", font_size) | |
colour = (250, 250, 250) | |
temp_message = "Updating data..." | |
x = 40 | |
y = 35 | |
draw.text((x, y), temp_message, font=font, fill=colour) | |
disp.display(img) | |
# Log init | |
logging.info("Reading new data from sensors...") | |
# ######################################### | |
# Leggere dati dai sensori nell'hat Enviro+ | |
# ######################################### | |
# Il sensore bme280 bisogna leggerlo qualche volta | |
# se no ritorna sempre lo stesso valore | |
counter = 0 | |
compensazione = 3 | |
while counter < 3: | |
temperature = bme280.get_temperature() - compensazione | |
humidity = bme280.get_humidity() | |
pressure = bme280.get_pressure() | |
time.sleep(1) | |
counter = counter + 1; | |
lux = ltr559.get_lux() | |
proximity = ltr559.get_proximity() | |
gasReadings = gas.read_all() # Required before reading singular values | |
gas_reducing = gasReadings.reducing | |
gas_oxidising = gasReadings.oxidising | |
gas_nh3 = gasReadings.nh3 | |
#try: | |
# particulateReadings = pms5003.read() # Same as for gas readings | |
# print(particulateReadings) | |
# particulate25 = particulateReadings.pm_ug_per_m3(2.5) | |
# particulate10 = particulateReadings.pm_ug_per_m3(10) | |
#except: | |
# particulate10 = 0 | |
# particulate25 = 0 | |
jsonData = { | |
'temperature': temperature, | |
'humidity': humidity, | |
'pressure': pressure, | |
'lux': lux, | |
'proximity': proximity, | |
'gas_reducing': gas_reducing, | |
'gas_oxidising': gas_oxidising, | |
'gas_nh3': gas_nh3 | |
} | |
logging.info("POST request to " + API_ENDPOINT + " start...") | |
# Costruzione chiamata POST | |
headers = { | |
"Content-Type": "application/json; charset=utf-8", | |
} | |
# Salvataggio risultato | |
postResponse = requests.post( | |
API_ENDPOINT, | |
headers = headers, | |
json = jsonData | |
) | |
print("Response code:", postResponse.status_code) | |
# Debug risultato | |
if postResponse.status_code == 200: | |
logging.info('POST success! Response: ' + postResponse.text) | |
print('POST Success! Response: ', postResponse.text) | |
# LCD pulizia | |
img = Image.new('RGB', (WIDTH, HEIGHT), color=(0,0,0)) | |
draw = ImageDraw.Draw(img) | |
# LCD update risultato | |
font_size = 11 | |
font = ImageFont.truetype("/usr/share/fonts/truetype/lato/Lato-Bold.ttf", font_size) | |
colour = (250, 250, 250) | |
last_sync_date = "Sync: " + datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S") | |
temperature_text = "{:.2f} C | {:.2f}% | {:.2f} hPa".format(temperature, humidity, pressure) | |
luxprox_text = "lux: {:.2f}, prox: {:.2f} ".format(lux, proximity) | |
gas_text1 = "redu: {:.2f}, nh3 {:.2f} ".format(gas_reducing, gas_nh3) | |
gas_text2 = "oxi: {:.2f} ".format(gas_oxidising) | |
result_text = "OK" | |
x = 140 | |
y = 66 | |
draw.text((x, y), result_text, font=font, fill=(0, 250, 0)) | |
x = 0 | |
y = 0 | |
draw.text((x, y), last_sync_date, font=font, fill=(250,160,160)) | |
x = 0 | |
y = 16 | |
draw.text((x, y), temperature_text, font=font, fill=(160,250,160)) | |
x = 0 | |
y = 32 | |
draw.text((x, y), luxprox_text, font=font, fill=(160,160,250)) | |
x = 0 | |
y = 48 | |
draw.text((x, y), gas_text1, font=font, fill=(100,100,100)) | |
x = 0 | |
y = 64 | |
draw.text((x, y), gas_text2, font=font, fill=(100,100,100)) | |
disp.display(img) | |
else: | |
logging.error('POST error! Info: ' + postResponse.text + ' | ' + postResponse.headers) | |
print('POST Not Found. Response:', postResponse.text) | |
print('HEADERS: ', postResponse.headers) | |
print('content: ', postResponse.content) | |
# LCD pulizia | |
img = Image.new('RGB', (WIDTH, HEIGHT), color=(0,0,0)) | |
draw = ImageDraw.Draw(img) | |
# LCD update risultato | |
font = ImageFont.truetype("/usr/share/fonts/truetype/lato/Lato-Bold.ttf", 12) | |
result_text = "ERROR " + str(postResponse.status_code) | |
metadatadate = postResponse.headers['Date'] | |
metadata1 = 'Length: ' + postResponse.headers['Content-Length'] + ", Type: " + postResponse.headers['Content-Type'] | |
metadata2 = postResponse.headers['Connection'] + " / " + postResponse.headers['Server'] | |
error_content = postResponse.text | |
x = 48 | |
y = 10 | |
draw.text((x, y), result_text, font=font, fill=(250, 0, 0)) | |
font = ImageFont.truetype("/usr/share/fonts/truetype/lato/Lato-Bold.ttf", 8) | |
x = 5 | |
y = 25 | |
draw.text((x, y), metadatadate, font=font, fill=(150, 150, 150)) | |
font = ImageFont.truetype("/usr/share/fonts/truetype/lato/Lato-Bold.ttf", 8) | |
x = 5 | |
y = 35 | |
draw.text((x, y), metadata1, font=font, fill=(150, 150, 150)) | |
font = ImageFont.truetype("/usr/share/fonts/truetype/lato/Lato-Bold.ttf", 7) | |
x = 50 | |
y = 1 | |
draw.text((x, y), metadata2, font=font, fill=(150, 150, 150)) | |
# 'Connection': 'keep-alive', 'Server': 'nginx | |
font = ImageFont.truetype("/usr/share/fonts/truetype/lato/Lato-Bold.ttf", 7) | |
x = 5 | |
y = 45 | |
draw.text((x, y), error_content, font=font, fill=(100, 100, 100)) | |
disp.display(img) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment