การทดลองใช้งาน NodeMCU กับ MQTT โดยเปิดปิดไฟ LED IN บน NODEMCU ผ่านหน้าเว็บ



จากที่ผ่านมา เราสามารถสั่งเปิดปิดไฟจาก Blynk บนมือถือได้แล้ว  แต่มันคงไม่ค่อยสะดวก เพราะความเป็นจริง อาจมีหลายคนที่ช่วยกันดูแล สั่งงานได้หลายคน  MQTT จึงเป็นทางเลือกหนึ่งที่ทำให้เราสามารถสั่งเปิดปิดไฟ ได้จากหน้าเว็บไซด์ได้เลย  เราสามารถไปประยุกต์โดยใช้ไฟบ้านจริง  หรืออะไรก็ได้ ผ่านอุปกรณ์ relay ก็สามารถสั่งเปิดปิดได้จากหน้าเว็บไซด์ได้เลย




 กดปุ่ม ON ที่หน้าเว็บไซด์ ไฟที่ nodemcu ก็จะติด


เราสามารถลง MQTT TOOL บนมือถือ เพื่อทดสอบได้


อุปกรณ์ที่ใช้มีเพียง  nodemcu  ตัวเดียว เราจะใช้หลอดไฟจาก LED IN อยู่ที่ขา GPIO16
ขั้นตอน
1.สมัคร  https://customer.cloudmqtt.com/




ตั้งชื่อ TOPIC เป็น /IOT



2.download https://www.dropbox.com/s/b2rromz9ijg9puh/mqtt_html.zip?dl=0

 เปิดไฟล์ index.html ขึ้นมาแก้ ตรง var config แก้ข้อมูลตรงส่วน mqtt_server และ mqtt_websockets_port ให้ถูกต้อง และในส่วนของ TOPIC   /IOT ต้องให้ตรงกับที่ตั้งไว้

///////////////////////////////// index.html /////////////////
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>MQTT WebSocket</title>
<script src="jquery-1.11.3.min.js"></script>
<script src="mqttws31.js"></script>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}

#status {
background: #333;
color: #FFF;
border-radius: 3px;
font-weight: bold;
padding: 3px 6px;
}

#status.connect {
background: #E18C1A;
color: #FFF;
}

#status.connected {
background: #00AE04;
color: #FFF;
}

#status.error {
background: #F00;
color: #FFF;
}

button {
font-size: 32px;
}
</style>
<script>
var config = {
mqtt_server: "m12.cloudmqtt.com",    //แก้ให้ตรงกับบน cloud MQTT
mqtt_websockets_port: 33681,       //แก้ให้ตรงกับบน cloud MQTT
mqtt_user: "qxxxxxx",                         //แก้ให้ตรงกับบน cloud MQTT
mqtt_password: "Oxxxxxx"      //แก้ให้ตรงกับบน cloud MQTT
};

$(document).ready(function(e) {
// Create a client instance
client = new Paho.MQTT.Client(config.mqtt_server, config.mqtt_websockets_port, "web_" + parseInt(Math.random() * 100, 10));
//Example client = new Paho.MQTT.Client("m11.cloudmqtt.com", 32903, "web_" + parseInt(Math.random() * 100, 10));

// connect the client
client.connect({
useSSL: true,
userName: config.mqtt_user,
password: config.mqtt_password,
onSuccess: function() {
// Once a connection has been made, make a subscription and send a message.
// console.log("onConnect");
$("#status").text("Connected").removeClass().addClass("connected");
client.subscribe("/IOT");       //แก้ให้ตรงกับบน cloud MQTT
mqttSend("/IOT", "GET");    //แก้ให้ตรงกับบน cloud MQTT
},
onFailure: function(e) {
$("#status").text("Error : " + e).removeClass().addClass("error");
// console.log(e);
}
});

client.onConnectionLost = function(responseObject) {
if (responseObject.errorCode !== 0) {
$("#status").text("onConnectionLost:" + responseObject.errorMessage).removeClass().addClass("connect");
setTimeout(function() { client.connect() }, 1000);
}
}

client.onMessageArrived = function(message) {
// $("#status").text("onMessageArrived:" + message.payloadString).removeClass().addClass("error");
console.log(message.payloadString);
if (message.payloadString == "LEDON" || message.payloadString == "LEDOFF") {
$("#led-on").attr("disabled", (message.payloadString == "LEDON" ? true : false));
$("#led-off").attr("disabled", (message.payloadString == "LEDOFF" ? true : false));
}
}

$("#led-on").click(function(e) {
        mqttSend("/IOT", "LEDON");     //แก้ให้ตรงกับบน cloud MQTT
    });

$("#led-off").click(function(e) {
        mqttSend("/IOT", "LEDOFF");    //แก้ให้ตรงกับบน cloud MQTT
    });
});

var mqttSend = function(topic, msg) {
var message = new Paho.MQTT.Message(msg);
message.destinationName = topic;
client.send(message);
}
</script>
</head>

<body>
<h1>MQTT WebSocket</h1>
<h3>LED Control : <span id="status" class="connect">Connect...</span></h3>
<!-- <hr /> -->
<button id="led-on" disabled>ON</button>&nbsp;&nbsp;&nbsp;<button id="led-off" disabled>OFF</button>
</body>
</html>



///////////////////////////////////////


3. code  arduino

////////////////////////////////
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.
const char* ssid = "SSID";
const char* password = "WIFI_PASSWORD";

// Config MQTT Server
#define mqtt_server "m12.cloudmqtt.com"     //แก้ให้ตรงกับบน cloud MQTT
#define mqtt_port 13681                                   ////แก้ให้ตรงกับบน cloud MQTT
#define mqtt_user "qxxxxxx"                        //แก้ให้ตรงกับบน cloud MQTT
#define mqtt_password "Oxxxxx"    //แก้ให้ตรงกับบน cloud MQTT

#define LED_PIN 16    //ใช้ ไฟด LED IN  ของ nodeMCU ซึ่งตรงกับขา GPIO16

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  pinMode(LED_PIN, OUTPUT);

  Serial.begin(115200);
  delay(10);

  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("view", mqtt_user, mqtt_password)) {
      Serial.println("connected");
      client.subscribe("/IOT");  //แก้ให้ตรงกับบน cloud MQTT
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
      return;
    }
  }
  client.loop();
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String msg = "";
  int i=0;
  while (i<length) msg += (char)payload[i++];
  if (msg == "GET") {
    client.publish("/IOT", (digitalRead(LED_PIN) ? "LEDON" : "LEDOFF"));  //แก้ให้ตรงกับบน cloud MQTT
    Serial.println("Send !");
    return;
  }
  digitalWrite(LED_PIN, (msg == "LEDON" ? HIGH : LOW));
  Serial.println(msg);
}


//////////////////////////
 หลังจากนั้น เปิดไฟล์ index.html ใน mqtt_html ด้วย google chrome แล้วกดปุ่ม on / off เพื่อทดสอบ

ความคิดเห็น

  1. เปิดปิดได้แค่หลอดเดียวหรอครับ

    ตอบลบ
  2. ตย.ดีครับใช้งานได้จริง เหมาะไปประยุกต์ใช้งาน

    ตอบลบ

แสดงความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

แจ้งเตือนเข้าไลน์กลุ่ม ผ่าน Line notify เมื่อมีคน login เข้า server ของเราผ่าน SSH (linux) หรือ remote desktop เข้ามา (windows server)

การทำ cloud iot ด้วย thingsboard ไว้ใช้เองครับ

การประยุกต์ใช้ line notify ในการแจ้งปัญหาการใช้งาน สำหรับ php