import machine
import network
import time
import sys
import json
import random
from umqtt.simple import MQTTClient
from machine import I2C, Pin
from i2c_lcd import I2cLcd
import _thread
from _thread import start_new_thread
AddressOfLcd = 0x27
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000) # connect scl to GPIO 22, sda to GPIO 21
lcd = I2cLcd(i2c, AddressOfLcd, 2, 16)
led = Pin(2, Pin.OUT)
#----------Kết nối wifi---
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected xong wifi!")
#-------------KẾT NỐI VỚI THINGSBOARD-----------
THINGSBOARD_HOST = 'demo.thingsboard.io' # Change IP Address
ACCESS_TOKEN = 'nxnyDCA4UYhDMsjQQXj9'
client_id = 'e0fc0760-e239-11ed-a4fc-57550caf43ca'
topic = 'v1/devices/me/telemetry'
#----------------
sensor_data = {'temperature': 22}
def publishValue(client): #Publish trạng thái của LED lên Thingsboard để đồng bộ trạng thái ban đầu của LED.
INTERVAL = 2
print("Thread Started")
next_reading = time.time()
while True:
client.publish(topic, json.dumps(sensor_data),1)
next_reading += INTERVAL
sleep_time = next_reading - time.time()
if sleep_time > 0:
time.sleep(sleep_time)
def setValue (params):
sensor_data['temperature'] = params
#print("Temperature Set : ",params,"C")
# Nếu params=True, bật đèn LED lên
if params == True:
led.value(1) #Bật led trạng thái
# Ngược lại, tắt đèn LED đi
elif params == False:
led.value(0) #Tắt led trạng thái
# Nếu params không phải True hoặc False, thực hiện lệnh in giá trị nhiệt độ lên màn hình LCD
else:
lcd.move_to(0,0)
lcd.putstr("Temperature :")
lcd.move_to(0,1)
lcd.putstr(str(params) + "C")
def on_connect():
client = MQTTClient(client_id, THINGSBOARD_HOST, port=1883, user=ACCESS_TOKEN, password="", keepalive=10000)
try:
client.connect()
except OSError:
print('Kết nối thất bại')
sys.exit()
client.set_callback(on_message)
client.subscribe('v1/devices/me/rpc/request/+')
return client
def on_message(topic, msg):
if topic.startswith(b'v1/devices/me/rpc/request/'):
requestId = topic[len(b'v1/devices/me/rpc/request/'):].decode()
data = json.loads(msg.decode())
if data['method'] == 'getValue':
client.publish(b'v1/devices/me/rpc/response/' + requestId.encode(), json.dumps(sensor_data['temperature']), 1)
if data['method'] == 'setValue':
params = data['params']
setValue(params)
if data['method'] == 'setLedStatus':
params = data['params']
setLedStatus(params)
#----------------
client = on_connect()
_thread.start_new_thread(publishValue, (client,))
while True:
client.check_msg()
time.sleep(1)