Archived
1
0

Converted MQTT publish to be JSON payloads.

This commit is contained in:
Shaun Setlock
2022-11-21 21:58:03 -05:00
parent 8fdcb51c08
commit af75511792

69
main.py
View File

@@ -1,6 +1,7 @@
import network import network
import rp2 import rp2
import time import time
import json
import machine import machine
from machine import Pin from machine import Pin
from umqtt.simple import MQTTClient from umqtt.simple import MQTTClient
@@ -12,6 +13,9 @@ import mqtt_config
# Change this GPIO PIN where your DHT22 sensor is connected # Change this GPIO PIN where your DHT22 sensor is connected
DHT_22_GPIO_PIN = 3 DHT_22_GPIO_PIN = 3
# Debug Mode
DEBUG = False
def read_cpu_temp(): def read_cpu_temp():
""" """
If you print the value of the temperature value you are going to get an integer number between 0 and 65535. If you print the value of the temperature value you are going to get an integer number between 0 and 65535.
@@ -55,6 +59,7 @@ def wlan_up(wlan):
if wlan.status() < 0 or wlan.status() >= 3: if wlan.status() < 0 or wlan.status() >= 3:
break break
max_wait -= 1 max_wait -= 1
if DEBUG:
print('Waiting for WiFi connection...') print('Waiting for WiFi connection...')
time.sleep(1) time.sleep(1)
@@ -62,11 +67,13 @@ def wlan_up(wlan):
return None return None
ifconfig = wlan.ifconfig() ifconfig = wlan.ifconfig()
if DEBUG:
print(ifconfig) print(ifconfig)
return ifconfig return ifconfig
def led_error_code(led, error_code: int): def led_error_code(led, error_code: int):
"""Blink LED for a given error code (int). error code == number of times to blink""" """Blink LED for a given error code (int). error code == number of times to blink"""
if DEBUG:
print("LED Error Status code: {}".format(error_code)) print("LED Error Status code: {}".format(error_code))
# Run a quick 'start error code sequence' # Run a quick 'start error code sequence'
@@ -89,78 +96,108 @@ def led_error_code(led, error_code: int):
blink_counter += 1 blink_counter += 1
# Make sure to turn off LED when this subroutine finished # Make sure to turn off LED when this subroutine finished
led.value(False) led.value(False)
if DEBUG:
print("LED Error Status code finished for: {}".format(error_code)) print("LED Error Status code finished for: {}".format(error_code))
def main(): def main():
# Start Up Activities
if DEBUG:
print("Start up") print("Start up")
count = 0 count = 0
led = machine.Pin('LED', machine.Pin.OUT)
led.value(False)
led_error_code(led, 1)
# Set Wi-Fi Country # Set Wi-Fi Country
rp2.country('US') rp2.country('US')
wlan = network.WLAN(network.STA_IF) wlan = network.WLAN(network.STA_IF)
# Create MQTT Client
mqtt_client = MQTTClient(mqtt_config.MQTT_CLIENT_ID, mqtt_config.MQTT_HOST_NAME) mqtt_client = MQTTClient(mqtt_config.MQTT_CLIENT_ID, mqtt_config.MQTT_HOST_NAME)
# Create DHT22
sensor = dht.DHT22(Pin(DHT_22_GPIO_PIN)) sensor = dht.DHT22(Pin(DHT_22_GPIO_PIN))
led = machine.Pin('LED', machine.Pin.OUT) # Let's Go!
led.value(False) if DEBUG:
led_error_code(led, 1)
print("Enter main loop") print("Enter main loop")
while True: while True:
# Loop Clean-Up and Prep
led.value(False) led.value(False)
count += 1 count += 1
if DEBUG:
print(f'\nStarting loop #{count}... \nWiFI Status is {wlan.status()}.') print(f'\nStarting loop #{count}... \nWiFI Status is {wlan.status()}.')
# WiFi Connection.
if wlan.status() != 3: if wlan.status() != 3:
ifconfig = wlan_up(wlan) ifconfig = wlan_up(wlan)
if ifconfig is None: if ifconfig is None:
if DEBUG:
print("Trouble to connecting WiFi: {}".format(e)) print("Trouble to connecting WiFi: {}".format(e))
led_error_code(led, 3) led_error_code(led, 3)
continue continue
else: else:
if DEBUG:
print("Connected to WiFi: {}".format(ifconfig)) print("Connected to WiFi: {}".format(ifconfig))
else: else:
ifconfig = wlan.ifconfig() ifconfig = wlan.ifconfig()
if DEBUG:
print(f"Skipping WiFi Activation since WiFi Status is {wlan.status()} \n{ifconfig}.") print(f"Skipping WiFi Activation since WiFi Status is {wlan.status()} \n{ifconfig}.")
# MQTT Conneciton.
try: try:
mqtt_client.connect() mqtt_client.connect()
if DEBUG:
print(f'MQTT Connected.') print(f'MQTT Connected.')
except Exception as e: except Exception as e:
if DEBUG:
print("Trouble to connecting to MQTT: {}".format(e)) print("Trouble to connecting to MQTT: {}".format(e))
led_error_code(led, 2) led_error_code(led, 2)
continue continue # Start back at the top of the While Loop
# DHT22 Reading.
dht22_reading = read_dht_22(sensor) dht22_reading = read_dht_22(sensor)
#debug_str = "None"
debug_str = "None"
if dht22_reading is not None: if dht22_reading is not None:
temp,hum = dht22_reading temp,hum = dht22_reading
temp = temp * 9/5. + 32.0 temp = temp * 9/5. + 32.0
mqtt_client.publish("m/v1/home/{}/0/temperature".format(mqtt_config.MQTT_ZONE_ID), "DHT22 Temp = {} degF".format(str(temp)), retain=True)
mqtt_client.publish("m/v1/home/{}/0/humidity".format(mqtt_config.MQTT_ZONE_ID), "DHT22 %Hum = {} %".format(str(hum)), retain=True)
debug_str = "{} ; {}".format(temp, hum)
# CPU Reading.
cpu_temp = read_cpu_temp() cpu_temp = read_cpu_temp()
print("{} ; CPU: {}".format(debug_str, cpu_temp)) # Timestamp
time_now = time.localtime()
timestamp = "{}/{}/{} {}:{}:{}".format(time_now[1],time_now[2],time_now[0],time_now[3],time_now[4],time_now[5])
# HW Info # Build JSON Payloads
mqtt_client.publish("m/v1/hw/{}/cpu/temperature".format(mqtt_config.MQTT_HW_ID), "CPU Temp = {} degF".format(str(cpu_temp)), retain=True) dht_data = {
mqtt_client.publish("m/v1/hw/{}/wlan/info".format(mqtt_config.MQTT_HW_ID), str(ifconfig), retain=True) 'Temperature':temp,
'Relative Humidity':hum,
}
dht_payload = json.dumps(dht_data)
hw_data = {
'Timestamp':timestamp,
'CPU Temperature':cpu_temp,
'WiFi Information':ifconfig,
}
hw_payload = json.dumps(hw_data)
# Publish
mqtt_client.publish("home/{}".format(mqtt_config.MQTT_ZONE_ID),dht_payload, retain=True)
mqtt_client.publish("hw/{}".format(mqtt_config.MQTT_HW_ID),hw_payload, retain=True)
mqtt_client.disconnect() mqtt_client.disconnect()
if DEBUG:
print(f'MQTT Disconnected.') print(f'MQTT Disconnected.')
# Sleep for a bit. # Sleep for a bit.
if DEBUG:
print(f'Finished loop #{count}.') print(f'Finished loop #{count}.')
time.sleep(5) time.sleep(5)