import utime
import rp2
from machine import I2C, Pin
import network
import time
import urequests as requests
import am2320
import ujson
import umqtt.simple
mqtt_broker_ip = "IP at mosquitto"
client_id = "d2"
ssid = '공유기 ID'
password = '공유기 비번'
def send_message_mqtt(client, h,t):
print("Publish Mqtt Message")
msg = ujson.dumps({'device_id': client_id, 'temperature': t, 'humidity': h})
try:
client.publish("구독토픽", msg)
except OSError as e:
print(e)
def wlan_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# Setup onboard LED
onboard_led = Pin('LED', Pin.OUT) # Adjust the pin number if necessary
# Initial connection attempt
max_attempts = 10
attempts = 0
connected = False # Flag to track connection status
while not wlan.isconnected() and attempts < max_attempts:
onboard_led.toggle() # Blink LED while trying to connect
time.sleep(1)
attempts += 1
if wlan.isconnected():
print(f"Connected to {ssid} successfully!")
print("Network Config:", wlan.ifconfig())
onboard_led.value(1) # Keep LED on when connected
connected = True
else:
print("Failed to connect to WiFi.")
onboard_led.value(0) # Turn off LED if initial connection fails
return [wlan, connected]
def mqtt_connect():
print("Try Mqtt Connect")
client = umqtt.simple.MQTTClient(client_id = client_id, server = mqtt_broker_ip, port = #MQTT포트)
client.connect()
return client
def am2320_connect():
i2c = I2C(0, scl=Pin(17), sda=Pin(16), freq=400000)
sensor = am2320.AM2320(i2c)
if sensor.check():
print(f"AM2320 found at I2C address {am2320.I2C_ADDRESS:#x}")
return sensor
def main_mqtt():
wret = wlan_connect()
wlan = wret[0]
connected = wret[1]
client = 0
utime.sleep(3)
try:
client = mqtt_connect()
except OSError as e:
print(f"Error: %s" % e)
print("Mqtt Connect Done")
step1 = 2
utime.sleep(1)
sensor = am2320_connect()
while True:
if step1 == 2:
print('reading')
total=0
sensor.measure()
humidity = sensor.humidity()
temperature = sensor.temperature()
print("M2 Humidity: %d%%, Temp: %dC" % (humidity, temperature))
if wlan.isconnected() and not connected:
print("Reconnected to WiFi.")
onboard_led.value(1) # Keep LED on when connected
print("Network Config:", wlan.ifconfig())
connected = True
elif not wlan.isconnected() and connected:
print("Disconnected from WiFi.")
connected = False
if not connected:
print("Wlan Not Connected")
onboard_led.toggle() # Blink LED if disconnected
else:
if client == 0:
print("MQTT is not connected")
else:
send_message_mqtt(client, humidity, temperature)
step1 = 1
else:
step1 = step1 + 1
utime.sleep(30)
main_mqtt()
Comments