2020年10月19日 星期一

Auto connect WIFI ESP32 LED Control

 Auto connect WIFI  ESP32 LED Control

更換地點時需更換新的WIFI SSID , Password











將程式匯入到https://fred.sensetecnic.com/ 
要先將錯誤的先移除 再匯入
litedb 與 mysql 內容需檢視
litedb與sqlite 二者不同 須參照 http://alex9ufoexploer.blogspot.com/2019/12/httpsfred.html






Mysql database 需將XAMPP程式Running


SQlite database設定後不用打開其他程式 可以利用DB Browser for SQlite檢視資料庫










Arduino程式

#include <WiFi.h>

#include <WebServer.h>

#include <AutoConnect.h>


#include <PubSubClient.h>

#include <SPI.h>

#define BUILTIN_LED 2


#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             "alex1234"                   //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


//Variables

long lastMsg = 0;

char jsonChar[100];

String json = "";


bool Flash = false;  //true

bool Timer = false;  //true

bool Send = false;  //true

int Count= 0;


WebServer Server;

AutoConnect  Portal(Server);


//=============================================================================

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/led/led_status", jsonChar, MQTTpubQos, true); // true means retain

  // ... and resubscribe

  client.subscribe("alex9ufo/led/led_event", 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;


  Serial.print("Message arrived [");

  Serial.print(topic);

  Serial.print("] ");

  Serial.println(message);

  String s = message;


  s.trim();

  // Switch on the LED if an 1 was received as first character

  if (s == "OFF") {

     digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level

     // but actually the LED is on; this is because 

     Serial.println("Received OFF , Send LOW TO BuildIn_LED");

     Flash = false;

     Timer = false;

     json ="OFF";

     Send = true ;

    } 

   if (s == "ON") {

     digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level

     // but actually the LED is on; this is because

     Serial.println("Received ON , Send HIGH TO BuildIn_LED");

     Flash = false; 

     Timer = false; 

     json ="ON";

     Send = true ;

   }

   if (s == "TOGGLE") {

     digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));   // Turn the LED toggle 

     // but actually the LED is on; this is because

     Serial.println("Received TOGGLE , Send Toggle(H->L , L->H) TO BuildIn_LED");

     Flash = false; 

     Timer = false; 

     json ="TOGGLE";

     Send = true ;     

   }

   

    if (s == "FLASH") {

     digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level

     // but actually the LED is on; this is because

     Serial.println("Received FLASH , Flashing BuildIn_LED ");

     Flash = true;

     Timer = false;

     json ="FLASH";

     Send = true ;  

     

   } //if (message[0] == '2')

   

    if (s == "TIMER") {

     digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level

     // but actually the LED is on; this is because

     Serial.println("Received TIMER ,  BuildIn_LED ON 5 SEC");

     Flash = false;

     Timer = true;

     Count= 10;

     json ="TIMER";

     Send = true ; 

     

   } //if (message[0] == '2')


    

}

//======================================================


void rootPage() {

  char content[] = "Hello, world";

  Server.send(200, "text/plain", content);

}

//======================================================

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() {

  delay(1000);

  Serial.begin(115200);

  pinMode(BUILTIN_LED, OUTPUT);

  Serial.println(F("Booting...."));

  Serial.println();

  Server.on("/", rootPage);

  if (Portal.begin()) {

    Serial.println("HTTP server:" + WiFi.localIP().toString());

  }

}


void loop() {

  if (WiFi.status() == WL_CONNECTED) { 

  process_mqtt();

      if (Flash)

  {

    digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));

    delay(500);

  }

  if (Timer) 

  {

    digitalWrite(BUILTIN_LED, HIGH);

    delay(500);

    Count=Count-1;

    if (Count == 0 ){

       Timer=false;

       digitalWrite(BUILTIN_LED, LOW);

    }

      

  }

  if (Send) {

     // 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/led/led_status",jsonChar);

         } 

     Send = false;    

   }

  }

  Portal.handleClient();

}


Node-red程式

[

    {

        "id": "2e4a570e.3c47b8",

        "type": "mqtt in",

        "z": "619a4359.cfd9ec",

        "name": "",

        "topic": "alex9ufo/led/led_status",

        "qos": "1",

        "datatype": "auto",

        "broker": "afecebb2.8dd128",

        "x": 170,

        "y": 100,

        "wires": [

            [

                "a8c8c8d0.19a428",

                "f199e867.ad6168",

                "4b1bef71.00d28",

                "3ae6258c.90fd1a"

            ]

        ]

    },

    {

        "id": "a8c8c8d0.19a428",

        "type": "ui_text",

        "z": "619a4359.cfd9ec",

        "group": "64a05f20.513cb",

        "order": 0,

        "width": 0,

        "height": 0,

        "name": "",

        "label": "MQTT Suscribe Data",

        "format": "{{msg.payload}}",

        "layout": "col-center",

        "x": 450,

        "y": 120,

        "wires": []

    },

    {

        "id": "da58357a.833408",

        "type": "ui_button",

        "z": "619a4359.cfd9ec",

        "name": "",

        "group": "64a05f20.513cb",

        "order": 0,

        "width": 0,

        "height": 0,

        "passthru": false,

        "label": "LED 開",

        "tooltip": "",

        "color": "white",

        "bgcolor": "",

        "icon": "fa-circle",

        "payload": "ON",

        "payloadType": "str",

        "topic": "",

        "x": 130,

        "y": 380,

        "wires": [

            [

                "c1853430.5bd598"

            ]

        ]

    },

    {

        "id": "3d3c0e3.82348f2",

        "type": "ui_button",

        "z": "619a4359.cfd9ec",

        "name": "",

        "group": "64a05f20.513cb",

        "order": 0,

        "width": 0,

        "height": 0,

        "passthru": false,

        "label": "LED 關",

        "tooltip": "",

        "color": "black",

        "bgcolor": "",

        "icon": "fa-circle-o",

        "payload": "OFF",

        "payloadType": "str",

        "topic": "",

        "x": 130,

        "y": 420,

        "wires": [

            [

                "c1853430.5bd598"

            ]

        ]

    },

    {

        "id": "c1853430.5bd598",

        "type": "mqtt out",

        "z": "619a4359.cfd9ec",

        "name": "",

        "topic": "alex9ufo/led/led_event",

        "qos": "1",

        "retain": "false",

        "broker": "afecebb2.8dd128",

        "x": 410,

        "y": 460,

        "wires": []

    },

    {

        "id": "f199e867.ad6168",

        "type": "function",

        "z": "619a4359.cfd9ec",

        "name": "Format timestamp",

        "func": "var date = new Date();\nvar h = date.getHours();\nvar m = date.getMinutes();\nvar s = date.getSeconds();\nif(h<10){\n    h = '0'+h;\n}\nif(m<10){\n    m = '0' + m;\n}\nif(s<10){\n    s = '0' + s;\n}\nmsg.payload = msg.payload + ' --> Time:(' + h + ':' + m + ':' + s + ')' ;\n\nreturn msg;",

        "outputs": 1,

        "noerr": 0,

        "x": 180,

        "y": 340,

        "wires": [

            [

                "55b3b0cc.0935a"

            ]

        ]

    },

    {

        "id": "55b3b0cc.0935a",

        "type": "function",

        "z": "619a4359.cfd9ec",

        "name": "Set Line API ",

        "func": "msg.headers = {'content-type':'application/x-www-form-urlencoded','Authorization':'Bearer A4wwPNh2WqB7dlfeQyyIAwtggn1kfZSI5LkkCdia1gB'};\nmsg.payload = {\"message\":msg.payload};\nreturn msg;\n\n//oR7KdXvK1eobRr2sRRgsl4PMq23DjDlhfUs96SyUBZu",

        "outputs": 1,

        "noerr": 0,

        "x": 320,

        "y": 380,

        "wires": [

            [

                "eb859e9f.73a2c"

            ]

        ]

    },

    {

        "id": "eb859e9f.73a2c",

        "type": "http request",

        "z": "619a4359.cfd9ec",

        "name": "",

        "method": "POST",

        "ret": "txt",

        "paytoqs": false,

        "url": "https://notify-api.line.me/api/notify",

        "tls": "",

        "persist": false,

        "proxy": "",

        "authType": "",

        "x": 470,

        "y": 380,

        "wires": [

            [

                "18bbff4e.026071"

            ]

        ]

    },

    {

        "id": "18bbff4e.026071",

        "type": "debug",

        "z": "619a4359.cfd9ec",

        "name": "",

        "active": true,

        "tosidebar": true,

        "console": false,

        "tostatus": false,

        "complete": "false",

        "x": 620,

        "y": 380,

        "wires": []

    },

    {

        "id": "4b1bef71.00d28",

        "type": "debug",

        "z": "619a4359.cfd9ec",

        "name": "",

        "active": true,

        "tosidebar": true,

        "console": false,

        "tostatus": false,

        "complete": "false",

        "x": 420,

        "y": 80,

        "wires": []

    },

    {

        "id": "2bc802f1.a4ae0e",

        "type": "ui_audio",

        "z": "619a4359.cfd9ec",

        "name": "",

        "group": "64a05f20.513cb",

        "voice": "zh-TW",

        "always": true,

        "x": 370,

        "y": 220,

        "wires": []

    },

    {

        "id": "d4cba968.5c1d68",

        "type": "ui_button",

        "z": "619a4359.cfd9ec",

        "name": "",

        "group": "64a05f20.513cb",

        "order": 0,

        "width": 0,

        "height": 0,

        "passthru": false,

        "label": "LED 開關反向",

        "tooltip": "",

        "color": "blue",

        "bgcolor": "",

        "icon": "fa-circle-o",

        "payload": "TOGGLE",

        "payloadType": "str",

        "topic": "",

        "x": 150,

        "y": 460,

        "wires": [

            [

                "c1853430.5bd598"

            ]

        ]

    },

    {

        "id": "3ae6258c.90fd1a",

        "type": "function",

        "z": "619a4359.cfd9ec",

        "name": "",

        "func": "var st1;\nif (msg.payload === \"ON\") {\n   st1=\"LED開\"; \n} \nelse if (msg.payload === \"OFF\") {\n  st1=\"LED關\";\n}\nelse if (msg.payload === \"FLASH\") {\n  st1=\"LED閃爍\";\n}\nelse if (msg.payload === \"TIMER\") {\n  st1=\"LED開五秒鐘\";\n}\nelse if (msg.payload === \"TOGGLE\") {\n  st1=\"LED ON OFF 交換\";\n}\n\nmsg.payload=st1;\nreturn msg;",

        "outputs": 1,

        "noerr": 0,

        "x": 200,

        "y": 220,

        "wires": [

            [

                "2bc802f1.a4ae0e",

                "48bf351b.55e5dc",

                "a65d8268.fba5f"

            ]

        ]

    },

    {

        "id": "aa830489.b37bd8",

        "type": "ui_button",

        "z": "619a4359.cfd9ec",

        "name": "",

        "group": "64a05f20.513cb",

        "order": 0,

        "width": 0,

        "height": 0,

        "passthru": false,

        "label": "LED 開5秒鐘",

        "tooltip": "",

        "color": "purple",

        "bgcolor": "",

        "icon": "fa-circle-o",

        "payload": "TIMER",

        "payloadType": "str",

        "topic": "",

        "x": 140,

        "y": 540,

        "wires": [

            [

                "c1853430.5bd598"

            ]

        ]

    },

    {

        "id": "6f7301fe.bd5ec",

        "type": "mysql",

        "z": "619a4359.cfd9ec",

        "mydb": "29736fc5.560a3",

        "name": "LED STATUS",

        "x": 410,

        "y": 320,

        "wires": [

            [

                "dab3fffb.24fdd"

            ]

        ]

    },

    {

        "id": "48bf351b.55e5dc",

        "type": "function",

        "z": "619a4359.cfd9ec",

        "name": "MySQL Function",

        "func": "var status = msg.payload ;\nmsg.topic = \"INSERT INTO mysql_led_status (`LED_MQTT_Status`) VALUES  ( '\" + status + \"');\"\nnode.status({text:msg.topic});\nreturn msg;",

        "outputs": 1,

        "noerr": 0,

        "x": 220,

        "y": 300,

        "wires": [

            [

                "6f7301fe.bd5ec"

            ]

        ]

    },

    {

        "id": "dab3fffb.24fdd",

        "type": "debug",

        "z": "619a4359.cfd9ec",

        "name": "",

        "active": true,

        "tosidebar": true,

        "console": false,

        "tostatus": false,

        "complete": "false",

        "x": 580,

        "y": 320,

        "wires": []

    },

    {

        "id": "a65d8268.fba5f",

        "type": "function",

        "z": "619a4359.cfd9ec",

        "name": "INSERT",

        "func": "msg.topic = \"INSERT INTO LED (time_led, led_status) VALUES (?,?)\";\n//msg.topic = \"INSERT INTO LED (id, time_led, led_status) VALUES (?,?,?)\";\n\n\nvar Today = new Date();\nvar yyyy = Today.getFullYear(); //年\nvar MM = Today.getMonth()+1;    //月\nvar dd = Today.getDate();       //日\nvar h = Today.getHours();       //時\nvar m = Today.getMinutes();     //分\nvar s = Today.getSeconds();     //秒\n\nif(MM<10)\n{\n   MM = '0'+MM;\n}\n\nif(dd<10)\n{\n   dd = '0'+dd;\n}\n\nif(h<10)\n{\n   h = '0'+h;\n}\n\nif(m<10)\n{\n  m = '0' + m;\n}\n\nif(s<10)\n{\n  s = '0' + s;\n}\n\nvar hms= yyyy + '/'+ MM + '/'+ dd + ' ' + h + ':' + m + ':' + s ;\n//var id= Date.now() ;\n//msg.payload = [id ,hms, msg.payload];\nmsg.payload = [hms, msg.payload];\n\nreturn msg;\n",

        "outputs": 1,

        "noerr": 0,

        "x": 370,

        "y": 260,

        "wires": [

            [

                "70088b58.a11ed4"

            ]

        ]

    },

    {

        "id": "885899e9.e55ba8",

        "type": "comment",

        "z": "619a4359.cfd9ec",

        "name": "publish 到 HiveMQ Broker ",

        "info": "將 alex9ufo/led/led_event 發行到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)",

        "x": 400,

        "y": 520,

        "wires": []

    },

    {

        "id": "5106c57.25b173c",

        "type": "comment",

        "z": "619a4359.cfd9ec",

        "name": "向 HiveMQ Broker 訂閱subscribe",

        "info": "將  Arduino 發行到(publish)HiveMQ Broker alex9ufo/led/led_status \n給 Node-red 或 MQTTB-Box 訂閱(Subscribe)",

        "x": 200,

        "y": 60,

        "wires": []

    },

    {

        "id": "e722c2d4.edc0d",

        "type": "ui_button",

        "z": "619a4359.cfd9ec",

        "name": "",

        "group": "64a05f20.513cb",

        "order": 0,

        "width": 0,

        "height": 0,

        "passthru": false,

        "label": "LED 閃爍",

        "tooltip": "",

        "color": "blue",

        "bgcolor": "",

        "icon": "fa-circle-o",

        "payload": "FLASH",

        "payloadType": "str",

        "topic": "",

        "x": 130,

        "y": 500,

        "wires": [

            [

                "c1853430.5bd598"

            ]

        ]

    },

    {

        "id": "70088b58.a11ed4",

        "type": "litedb",

        "z": "619a4359.cfd9ec",

        "name": "MQTT_Fred_LED",

        "x": 560,

        "y": 260,

        "wires": [

            [

                "2d15ddc0.a67572"

            ]

        ]

    },

    {

        "id": "2d15ddc0.a67572",

        "type": "debug",

        "z": "619a4359.cfd9ec",

        "name": "",

        "active": true,

        "tosidebar": true,

        "console": false,

        "tostatus": false,

        "complete": "false",

        "x": 740,

        "y": 260,

        "wires": []

    },

    {

        "id": "afecebb2.8dd128",

        "type": "mqtt-broker",

        "z": "",

        "name": "",

        "broker": "broker.mqtt-dashboard.com",

        "port": "1883",

        "clientid": "",

        "usetls": false,

        "compatmode": false,

        "keepalive": "15",

        "cleansession": true,

        "birthTopic": "",

        "birthQos": "0",

        "birthPayload": "",

        "closeTopic": "",

        "closePayload": "",

        "willTopic": "",

        "willQos": "0",

        "willPayload": ""

    },

    {

        "id": "64a05f20.513cb",

        "type": "ui_group",

        "z": "",

        "name": "Storing IOT Data ",

        "tab": "818c2599.3cdb18",

        "order": 1,

        "disp": true,

        "width": "6",

        "collapse": true

    },

    {

        "id": "29736fc5.560a3",

        "type": "MySQLdatabase",

        "z": "",

        "host": "127.0.0.1",

        "port": "3306",

        "db": "mysql_mqtt_led",

        "tz": "GMT +8"

    },

    {

        "id": "818c2599.3cdb18",

        "type": "ui_tab",

        "z": "",

        "name": "eWeLink",

        "icon": "dashboard",

        "disabled": false,

        "hidden": false

    }

]

沒有留言:

張貼留言

Messaging API作為替代方案

  LINE超好用功能要沒了!LINE Notify明年3月底終止服務,有什麼替代方案? LINE Notify將於2025年3月31日結束服務,官方建議改用Messaging API作為替代方案。 //CHANNEL_ACCESS_TOKEN = 'Messaging ...