|
|
from bme680 import BME680_I2C |
|
|
from machine import I2C, Pin |
|
|
from netman import connectWiFi |
|
|
from umqtt.simple import MQTTClient |
|
|
import time |
|
|
|
|
|
|
|
|
SSID = 'Pixel 8' |
|
|
PASSWORD = '123456789' |
|
|
MQTT_BROKER = 'b6bdb89571144b3d8e5ca4bbe666ddb5.s1.eu.hivemq.cloud' |
|
|
MQTT_PORT = 8883 |
|
|
MQTT_TOPIC = "sensors/bme680/data" |
|
|
|
|
|
MQTT_USER = 'Luthiraa' |
|
|
MQTT_PASS = 'theboss1010' |
|
|
|
|
|
def connect_to_internet(): |
|
|
try: |
|
|
status = connectWiFi(SSID, PASSWORD, country='US', retries=3) |
|
|
print("Connected to Wi-Fi successfully!") |
|
|
print("IP Address:", status[0]) |
|
|
except RuntimeError as e: |
|
|
print(f"Failed to connect to Wi-Fi: {e}") |
|
|
raise |
|
|
|
|
|
|
|
|
i2c = I2C(1, scl=Pin(27), sda=Pin(26)) |
|
|
bme = BME680_I2C(i2c) |
|
|
|
|
|
|
|
|
client = MQTTClient( |
|
|
client_id=b"kudzai_raspberrypi_picow", |
|
|
server=MQTT_BROKER, |
|
|
port=MQTT_PORT, |
|
|
user=MQTT_USER, |
|
|
password=MQTT_PASS, |
|
|
keepalive=60, |
|
|
ssl=True, |
|
|
ssl_params={'server_hostname': MQTT_BROKER} |
|
|
) |
|
|
|
|
|
def connect_to_mqtt(): |
|
|
try: |
|
|
client.connect() |
|
|
print("Connected to MQTT broker") |
|
|
print("Client ID:", client.client_id) |
|
|
except Exception as e: |
|
|
print(f"Failed to connect to MQTT broker: {e}") |
|
|
raise |
|
|
|
|
|
|
|
|
connect_to_internet() |
|
|
connect_to_mqtt() |
|
|
|
|
|
while True: |
|
|
|
|
|
temperature = bme.temperature |
|
|
humidity = bme.humidity |
|
|
pressure = bme.pressure |
|
|
gas = bme.gas |
|
|
|
|
|
|
|
|
payload = ( |
|
|
f"Temperature: {temperature:.2f} °C, " |
|
|
f"Humidity: {humidity:.2f} %, " |
|
|
f"Pressure: {pressure:.2f} hPa, " |
|
|
f"Gas: {gas:.2f} ohms" |
|
|
) |
|
|
|
|
|
|
|
|
print("--------------------------------------------------") |
|
|
print(payload) |
|
|
print("--------------------------------------------------") |
|
|
|
|
|
|
|
|
try: |
|
|
client.publish(MQTT_TOPIC, payload) |
|
|
print("Data published to MQTT topic:", MQTT_TOPIC) |
|
|
except Exception as e: |
|
|
print(f"Failed to publish data: {e}") |
|
|
client.connect() |
|
|
|
|
|
time.sleep(2) |
|
|
|