#include <Arduino.h>
#include <WiFi.h>
#include <Wire.h>
#include <ArduinoJson.h> //https://github.com/arduino-libraries/Arduino_JSON/tree/master
#include <PubSubClient.h> //https://github.com/knolleary/pubsubclient.git
#include <LiquidCrystal_I2C.h> //https://github.com/johnrickman/LiquidCrystal_I2C
LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);
//Thông số MQTT
//mqtt://testesp32-6h:[email protected]
const char *broker = "testesp32-6h.cloud.shiftr.io";
const char *topic_control = "/controller";
const char *topic_sensor = "/sensor";
const char *mqtt_user = "testesp32-6h";
const char *mqtt_pass = "gor5W7lwNvMOz8qB";
const char* mqtt_client_name = "ESP32 test";//tên client kết nối
#define PORT_MQTT 1883
WiFiClient wifiClient;
PubSubClient wifiMqtt(wifiClient);
// hàm sẽ được gọi khi có dữ liệu gửi đến esp qua mqtt
void mqttCallback(char* topic, byte* payload, unsigned int len) {
Serial.print("Du lieu gui den [");
Serial.print(topic);
Serial.print("]: ");
Serial.write(payload, len);
Serial.println();
String msg="";
JsonDocument myObject;
for (int i = 0; i<len; ++i) {
msg += (char)payload[i]; // typecast because String takes uint8_t as something else than char
}
//
if (String(topic) == topic_control){
deserializeJson(myObject, msg)
Serial.println(myObject);
DeserializationError error = deserializeMsgPack(myObject, input);
if (error) {
//đối tượng ko phải là kiểu json
Serial.print("deserializeMsgPack() failed: ");
Serial.println(error.f_str());
}else{
if (myObject.containsKey("type"))
{
Serial.print("myObject[\"type\"] = ");
Serial.println(JSON.stringify(myObject["type"]));
} else return;
if (myObject.containsKey("data"))
{
Serial.print("myObject[\"data\"] = ");
Serial.println(myObject["data"]);
} else return;
if (myObject["type"].as<String>().equals("\"LCD\""))
{
Serial.println(myObject["data"]);
String dataS= myObject["data"].as<String>().substring(1, myObject["data"].as<String>().length()-1);
int idx = dataS.indexOf(";");
LCD.clear();
if (idx == -1)
{
LCD.setCursor(0, 0);
LCD.println(dataS);
}
else
{
LCD.setCursor(0, 0);
LCD.println(dataS.substring(0, idx));
LCD.setCursor(0, 1);
LCD.println(dataS.substring(idx+1, dataS.length()));
}
}
}
}
}
// Hàm setup cho MQTT Client
void setupMQTT(PubSubClient *mqtt) {
mqtt->setServer(broker, PORT_MQTT);
mqtt->setCallback(mqttCallback);
}
bool isWifiConnected() {
return (WiFi.status() == WL_CONNECTED);
}
// Hàm kết nối tới MQTT Broker
boolean connectMQTT(PubSubClient *mqtt) {
Serial.print("Ket noi broker ");
Serial.print(broker);
boolean status = mqtt->connect(mqtt_client_name, mqtt_user, mqtt_pass);
if (status == false) {
Serial.println(" khong thanh cong!");
return false;
}
Serial.println(" thanh cong!");
mqtt->subscribe(topic_control);// Đăng ký nhận dữ liệu từ topic topic_relays
return mqtt->connected();
}
// Hàm xử lý trong loop() dành cho MQTT Client dùng wifi
void mqttLoopWithWifi() {
// Vì dùng wifi, nên nếu có kết nối GPRS với MQTT thì ngắt kết nối
if (!wifiMqtt.connected()) {
Serial.println("Ket noi MQTT voi Wifi");
while ( (!wifiMqtt.connected()) && isWifiConnected()) {
connectMQTT(&wifiMqtt);
delay(5000);
}
} else
wifiMqtt.loop();// Hàm xử lý của thư viện mqtt
}
void setup() {
Serial.begin(115200);
Wire.begin();
LCD.init();
LCD.backlight();
LCD.setCursor(0, 0);
LCD.print("Connecting to ");
LCD.setCursor(0, 1);
LCD.print("WiFi ");
// while (!Serial);
//Bật wifi chế độ sta, kết nối với mạng internet
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println("Connected to the Wi-Fi network");
LCD.clear();
LCD.setCursor(0, 0);
LCD.println("Online");
LCD.setCursor(0, 1);
LCD.println("setup MQTT");
setupMQTT(&wifiMqtt);
LCD.clear();
LCD.setCursor(0, 0);
LCD.println("Online");
LCD.setCursor(0, 1);
LCD.println("setup MQTT run");
}
void loop() {
if (isWifiConnected()) {// Ưu tiên đầu, nếu có wifi thì xử lý kết nối mqtt với wifi
mqttLoopWithWifi();
}
// if (wifiMqtt.connected() && (millis()-t0)>1000)
// {
// int gasValue = analogRead(GASpin);
// float temp = dht.readTemperature();
// float hum = dht.readHumidity();
// // if (isnan(temp)) temp = 0;
// // if (isnan(hum)) hum = 0;
// JSONVar sendJson;
// sendJson["type"] = "data";
// sendJson["Gas"] = gasValue;
// sendJson["Temp"] = temp;
// sendJson["Hum"] = hum;
// String jsonString = JSON.stringify(sendJson); //có 2 ms
// Serial.print("JSON.stringify(myObject) = ");
// Serial.println(jsonString);
// wifiMqtt.publish(topic_sensor, jsonString.c_str());
// if(foundOled) printDisplay(gasValue, temp, hum);
// if (gasValue >= 100) digitalWrite(LED, HIGH);
// else digitalWrite(LED, LOW);
// t0=millis();
// }
}