2019年8月12日 星期一

Node-RED UI 控制ESp8266 Build in LED ON/OFF/Flash

    Node-RED UI 控制ESp8266 Build in LED  ON/OFF/Flash
   











==============Esp8266程式==================
//=============================================================================
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
//=============================================================================
//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 = "******";    //你的wifi名
//const char* pass = "*******";   //你的wifi密码

//=============================================================================
//服务器地址
#define MQTTid              ""                           //id of this mqtt client
#define MQTTip              "broker.mqtt-dashboard.com"  //ip address or hostname of the mqtt broker
//#define MQTTip              "iot.eclipse.org"            //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
//=============================================================================
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 espclient;
PubSubClient client(MQTTip, MQTTport, mqttDataCb, espclient);
//=============================================================================
// Variable 存放區
long lastMsg = 0;
int value = 0;

char msg[100]; //存放json数据
bool Flash = false;  //true
byte LED_stst=10;   //LED Status = 0 (0ff)  , 1(on) , 2(flash)

//=============================================================================
void mqttConnectedCb() {
  Serial.println("connected");

  // Once connected, publish an announcement...
  client.publish("alex9ufo/outLEDTopic", msg, MQTTpubQos, true); // true means retain
  // ... and resubscribe
  client.subscribe("alex9ufo/inLEDTopic", MQTTsubQos);

}
//=============================================================================
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
  }
  //Serial.print(message);
  if(message1 == "#on")
  {
      digitalWrite(BUILTIN_LED,LOW);
      Flash = false;
      LED_stst=1;
  }   //LED on 
  if(message1 == "#off")
  {
    digitalWrite(BUILTIN_LED,HIGH);
    Flash = false;
    LED_stst=0;
  } //LED off
  if(message1== "#flash") {
     Flash = true;
     digitalWrite(BUILTIN_LED, HIGH);
     LED_stst=2; 
   } // if(message== "#flashLED")

 }
//=============================================================================
void mqttDisconnectedCb() {
  Serial.println("disconnected");
}
//======================================================
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 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);
  Serial.println();
  setup_wifi();
  pinMode(BUILTIN_LED, OUTPUT);  //set Buildin_LED out mode
}
//======================================================
void loop()
{
  process_mqtt();
  if (Flash)
  {
    digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));
    delay(500);
  }
 
  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;
    String LED_status="";
    if(LED_stst==0)
    {
      LED_status="#led_off";
    }
    else if (LED_stst==1)
    {
      LED_status="#led_on";
    }
    else if(LED_stst==2)
    {
      LED_status="#led_flash";
    }
    else
    {
      LED_status="#led_undefine";
    }
    /*
    String payload="{\"data\":["+String(ana0)+","+String(ana1)+","+String(ana2)+","+String(ana3)+","+String(ana4)+","+String(ana5)+","+String(ana6)+","+String(ana7)+","+String(ana8)+","+String(ana9)+","+String(ana10)+","+String(ana11)+ "]}";
    payload.toCharArray(data, (payload.length() + 1));
    client.publish("home/json", data);
    */
    String payload="{\"LED\":"+LED_status+"} ";
    payload.toCharArray(msg, (payload.length() + 1));
    if  (client.connected()) {
         Serial.print("Publish message: ");
         Serial.println(msg);
         // Publish JSON character array to MQTT topic
         client.publish("alex9ufo/outLEDTopic",msg);
    }   //(client.connected())
  } //if (now - lastMsg > 5000)
 
}
//======================================================


================Node-RED=======================

[{"id":"3d52fce2.15d484","type":"mqtt in","z":"82b1fd24.9884c","name":"MQTT_sub","topic":"alex9ufo/outLEDTopic","qos":"2","broker":"40bf4d5e.0395f4","x":120,"y":120,"wires":[["fb750b9d.fe2088"]]},{"id":"ddbb1187.c3fb6","type":"ui_button","z":"82b1fd24.9884c","name":"","group":"e3b9c52c.4d99e8","order":0,"width":0,"height":0,"passthru":false,"label":"On led","color":"white","bgcolor":"","icon":"fa-circle","payload":"#on","payloadType":"str","topic":"","x":110,"y":180,"wires":[["23393961.2ec876"]]},{"id":"e832ca2d.7908a8","type":"ui_button","z":"82b1fd24.9884c","name":"","group":"e3b9c52c.4d99e8","order":0,"width":0,"height":0,"passthru":false,"label":"Off led","color":"black","bgcolor":"","icon":"fa-circle-o","payload":"#off","payloadType":"str","topic":"","x":110,"y":240,"wires":[["23393961.2ec876"]]},{"id":"2c38e8c5.93cb98","type":"ui_button","z":"82b1fd24.9884c","name":"","group":"e3b9c52c.4d99e8","order":0,"width":0,"height":0,"passthru":false,"label":"Flash led","color":"black","bgcolor":"","icon":"fa-circle-o","payload":"#flash","payloadType":"str","topic":"","x":120,"y":300,"wires":[["23393961.2ec876"]]},{"id":"fb750b9d.fe2088","type":"ui_text","z":"82b1fd24.9884c","group":"e3b9c52c.4d99e8","order":0,"width":0,"height":0,"name":"","label":"LED Status (On/Off/Flash)","format":"{{msg.payload}}","layout":"col-center","x":330,"y":120,"wires":[]},{"id":"23393961.2ec876","type":"mqtt out","z":"82b1fd24.9884c","name":"MQTT_Pub","topic":"alex9ufo/inLEDTopic","qos":"2","retain":"true","broker":"d9663c87.7e7da","x":370,"y":240,"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":"e3b9c52c.4d99e8","type":"ui_group","z":"","name":"Control led ESP8266","tab":"ae428cdc.a1819","order":1,"disp":true,"width":"6"},{"id":"d9663c87.7e7da","type":"mqtt-broker","z":"","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"ae428cdc.a1819","type":"ui_tab","name":"Tab 1","icon":"dashboard","order":1}]

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...