from machine import Pin, SoftI2C, ADC, PWM
from servo import Servo
import dht
import math
import time
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
import wifi
from umqtt.simple import MQTTClient
import uasyncio as asyncio
################################
#man hinh led
I2C_ADDR = 0x27
totalRow = 4
totalColumns = 20
i2c = SoftI2C(scl = Pin(22), sda = Pin(21), freq = 10000) #initializing I2C method for ESP32
lcd = I2cLcd(i2c, I2C_ADDR, totalRow, totalColumns)
lcd.putstr("Hello")
time.sleep(1)
# lcd.clear()
wifi.connect_ap()
#MQTT
# client_id = "720e81de16ff4f6786bbed0c1da73392.s2.eu.hivemq.cloud"
# server = "broker.hivemq.com"
# client = MQTTClient(client_id, server)
# client.connect()
#ThinkSpeak
# client_id1 = "CQAfHRwVKCMuDy8FGh8VHDs"
# user_name1 = "CQAfHRwVKCMuDy8FGh8VHDs"
# password1 = "iTtNunL32EtXNrMKsSudXmAB"
# server1 = "mqtt3.thingspeak.com"
# client1 = MQTTClient(client_id = client_id1, server =server1, user=user_name1, password=password1)
# client1.connect()
# publish_topic = b"channels/2384358/publish"
#####################
# Giải thích giá trị nút bấm
# value = 1 là nút chưa được bấm, thiết bị tự động hoạt động bình thường
# value = 0 là nút được bấm, bắt buộc khởi động thiết bị
t = -1000
h = -1000
lux = -1000
soilMoisterValue = - 1000
def handle_callback(topic, msg):
global t, h, lux, soilMoisterValue
print(f"Received message on topic {topic}: {msg.decode()}")
if topic == b'IoT_MQTT_TemperatureA':
t = float(msg)
elif topic == b'IoT_MQTT_HumidityA':
h = float(msg)
elif topic == b'IoT_MQTT_LuxA':
lux = float(msg)
else:
soilMoisterValue = float(msg)
client_id = "iotnhakinh"
server = "broker.hivemq.com"
client = MQTTClient(client_id, server)
client.set_callback(handle_callback)
client.connect()
# Subcribe topics
client.subscribe(b"IoT_MQTT_TemperatureA")
client.subscribe(b"IoT_MQTT_HumidityA")
client.subscribe(b"IoT_MQTT_LuxA")
client.subscribe(b"IoT_MQTT_SoilMoisterA")
while True:
client.wait_msg()
# Nhận dữ liệu từ MQTT và gán vào các biến sau
# Code here.................
# t =
# h =
# lux =
# soilMoisterValue =
#Hiển thị lên led
lcd.clear()
if(t != -1000):
lcd.putstr(f"Temp: {t}\n")
if(h != - 1000):
lcd.putstr(f"Humid: {h}\n")
if(lux != - 1000):
lcd.putstr(f"Lux: {lux}\n")
if(soilMoisterValue != - 1000):
lcd.putstr(f"SoilMois: {soilMoisterValue}\n")
time.sleep(1)