#include <WiFi.h>
#include <PubSubClient.h>
// Đặt thông tin Wi-Fi
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Đặt thông tin ThingsBoard
const char* thingsboardServer = "147.185.221.23"; // IP hoặc hostname của ThingsBoard
const char* accessToken = "1vjCHpeKL0tyUS2B8bX6"; // Token của thiết bị trên ThingsBoard
WiFiClient wifiClient;
PubSubClient client(wifiClient);
void setup() {
Serial.begin(115200);
// Kết nối Wi-Fi
setup_wifi();
// Cấu hình client MQTT
client.setServer(thingsboardServer, 50129); // Đảm bảo sử dụng đúng port (1883)
client.setCallback(callback);
// Kết nối tới ThingsBoard
while (!client.connected()) {
Serial.print("Connecting to ThingsBoard...");
if (client.connect("ESP32Client", accessToken, NULL)) {
Serial.println("Connected");
} else {
Serial.print(".");
delay(1000);
}
}
}
void loop() {
if (!client.connected()) {
while (!client.connect("ESP32Client", accessToken, NULL)) {
delay(1000);
}
}
client.loop();
// Gửi dữ liệu lên ThingsBoard với giá trị ngẫu nhiên
int randomTemperature = random(1000, 10000); // Giá trị ngẫu nhiên từ 1000 đến 9999
String payload = "{\"temperature\":" + String(randomTemperature) + "}"; // Gửi dữ liệu ngẫu nhiên
client.publish("v1/devices/me/telemetry", payload.c_str());
delay(5000); // Gửi dữ liệu mỗi 5 giây
}
void setup_wifi() {
delay(10);
// Kết nối tới Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("WiFi connected");
}
void callback(char* topic, byte* payload, unsigned int length) {
// Hàm callback khi nhận dữ liệu từ ThingsBoard
}