ESP32 เชื่อมต่อ IoT ผ่าน MQTT ด้วย NETPIE2020

ESP32 เชื่อมต่อ IoT ผ่าน MQTT ด้วย NETPIE2020

บทนำ

NETPIE2020 เป็นแพลตฟอร์ม IoT ที่ช่วยให้ ESP32-C3 Super Mini บน MicroLearner ของคุณสามารถเชื่อมต่อและส่งข้อมูลผ่านโปรโตคอล MQTT ได้อย่างง่ายดาย บทความนี้จะแนะนำวิธีการใช้งานโค้ดตัวอย่างเพื่อให้ ESP32-C3 Super Mini สามารถเชื่อมต่อกับ WiFi และ NETPIE2020 เพื่อส่งข้อมูล

สิ่งที่ต้องเตรียม

  1. ESP32-C3 Super Mini บน MicroLearner
  2. Arduino IDE พร้อมติดตั้ง ESP32 Board Manager
  3. Library ที่ต้องใช้
    • WiFi.h (มีอยู่แล้วในแพ็คเกจบอร์ด ESP32)
    • PubSubClient (สามารถติดตั้งจาก Arduino Library Manager)
  4. https://netpie.io/  บัญชี NETPIE2020 และข้อมูล Client ID, Token, Secret

โค้ดตัวอย่างและคำอธิบาย

#include <WiFi.h>
#include <PubSubClient.h>
// ข้อมูล WiFi
const char* ssid = "xxx";
const char* password = "xxx";
// ข้อมูล NETPIE2020
const char* mqttServer = "broker.netpie.io";
const int mqttPort = 1883;
const char* mqttClientID = "xxx";
const char* mqttUsername = "xxx";
const char* mqttPassword = "xxx";
WiFiClient espClient;
PubSubClient client(espClient);
// กำหนดขาของปุ่ม
const int buttonA = 6;
const int buttonB = 7;
const int buttonC = 10;
// เก็บสถานะปุ่มล่าสุด
bool lastStateA = LOW;
bool lastStateB = LOW;
bool lastStateC = LOW;
// เวลาสำหรับ debounce
unsigned long lastDebounceTimeA = 0;
unsigned long lastDebounceTimeB = 0;
unsigned long lastDebounceTimeC = 0;
const unsigned long debounceDelay = 50;
void setupWiFi() {
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("WiFi connected!");
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message received: ");
Serial.write(payload, length);
Serial.println();
}
void connectToMqtt() {
while (!client.connected()) {
Serial.print("Connecting to NETPIE2020...");
if (client.connect(mqttClientID, mqttUsername, mqttPassword)) {
Serial.println("Connected!");
client.subscribe("@msg/your_topic");
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" trying again in 5 seconds...");
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
pinMode(buttonA, INPUT_PULLDOWN);
pinMode(buttonB, INPUT_PULLDOWN);
pinMode(buttonC, INPUT_PULLDOWN);
setupWiFi();
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
connectToMqtt();
}
void loop() {
if (!client.connected()) {
connectToMqtt();
}
client.loop();
unsigned long currentMillis = millis();
bool stateA = digitalRead(buttonA);
bool stateB = digitalRead(buttonB);
bool stateC = digitalRead(buttonC);
if (stateA != lastStateA && (currentMillis - lastDebounceTimeA) > debounceDelay) {
lastDebounceTimeA = currentMillis;
if (stateA == HIGH) {
updateShadow("A");
}
}
lastStateA = stateA;
if (stateB != lastStateB && (currentMillis - lastDebounceTimeB) > debounceDelay) {
lastDebounceTimeB = currentMillis;
if (stateB == HIGH) {
updateShadow("B");
}
}
lastStateB = stateB;
if (stateC != lastStateC && (currentMillis - lastDebounceTimeC) > debounceDelay) {
lastDebounceTimeC = currentMillis;
if (stateC == HIGH) {
updateShadow("C");
}
}
lastStateC = stateC;
}
void updateShadow(String button) {
String shadowData = "{\"data\": {\"button\": \"" + button + "\"}}";
client.publish("@shadow/data/update", shadowData.c_str());
Serial.println("Updated Shadow: " + button);
}

ตรวจสอบการอัพเดท

สังเกตตรง Shadow ว่าข้อมูลมีการเปลี่ยนแปลงตามการกดปุ่มหรือไม่ หากข้อมีการเปลี่ยนแปลงแสดงว่ามีการส่งและอัพเดท Shadow ได้สมบูรณ์แล้ว

การแสดงข้อมูลด้วย Dashboard

คุณสามารถใช้ Dashboard ของ NETPIE2020 หรือเครื่องมืออื่น ๆ เช่น Node-RED, Grafana หรือแอปพลิเคชันที่รองรับ MQTT เพื่อแสดงข้อมูลที่ได้รับจาก ESP32 ในรูปแบบกราฟหรือค่าต่าง ๆ ได้ง่าย ๆ

ข้อดีของ Shadow Data

Shadow Data ดีกว่าการ publish ข้อมูลไปที่หัวข้อทั่วไป (@msg/your_topic) ตรงที่มี ฐานข้อมูลชั่วคราว (Persistent Storage) ที่สามารถเก็บค่าล่าสุดของอุปกรณ์ไว้บนเซิร์ฟเวอร์ได้ ซึ่งมีข้อดีหลายอย่าง เช่น:

  1. เก็บค่าล่าสุดไว้ได้ – เมื่ออุปกรณ์เชื่อมต่อใหม่ หรือ Client อื่นเรียกดูข้อมูล ก็ยังสามารถเข้าถึงค่าล่าสุดได้ โดยไม่ต้องรอให้มีการส่งข้อมูลใหม่
  2. ลดภาระการส่งข้อมูลซ้ำ – ไม่ต้อง publish ข้อมูลเดิมซ้ำ ๆ หากค่าของอุปกรณ์ยังไม่เปลี่ยนแปลง
  3. รองรับการ Sync ข้อมูล – ถ้ามีหลายอุปกรณ์ที่ต้องใช้ข้อมูลเดียวกัน (เช่น Dashboard, อุปกรณ์ IoT อื่น ๆ) ก็สามารถดึงค่าล่าสุดจาก Shadow Data มาใช้ได้ทันที
  4. สะดวกต่อการติดตามสถานะอุปกรณ์ – เช่น ใช้เช็คว่าอุปกรณ์ยังออนไลน์หรือออฟไลน์อยู่

ในขณะที่การ publish ไปที่หัวข้อทั่วไป เป็นการส่งข้อมูลแบบทันทีและไม่ถูกเก็บไว้ หากไม่มี Client ที่ subscribe อยู่ตอนนั้น ข้อมูลก็อาจสูญหายไป ดังนั้น Shadow Data เป็นตัวเลือกที่ดีกว่า หากต้องการเก็บค่าล่าสุดของอุปกรณ์


สรุป

โค้ดตัวอย่างนี้ช่วยให้ ESP32-C3 Super Mini บน MicroLearner สามารถเชื่อมต่อกับ NETPIE2020 และรับ-ส่งข้อมูลผ่าน MQTT ได้ง่าย ๆ หากต้องการเปลี่ยน Topic หรือส่งข้อมูลรูปแบบอื่น สามารถปรับแต่งได้ตามต้องการ

หากคุณต้องการให้ ESP32-C3 Super Mini โต้ตอบกับอุปกรณ์อื่น ๆ หรือสร้างระบบ IoT ที่ซับซ้อนขึ้น ลองศึกษาเพิ่มเติมเกี่ยวกับ MQTT และ Shadow Data ของ NETPIE2020!

หวังว่าบทความนี้จะช่วยให้คุณเข้าใจและใช้งาน ESP32-C3 Super Mini กับ NETPIE2020 ได้ง่ายขึ้น! 


นี่เป็นเพียงตัวอย่างที่ช่วยให้คุณเริ่มต้นใช้งานได้รวดเร็วขึ้น
ศึกษา NETPIE2020 เพิ่มเติมได้ที่:
 https://netpie.io

 

 

 

@imiconsystem MicroLearner ESP32 ส่งข้อมูลขึ้น NETPIE2020 : Update shadow [MQTT] and API reader #netpie2020 #iot #mqtt #api #microlearner #esp32 #imicon ♬ FUTURE HOUSE – Sergey Wednesday

 

 

 

ศึกษาเพิ่มเติม: การเรียกใช้ข้อมูลจาก Shadow ด้วย API

NETPIE2020 มี API ที่ช่วยให้คุณสามารถดึงค่าล่าสุดจาก Shadow Data ได้ผ่าน HTTP Request ซึ่งสามารถนำไปใช้ในแอปพลิเคชันอื่น ๆ ได้ เช่น เว็บแอปพลิเคชัน หรือ Mobile App

ในตัวอย่างสามารถใช้โค้ด HTML นี้อ่าน Shadow Data ได้เลย (เปลี่ยนแค่ deviceToken)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NETPIE Shadow Data Reader</title>
</head>
<body>
<h1>NETPIE Shadow Data Reader</h1>
<button id="get-shadow-data">Get Shadow Data</button>
<pre id="shadow-data-output">Shadow Data will appear here...</pre>
<script>
document.getElementById("get-shadow-data").addEventListener("click", function() {
const endpoint = "https://api.netpie.io/v2/device/shadow/data";
const alias = ""; // เปลี่ยนเป็น alias ของอุปกรณ์ที่คุณต้องการ
const deviceToken = "367702f2-f45e-4e7e-b5e1-1b2c91dc999f:BpeIMIWbxEeLAG9hByyRFcAV3NKm9Fqn"; // ใส่ Token ของคุณ
fetch(`${endpoint}?alias=${alias}`, {
method: "GET",
headers: {
"Authorization": `Device ${deviceToken}`
}
})
.then(response => response.json())
.then(data => {
document.getElementById("shadow-data-output").textContent = JSON.stringify(data, null, 2);
})
.catch(error => {
document.getElementById("shadow-data-output").textContent = `Error: ${error}`;
});
});
</script>
</body>
</html>

ทดสอบบน W3Schools Tryit Editor

 


ดูรายละเอียดเพิ่มเติมได้ที่ NETPIE2020 API Documentation

 

 

MicroLearner | ESP32-C3 Super Mini

 

BESTESP32 เชื่อมต่อ IoT ผ่าน MQTT ด้วย NETPIE2020

Related Posts