From 8ac41078e0bc53735aebeaef5260d2406f4d4c86 Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 04:43:38 +0100 Subject: [PATCH 01/18] Initial --- examples/mqtt-all.py | 212 +++++++++++++++++++++++++++++++++++++++++++ library/setup.cfg | 1 + 2 files changed, 213 insertions(+) create mode 100755 examples/mqtt-all.py diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py new file mode 100755 index 0000000..6c43135 --- /dev/null +++ b/examples/mqtt-all.py @@ -0,0 +1,212 @@ +""" +Run mqtt broker on localhost: sudo apt-get install mosquitto mosquitto-clients +""" +#!/usr/bin/env python3 + +import requests +import ST7735 +import time +from bme280 import BME280 +from pms5003 import PMS5003, ReadTimeoutError +from subprocess import PIPE, Popen, check_output +from PIL import Image, ImageDraw, ImageFont +from fonts.ttf import RobotoMedium as UserFont + +import paho.mqtt.client as mqtt +import paho.mqtt.publish as publish + +try: + from smbus2 import SMBus +except ImportError: + from smbus import SMBus + +print( + """mqtt-all.py - Reads temperature, pressure, humidity, +PM2.5, and PM10 from Enviro plus and sends data over mqtt. + +Press Ctrl+C to exit! + +""" +) + +mqtt_broker = "localhost" +mqtt_port = 1883 +mqtt_topic = "enviroplus" + +# mqtt callbacks +def on_connect(client, userdata, flags, rc): + print(f"CONNACK received with code {rc}") + if rc == 0: + print("connected OK") + else: + print("Bad connection Returned code=", rc) + + +def on_publish(client, userdata, mid): + print("mid: " + str(mid)) + + +mqtt_client = mqtt.Client() +mqtt_client.on_connect = on_connect +mqtt_client.on_publish = on_publish +mqtt_client.connect(mqtt_broker, port=mqtt_port) + +bus = SMBus(1) + +# Create BME280 instance +bme280 = BME280(i2c_dev=bus) + +# Create LCD instance +disp = ST7735.ST7735( + port=0, cs=1, dc=9, backlight=12, rotation=270, spi_speed_hz=10000000 +) + +# Initialize display +disp.begin() + +# Create PMS5003 instance +pms5003 = PMS5003() + + +# Read values from BME280 and PMS5003 and return as dict +def read_values(): + values = {} + cpu_temp = get_cpu_temperature() + raw_temp = bme280.get_temperature() + comp_temp = raw_temp - ((cpu_temp - raw_temp) / comp_factor) + values["temperature"] = "{:.2f}".format(comp_temp) + values["pressure"] = "{:.2f}".format(bme280.get_pressure() * 100) + values["humidity"] = "{:.2f}".format(bme280.get_humidity()) + try: + pm_values = pms5003.read() + values["P2"] = str(pm_values.pm_ug_per_m3(2.5)) + values["P1"] = str(pm_values.pm_ug_per_m3(10)) + except ReadTimeoutError: + pms5003.reset() + pm_values = pms5003.read() + values["P2"] = str(pm_values.pm_ug_per_m3(2.5)) + values["P1"] = str(pm_values.pm_ug_per_m3(10)) + return values + + +# Get CPU temperature to use for compensation +def get_cpu_temperature(): + process = Popen(["vcgencmd", "measure_temp"], stdout=PIPE, universal_newlines=True) + output, _error = process.communicate() + return float(output[output.index("=") + 1 : output.rindex("'")]) + + +# Get Raspberry Pi serial number to use as ID +def get_serial_number(): + with open("/proc/cpuinfo", "r") as f: + for line in f: + if line[0:6] == "Serial": + return line.split(":")[1].strip() + + +# Check for Wi-Fi connection +def check_wifi(): + if check_output(["hostname", "-I"]): + return True + else: + return False + + +# Display Raspberry Pi serial and Wi-Fi status on LCD +def display_status(): + wifi_status = "connected" if check_wifi() else "disconnected" + text_colour = (255, 255, 255) + back_colour = (0, 170, 170) if check_wifi() else (85, 15, 15) + id = get_serial_number() + message = "{}\nWi-Fi: {}".format(id, wifi_status) + img = Image.new("RGB", (WIDTH, HEIGHT), color=(0, 0, 0)) + draw = ImageDraw.Draw(img) + size_x, size_y = draw.textsize(message, font) + x = (WIDTH - size_x) / 2 + y = (HEIGHT / 2) - (size_y / 2) + draw.rectangle((0, 0, 160, 80), back_colour) + draw.text((x, y), message, font=font, fill=text_colour) + disp.display(img) + + +def send_to_mqtt(values, id): + pm_values = dict(i for i in values.items() if i[0].startswith("P")) + temp_values = dict(i for i in values.items() if not i[0].startswith("P")) + + pm_values_json = [ + {"value_type": key, "value": val} for key, val in pm_values.items() + ] + temp_values_json = [ + {"value_type": key, "value": val} for key, val in temp_values.items() + ] + + resp_1 = requests.post( + "https://api.luftdaten.info/v1/push-sensor-data/", + json={ + "software_version": "enviro-plus 0.0.1", + "sensordatavalues": pm_values_json, + }, + headers={ + "X-PIN": "1", + "X-Sensor": id, + "Content-Type": "application/json", + "cache-control": "no-cache", + }, + ) + + resp_2 = requests.post( + "https://api.luftdaten.info/v1/push-sensor-data/", + json={ + "software_version": "enviro-plus 0.0.1", + "sensordatavalues": temp_values_json, + }, + headers={ + "X-PIN": "11", + "X-Sensor": id, + "Content-Type": "application/json", + "cache-control": "no-cache", + }, + ) + + if resp_1.ok and resp_2.ok: + return True + else: + return False + + +# Compensation factor for temperature +comp_factor = 2.25 + +# Raspberry Pi ID to send to Luftdaten +id = "raspi-" + get_serial_number() + +# Width and height to calculate text position +WIDTH = disp.width +HEIGHT = disp.height + +# Text settings +font_size = 16 +font = ImageFont.truetype(UserFont, font_size) + +# Display Raspberry Pi serial and Wi-Fi status +print("Raspberry Pi serial: {}".format(get_serial_number())) +print("Wi-Fi: {}\n".format("connected" if check_wifi() else "disconnected")) +print("MQTT broker IP: {}".format(mqtt_broker)) + +time_since_update = 0 +update_time = time.time() + +# Main loop to read data, display, and send over mqtt +mqtt_client.loop_start() +while True: + try: + time_since_update = time.time() - update_time + values = read_values() + print(values) + if time_since_update > 145: + mqtt_client.publish(mqtt_topic, values) + # resp = send_to_mqtt(values, id) + update_time = time.time() + display_status() + except Exception as e: + print(e) diff --git a/library/setup.cfg b/library/setup.cfg index d2909c1..c59250c 100644 --- a/library/setup.cfg +++ b/library/setup.cfg @@ -38,6 +38,7 @@ install_requires = astral pytz sounddevice + paho-mqtt [flake8] exclude = From 9b5079302bd7e501f0f6e6460ad454a7d51bf2e9 Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 04:49:32 +0100 Subject: [PATCH 02/18] add debug topic --- examples/mqtt-all.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index 6c43135..08fe41b 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -198,13 +198,14 @@ def send_to_mqtt(values, id): # Main loop to read data, display, and send over mqtt mqtt_client.loop_start() +mqtt_client.publish(mqtt_topic, "publishing from enviroplus") while True: try: time_since_update = time.time() - update_time values = read_values() print(values) if time_since_update > 145: - mqtt_client.publish(mqtt_topic, values) + mqtt_client.publish(mqtt_topic, str(values)) # resp = send_to_mqtt(values, id) update_time = time.time() display_status() From 61cec50e4c945abfdb3ec96c45dbd0989ad9ec55 Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 04:53:28 +0100 Subject: [PATCH 03/18] add json dumps --- examples/mqtt-all.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index 08fe41b..d5d1042 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -11,6 +11,7 @@ from subprocess import PIPE, Popen, check_output from PIL import Image, ImageDraw, ImageFont from fonts.ttf import RobotoMedium as UserFont +import json import paho.mqtt.client as mqtt import paho.mqtt.publish as publish @@ -198,14 +199,14 @@ def send_to_mqtt(values, id): # Main loop to read data, display, and send over mqtt mqtt_client.loop_start() -mqtt_client.publish(mqtt_topic, "publishing from enviroplus") +mqtt_client.publish(mqtt_topic, "test message from {}".format(mqtt_topic)) while True: try: time_since_update = time.time() - update_time values = read_values() print(values) if time_since_update > 145: - mqtt_client.publish(mqtt_topic, str(values)) + mqtt_client.publish(mqtt_topic, json.dumps(values)) # resp = send_to_mqtt(values, id) update_time = time.time() display_status() From 0d63b4ac8c63bfe05a86aa41bfddda15e427e48c Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 04:56:14 +0100 Subject: [PATCH 04/18] debug --- examples/mqtt-all.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index d5d1042..263addb 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -206,7 +206,9 @@ def send_to_mqtt(values, id): values = read_values() print(values) if time_since_update > 145: - mqtt_client.publish(mqtt_topic, json.dumps(values)) + # mqtt_client.publish(mqtt_topic, json.dumps(values)) + mqtt_client.publish(mqtt_topic, values["temperature"]) + mqtt_client.publish(mqtt_topic, "test") # resp = send_to_mqtt(values, id) update_time = time.time() display_status() From 799666a2b3d7260fc10a3be9a549d18fcb024d32 Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 04:58:08 +0100 Subject: [PATCH 05/18] move mqtt publish --- examples/mqtt-all.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index 263addb..97706a5 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -205,10 +205,10 @@ def send_to_mqtt(values, id): time_since_update = time.time() - update_time values = read_values() print(values) + mqtt_client.publish(mqtt_topic, values["temperature"]) + mqtt_client.publish(mqtt_topic, "test") if time_since_update > 145: # mqtt_client.publish(mqtt_topic, json.dumps(values)) - mqtt_client.publish(mqtt_topic, values["temperature"]) - mqtt_client.publish(mqtt_topic, "test") # resp = send_to_mqtt(values, id) update_time = time.time() display_status() From 88eb2e26b1d13e200e15e35af67a4f69b178f4c3 Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 05:01:43 +0100 Subject: [PATCH 06/18] post json --- examples/mqtt-all.py | 54 +++----------------------------------------- 1 file changed, 3 insertions(+), 51 deletions(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index 97706a5..4ad64bc 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -130,56 +130,12 @@ def display_status(): disp.display(img) -def send_to_mqtt(values, id): - pm_values = dict(i for i in values.items() if i[0].startswith("P")) - temp_values = dict(i for i in values.items() if not i[0].startswith("P")) - - pm_values_json = [ - {"value_type": key, "value": val} for key, val in pm_values.items() - ] - temp_values_json = [ - {"value_type": key, "value": val} for key, val in temp_values.items() - ] - - resp_1 = requests.post( - "https://api.luftdaten.info/v1/push-sensor-data/", - json={ - "software_version": "enviro-plus 0.0.1", - "sensordatavalues": pm_values_json, - }, - headers={ - "X-PIN": "1", - "X-Sensor": id, - "Content-Type": "application/json", - "cache-control": "no-cache", - }, - ) - - resp_2 = requests.post( - "https://api.luftdaten.info/v1/push-sensor-data/", - json={ - "software_version": "enviro-plus 0.0.1", - "sensordatavalues": temp_values_json, - }, - headers={ - "X-PIN": "11", - "X-Sensor": id, - "Content-Type": "application/json", - "cache-control": "no-cache", - }, - ) - - if resp_1.ok and resp_2.ok: - return True - else: - return False - - # Compensation factor for temperature comp_factor = 2.25 # Raspberry Pi ID to send to Luftdaten -id = "raspi-" + get_serial_number() +device_serial_number = get_serial_number() +id = "raspi-" + device_serial_number # Width and height to calculate text position WIDTH = disp.width @@ -199,17 +155,13 @@ def send_to_mqtt(values, id): # Main loop to read data, display, and send over mqtt mqtt_client.loop_start() -mqtt_client.publish(mqtt_topic, "test message from {}".format(mqtt_topic)) while True: try: time_since_update = time.time() - update_time values = read_values() print(values) - mqtt_client.publish(mqtt_topic, values["temperature"]) - mqtt_client.publish(mqtt_topic, "test") + mqtt_client.publish(mqtt_topic, json.dumps(values)) if time_since_update > 145: - # mqtt_client.publish(mqtt_topic, json.dumps(values)) - # resp = send_to_mqtt(values, id) update_time = time.time() display_status() except Exception as e: From 067a1163896b03a20991fb4b6d42cb68e8813724 Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 05:04:39 +0100 Subject: [PATCH 07/18] return numerics --- examples/mqtt-all.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index 4ad64bc..1bbeec9 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -75,18 +75,18 @@ def read_values(): cpu_temp = get_cpu_temperature() raw_temp = bme280.get_temperature() comp_temp = raw_temp - ((cpu_temp - raw_temp) / comp_factor) - values["temperature"] = "{:.2f}".format(comp_temp) - values["pressure"] = "{:.2f}".format(bme280.get_pressure() * 100) - values["humidity"] = "{:.2f}".format(bme280.get_humidity()) + values["temperature"] = float("{:.2f}".format(comp_temp)) + values["pressure"] = float("{:.2f}".format(bme280.get_pressure() * 100)) + values["humidity"] = float("{:.2f}".format(bme280.get_humidity())) try: pm_values = pms5003.read() - values["P2"] = str(pm_values.pm_ug_per_m3(2.5)) - values["P1"] = str(pm_values.pm_ug_per_m3(10)) + values["P2"] = pm_values.pm_ug_per_m3(2.5) + values["P1"] = pm_values.pm_ug_per_m3(10) except ReadTimeoutError: pms5003.reset() pm_values = pms5003.read() - values["P2"] = str(pm_values.pm_ug_per_m3(2.5)) - values["P1"] = str(pm_values.pm_ug_per_m3(10)) + values["P2"] = pm_values.pm_ug_per_m3(2.5) + values["P1"] = pm_values.pm_ug_per_m3(10) return values From 395983ea9d71d8fd89ca1db90099e026c1c99b56 Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 05:17:13 +0100 Subject: [PATCH 08/18] Add main --- examples/mqtt-all.py | 137 +++++++++++++++++++++++-------------------- 1 file changed, 72 insertions(+), 65 deletions(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index 1bbeec9..f7225ce 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -3,6 +3,7 @@ """ #!/usr/bin/env python3 +import argparse import requests import ST7735 import time @@ -21,19 +22,6 @@ except ImportError: from smbus import SMBus -print( - """mqtt-all.py - Reads temperature, pressure, humidity, -PM2.5, and PM10 from Enviro plus and sends data over mqtt. - -Press Ctrl+C to exit! - -""" -) - -mqtt_broker = "localhost" -mqtt_port = 1883 -mqtt_topic = "enviroplus" - # mqtt callbacks def on_connect(client, userdata, flags, rc): print(f"CONNACK received with code {rc}") @@ -47,28 +35,6 @@ def on_publish(client, userdata, mid): print("mid: " + str(mid)) -mqtt_client = mqtt.Client() -mqtt_client.on_connect = on_connect -mqtt_client.on_publish = on_publish -mqtt_client.connect(mqtt_broker, port=mqtt_port) - -bus = SMBus(1) - -# Create BME280 instance -bme280 = BME280(i2c_dev=bus) - -# Create LCD instance -disp = ST7735.ST7735( - port=0, cs=1, dc=9, backlight=12, rotation=270, spi_speed_hz=10000000 -) - -# Initialize display -disp.begin() - -# Create PMS5003 instance -pms5003 = PMS5003() - - # Read values from BME280 and PMS5003 and return as dict def read_values(): values = {} @@ -130,39 +96,80 @@ def display_status(): disp.display(img) -# Compensation factor for temperature -comp_factor = 2.25 +def main(): + """Main.""" -# Raspberry Pi ID to send to Luftdaten -device_serial_number = get_serial_number() -id = "raspi-" + device_serial_number + print( + """mqtt-all.py - Reads temperature, pressure, humidity, + PM2.5, and PM10 from Enviro plus and sends data over mqtt. -# Width and height to calculate text position -WIDTH = disp.width -HEIGHT = disp.height + Press Ctrl+C to exit! -# Text settings -font_size = 16 -font = ImageFont.truetype(UserFont, font_size) + """ + ) -# Display Raspberry Pi serial and Wi-Fi status -print("Raspberry Pi serial: {}".format(get_serial_number())) -print("Wi-Fi: {}\n".format("connected" if check_wifi() else "disconnected")) -print("MQTT broker IP: {}".format(mqtt_broker)) + mqtt_broker = "localhost" + mqtt_port = 1883 + mqtt_topic = "enviroplus" -time_since_update = 0 -update_time = time.time() + mqtt_client = mqtt.Client() + mqtt_client.on_connect = on_connect + mqtt_client.on_publish = on_publish + mqtt_client.connect(mqtt_broker, port=mqtt_port) -# Main loop to read data, display, and send over mqtt -mqtt_client.loop_start() -while True: - try: - time_since_update = time.time() - update_time - values = read_values() - print(values) - mqtt_client.publish(mqtt_topic, json.dumps(values)) - if time_since_update > 145: - update_time = time.time() - display_status() - except Exception as e: - print(e) + bus = SMBus(1) + + # Create BME280 instance + bme280 = BME280(i2c_dev=bus) + + # Create LCD instance + disp = ST7735.ST7735( + port=0, cs=1, dc=9, backlight=12, rotation=270, spi_speed_hz=10000000 + ) + + # Initialize display + disp.begin() + + # Create PMS5003 instance + pms5003 = PMS5003() + + # Compensation factor for temperature + comp_factor = 2.25 + + # Raspberry Pi ID to send to Luftdaten + device_serial_number = get_serial_number() + id = "raspi-" + device_serial_number + + # Width and height to calculate text position + WIDTH = disp.width + HEIGHT = disp.height + + # Text settings + font_size = 16 + font = ImageFont.truetype(UserFont, font_size) + + # Display Raspberry Pi serial and Wi-Fi status + print("Raspberry Pi serial: {}".format(get_serial_number())) + print("Wi-Fi: {}\n".format("connected" if check_wifi() else "disconnected")) + print("MQTT broker IP: {}".format(mqtt_broker)) + + time_since_update = 0 + update_time = time.time() + + # Main loop to read data, display, and send over mqtt + mqtt_client.loop_start() + while True: + try: + time_since_update = time.time() - update_time + values = read_values() + print(values) + mqtt_client.publish(mqtt_topic, json.dumps(values)) + if time_since_update > 145: + update_time = time.time() + display_status() + except Exception as e: + print(e) + + +if __name__ == "__main__": + main() From 7ac42c7987304f4fb376df93958178f6b478da35 Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 05:19:26 +0100 Subject: [PATCH 09/18] update read values --- examples/mqtt-all.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index f7225ce..93c460a 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -36,7 +36,7 @@ def on_publish(client, userdata, mid): # Read values from BME280 and PMS5003 and return as dict -def read_values(): +def read_values(bme280, pms5003): values = {} cpu_temp = get_cpu_temperature() raw_temp = bme280.get_temperature() @@ -161,7 +161,7 @@ def main(): while True: try: time_since_update = time.time() - update_time - values = read_values() + values = read_values(bme280, pms5003) print(values) mqtt_client.publish(mqtt_topic, json.dumps(values)) if time_since_update > 145: From be6c614df983f85b7a1b8e239cb32226e643c1b5 Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 05:22:01 +0100 Subject: [PATCH 10/18] fix read_values --- examples/mqtt-all.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index 93c460a..e1fd075 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -37,6 +37,9 @@ def on_publish(client, userdata, mid): # Read values from BME280 and PMS5003 and return as dict def read_values(bme280, pms5003): + # Compensation factor for temperature + comp_factor = 2.25 + values = {} cpu_temp = get_cpu_temperature() raw_temp = bme280.get_temperature() @@ -133,10 +136,7 @@ def main(): # Create PMS5003 instance pms5003 = PMS5003() - # Compensation factor for temperature - comp_factor = 2.25 - - # Raspberry Pi ID to send to Luftdaten + # Raspberry Pi ID device_serial_number = get_serial_number() id = "raspi-" + device_serial_number From e93cd5b94ae239b866634f012f136b50c9d569ea Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 05:24:09 +0100 Subject: [PATCH 11/18] fix display_status --- examples/mqtt-all.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index e1fd075..736f30b 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -83,7 +83,11 @@ def check_wifi(): # Display Raspberry Pi serial and Wi-Fi status on LCD -def display_status(): +def display_status(disp): + # Width and height to calculate text position + WIDTH = disp.width + HEIGHT = disp.height + wifi_status = "connected" if check_wifi() else "disconnected" text_colour = (255, 255, 255) back_colour = (0, 170, 170) if check_wifi() else (85, 15, 15) @@ -140,10 +144,6 @@ def main(): device_serial_number = get_serial_number() id = "raspi-" + device_serial_number - # Width and height to calculate text position - WIDTH = disp.width - HEIGHT = disp.height - # Text settings font_size = 16 font = ImageFont.truetype(UserFont, font_size) @@ -166,7 +166,7 @@ def main(): mqtt_client.publish(mqtt_topic, json.dumps(values)) if time_since_update > 145: update_time = time.time() - display_status() + display_status(disp) except Exception as e: print(e) From 5c17ad06dcab2e22b0c2848f4cbebf61fe87ae77 Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 05:25:50 +0100 Subject: [PATCH 12/18] fix font --- examples/mqtt-all.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index 736f30b..6ba8be2 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -87,6 +87,9 @@ def display_status(disp): # Width and height to calculate text position WIDTH = disp.width HEIGHT = disp.height + # Text settings + font_size = 16 + font = ImageFont.truetype(UserFont, font_size) wifi_status = "connected" if check_wifi() else "disconnected" text_colour = (255, 255, 255) @@ -144,10 +147,6 @@ def main(): device_serial_number = get_serial_number() id = "raspi-" + device_serial_number - # Text settings - font_size = 16 - font = ImageFont.truetype(UserFont, font_size) - # Display Raspberry Pi serial and Wi-Fi status print("Raspberry Pi serial: {}".format(get_serial_number())) print("Wi-Fi: {}\n".format("connected" if check_wifi() else "disconnected")) From a0102167feade1a83133e43e427f8dda8799591f Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 05:28:54 +0100 Subject: [PATCH 13/18] display mqtt-broker --- examples/mqtt-all.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index 6ba8be2..f4da07d 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -83,7 +83,7 @@ def check_wifi(): # Display Raspberry Pi serial and Wi-Fi status on LCD -def display_status(disp): +def display_status(disp, mqtt_broker): # Width and height to calculate text position WIDTH = disp.width HEIGHT = disp.height @@ -95,7 +95,7 @@ def display_status(disp): text_colour = (255, 255, 255) back_colour = (0, 170, 170) if check_wifi() else (85, 15, 15) id = get_serial_number() - message = "{}\nWi-Fi: {}".format(id, wifi_status) + message = "{}\nWi-Fi: {}\nmqtt-broker: {}".format(id, wifi_status, mqtt_broker) img = Image.new("RGB", (WIDTH, HEIGHT), color=(0, 0, 0)) draw = ImageDraw.Draw(img) size_x, size_y = draw.textsize(message, font) @@ -165,7 +165,7 @@ def main(): mqtt_client.publish(mqtt_topic, json.dumps(values)) if time_since_update > 145: update_time = time.time() - display_status(disp) + display_status(disp, mqtt_broker) except Exception as e: print(e) From 8819092886a971b47607ad7a6088edd09424b4df Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 06:25:19 +0100 Subject: [PATCH 14/18] use args --- examples/mqtt-all.py | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index f4da07d..58b9ff0 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -22,6 +22,11 @@ except ImportError: from smbus import SMBus + +DEFAULT_MQTT_BROKER_IP = "localhost" +DEFAULT_MQTT_BROKER_PORT = 1883 +DEFAULT_MQTT_TOPIC = "enviroplus" + # mqtt callbacks def on_connect(client, userdata, flags, rc): print(f"CONNACK received with code {rc}") @@ -107,7 +112,23 @@ def display_status(disp, mqtt_broker): def main(): - """Main.""" + parser = argparse.ArgumentParser(description="Publish enviroplus values over mqtt") + parser.add_argument( + "--mqtt-broker-ip", + default=DEFAULT_MQTT_BROKER_IP, + type=str, + help="mqtt broker IP", + ) + parser.add_argument( + "--mqtt-broker-port", + default=DEFAULT_MQTT_BROKER_PORT, + type=int, + help="mqtt broker port", + ) + parser.add_argument( + "--mqtt-topic", default=DEFAULT_MQTT_TOPIC, type=str, help="mqtt topic" + ) + args = parser.parse_args() print( """mqtt-all.py - Reads temperature, pressure, humidity, @@ -118,14 +139,10 @@ def main(): """ ) - mqtt_broker = "localhost" - mqtt_port = 1883 - mqtt_topic = "enviroplus" - mqtt_client = mqtt.Client() mqtt_client.on_connect = on_connect mqtt_client.on_publish = on_publish - mqtt_client.connect(mqtt_broker, port=mqtt_port) + mqtt_client.connect(args.mqtt-broker-ip, port=port=args.mqtt-broker-port) bus = SMBus(1) @@ -150,7 +167,7 @@ def main(): # Display Raspberry Pi serial and Wi-Fi status print("Raspberry Pi serial: {}".format(get_serial_number())) print("Wi-Fi: {}\n".format("connected" if check_wifi() else "disconnected")) - print("MQTT broker IP: {}".format(mqtt_broker)) + print("MQTT broker IP: {}".format(args.mqtt-broker-ip)) time_since_update = 0 update_time = time.time() @@ -162,10 +179,10 @@ def main(): time_since_update = time.time() - update_time values = read_values(bme280, pms5003) print(values) - mqtt_client.publish(mqtt_topic, json.dumps(values)) + mqtt_client.publish(args.mqtt-topic, json.dumps(values)) if time_since_update > 145: update_time = time.time() - display_status(disp, mqtt_broker) + display_status(disp, args.mqtt-broker-ip) except Exception as e: print(e) From ed9c748705d69206731ac177781f0964ef1cd2f6 Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 06:29:21 +0100 Subject: [PATCH 15/18] rename args --- examples/mqtt-all.py | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index 58b9ff0..cecd3c6 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -114,19 +114,13 @@ def display_status(disp, mqtt_broker): def main(): parser = argparse.ArgumentParser(description="Publish enviroplus values over mqtt") parser.add_argument( - "--mqtt-broker-ip", - default=DEFAULT_MQTT_BROKER_IP, - type=str, - help="mqtt broker IP", + "--broker", default=DEFAULT_MQTT_BROKER_IP, type=str, help="mqtt broker IP", ) parser.add_argument( - "--mqtt-broker-port", - default=DEFAULT_MQTT_BROKER_PORT, - type=int, - help="mqtt broker port", + "--port", default=DEFAULT_MQTT_BROKER_PORT, type=int, help="mqtt broker port", ) parser.add_argument( - "--mqtt-topic", default=DEFAULT_MQTT_TOPIC, type=str, help="mqtt topic" + "--topic", default=DEFAULT_MQTT_TOPIC, type=str, help="mqtt topic" ) args = parser.parse_args() @@ -134,15 +128,21 @@ def main(): """mqtt-all.py - Reads temperature, pressure, humidity, PM2.5, and PM10 from Enviro plus and sends data over mqtt. + broker: {} + port: {} + topic: {} + Press Ctrl+C to exit! - """ + """.format( + args.broker, args.port, args.topic + ) ) mqtt_client = mqtt.Client() mqtt_client.on_connect = on_connect mqtt_client.on_publish = on_publish - mqtt_client.connect(args.mqtt-broker-ip, port=port=args.mqtt-broker-port) + mqtt_client.connect(args.broker, port=args.port) bus = SMBus(1) @@ -167,7 +167,7 @@ def main(): # Display Raspberry Pi serial and Wi-Fi status print("Raspberry Pi serial: {}".format(get_serial_number())) print("Wi-Fi: {}\n".format("connected" if check_wifi() else "disconnected")) - print("MQTT broker IP: {}".format(args.mqtt-broker-ip)) + print("MQTT broker IP: {}".format(args.broker)) time_since_update = 0 update_time = time.time() @@ -178,11 +178,12 @@ def main(): try: time_since_update = time.time() - update_time values = read_values(bme280, pms5003) + values["serial"] = device_serial_number print(values) - mqtt_client.publish(args.mqtt-topic, json.dumps(values)) + mqtt_client.publish(args.topic, json.dumps(values)) if time_since_update > 145: update_time = time.time() - display_status(disp, args.mqtt-broker-ip) + display_status(disp, args.broker) except Exception as e: print(e) From 6ddb7d011e0d7dc27cd5802d237158fd01930a3f Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Tue, 2 Jun 2020 06:33:37 +0100 Subject: [PATCH 16/18] Add to docstring --- examples/mqtt-all.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index cecd3c6..65d468d 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -1,5 +1,7 @@ """ Run mqtt broker on localhost: sudo apt-get install mosquitto mosquitto-clients + +Example run: python3 mqtt-all.py --broker 192.168.1.164 --topic enviro """ #!/usr/bin/env python3 From 0d4bdeaef978f9378544de1f8b09f560b487ece4 Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Wed, 3 Jun 2020 08:29:47 +0100 Subject: [PATCH 17/18] Update mqtt-all.py --- examples/mqtt-all.py | 1 - 1 file changed, 1 deletion(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index 65d468d..85e38bd 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -6,7 +6,6 @@ #!/usr/bin/env python3 import argparse -import requests import ST7735 import time from bme280 import BME280 From b2d4718ca83bcd31ab19223c0176d6219ab8b9b2 Mon Sep 17 00:00:00 2001 From: Robin Cole Date: Thu, 4 Jun 2020 03:58:31 +0100 Subject: [PATCH 18/18] add gas and lux --- examples/mqtt-all.py | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/examples/mqtt-all.py b/examples/mqtt-all.py index 85e38bd..26f46bb 100755 --- a/examples/mqtt-all.py +++ b/examples/mqtt-all.py @@ -10,6 +10,16 @@ import time from bme280 import BME280 from pms5003 import PMS5003, ReadTimeoutError +from enviroplus import gas + +try: + # Transitional fix for breaking change in LTR559 + from ltr559 import LTR559 + + ltr559 = LTR559() +except ImportError: + import ltr559 + from subprocess import PIPE, Popen, check_output from PIL import Image, ImageDraw, ImageFont from fonts.ttf import RobotoMedium as UserFont @@ -48,20 +58,29 @@ def read_values(bme280, pms5003): values = {} cpu_temp = get_cpu_temperature() - raw_temp = bme280.get_temperature() + raw_temp = bme280.get_temperature() # float comp_temp = raw_temp - ((cpu_temp - raw_temp) / comp_factor) - values["temperature"] = float("{:.2f}".format(comp_temp)) - values["pressure"] = float("{:.2f}".format(bme280.get_pressure() * 100)) - values["humidity"] = float("{:.2f}".format(bme280.get_humidity())) + values["temperature"] = int(comp_temp) + values["pressure"] = round( + int(bme280.get_pressure() * 100), -1 + ) # round to nearest 10 + values["humidity"] = int(bme280.get_humidity()) try: - pm_values = pms5003.read() - values["P2"] = pm_values.pm_ug_per_m3(2.5) - values["P1"] = pm_values.pm_ug_per_m3(10) + pm_values = pms5003.read() # int + values["pm1"] = pm_values.pm_ug_per_m3(1) + values["pm25"] = pm_values.pm_ug_per_m3(2.5) + values["pm10"] = pm_values.pm_ug_per_m3(10) except ReadTimeoutError: pms5003.reset() pm_values = pms5003.read() - values["P2"] = pm_values.pm_ug_per_m3(2.5) - values["P1"] = pm_values.pm_ug_per_m3(10) + values["pm1"] = pm_values.pm_ug_per_m3(1) + values["pm25"] = pm_values.pm_ug_per_m3(2.5) + values["pm10"] = pm_values.pm_ug_per_m3(10) + data = gas.read_all() + values["oxidised"] = int(data.oxidising / 1000) + values["reduced"] = int(data.reducing / 1000) + values["nh3"] = int(data.nh3 / 1000) + values["lux"] = int(ltr559.get_lux()) return values