2019年8月11日 星期日

Node-RED UI人機介面 控制LED並將LED狀態 展示於UI的Text 與Gauge上(Update Node-RED)


Node-RED UI人機介面 控制LED並將LED狀態 展示於UI的Text 與Gauge上(Update Node-RED)

Node-RED UI人機介面 控制LED並將LED狀態 展示於UI的Text 與Gauge上

利用 Node-RED UI人機介面控制 Esp8266(ESP32) 內建LED,
 Node-RED UI(輸入) 送出MQTT 發行的訊息 ,Esp8266(ESP32)訂閱MQTT 訊息解讀MQTT的訊息,控制LED ON/OFF/Flash .

Esp8266(ESP32)將LED ON/OFF/Flash的訊息發行到MQTT . Node-RED UI去訂閱MQTT 訊息,並解讀MQTT的訊息,將LED訊息顯示在UI的Text 與 Gauge上.


https://www.youtube.com/watch?v=2VQPKguAgKE










==============ESP8266(ESP32)程式=======================
/*
Many thanks to nikxha from the ESP8266 or WEMOSD1 forum
*/

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

// Update these with values suitable for your network.
//const char *ssid = "PTS-2F";
//const char *pass = "PTS6662594";
const char *ssid = "74170287";
const char *pass = "24063173";
//const char *ssid = "alex9ufo";
//const char *pass = "alex9981";
//const char *ssid =  "yourSSID";     // change according to your Network - cannot be longer than 32 characters!
//const char *pass =  "yourPASSWORD"; // change according to your Network


#define MQTTid              ""                           //id of this mqtt client
#define MQTTip              "broker.mqtt-dashboard.com"  //ip address or hostname of the mqtt broker
#define MQTTport            1883                         //port of the mqtt broker
#define MQTTuser            "alex9ufo"                   //username of this mqtt client
#define MQTTpsw             "alex9981"                   //password of this mqtt client
//#define MQTTuser          "your_username"              //username of this mqtt client
//#define MQTTpsw           "your_password"              //password of this mqtt client
#define MQTTpubQos          2                            //qos of publish (see README)
#define MQTTsubQos          1                            //qos of subscribe

#define BUILTIN_LED        2                             // Arduino standard is GPIO13 but lolin nodeMCU is 2

//Variables
long lastMsg = 0;
char jsonChar[100];
bool Flash = false;  //true
char LEDStatus =10;  // LED Status 0:off , 1:on , 2:Flash
bool mqtt_pub = false;  //true
String LED_StBuf="";
//=============================================================================
boolean pendingDisconnect = false;
void mqttConnectedCb(); // on connect callback
void mqttDisconnectedCb(); // on disconnect callback
void mqttDataCb(char* topic, byte* payload, unsigned int length); // on new message callback

WiFiClient wclient;
PubSubClient client(MQTTip, MQTTport, mqttDataCb, wclient);
//=============================================================================
void mqttConnectedCb() {
  Serial.println("connected");

  // Once connected, publish an announcement...
  client.publish("alex9ufo/outTopic/RFID/json", jsonChar, MQTTpubQos, true); // true means retain
  // ... and resubscribe
  client.subscribe("alex9ufo/inTopic", MQTTsubQos);
}
//=============================================================================
void mqttDisconnectedCb() {
  Serial.println("disconnected");
}
//=============================================================================
void mqttDataCb(char* topic, byte* payload, unsigned int length) {

  /*
  you can convert payload to a C string appending a null terminator to it;
  this is possible when the message (including protocol overhead) doesn't
  exceeds the MQTT_MAX_PACKET_SIZE defined in the library header.
  you can consider safe to do so when the length of topic plus the length of
  message doesn't exceeds 115 characters
  */
  char* message = (char *) payload;
  message[length] = 0;
  //String message;
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  Serial.println(message);
  String message1;
  for (int i = 0; i < length; i++) {
    message1 = message1 + (char)payload[i];  //Conver *byte to String
  }
  //=============================================
  if(message1 == "#on")
  {
      digitalWrite(BUILTIN_LED,LOW);
      Flash = false;
      LEDStatus =1;
  }   //LED on
  //=============================================
  if(message1 == "#off")
  {
    digitalWrite(BUILTIN_LED,HIGH);
    Flash = false;
    LEDStatus =0;
  } //LED off
  //=============================================
  if(message1== "#flash") {
     Flash = true;
     digitalWrite(BUILTIN_LED, HIGH);
     LEDStatus =2;
   } // if(message== "#flashLED")

 }
//======================================================
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, pass);

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

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

}
//======================================================
void setup() {
  Serial.begin(115200);
  setup_wifi();
  pinMode(BUILTIN_LED, OUTPUT);
}
//======================================================
void process_mqtt() {
  if (WiFi.status() == WL_CONNECTED) {
    if (client.connected()) {
      client.loop();
    } else {
    // client id, client username, client password, last will topic, last will qos, last will retain, last will message
      if (client.connect(MQTTid, MQTTuser, MQTTpsw, MQTTid "/status", 2, true, "0")) {
          pendingDisconnect = false;
          mqttConnectedCb();
      }
    }
  } else {
    if (client.connected())
      client.disconnect();
  }
  if (!client.connected() && !pendingDisconnect) {
    pendingDisconnect = true;
    mqttDisconnectedCb();
  }
}
//======================================================
void loop() {
  process_mqtt();
  long now = millis();

  if (Flash)
  {
    digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));
    delay(500);
  }
  //=========================================
  if (now - lastMsg > 6000) {
      lastMsg = now;
      LED_StBuf="";
      if (LEDStatus ==1)
      {
        LED_StBuf="#onLED";
        mqtt_pub = true;
      }
      else if (LEDStatus ==0)
      {
        LED_StBuf="#offLED";
        mqtt_pub = true;
      }
      else if (LEDStatus ==2)
      {
        LED_StBuf="#flashLED";
        mqtt_pub = true;
      }
      else
      {
        LED_StBuf="";
        mqtt_pub = false;
      }
   
     if (mqtt_pub == true)
     {
        // Convert data to JSON string
        String json =
        "{\"LED_Status\":\"" + LED_StBuf + "\"}";
        // Convert JSON string to character array
        json.toCharArray(jsonChar, json.length()+1);
   
      if  (client.connected()) {
            Serial.print("Publish message: ");
            Serial.println(json);
            // Publish JSON character array to MQTT topic
            client.publish("alex9ufo/outTopic",jsonChar);
        }
     } //  if (mqtt_pub == true)
  }   //if (now - lastMsg > 6000)
}   //Loop
//======================================================


===========NEW Node-RED程式===================
[{"id":"115e0d36.7a7f03","type":"switch","z":"c2a1bdb4.b5abd","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"#onLED","vt":"str"},{"t":"cont","v":"#offLED","vt":"str"},{"t":"cont","v":"#flashLED","vt":"str"}],"checkall":"true","repair":false,"outputs":3,"x":230,"y":360,"wires":[["f604e09f.858b9","10194fe8.69862"],["1e8d531b.fff50d","483195f4.1582ec"],["e3e49b4a.431128","8ce7c6fb.370d18"]]},{"id":"314565fd.ffae8a","type":"debug","z":"c2a1bdb4.b5abd","name":"","active":true,"tosidebar":true,"console":false,"complete":"false","x":630,"y":260,"wires":[]},{"id":"399977ad.848d28","type":"debug","z":"c2a1bdb4.b5abd","name":"","active":true,"console":"false","complete":"false","x":650,"y":420,"wires":[]},{"id":"82b84307.0e453","type":"mqtt out","z":"c2a1bdb4.b5abd","name":"MQTT_pub","topic":"alex9ufo/inTopic","qos":"","retain":"","broker":"40bf4d5e.0395f4","x":630,"y":200,"wires":[]},{"id":"2cedadb4.d43fa2","type":"mqtt in","z":"c2a1bdb4.b5abd","name":"MQTT_sub","topic":"alex9ufo/outTopic","qos":"2","broker":"40bf4d5e.0395f4","x":80,"y":420,"wires":[["ea9b5561.7180f8","115e0d36.7a7f03"]]},{"id":"2aee0421.3a9eac","type":"switch","z":"c2a1bdb4.b5abd","name":"","property":"payload","propertyType":"msg","rules":[{"t":"eq","v":"#on","vt":"str"},{"t":"eq","v":"#off","vt":"str"},{"t":"eq","v":"#flash","vt":"str"}],"checkall":"true","repair":false,"outputs":3,"x":270,"y":220,"wires":[["6f1e9ac9.184a14"],["2b83bdbb.ddb752"],["3e483b6d.875494"]]},{"id":"6f1e9ac9.184a14","type":"function","z":"c2a1bdb4.b5abd","name":"#on","func":"msg.payload =\"#on\";\nreturn msg;\n","outputs":1,"noerr":0,"x":430,"y":180,"wires":[["82b84307.0e453","314565fd.ffae8a"]]},{"id":"2b83bdbb.ddb752","type":"function","z":"c2a1bdb4.b5abd","name":"#off","func":"msg.payload =\"#off\";\nreturn msg;\n","outputs":1,"noerr":0,"x":430,"y":220,"wires":[["82b84307.0e453","314565fd.ffae8a"]]},{"id":"1e8d531b.fff50d","type":"function","z":"c2a1bdb4.b5abd","name":"#off","func":"msg.payload =\"LED@off\";\nreturn msg;\n","outputs":1,"noerr":0,"x":450,"y":360,"wires":[["399977ad.848d28","33293e07.4d5d52"]]},{"id":"f604e09f.858b9","type":"function","z":"c2a1bdb4.b5abd","name":"#on","func":"msg.payload =\"LED@on\";\nreturn msg;\n","outputs":1,"noerr":0,"x":450,"y":320,"wires":[["33293e07.4d5d52","399977ad.848d28"]]},{"id":"28323aef.0d3836","type":"ui_gauge","z":"c2a1bdb4.b5abd","name":"","group":"385a9af3.d72756","order":0,"width":0,"height":0,"gtype":"gage","title":"Gauge","label":"units","format":"{{value}}","min":0,"max":10,"colors":["#00b500","#e6e600","#ca3838"],"seg1":"","seg2":"","x":690,"y":520,"wires":[]},{"id":"33293e07.4d5d52","type":"ui_text","z":"c2a1bdb4.b5abd","group":"385a9af3.d72756","order":0,"width":0,"height":0,"name":"","label":"text","format":"{{msg.payload}}","layout":"row-center","x":630,"y":360,"wires":[]},{"id":"10194fe8.69862","type":"function","z":"c2a1bdb4.b5abd","name":"#on_10","func":"msg.payload =\"10\";\nreturn msg;\n","outputs":1,"noerr":0,"x":480,"y":440,"wires":[["28323aef.0d3836","64666b3f.f23cd4"]]},{"id":"483195f4.1582ec","type":"function","z":"c2a1bdb4.b5abd","name":"#off_0","func":"msg.payload =\"0\";\nreturn msg;\n","outputs":1,"noerr":0,"x":470,"y":480,"wires":[["28323aef.0d3836","64666b3f.f23cd4"]]},{"id":"ee87dd36.57b85","type":"ui_button","z":"c2a1bdb4.b5abd","name":"","group":"385a9af3.d72756","order":0,"width":0,"height":0,"passthru":false,"label":"OFF_LED","color":"black","bgcolor":"","icon":"fa-circle-o","payload":"#off","payloadType":"str","topic":"","x":80,"y":220,"wires":[["2aee0421.3a9eac"]]},{"id":"1963c7fc.004458","type":"ui_button","z":"c2a1bdb4.b5abd","name":"","group":"385a9af3.d72756","order":0,"width":0,"height":0,"passthru":false,"label":"ON_LED","color":"white","bgcolor":"","icon":"fa-circle","payload":"#on","payloadType":"str","topic":"","x":80,"y":180,"wires":[["2aee0421.3a9eac"]]},{"id":"3488e387.a47c8c","type":"ui_button","z":"c2a1bdb4.b5abd","name":"","group":"385a9af3.d72756","order":0,"width":0,"height":0,"passthru":false,"label":"Flash_LED","color":"red","bgcolor":"","icon":"fa-circle-o","payload":"#flash","payloadType":"str","topic":"","x":90,"y":260,"wires":[["2aee0421.3a9eac"]]},{"id":"3e483b6d.875494","type":"function","z":"c2a1bdb4.b5abd","name":"#flash","func":"msg.payload =\"#flash\";\nreturn msg;\n","outputs":1,"noerr":0,"x":430,"y":260,"wires":[["82b84307.0e453","314565fd.ffae8a"]]},{"id":"e3e49b4a.431128","type":"function","z":"c2a1bdb4.b5abd","name":"#flash","func":"msg.payload =\"LED@flash\";\nreturn msg;\n","outputs":1,"noerr":0,"x":450,"y":400,"wires":[["33293e07.4d5d52","399977ad.848d28"]]},{"id":"8ce7c6fb.370d18","type":"function","z":"c2a1bdb4.b5abd","name":"#flash_0&10","func":"if( context.global.i == undefined ) context.global.i = 0;\ncontext.global.i += 1;\nif (context.global.i %2 === 0 ){\n    msg.payload = 0;\n} else {\n    msg.payload = 10;\n}\nreturn msg;\n","outputs":1,"noerr":0,"x":490,"y":520,"wires":[["64666b3f.f23cd4","28323aef.0d3836"]]},{"id":"ea9b5561.7180f8","type":"debug","z":"c2a1bdb4.b5abd","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":250,"y":560,"wires":[]},{"id":"64666b3f.f23cd4","type":"debug","z":"c2a1bdb4.b5abd","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":690,"y":600,"wires":[]},{"id":"40bf4d5e.0395f4","type":"mqtt-broker","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":15,"cleansession":true,"birthQos":"0","willQos":"0"},{"id":"385a9af3.d72756","type":"ui_group","z":"","name":"Default","tab":"33a2f8d4.7049d8","disp":true,"width":"6","collapse":false},{"id":"33a2f8d4.7049d8","type":"ui_tab","z":"","name":"ESP8266_LED","icon":"dashboard"}]

沒有留言:

張貼留言

2024產專班 作業2 (純模擬)

2024產專班 作業2  (純模擬) 1) LED ON,OFF,TIMER,FLASH 模擬 (switch 控制) 2)RFID卡號模擬 (buttom  模擬RFID UID(不從ESP32) Node-Red 程式 [{"id":"d8886...