Moving to dotenv.
This commit is contained in:
182
main.py
182
main.py
@@ -2,14 +2,15 @@ import network
|
|||||||
import rp2
|
import rp2
|
||||||
import time
|
import time
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
import machine
|
import machine
|
||||||
from machine import Pin
|
from machine import Pin
|
||||||
from umqtt.robust import MQTTClient
|
from umqtt.robust import MQTTClient
|
||||||
import dht
|
import dht
|
||||||
import urequests
|
import urequests
|
||||||
import wifi_config
|
from dotenv import load_dotenv
|
||||||
import mqtt_config
|
|
||||||
import ha_mqtt_config
|
load_dotenv()
|
||||||
|
|
||||||
# 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
|
||||||
@@ -17,29 +18,31 @@ DHT_22_GPIO_PIN = 3
|
|||||||
# Debug Mode
|
# Debug Mode
|
||||||
DEBUG = False
|
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.
|
||||||
So, we have to convert this value either to the Celsius degree scales.
|
So, we have to convert this value either to the Celsius degree scales.
|
||||||
|
|
||||||
The temperature sensor works by delivering a voltage to the ADC4 pin that is proportional to the temperature.
|
The temperature sensor works by delivering a voltage to the ADC4 pin that is proportional to the temperature.
|
||||||
From the datasheet, a temperature of 27 degrees Celsius delivers a voltage of 0.706 V.
|
From the datasheet, a temperature of 27 degrees Celsius delivers a voltage of 0.706 V.
|
||||||
With each additional degree the voltage reduces by 1.721 mV or 0.001721 V.
|
With each additional degree the voltage reduces by 1.721 mV or 0.001721 V.
|
||||||
The first step in converting the 16-bit temperature is to convert it back to volts, which is done based on the 3.3 V maximum voltage used by the Pico board.
|
The first step in converting the 16-bit temperature is to convert it back to volts, which is done based on the 3.3 V maximum voltage used by the Pico board.
|
||||||
ref: https://how2electronics.com/read-temperature-sensor-value-from-raspberry-pi-pico/
|
ref: https://how2electronics.com/read-temperature-sensor-value-from-raspberry-pi-pico/
|
||||||
"""
|
"""
|
||||||
cpu_temp_conversion_factor = 3.3 / 65535
|
cpu_temp_conversion_factor = 3.3 / 65535
|
||||||
cpu_temp_sensor = machine.ADC(4)
|
cpu_temp_sensor = machine.ADC(4)
|
||||||
reading = cpu_temp_sensor.read_u16() * cpu_temp_conversion_factor
|
reading = cpu_temp_sensor.read_u16() * cpu_temp_conversion_factor
|
||||||
temperature_c = 27 - (reading - 0.706) / 0.001721
|
temperature_c = 27 - (reading - 0.706) / 0.001721
|
||||||
temperature_f = temperature_c * 9/5. + 32.0
|
temperature_f = temperature_c * 9 / 5.0 + 32.0
|
||||||
return temperature_f
|
return temperature_f
|
||||||
|
|
||||||
|
|
||||||
def read_dht_22(sensor):
|
def read_dht_22(sensor):
|
||||||
"""
|
"""
|
||||||
reads the temperature and humidity from dht.DHT22 sensor.
|
reads the temperature and humidity from dht.DHT22 sensor.
|
||||||
returns tuple(temperature, humidity) if no errors
|
returns tuple(temperature, humidity) if no errors
|
||||||
returns None if there was an error
|
returns None if there was an error
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
sensor.measure()
|
sensor.measure()
|
||||||
@@ -50,10 +53,11 @@ def read_dht_22(sensor):
|
|||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def wlan_up(wlan):
|
def wlan_up(wlan):
|
||||||
wlan.active(True)
|
wlan.active(True)
|
||||||
wlan.connect(wifi_config.HOME_WIFI_SSID, wifi_config.HOME_WIFI_PWD)
|
wlan.connect(os.getenv("HOME_WIFI_SSID"), os.getenv("HOME_WIFI_PWD"))
|
||||||
|
|
||||||
# Wait for connect or fail
|
# Wait for connect or fail
|
||||||
max_wait = 10
|
max_wait = 10
|
||||||
while max_wait > 0:
|
while max_wait > 0:
|
||||||
@@ -61,22 +65,23 @@ def wlan_up(wlan):
|
|||||||
break
|
break
|
||||||
max_wait -= 1
|
max_wait -= 1
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
print('Waiting for WiFi connection...')
|
print("Waiting for WiFi connection...")
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
|
||||||
if max_wait == 0:
|
if max_wait == 0:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
ifconfig = wlan.ifconfig()
|
ifconfig = wlan.ifconfig()
|
||||||
if DEBUG:
|
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:
|
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'
|
||||||
# So we know when LED error sequence starts
|
# So we know when LED error sequence starts
|
||||||
start_sequence_counter = 0
|
start_sequence_counter = 0
|
||||||
@@ -86,7 +91,7 @@ def led_error_code(led, error_code: int):
|
|||||||
led.value(False)
|
led.value(False)
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
start_sequence_counter += 1
|
start_sequence_counter += 1
|
||||||
|
|
||||||
# Run real error code sequence
|
# Run real error code sequence
|
||||||
blink_counter = 0
|
blink_counter = 0
|
||||||
while blink_counter < error_code:
|
while blink_counter < error_code:
|
||||||
@@ -99,40 +104,40 @@ def led_error_code(led, error_code: int):
|
|||||||
led.value(False)
|
led.value(False)
|
||||||
if DEBUG:
|
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
|
# Start Up Activities
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
print("Start up")
|
print("Start up")
|
||||||
count = 0
|
count = 0
|
||||||
led = machine.Pin('LED', machine.Pin.OUT)
|
led = machine.Pin("LED", machine.Pin.OUT)
|
||||||
led.value(False)
|
led.value(False)
|
||||||
led_error_code(led, 1)
|
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
|
# Create MQTT Client
|
||||||
mqtt_client = MQTTClient(
|
mqtt_client = MQTTClient(
|
||||||
client_id = mqtt_config.MQTT_CLIENT_ID,
|
client_id=os.getenv("MQTT_CLIENT_ID"),
|
||||||
server = mqtt_config.MQTT_HOST_NAME,
|
server=os.getenv("MQTT_HOST_NAME"),
|
||||||
)
|
)
|
||||||
|
|
||||||
# Create Home Assistant MQTT Client
|
# Create Home Assistant MQTT Client
|
||||||
ha_mqtt_client = MQTTClient(
|
ha_mqtt_client = MQTTClient(
|
||||||
client_id = ha_mqtt_config.MQTT_CLIENT_ID,
|
client_id=os.getenv("MQTT_CLIENT_ID"),
|
||||||
server = ha_mqtt_config.MQTT_HOST_NAME,
|
server=os.getenv("MQTT_HOST_NAME"),
|
||||||
keepalive = ha_mqtt_config.MQTT_KEEP,
|
keepalive=os.getenv("MQTT_KEEP"),
|
||||||
user = ha_mqtt_config.MQTT_USERNAME,
|
user=os.getenv("MQTT_USERNAME"),
|
||||||
password = ha_mqtt_config.MQTT_PASSWORD,
|
password=os.getenv("MQTT_PASSWORD"),
|
||||||
)
|
)
|
||||||
|
|
||||||
# Create DHT22
|
# Create DHT22
|
||||||
sensor = dht.DHT22(Pin(DHT_22_GPIO_PIN))
|
sensor = dht.DHT22(Pin(DHT_22_GPIO_PIN))
|
||||||
|
|
||||||
# Let's Go!
|
# Let's Go!
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
print("Enter main loop")
|
print("Enter main loop")
|
||||||
@@ -143,8 +148,8 @@ def main():
|
|||||||
led.value(False)
|
led.value(False)
|
||||||
count += 1
|
count += 1
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
print(f'\nStarting loop #{count}... \nWiFI Status is {wlan.status()}.')
|
print(f"\nStarting loop #{count}... \nWiFI Status is {wlan.status()}.")
|
||||||
|
|
||||||
# Create Local Flags for Control
|
# Create Local Flags for Control
|
||||||
wifi_ready = False
|
wifi_ready = False
|
||||||
mqtt_ready = False
|
mqtt_ready = False
|
||||||
@@ -157,10 +162,10 @@ def main():
|
|||||||
|
|
||||||
# DHT22 Reading.
|
# 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.0 + 32.0
|
||||||
dht22_ready = True
|
dht22_ready = True
|
||||||
except:
|
except:
|
||||||
continue
|
continue
|
||||||
@@ -183,93 +188,116 @@ def main():
|
|||||||
wifi_ready = True
|
wifi_ready = True
|
||||||
ifconfig = wlan.ifconfig()
|
ifconfig = wlan.ifconfig()
|
||||||
if DEBUG:
|
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}."
|
||||||
|
)
|
||||||
except:
|
except:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# MQTT Connection to Primary Broker.
|
# MQTT Connection to Primary Broker.
|
||||||
try:
|
try:
|
||||||
mqtt_client.connect(clean_session = False)
|
mqtt_client.connect(clean_session=False)
|
||||||
mqtt_ready = True
|
mqtt_ready = True
|
||||||
mqtt = 'mosquitto'
|
mqtt = "mosquitto"
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
print(f'Connected to Mosquitto MQTT broker.')
|
print(f"Connected to Mosquitto MQTT broker.")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
print("Trouble to connecting to Mosquitto MQTT: {}".format(e))
|
print("Trouble to connecting to Mosquitto MQTT: {}".format(e))
|
||||||
|
|
||||||
|
|
||||||
# MQTT Connection to Back Up Broker.
|
# MQTT Connection to Back Up Broker.
|
||||||
if not mqtt_ready:
|
if not mqtt_ready:
|
||||||
try:
|
try:
|
||||||
try:
|
try:
|
||||||
ha_mqtt_client.connect(clean_session = False)
|
ha_mqtt_client.connect(clean_session=False)
|
||||||
mqtt_ready = True
|
mqtt_ready = True
|
||||||
mqtt = 'ha'
|
mqtt = "ha"
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
print(f'Connected to the back up, Home Assistant, MQTT broker.')
|
print(f"Connected to the back up, Home Assistant, MQTT broker.")
|
||||||
|
|
||||||
except Exception as f:
|
except Exception as f:
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
print("Trouble to connecting to Home Assistant MQTT: {}".format(f))
|
print(
|
||||||
|
"Trouble to connecting to Home Assistant MQTT: {}".format(f)
|
||||||
|
)
|
||||||
led_error_code(led, 2)
|
led_error_code(led, 2)
|
||||||
time.sleep(5)
|
time.sleep(5)
|
||||||
continue # Start back at the top of the While Loop
|
continue # Start back at the top of the While Loop
|
||||||
|
|
||||||
except:
|
except:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|
||||||
# Ready to Publish?
|
# Ready to Publish?
|
||||||
try:
|
try:
|
||||||
if wifi_ready and mqtt_ready and dht22_ready:
|
if wifi_ready and mqtt_ready and dht22_ready:
|
||||||
# Timestamp
|
# Timestamp
|
||||||
time_now = time.localtime()
|
time_now = time.localtime()
|
||||||
timestamp = "{}/{}/{} {}:{}:{}".format(time_now[1],time_now[2],time_now[0],time_now[3],time_now[4],time_now[5])
|
timestamp = "{}/{}/{} {}:{}:{}".format(
|
||||||
|
time_now[1],
|
||||||
|
time_now[2],
|
||||||
|
time_now[0],
|
||||||
|
time_now[3],
|
||||||
|
time_now[4],
|
||||||
|
time_now[5],
|
||||||
|
)
|
||||||
|
|
||||||
# Build JSON Payloads
|
# Build JSON Payloads
|
||||||
dht_data = {
|
dht_data = {
|
||||||
'Location':mqtt_config.MQTT_ZONE_ID,
|
"Location": os.getenv("MQTT_ZONE_ID"),
|
||||||
'Temperature':temp,
|
"Temperature": temp,
|
||||||
'Relative Humidity':hum,
|
"Relative Humidity": hum,
|
||||||
}
|
}
|
||||||
dht_payload = json.dumps(dht_data)
|
dht_payload = json.dumps(dht_data)
|
||||||
|
|
||||||
hw_data = {
|
hw_data = {
|
||||||
'Timestamp':timestamp,
|
"Timestamp": timestamp,
|
||||||
'CPU Temperature':cpu_temp,
|
"CPU Temperature": cpu_temp,
|
||||||
'Device':mqtt_config.MQTT_HW_ID,
|
"Device": os.getenv("MQTT_HW_ID"),
|
||||||
'WiFi Information':ifconfig,
|
"WiFi Information": ifconfig,
|
||||||
}
|
}
|
||||||
hw_payload = json.dumps(hw_data)
|
hw_payload = json.dumps(hw_data)
|
||||||
|
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
print(f'Trying to publish...')
|
print(f"Trying to publish...")
|
||||||
|
|
||||||
|
if mqtt == "mosquitto":
|
||||||
if mqtt == 'mosquitto':
|
|
||||||
# Publish
|
# Publish
|
||||||
mqtt_client.publish("home/{}".format(mqtt_config.MQTT_ZONE_ID),dht_payload, retain=True)
|
mqtt_client.publish(
|
||||||
mqtt_client.publish("hw/{}".format(mqtt_config.MQTT_HW_ID),hw_payload, retain=True)
|
"home/{}".format(os.getenv("MQTT_ZONE_ID")),
|
||||||
|
dht_payload,
|
||||||
|
retain=True,
|
||||||
|
)
|
||||||
|
mqtt_client.publish(
|
||||||
|
"hw/{}".format(os.getenv("MQTT_HW_ID")), hw_payload, retain=True
|
||||||
|
)
|
||||||
mqtt_client.disconnect()
|
mqtt_client.disconnect()
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
print(f'MQTT Disconnected.')
|
print(f"MQTT Disconnected.")
|
||||||
|
|
||||||
if mqtt == 'ha':
|
if mqtt == "ha":
|
||||||
# Publish
|
# Publish
|
||||||
ha_mqtt_client.publish("home/{}".format(mqtt_config.MQTT_ZONE_ID),dht_payload, retain=True)
|
ha_mqtt_client.publish(
|
||||||
ha_mqtt_client.publish("hw/{}".format(mqtt_config.MQTT_HW_ID),hw_payload, retain=True)
|
"home/{}".format(os.getenv("HA_MQTT_ZONE_ID")),
|
||||||
|
dht_payload,
|
||||||
|
retain=True,
|
||||||
|
)
|
||||||
|
ha_mqtt_client.publish(
|
||||||
|
"hw/{}".format(os.getenv("HA_MQTT_HW_ID")),
|
||||||
|
hw_payload,
|
||||||
|
retain=True,
|
||||||
|
)
|
||||||
ha_mqtt_client.disconnect()
|
ha_mqtt_client.disconnect()
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
print(f'MQTT Disconnected.')
|
print(f"MQTT Disconnected.")
|
||||||
|
|
||||||
except:
|
except:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Sleep for a bit.
|
# Sleep for a bit.
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
print(f'Finished loop #{count}.')
|
print(f"Finished loop #{count}.")
|
||||||
time.sleep(5)
|
time.sleep(5)
|
||||||
|
|
||||||
|
|
||||||
main()
|
main()
|
||||||
|
|||||||
Reference in New Issue
Block a user