2019年12月17日 星期二

RFID 第二次作業 程式 說明 (1)

RFID 第二次作業 程式 說明   
 (在 https://fred.sensetecnic.com 執行Node-RED)

1)  程式說明下載
http://www.mediafire.com/file/qsxochx65fc21py/RFID%25E7%25AC%25AC%25E4%25BA%258C%25E6%25AC%25A1%25E4%25BD%259C%25E6%25A5%25AD1211.pdf/file


2)   https://fred.sensetecnic.com/上的 Node-RED上的 Json檔案下載

      http://www.mediafire.com/file/9wc8tpgdo0897ma/RFID_1211_flows.json/file



3)   RFID第二次作業Arduino程式 ----須配合Node-RED下載
      http://www.mediafire.com/file/60xt2x91j6zpjh8/RFID1211.ino/file



=================https://fred.sensetecnic.com/=================================


[
    {
        "id": "6725046c.914358",
        "type": "mqtt in",
        "z": "bc8649ea.abc108",
        "name": "MQTT",
        "topic": "alex9ufo/outTopic/RFID/json",
        "qos": "2",
        "datatype": "auto",
        "broker": "2071d72e.140ab8",
        "x": 130,
        "y": 180,
        "wires": [
            [
                "e38548f3.2887c8",
                "8ea91e3f.2c5c1",
                "6cff9373.69879",
                "991ae1d6.fab0c",
                "6206a6c3.58201c"
            ]
        ]
    },
    {
        "id": "69463aa.990c804",
        "type": "mqtt out",
        "z": "bc8649ea.abc108",
        "name": "",
        "topic": "alex9ufo/inTopic",
        "qos": "1",
        "retain": "false",
        "broker": "2071d72e.140ab8",
        "x": 540,
        "y": 600,
        "wires": []
    },
    {
        "id": "335a27f.1407018",
        "type": "ui_button",
        "z": "bc8649ea.abc108",
        "name": "",
        "group": "54d05f53.b0203",
        "order": 0,
        "width": "4",
        "height": "4",
        "passthru": false,
        "label": "on_LED",
        "color": "white",
        "bgcolor": "",
        "icon": "fa-circle",
        "payload": "#on",
        "payloadType": "str",
        "topic": "",
        "x": 140,
        "y": 600,
        "wires": [
            [
                "69463aa.990c804",
                "d78467e4.9e179",
                "9ef07336.74c3c",
                "9ae25ee.d07bd2"
            ]
        ]
    },
    {
        "id": "c346b40e.8003b",
        "type": "ui_button",
        "z": "bc8649ea.abc108",
        "name": "",
        "group": "54d05f53.b0203",
        "order": 0,
        "width": "4",
        "height": "4",
        "passthru": false,
        "label": "off_LED",
        "color": "black",
        "bgcolor": "",
        "icon": "fa-circle-o",
        "payload": "#off",
        "payloadType": "str",
        "topic": "",
        "x": 140,
        "y": 700,
        "wires": [
            [
                "69463aa.990c804",
                "d78467e4.9e179",
                "9ae25ee.d07bd2",
                "9ef07336.74c3c"
            ]
        ]
    },
    {
        "id": "d78467e4.9e179",
        "type": "debug",
        "z": "bc8649ea.abc108",
        "name": "",
        "active": false,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "x": 530,
        "y": 660,
        "wires": []
    },
    {
        "id": "468f948a.73d72",
        "type": "ui_button",
        "z": "bc8649ea.abc108",
        "name": "",
        "group": "54d05f53.b0203",
        "order": 0,
        "width": "4",
        "height": "4",
        "passthru": false,
        "label": "flash_LED",
        "color": "black",
        "bgcolor": "",
        "icon": "fa-circle-o",
        "payload": "#flash",
        "payloadType": "str",
        "topic": "",
        "x": 150,
        "y": 804,
        "wires": [
            [
                "69463aa.990c804",
                "d78467e4.9e179",
                "9ae25ee.d07bd2",
                "9ef07336.74c3c"
            ]
        ]
    },
    {
        "id": "e38548f3.2887c8",
        "type": "function",
        "z": "bc8649ea.abc108",
        "name": "json+時分秒",
        "func": "//var date =  new Date().toLocaleString();\nvar date =  new Date();\n\nvar h = 8+ 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 = 'Time:(' + h + ':' + m + ':' + s + ')'+ msg.payload ;\nreturn msg;\n",
        "outputs": 1,
        "noerr": 0,
        "x": 330,
        "y": 80,
        "wires": [
            [
                "bd2a69f5.4b5928"
            ]
        ]
    },
    {
        "id": "8ea91e3f.2c5c1",
        "type": "switch",
        "z": "bc8649ea.abc108",
        "name": "",
        "property": "payload",
        "propertyType": "msg",
        "rules": [
            {
                "t": "cont",
                "v": "Alex9ufo",
                "vt": "str"
            },
            {
                "t": "cont",
                "v": "RaspberryPi",
                "vt": "str"
            },
            {
                "t": "empty"
            }
        ],
        "checkall": "true",
        "repair": false,
        "outputs": 3,
        "x": 290,
        "y": 180,
        "wires": [
            [
                "539807da.b0d368",
                "4d5b3b35.720cdc"
            ],
            [
                "539807da.b0d368",
                "de57b410.711c9"
            ],
            [
                "539807da.b0d368",
                "27375244.95a736"
            ]
        ]
    },
    {
        "id": "539807da.b0d368",
        "type": "debug",
        "z": "bc8649ea.abc108",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "x": 470,
        "y": 160,
        "wires": []
    },
    {
        "id": "6b4ebb94.a6cd98",
        "type": "ui_audio",
        "z": "bc8649ea.abc108",
        "name": "",
        "group": "54d05f53.b0203",
        "voice": "en-US",
        "always": "",
        "x": 900,
        "y": 240,
        "wires": []
    },
    {
        "id": "a8cb4759.4de458",
        "type": "ui_audio",
        "z": "bc8649ea.abc108",
        "name": "",
        "group": "54d05f53.b0203",
        "voice": "en-US",
        "always": "",
        "x": 620,
        "y": 800,
        "wires": []
    },
    {
        "id": "9ef07336.74c3c",
        "type": "function",
        "z": "bc8649ea.abc108",
        "name": "Format timestamp",
        "func": "var date = new Date();\nvar h = 8+ 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": 450,
        "y": 740,
        "wires": [
            [
                "5b2d87f3.06919"
            ]
        ]
    },
    {
        "id": "77528385.4c63b4",
        "type": "debug",
        "z": "bc8649ea.abc108",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "x": 530,
        "y": 360,
        "wires": []
    },
    {
        "id": "844f8bb2.481158",
        "type": "inject",
        "z": "bc8649ea.abc108",
        "name": "CREATE DB",
        "topic": "CREATE TABLE RFIDtable( id INT PRIMARY KEY NOT NULL, currenttime TEXT , uidname TEXT)",
        "payload": "",
        "payloadType": "date",
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "x": 230,
        "y": 460,
        "wires": [
            [
                "f848bb96.505d48"
            ]
        ]
    },
    {
        "id": "9ae25ee.d07bd2",
        "type": "ui_text_input",
        "z": "bc8649ea.abc108",
        "name": "",
        "label": "",
        "group": "54d05f53.b0203",
        "order": 9,
        "width": "12",
        "height": "2",
        "passthru": true,
        "mode": "text",
        "delay": "0",
        "topic": "",
        "x": 440,
        "y": 804,
        "wires": [
            [
                "a8cb4759.4de458",
                "4db6e8c9.ebb5d"
            ]
        ]
    },
    {
        "id": "bac428d9.44b9e8",
        "type": "ui_text_input",
        "z": "bc8649ea.abc108",
        "name": "",
        "label": "",
        "group": "54d05f53.b0203",
        "order": 9,
        "width": "12",
        "height": "1",
        "passthru": true,
        "mode": "text",
        "delay": "0",
        "topic": "",
        "x": 720,
        "y": 240,
        "wires": [
            [
                "6b4ebb94.a6cd98",
                "ad826444.eb5f8"
            ]
        ]
    },
    {
        "id": "ad826444.eb5f8",
        "type": "delay",
        "z": "bc8649ea.abc108",
        "name": "",
        "pauseType": "delay",
        "timeout": "80",
        "timeoutUnits": "milliseconds",
        "rate": "1",
        "nbRateUnits": "1",
        "rateUnits": "second",
        "randomFirst": "1",
        "randomLast": "5",
        "randomUnits": "seconds",
        "drop": false,
        "x": 690,
        "y": 320,
        "wires": [
            [
                "1a1afdc3.ff113a"
            ]
        ]
    },
    {
        "id": "1a1afdc3.ff113a",
        "type": "function",
        "z": "bc8649ea.abc108",
        "name": "Check Text",
        "func": "text=msg.payload;\nif(text !== \"\"){\n    msg.payload = \"\";\n    return msg;\n}",
        "outputs": 1,
        "noerr": 0,
        "x": 850,
        "y": 320,
        "wires": [
            [
                "bac428d9.44b9e8"
            ]
        ]
    },
    {
        "id": "4db6e8c9.ebb5d",
        "type": "delay",
        "z": "bc8649ea.abc108",
        "name": "",
        "pauseType": "delay",
        "timeout": "80",
        "timeoutUnits": "milliseconds",
        "rate": "1",
        "nbRateUnits": "1",
        "rateUnits": "second",
        "randomFirst": "1",
        "randomLast": "5",
        "randomUnits": "seconds",
        "drop": false,
        "x": 370,
        "y": 860,
        "wires": [
            [
                "824fac6e.2ee458"
            ]
        ]
    },
    {
        "id": "824fac6e.2ee458",
        "type": "function",
        "z": "bc8649ea.abc108",
        "name": "Check Text",
        "func": "text=msg.payload;\nif(text !== \"\"){\n    msg.payload = \"\";\n    return msg;\n}",
        "outputs": 1,
        "noerr": 0,
        "x": 530,
        "y": 860,
        "wires": [
            [
                "9ae25ee.d07bd2"
            ]
        ]
    },
    {
        "id": "b433cfda.9f63",
        "type": "ui_button",
        "z": "bc8649ea.abc108",
        "name": "",
        "group": "54d05f53.b0203",
        "order": 0,
        "width": "12",
        "height": "2",
        "passthru": false,
        "label": "Testing......",
        "color": "white",
        "bgcolor": "",
        "icon": "fa-circle",
        "payload": "Testing",
        "payloadType": "str",
        "topic": "",
        "x": 470,
        "y": 320,
        "wires": [
            [
                "bac428d9.44b9e8"
            ]
        ]
    },
    {
        "id": "7dfb5af7.d623d4",
        "type": "ui_template",
        "z": "bc8649ea.abc108",
        "group": "54d05f53.b0203",
        "name": "",
        "order": 0,
        "width": "15",
        "height": "10",
        "format": "<table style=\"width:100%\">\n  <tr>\n    <th>Index</th> \n    <th>Date</th> \n    <th>RFID</th>\n  </tr>\n  <tr ng-repeat=\"x in msg.payload | limitTo:100\">\n    <td>{{$index}}</td>\n    <td>{{msg.payload[$index].currenttime}}</td>\n    <td>{{msg.payload[$index].uidname}}</td> \n  </tr>\n</table>",
        "storeOutMessages": true,
        "fwdInMessages": true,
        "templateScope": "local",
        "x": 720,
        "y": 420,
        "wires": [
            []
        ]
    },
    {
        "id": "bd2a69f5.4b5928",
        "type": "ui_text",
        "z": "bc8649ea.abc108",
        "group": "54d05f53.b0203",
        "order": 0,
        "width": "0",
        "height": "0",
        "name": "",
        "label": "MQTT_send_Message",
        "format": "{{msg.payload}}",
        "layout": "row-left",
        "x": 540,
        "y": 80,
        "wires": []
    },
    {
        "id": "69cbb656.cccc",
        "type": "function",
        "z": "bc8649ea.abc108",
        "name": "INSERT",
        "func": "msg.topic = \"INSERT INTO RFIDtable (id,currenttime, uidname) VALUES (?,?,?)\";\n\n\nvar date = new Date();\n\nvar h = 8+ date.getHours();\n\nvar m = date.getMinutes();\n\nvar s = date.getSeconds();\n\nif(h<10)\n{\n    \n  h = '0'+h;\n\n}\n\nif(m<10)\n{\n    \n  m = '0' + m;\n\n}\n\nif(s<10)\n{\n    \n  s = '0' + s;\n\n}\n\nvar hms= h + ':' + m + ':' + s ;\nvar id= Date.now() ;\n\nmsg.payload = [id ,hms, msg.payload];\nreturn msg;\n",
        "outputs": 1,
        "noerr": 0,
        "x": 380,
        "y": 360,
        "wires": [
            [
                "77528385.4c63b4",
                "f848bb96.505d48"
            ]
        ]
    },
    {
        "id": "27375244.95a736",
        "type": "function",
        "z": "bc8649ea.abc108",
        "name": "不合法卡片",
        "func": "msg.payload = 'illegal Card'\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "x": 470,
        "y": 280,
        "wires": [
            [
                "bac428d9.44b9e8"
            ]
        ]
    },
    {
        "id": "26d4ef0f.ee0f78",
        "type": "inject",
        "z": "bc8649ea.abc108",
        "name": "",
        "topic": "",
        "payload": "",
        "payloadType": "date",
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "x": 280,
        "y": 280,
        "wires": [
            [
                "27375244.95a736"
            ]
        ]
    },
    {
        "id": "de57b410.711c9",
        "type": "function",
        "z": "bc8649ea.abc108",
        "name": "RaspberryPi卡片",
        "func": "msg.payload = 'RaspberryPi Card'\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "x": 490,
        "y": 240,
        "wires": [
            [
                "bac428d9.44b9e8"
            ]
        ]
    },
    {
        "id": "4d5b3b35.720cdc",
        "type": "function",
        "z": "bc8649ea.abc108",
        "name": "Alex9ufo卡片",
        "func": "msg.payload = 'Alex9ufo Card'\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "x": 470,
        "y": 200,
        "wires": [
            [
                "bac428d9.44b9e8"
            ]
        ]
    },
    {
        "id": "5b2d87f3.06919",
        "type": "function",
        "z": "bc8649ea.abc108",
        "name": "Set Line API ",
        "func": "msg.headers = {'content-type':'application/x-www-form-urlencoded','Authorization':'Bearer cEI4hx24xyopKGAArgZcKJNHE1V7KeeIi4Lzny3dDNO'};\nmsg.payload = {\"message\":msg.payload};\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "x": 630,
        "y": 740,
        "wires": [
            [
                "41bd1482.4acb14"
            ]
        ]
    },
    {
        "id": "41bd1482.4acb14",
        "type": "http request",
        "z": "bc8649ea.abc108",
        "name": "",
        "method": "POST",
        "ret": "txt",
        "url": "https://notify-api.line.me/api/notify",
        "tls": "",
        "x": 790,
        "y": 740,
        "wires": [
            [
                "41011fee.7f9f48"
            ]
        ]
    },
    {
        "id": "41011fee.7f9f48",
        "type": "debug",
        "z": "bc8649ea.abc108",
        "name": "",
        "active": false,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "false",
        "x": 950,
        "y": 740,
        "wires": []
    },
    {
        "id": "6206a6c3.58201c",
        "type": "debug",
        "z": "bc8649ea.abc108",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "false",
        "x": 330,
        "y": 40,
        "wires": []
    },
    {
        "id": "6cff9373.69879",
        "type": "json",
        "z": "bc8649ea.abc108",
        "name": "",
        "property": "payload",
        "action": "str",
        "pretty": false,
        "x": 210,
        "y": 360,
        "wires": [
            [
                "69cbb656.cccc"
            ]
        ]
    },
    {
        "id": "7e4a1fdb.70db6c",
        "type": "ui_button",
        "z": "bc8649ea.abc108",
        "name": "",
        "group": "54d05f53.b0203",
        "order": 10,
        "width": "4",
        "height": "4",
        "passthru": false,
        "label": "View Data",
        "color": "",
        "bgcolor": "",
        "icon": "",
        "payload": "",
        "payloadType": "str",
        "topic": "SELECT * FROM RFIDtable ORDER BY  id  DESC LIMIT 100;",
        "x": 410,
        "y": 520,
        "wires": [
            [
                "f848bb96.505d48"
            ]
        ]
    },
    {
        "id": "991ae1d6.fab0c",
        "type": "function",
        "z": "bc8649ea.abc108",
        "name": "Format timestamp",
        "func": "var date = new Date();\nvar h = 8+ 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": 350,
        "y": 120,
        "wires": [
            [
                "275fd776.28cd08"
            ]
        ]
    },
    {
        "id": "275fd776.28cd08",
        "type": "function",
        "z": "bc8649ea.abc108",
        "name": "Set Line API ",
        "func": "msg.headers = {'content-type':'application/x-www-form-urlencoded','Authorization':'Bearer cEI4hx24xyopKGAArgZcKJNHE1V7KeeIi4Lzny3dDNO'};\nmsg.payload = {\"message\":msg.payload};\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "x": 530,
        "y": 120,
        "wires": [
            [
                "b5e9dc82.b827a"
            ]
        ]
    },
    {
        "id": "b5e9dc82.b827a",
        "type": "http request",
        "z": "bc8649ea.abc108",
        "name": "",
        "method": "POST",
        "ret": "txt",
        "url": "https://notify-api.line.me/api/notify",
        "tls": "",
        "x": 690,
        "y": 120,
        "wires": [
            [
                "826c8303.bfd01"
            ]
        ]
    },
    {
        "id": "826c8303.bfd01",
        "type": "debug",
        "z": "bc8649ea.abc108",
        "name": "",
        "active": false,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "false",
        "x": 850,
        "y": 120,
        "wires": []
    },
    {
        "id": "ae33306a.d5d51",
        "type": "comment",
        "z": "bc8649ea.abc108",
        "name": "CREATE TABLE RFIDtable",
        "info": "CREATE TABLE RFIDtable( id INT PRIMARY KEY NOT NULL, currenttime TEXT , rfid TEXT)",
        "x": 210,
        "y": 500,
        "wires": []
    },
    {
        "id": "1abae79e.ae9764",
        "type": "ui_button",
        "z": "bc8649ea.abc108",
        "name": "Alex9ufo",
        "group": "54d05f53.b0203",
        "order": 2,
        "width": "4",
        "height": "4",
        "passthru": false,
        "label": "手動插入測試資料",
        "color": "",
        "bgcolor": "",
        "icon": "",
        "payload": "{\"RFIDNo\":\"Alex9ufo測試\"}",
        "payloadType": "json",
        "topic": "",
        "x": 560,
        "y": 540,
        "wires": [
            [
                "75b01ea3.2a3a9"
            ]
        ]
    },
    {
        "id": "75b01ea3.2a3a9",
        "type": "mqtt out",
        "z": "bc8649ea.abc108",
        "name": "",
        "topic": "alex9ufo/outTopic/RFID/json",
        "qos": "",
        "retain": "",
        "broker": "2071d72e.140ab8",
        "x": 780,
        "y": 540,
        "wires": []
    },
    {
        "id": "3259bfa7.87607c",
        "type": "ui_button",
        "z": "bc8649ea.abc108",
        "name": "",
        "group": "54d05f53.b0203",
        "order": 11,
        "width": "4",
        "height": "4",
        "passthru": false,
        "label": "建立資料庫(只能執行一次)",
        "color": "",
        "bgcolor": "",
        "icon": "",
        "payload": "",
        "payloadType": "str",
        "topic": "CREATE TABLE RFIDtable( id INT PRIMARY KEY NOT NULL, currenttime TEXT , uidname TEXT)",
        "x": 240,
        "y": 420,
        "wires": [
            [
                "f848bb96.505d48"
            ]
        ]
    },
    {
        "id": "f848bb96.505d48",
        "type": "litedb",
        "z": "bc8649ea.abc108",
        "name": "RFID",
        "x": 590,
        "y": 420,
        "wires": [
            [
                "7dfb5af7.d623d4"
            ]
        ]
    },
    {
        "id": "2071d72e.140ab8",
        "type": "mqtt-broker",
        "broker": "broker.mqtt-dashboard.com",
        "port": "1883",
        "clientid": "",
        "usetls": false,
        "compatmode": true,
        "keepalive": 15,
        "cleansession": true,
        "birthQos": "0",
        "willQos": "0"
    },
    {
        "id": "54d05f53.b0203",
        "type": "ui_group",
        "z": "",
        "name": "Control led ESP8266 (ESP32)",
        "tab": "e6e7f124.a59e4",
        "order": 1,
        "disp": true,
        "width": "15",
        "collapse": false
    },
    {
        "id": "e6e7f124.a59e4",
        "type": "ui_tab",
        "z": "",
        "name": "RFID",
        "icon": "dashboard",
        "order": 1
    }
]


==================================================

 RFID第二次作業Arduino程式 ----須配合Node-RED

/*
2019-12 RFID第二次作業Arduino程式  
*/
/*
Many thanks to nikxha from the ESP8266 or WEMOSD1 forum
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SPI.h>
#include "MFRC522.h"

/* Wiring RFID RC522 module
=============================================================================
GND     = GND   3.3V    = 3.3V
The following table shows the typical pin layout used:
Signal              MFRC522     WeMos D1 mini     NodeMcu       Generic
RST/Reset     RST                  D3 [1]                     D3 [1]           GPIO-0 [1]
SPI SS            SDA [3]           D8 [2]                     D8 [2]           GPIO-15 [2]
SPI MOSI      MOSI               D7                           D7                 GPIO-13
SPI MISO      MISO               D6                           D6                 GPIO-12
SPI SCK         SCK                D5                            D5                GPIO-14
[1] (1, 2) Configurable, typically defined as RST_PIN in sketch/program.
[2] (1, 2) Configurable, typically defined as SS_PIN in sketch/program.
[3] The SDA pin might be labeled SS on some/older MFRC522 boards
=============================================================================
*/

#define RST_PIN  D3     // RST-PIN für RC522 - RFID - SPI - D3
#define SS_PIN   D8     // SDA-PIN für RC522 - RFID - SPI - D8

// 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 =  "yourSSID";     // change according to your Network - cannot be longer than 32
characters!
//const char *pass =  "yourPASSWORD"; // change according to your Network
//修改成自己的SSID Password

#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
//修改成自己的 username  password

//#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
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance

struct RFIDTag {    // 定義結構
   byte uid[4];
   char *name;
};
//==================================
//先執行RFID_2程式確認卡號再來設定
// 初始化結構資料
// 將卡號變成代號Arduino....Raspberry Pi.....Espruino
//==================================
struct RFIDTag tags[] = {  // 初始化結構資料
   {{0x70,0x21,0xED,0x10}, "Alex9ufo"},
   {{0x44,0x51,0xBB,0x96}, "RaspberryPi"},
   {{0x15,0x8,0xA,0x53}, "Espruino"}
//自己的卡片 號碼 自己的命名Alex9ufo  RaspberryPi  Espruino
};

byte totalTags = sizeof(tags) / sizeof(RFIDTag);

//Variables
long lastMsg = 0;
char jsonChar[100];
String IDNo_buf="";
bool Flash = false;  //true
//=============================================================================
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);

//=============================================================================
String printHex(byte *buffer, byte bufferSize) {
      String id = "";
      for (byte i = 0; i < bufferSize; i++) {
        id += buffer[i] < 0x10 ? "0" : "";
        id += String(buffer[i], HEX);
      }
      return id;
    }
//=============================================================================
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);
  //修改成自己的MQTT 命名
}
//=============================================================================
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
  }
  //Serial.print(message);
  if(message1 == "#on")
  {
      digitalWrite(BUILTIN_LED,LOW);
      Flash = false;
  }   //LED on
  if(message1 == "#off")
  {
    digitalWrite(BUILTIN_LED,HIGH);
    Flash = false;
  } //LED off
  if(message1== "#flash") {
     Flash = true;
     digitalWrite(BUILTIN_LED, HIGH);
   } // 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);
  Serial.println(F("Booting...."));
  SPI.begin();           // Init SPI bus
  mfrc522.PCD_Init();    // Init MFRC522
  Serial.println(F("Ready!"));
  Serial.println(F("======================================================"));
  Serial.println(F("Scan for Card and print UID:"));
}
//======================================================
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 (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial())
  { // 如果出現新卡片就讀取卡片資料
      byte *id = mfrc522.uid.uidByte;   // 取得卡片的UID
      byte idSize = mfrc522.uid.size;   // 取得UID的長度
      bool foundTag = false;            // 是否找到紀錄中的標籤,預設為「否」。
      byte i=0;
      for (i=0; i<totalTags; i++) {
        if (memcmp(tags[i].uid, id, idSize) == 0) {
          Serial.print(F("Card UID:"));
          Serial.println(tags[i].name);  // 顯示標籤的名稱
          foundTag = true;  // 設定成「找到標籤了!」
          break;            // 退出for迴圈
        }
      }

      if (!foundTag) {    // 若掃描到紀錄之外的標籤,則顯示"Wrong card!"
        Serial.println("Wrong card!");
      }

    mfrc522.PICC_HaltA();  // 讓卡片進入停止模式  

    //Serial.println(tags[i].name);
    IDNo_buf="";
    IDNo_buf=tags[i].name;
    /* char json[] =
    //  "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
    //  char JSONMessage[] = " {\"SensorType\": \"Temperature\", \"Value\": 10}"; //Original message
    // Convert data to JSON string
    String json =
    "{\"data\":{"
    "\"RFID_No\": \"" + IDNo_buf + "\"}"
    "}";
    */
    // Convert data to JSON string
    String json =
    "{\"RFIDNo\": \"" + IDNo_buf + "\"}";
     // 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/RFID/json",jsonChar);
//修改成自己的MQTT 命名
    }
   }  // if (mfrc522.PICC_IsNewCardPresent()

}   //Loop


沒有留言:

張貼留言

Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3

  Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3 AngularJS 實例 <!DOCTYPE html> <html> <head> <meta charse...