import network
import time
import dht
import socket
import json
import ussl as ssl # or `import ssl` if your firmware supports it
from machine import Pin
from umqtt.simple import MQTTClient
# --- WiFi configuration ---
WIFI_SSID = "Wokwi-GUEST" # Replace with your WiFi SSID
WIFI_PASSWORD = "" # Replace with your WiFi Password
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print("Connecting to WiFi...", end="")
while not wlan.isconnected():
print(".", end="")
time.sleep(1)
print("\nWiFi connected. Network config:", wlan.ifconfig())
return wlan
# --- MQTT configuration for TLS ---
MQTT_BROKER = "3c6654b19eca4a84bc44bb25c3d3e054.s1.eu.hivemq.cloud" # Replace with your customized HiveMQ URL
MQTT_PORT = 8883 # Use the TLS secure port
MQTT_CLIENT_ID = "esp32_client_001" # A unique client ID for your device
MQTT_TOPIC = b"iaq/device01/temp"
HIVEMQ_USERNAME = "wokwiiaq" # Replace with your actual username
HIVEMQ_PASSWORD = "Rated123#" # Replace with your actual password
def connect_mqtt():
# Disable certificate verification for testing purposes.
ssl_params = {"server_hostname": MQTT_BROKER, "cert_reqs": 0}
client = MQTTClient(
MQTT_CLIENT_ID,
MQTT_BROKER,
port=MQTT_PORT,
user=HIVEMQ_USERNAME,
password=HIVEMQ_PASSWORD,
ssl=True,
ssl_params=ssl_params
)
client.connect()
print("Connected to MQTT broker over TLS")
return client
# --- DHT22 Sensor Setup ---
#dht_sensor = dht.DHT22(Pin(4)) # Ensure your DHT22 is wired correctly
wifi = connect_wifi()
mqtt_client = connect_mqtt()
try:
# Add this before the main loop, after MQTT connect
data_file = open('iaq_data.csv', 'r')
# Read and discard the header line
header = data_file.readline()
print("Opened iaq_data.csv, skipped header:", header.strip())
except OSError as e:
print("Error opening data file:", e)
data_file = None # Set to None so the loop knows not to proceed
while True:
# Inside the main while True loop:
if data_file: # Only proceed if file opened successfully
try:
line = data_file.readline()
if not line: # Check for End Of File
print("End of file reached, looping back.")
data_file.seek(0) # Go back to the start
data_file.readline() # Skip header again
line = data_file.readline() # Read the first data line
if not line: # Handle case where file is empty or just header
print("File empty after looping?")
time.sleep(10)
continue # Skip to next loop iteration
# Assuming CSV columns are in the order you listed:
# Timestamp,Temp,Hum,CO2,PM2.5,PM10,TVOC,CO,Light,Motion,Occupancy,Ventilation
parts = [p.strip() for p in line.strip().split(',')]
if len(parts) == 12: # Basic check for correct number of columns
# Create a dictionary payload - use keys that are easy for JSON/JS
payload_dict = {
"timestamp": parts[0],
"temperature_C": float(parts[1]),
"humidity_pct": float(parts[2]),
"co2_ppm": float(parts[3]),
"pm25_ug_m3": float(parts[4]),
"pm10_ug_m3": float(parts[5]),
"tvoc_ppb": float(parts[6]),
"co_ppm": float(parts[7]),
"light_lux": float(parts[8]),
"motion": int(parts[9]),
"occupancy": int(parts[10]),
"ventilation": parts[11]
}
# Convert dict to JSON string
message = json.dumps(payload_dict)
print(f"Publishing from CSV: {message}")
# Recommend changing the topic now
mqtt_topic_data = b"iaq/device01/data"
mqtt_client.publish(mqtt_topic_data, message.encode()) # Encode payload
else:
print(f"Skipping malformed line: {line.strip()}")
except ValueError as e:
print(f"Error converting data type on line: {line.strip()} - {e}")
except Exception as e:
print("Error during file reading/processing or MQTT publish:", e)
# Include reconnection logic as you had before if needed
else:
print("Data file not open, cannot read.")
time.sleep(10) # Keep the delay between sending rows