2023年6月13日 星期二

RFID 實驗 2-2 Node-Red + Arduino 程式

 RFID 實驗 2-2 Node-Red + Arduino 程式











[{"id":"b218efe2c820e620","type":"mqtt in","z":"41ee821f78a2e670","name":"RFID MQTT","topic":"alex9ufo/outTopic/RFID/json","qos":"2","datatype":"auto","broker":"e4d9b72d.d14398","inputs":0,"x":90,"y":160,"wires":[["f2dd0998bdd4c77c","5ab3503c04124ad5","119abaa4fcba6640","931cf47c071595d9"]]},{"id":"456e2eea27527c24","type":"mqtt out","z":"41ee821f78a2e670","name":"","topic":"alex9ufo/inTopic/led/led_event","qos":"1","retain":"true","broker":"e4d9b72d.d14398","x":390,"y":860,"wires":[]},{"id":"f2dd0998bdd4c77c","type":"function","z":"41ee821f78a2e670","name":"json+時分秒","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 = 'Time:(' + h + ':' + m + ':' + s + ')'+ msg.payload ;\nreturn msg;\n","outputs":1,"noerr":0,"x":270,"y":120,"wires":[["520f993e657f9d20"]]},{"id":"5ab3503c04124ad5","type":"switch","z":"41ee821f78a2e670","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"966aa5f4","vt":"str"},{"t":"cont","v":"7021ed10","vt":"str"},{"t":"cont","v":"96928cf4","vt":"str"},{"t":"cont","v":"b68b19f5","vt":"str"},{"t":"cont","v":"","vt":"str"}],"checkall":"true","repair":false,"outputs":5,"x":210,"y":260,"wires":[["771cc0da8ec79e9e"],["4f31e04cdd7e9275"],["9fa69f8fb9605f20"],["88c757acc6749324"],["40f9d71824f8b85c"]]},{"id":"b47c65da02c4902a","type":"debug","z":"41ee821f78a2e670","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","x":670,"y":200,"wires":[]},{"id":"958357d35ad4b327","type":"ui_audio","z":"41ee821f78a2e670","name":"播放聲音","group":"5bec47475e939f12","voice":"Google 國語(臺灣)","always":true,"x":920,"y":340,"wires":[]},{"id":"0e1004e19fc5d758","type":"sqlite","z":"41ee821f78a2e670","mydb":"5040fcb65dd58d7c","sqlquery":"msg.topic","sql":"","name":"RFID","x":290,"y":480,"wires":[["91dfd401861b363f"]]},{"id":"096bef3e86eae4b1","type":"function","z":"41ee821f78a2e670","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,"initialize":"","finalize":"","x":410,"y":920,"wires":[["d3733b8d9dcbf58f","de08d704062fe961"]]},{"id":"d3733b8d9dcbf58f","type":"debug","z":"41ee821f78a2e670","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":630,"y":920,"wires":[]},{"id":"6dd48a2740e8d446","type":"ui_text_input","z":"41ee821f78a2e670","name":"","label":"","tooltip":"","group":"5bec47475e939f12","order":9,"width":0,"height":0,"passthru":true,"mode":"text","delay":"0","topic":"","x":740,"y":340,"wires":[["958357d35ad4b327","1011d1c021742f9a"]]},{"id":"d1fdc549a1531b01","type":"ui_button","z":"41ee821f78a2e670","name":"","group":"5bec47475e939f12","order":0,"width":"4","height":"1","passthru":false,"label":"聲音測試","tooltip":"","color":"white","bgcolor":"orange","icon":"fa-circle","payload":"聲音測試","payloadType":"str","topic":"","x":660,"y":240,"wires":[["6dd48a2740e8d446"]]},{"id":"91dfd401861b363f","type":"ui_template","z":"41ee821f78a2e670","group":"5bec47475e939f12","name":"","order":0,"width":"12","height":"4","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:20\">\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,"resendOnRefresh":false,"templateScope":"local","x":420,"y":480,"wires":[[]]},{"id":"520f993e657f9d20","type":"ui_text","z":"41ee821f78a2e670","group":"5bec47475e939f12","order":0,"width":0,"height":0,"name":"","label":"MQTT_send_Message","format":"{{msg.payload}}","layout":"row-left","x":500,"y":120,"wires":[]},{"id":"40f9d71824f8b85c","type":"function","z":"41ee821f78a2e670","name":"不合法卡片","func":"var st1 = msg.payload.split('\": \"')[1].substr(0,8);\nvar st2='';\n switch (st1)\n {\n case '966aa5f4':\n     st2 = 'Alex9ufo Car';\n     break;\n case '7021ed10':\n     st2 = 'RaspberryPi Card';\n     break;\n case '96928cf4':\n     st2 = 'Node-red Car';\n     break;\n case 'b68b19f5':\n     st2 = 'VIP Car';\n     break;\n default:\n   st2 = 'illegal Card';\n }\n msg.payload=st2;\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","x":390,"y":340,"wires":[["6dd48a2740e8d446","1ad9f1a65e145b5d"]]},{"id":"a749133f03c0b155","type":"inject","z":"41ee821f78a2e670","name":"","repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":210,"y":340,"wires":[["40f9d71824f8b85c"]]},{"id":"4f31e04cdd7e9275","type":"function","z":"41ee821f78a2e670","name":"RaspberryPi卡片","func":"msg.payload = 'RaspberryPi Card'\nreturn msg;","outputs":1,"noerr":0,"x":410,"y":220,"wires":[["b47c65da02c4902a","f80464e09a1366f0"]]},{"id":"771cc0da8ec79e9e","type":"function","z":"41ee821f78a2e670","name":"Alex9ufo卡片","func":"msg.payload = 'Alex9ufo Card'\nreturn msg;","outputs":1,"noerr":0,"x":390,"y":180,"wires":[["b47c65da02c4902a","f80464e09a1366f0"]]},{"id":"de08d704062fe961","type":"function","z":"41ee821f78a2e670","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":470,"y":980,"wires":[["c2482647760135d2"]]},{"id":"c2482647760135d2","type":"http request","z":"41ee821f78a2e670","name":"","method":"POST","ret":"txt","url":"https://notify-api.line.me/api/notify","tls":"","x":620,"y":980,"wires":[["feb068a3991f8433"]]},{"id":"feb068a3991f8433","type":"debug","z":"41ee821f78a2e670","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":770,"y":980,"wires":[]},{"id":"119abaa4fcba6640","type":"debug","z":"41ee821f78a2e670","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":270,"y":80,"wires":[]},{"id":"1ad9f1a65e145b5d","type":"json","z":"41ee821f78a2e670","name":"","property":"payload","action":"str","pretty":false,"x":550,"y":380,"wires":[["f80464e09a1366f0"]]},{"id":"8756cb5a9260f4de","type":"ui_button","z":"41ee821f78a2e670","name":"","group":"5bec47475e939f12","order":10,"width":"4","height":"1","passthru":false,"label":"View Data (RFID)","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"檢視資料庫","payloadType":"str","topic":"SELECT * FROM RFIDtable ORDER BY  id  DESC LIMIT 100;","topicType":"str","x":110,"y":440,"wires":[["0e1004e19fc5d758","09bfb8b6504b8ef8"]]},{"id":"40cddbfcae11a53e","type":"comment","z":"41ee821f78a2e670","name":"CREATE TABLE RFIDtable","info":"CREATE TABLE RFIDtable( id INT PRIMARY KEY NOT NULL, currenttime TEXT , rfid TEXT)","x":170,"y":520,"wires":[]},{"id":"631c9a45744cf842","type":"ui_button","z":"41ee821f78a2e670","name":"Alex9ufo","group":"5bec47475e939f12","order":2,"width":"4","height":"1","passthru":false,"label":"手動插入測試資料","tooltip":"","color":"","bgcolor":"","icon":"","payload":"{\"RFIDNo\":\"Alex9ufo測試\"}","payloadType":"json","topic":"","x":700,"y":120,"wires":[["4faff2feb69b8f80"]]},{"id":"4faff2feb69b8f80","type":"mqtt out","z":"41ee821f78a2e670","name":"","topic":"alex9ufo/outTopic/RFID/json","qos":"1","retain":"true","broker":"e4d9b72d.d14398","x":920,"y":120,"wires":[]},{"id":"aaf4ca7549d62d85","type":"ui_button","z":"41ee821f78a2e670","name":"","group":"5bec47475e939f12","order":0,"width":"4","height":"1","passthru":false,"label":"LED 開","tooltip":"","color":"white","bgcolor":"","icon":"fa-circle","payload":"ON","payloadType":"str","topic":"","x":80,"y":820,"wires":[["456e2eea27527c24","096bef3e86eae4b1","b1ec6d7301ce619f"]]},{"id":"005ceb65888e0dc1","type":"ui_button","z":"41ee821f78a2e670","name":"","group":"5bec47475e939f12","order":0,"width":"4","height":"1","passthru":false,"label":"LED 關","tooltip":"","color":"black","bgcolor":"","icon":"fa-circle-o","payload":"OFF","payloadType":"str","topic":"","x":80,"y":860,"wires":[["456e2eea27527c24","096bef3e86eae4b1","b1ec6d7301ce619f"]]},{"id":"a4c0ca3c501e0bba","type":"ui_button","z":"41ee821f78a2e670","name":"","group":"5bec47475e939f12","order":0,"width":"4","height":"1","passthru":false,"label":"LED 開關反向","tooltip":"","color":"blue","bgcolor":"","icon":"fa-circle-o","payload":"TOGGLE","payloadType":"str","topic":"","x":100,"y":940,"wires":[["456e2eea27527c24","096bef3e86eae4b1","b1ec6d7301ce619f"]]},{"id":"58186c360087a5b2","type":"ui_button","z":"41ee821f78a2e670","name":"","group":"5bec47475e939f12","order":0,"width":"4","height":"1","passthru":false,"label":"LED 閃爍","tooltip":"","color":"blue","bgcolor":"","icon":"fa-circle-o","payload":"FLASH","payloadType":"str","topic":"","x":80,"y":900,"wires":[["456e2eea27527c24","096bef3e86eae4b1","b1ec6d7301ce619f"]]},{"id":"ac6a89160c76f1be","type":"ui_button","z":"41ee821f78a2e670","name":"","group":"5bec47475e939f12","order":0,"width":"4","height":"1","passthru":false,"label":"LED 開5秒鐘","tooltip":"","color":"purple","bgcolor":"","icon":"fa-circle-o","payload":"TIMER","payloadType":"str","topic":"","x":90,"y":980,"wires":[["456e2eea27527c24","096bef3e86eae4b1","b1ec6d7301ce619f"]]},{"id":"8a0b3ec032d0fcfa","type":"comment","z":"41ee821f78a2e670","name":"publish 到 HiveMQ Broker ","info":"將 alex9ufo/led/led_event 發行到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":310,"y":820,"wires":[]},{"id":"6fc8bd29e59d5e61","type":"comment","z":"41ee821f78a2e670","name":"向 HiveMQ Broker 訂閱subscribe","info":"將  Arduino 發行到(publish)HiveMQ Broker alex9ufo/led/led_status \n給 Node-red 或 MQTTB-Box 訂閱(Subscribe)","x":510,"y":620,"wires":[]},{"id":"06d8233e7853952c","type":"mqtt in","z":"41ee821f78a2e670","name":"","topic":"alex9ufo/led/led_status","qos":"1","datatype":"auto","broker":"841df58d.ee5e98","inputs":0,"x":480,"y":660,"wires":[["f343d1153ee38731","b0089dc58b55ac74","a5aa0f073a58a463","e6306c5d64fddb2f"]]},{"id":"b0089dc58b55ac74","type":"debug","z":"41ee821f78a2e670","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":750,"y":640,"wires":[]},{"id":"f343d1153ee38731","type":"ui_text","z":"41ee821f78a2e670","group":"5bec47475e939f12","order":0,"width":0,"height":0,"name":"","label":"Node-Red 向MQTT Suscribe Data","format":"{{msg.payload}}","layout":"col-center","x":980,"y":660,"wires":[]},{"id":"a5aa0f073a58a463","type":"function","z":"41ee821f78a2e670","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,"initialize":"","finalize":"","x":750,"y":700,"wires":[["a558d96dba30507d","f343d1153ee38731","e83a3dcd671db88e"]]},{"id":"a558d96dba30507d","type":"function","z":"41ee821f78a2e670","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.params = { $thetime:hms, $thevalue:msg.payload }\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":900,"y":720,"wires":[["771ebe30cb77054b"]]},{"id":"771ebe30cb77054b","type":"sqlite","z":"41ee821f78a2e670","mydb":"af927aba.0dc108","sqlquery":"prepared","sql":"insert into LEDS(timeled ,ledstatus) values ($thetime , $thevalue)\n","name":"LED","x":1050,"y":720,"wires":[["acd254e2b00aae5d"]]},{"id":"acd254e2b00aae5d","type":"debug","z":"41ee821f78a2e670","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":1190,"y":720,"wires":[]},{"id":"9fa69f8fb9605f20","type":"function","z":"41ee821f78a2e670","name":"Node-red卡片","func":"msg.payload = 'Node-red Card'\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":400,"y":260,"wires":[["b47c65da02c4902a","f80464e09a1366f0"]]},{"id":"88c757acc6749324","type":"function","z":"41ee821f78a2e670","name":"VIP卡片","func":"msg.payload = 'VIP Card'\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":380,"y":300,"wires":[["b47c65da02c4902a","f80464e09a1366f0"]]},{"id":"b1ec6d7301ce619f","type":"link out","z":"41ee821f78a2e670","name":"RFID-1","links":["564b571373992425","1a2e6a1f.317c06"],"x":295,"y":1020,"wires":[]},{"id":"564b571373992425","type":"link in","z":"41ee821f78a2e670","name":"","links":["b1ec6d7301ce619f"],"x":365,"y":140,"wires":[["520f993e657f9d20"]]},{"id":"7fc438fc5e897f32","type":"link in","z":"41ee821f78a2e670","name":"","links":["24818dd0fa5c0ea5","09bfb8b6504b8ef8","d939f2318c72a6b3"],"x":595,"y":440,"wires":[["6dd48a2740e8d446"]]},{"id":"1011d1c021742f9a","type":"debug","z":"41ee821f78a2e670","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":930,"y":300,"wires":[]},{"id":"09bfb8b6504b8ef8","type":"link out","z":"41ee821f78a2e670","name":"","links":["7fc438fc5e897f32"],"x":505,"y":440,"wires":[]},{"id":"3bba5c0026c79634","type":"link in","z":"41ee821f78a2e670","name":"LINE","links":["931cf47c071595d9","e6306c5d64fddb2f","d4c722e8.eaf73"],"x":475,"y":780,"wires":[["096bef3e86eae4b1"]]},{"id":"931cf47c071595d9","type":"link out","z":"41ee821f78a2e670","name":"To LINE","links":["3bba5c0026c79634"],"x":215,"y":160,"wires":[]},{"id":"e6306c5d64fddb2f","type":"link out","z":"41ee821f78a2e670","name":"TO Line 2","links":["3bba5c0026c79634"],"x":535,"y":740,"wires":[]},{"id":"32e9ed369a557646","type":"inject","z":"41ee821f78a2e670","name":"CREATE","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":120,"y":560,"wires":[["1a148550990b1d67"]]},{"id":"1a148550990b1d67","type":"sqlite","z":"41ee821f78a2e670","mydb":"5040fcb65dd58d7c","sqlquery":"fixed","sql":"CREATE TABLE RFIDtable( id INT PRIMARY KEY NOT NULL, currenttime TEXT , uidname TEXT)","name":"CREATE  rfid.db","x":380,"y":560,"wires":[["d525b7249bfade85"]]},{"id":"d525b7249bfade85","type":"debug","z":"41ee821f78a2e670","name":"debug  ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":530,"y":560,"wires":[]},{"id":"2bb84e9d4bc4c492","type":"ui_button","z":"41ee821f78a2e670","name":"","group":"5bec47475e939f12","order":11,"width":"4","height":"1","passthru":false,"label":"建立資料庫(RFID只能執行一次)","tooltip":"","color":"","bgcolor":" purple","className":"","icon":"","payload":"","payloadType":"str","topic":"","topicType":"str","x":170,"y":620,"wires":[["1a148550990b1d67"]]},{"id":"f80464e09a1366f0","type":"function","z":"41ee821f78a2e670","name":"msg.params","func":"msg.topic = \"INSERT INTO RFIDtable (id,currenttime, uidname) VALUES (?,?,?)\";\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}\nvar hms= yyyy + '/'+ MM + '/'+ dd + ' ' + h + ':' + m + ':' + s ;\nvar id= Date.now() ;\n\n\nmsg.params = { $theid:id,$thetime:hms, $thevalue:msg.payload }\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":750,"y":380,"wires":[["a40c038018149982"]]},{"id":"a40c038018149982","type":"sqlite","z":"41ee821f78a2e670","mydb":"5040fcb65dd58d7c","sqlquery":"prepared","sql":"insert into RFIDtable (id,  currenttime ,uidname ) values ($theid ,$thetime , $thevalue)\n","name":"INSERT INTO SQLITE","x":960,"y":380,"wires":[["31bd946934787ffd"]]},{"id":"31bd946934787ffd","type":"debug","z":"41ee821f78a2e670","name":"","active":false,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","x":1030,"y":420,"wires":[]},{"id":"6bd2f7a51b182033","type":"ui_button","z":"41ee821f78a2e670","name":"","group":"5bec47475e939f12","order":10,"width":"4","height":"1","passthru":false,"label":"View Data (LED)","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"檢視資料庫","payloadType":"str","topic":"SELECT * FROM LEDS ORDER BY  id  DESC LIMIT 100;","topicType":"str","x":770,"y":580,"wires":[["90fdb282e896197c","e83a3dcd671db88e"]]},{"id":"90fdb282e896197c","type":"sqlite","z":"41ee821f78a2e670","mydb":"af927aba.0dc108","sqlquery":"msg.topic","sql":"","name":"LED","x":950,"y":520,"wires":[["2a65f5f55917dd2b"]]},{"id":"2a65f5f55917dd2b","type":"ui_template","z":"41ee821f78a2e670","group":"5bec47475e939f12","name":"","order":0,"width":"12","height":"4","format":"<table style=\"width:100%\">\n  <tr>\n    <th>Index</th> \n    <th>Time</th> \n    <th>STATUS</th>\n  </tr>\n  <tr ng-repeat=\"x in msg.payload | limitTo:20\">\n    <td>{{$index}}</td>\n    <td>{{msg.payload[$index].timeled}}</td>\n    <td>{{msg.payload[$index].ledstatus}}</td> \n  </tr>\n</table>","storeOutMessages":true,"fwdInMessages":true,"resendOnRefresh":false,"templateScope":"local","className":"","x":1080,"y":520,"wires":[[]]},{"id":"e83a3dcd671db88e","type":"ui_text_input","z":"41ee821f78a2e670","name":"","label":"","tooltip":"","group":"5bec47475e939f12","order":9,"width":0,"height":0,"passthru":true,"mode":"text","delay":"0","topic":"","x":960,"y":600,"wires":[["b8a3a27e08392453"]]},{"id":"b8a3a27e08392453","type":"ui_audio","z":"41ee821f78a2e670","name":"播放聲音","group":"5bec47475e939f12","voice":"Google 國語(臺灣)","always":true,"x":1140,"y":600,"wires":[]},{"id":"ce801473d22534ef","type":"inject","z":"41ee821f78a2e670","name":"CREATE","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":740,"y":820,"wires":[["9ace087c39d42d6b"]]},{"id":"652dfaf5fd92c474","type":"ui_button","z":"41ee821f78a2e670","name":"","group":"5bec47475e939f12","order":11,"width":"4","height":"1","passthru":false,"label":"建立資料庫(LED只能執行一次)","tooltip":"","color":"","bgcolor":" purple","className":"","icon":"","payload":"","payloadType":"str","topic":"","topicType":"str","x":790,"y":780,"wires":[["9ace087c39d42d6b"]]},{"id":"9ace087c39d42d6b","type":"sqlite","z":"41ee821f78a2e670","mydb":"af927aba.0dc108","sqlquery":"fixed","sql":"CREATE TABLE LEDS (id INTEGER, timeled TEXT,ledstatus TEXT, PRIMARY KEY(id AUTOINCREMENT))","name":"CREATE led.db","x":1060,"y":820,"wires":[["ee10f8e203e0279c"]]},{"id":"ee10f8e203e0279c","type":"debug","z":"41ee821f78a2e670","name":"debug  ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":1210,"y":820,"wires":[]},{"id":"e4d9b72d.d14398","type":"mqtt-broker","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":"5bec47475e939f12","type":"ui_group","name":"RFID讀取","tab":"f6711f1636ffd623","order":1,"disp":true,"width":"15","collapse":false},{"id":"5040fcb65dd58d7c","type":"sqlitedb","db":"C:\\Users\\User\\.node-red\\rfid.db","mode":"RWC"},{"id":"841df58d.ee5e98","type":"mqtt-broker","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":"af927aba.0dc108","type":"sqlitedb","db":"C:\\Users\\User\\.node-red\\rfid_led.db","mode":"RWC"},{"id":"f6711f1636ffd623","type":"ui_tab","name":"RFID","icon":"dashboard","order":1}]


#include <WiFi.h>
#include <PubSubClient.h>
#include <SPI.h>
#include "MFRC522.h"
//=========================================
#include <WiFiManager.h>         // https://github.com/tzapu/WiFiManager
//=========================================
//#include <AutoConnect.h>
//#include <WebServer.h>
//WebServer server;
//AutoConnect  Portal(server);
/* Wiring RFID RC522 module
=============================================================================
GND     = GND   3.3V    = 3.3V
The following table shows the typical pin layout used:
 *             MFRC522      ESP32     Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD             Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin       Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          GPIO27    9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      GPIO5     10            53        D10        10               10
 * SPI MOSI    MOSI         GPIO23    11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         GPIO19    12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          GPIO18    13 / ICSP-3   52        D13        ICSP-3           15
 *
[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 SS_PIN  5  // ESP32 pin GIOP5
#define RST_PIN 27 // ESP32 pin GIOP27
#define BUILTIN_LED 2
// Update these with values suitable for 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             "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

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance

//Variables
long lastMsg = 0;
String IDNo_buf="";    //client.publish("alex9ufo/outTopic/RFID/json"
char jsonChar1[100];

String json = "";     //client.publish("alex9ufo/led/led_status",
char jsonChar2[100];

bool Flash = false;  //true
bool Timer = false;  //true
bool Send = false;  //true
int Count= 0;
//=============================================================================
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 rootPage() {
//  char content[] = "Hello, world";
//  server.send(200, "text/plain", content);
//}  
//=======================================================
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", jsonChar1, MQTTpubQos); // true means retain
  // Once connected, publish an announcement...
  client.publish("alex9ufo/led/led_status", jsonChar2, MQTTpubQos); // true means retain
  // ... and resubscribe
  client.subscribe("alex9ufo/inTopic/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 == "OFF")
   
   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 == "ON")
   
   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 == "TOGGLE")
   
   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] == 'FLASH')
   
    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] == 'TIMER')
   
}
//======================================================
void setup() {
  Serial.begin(115200);
  //===================================================  
  // WiFiManager
  // Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
 
  // Uncomment and run it once, if you want to erase all the stored information
  //wifiManager.resetSettings();
 
  // set custom ip for portal
  //wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

  // fetches ssid and pass from eeprom and tries to connect
  // if it does not connect it starts an access point with the specified name
  // here  "AutoConnectAP"
  // and goes into a blocking loop awaiting configuration
  //=================================================
  Serial.println("Configuring your Mobile WiFi to esp32ap...");
  Serial.println("Configuring another WiFi SSID,PWD...");
  //===================================================  
  wifiManager.autoConnect("AutoConnectAP");
  // or use this for auto generated name ESP + ChipID
  //wifiManager.autoConnect();
 
  // if you get here you have connected to the WiFi
  Serial.println("Connected.");

  Serial.println("Configuring ESP32...");
  pinMode(BUILTIN_LED, OUTPUT);
  Serial.println(F("Booting...."));
  SPI.begin();           // Init SPI bus
  mfrc522.PCD_Init();    // Init MFRC522

  //server.on("/", rootPage);
  //if (Portal.begin()) {
  //  Serial.println("HTTP server:" + WiFi.localIP().toString());
  //}
  //  else {
  //  Serial.println("Connection failed");
  //  while(true) {yield();}
  //}


  //===================================================
  Serial.println(F("Ready!"));
  Serial.println(F("Control Build LED ON,OFF,FLASH,TOGGLE,TIMER...."));
  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 (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(jsonChar2, 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",jsonChar2);
         }
     Send = false;    
   }
 
  if (WiFi.status() == WL_CONNECTED) {
    //========Auto Connect===============================

  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) { // 如果出現新卡片就讀取卡片資料
     delay(100);
     String IDNo = printHex(mfrc522.uid.uidByte, mfrc522.uid.size);
     // Show some details of the PICC (that is: the tag/card)
     if ((IDNo != IDNo_buf) || (now - lastMsg > 3000)) {  //不同卡片 或是 等3秒
         lastMsg = now;
         Serial.print(F("Card UID:"));
         Serial.println(IDNo);
         //Serial.println(IDNo_buf);
   
         IDNo_buf="";
         IDNo_buf=IDNo;
         // Convert data to JSON string
         String json1 =
         "{\"data\":{"
         "\"RFID_No\": \"" + IDNo + "\"}"
         "}";
         // Convert JSON string to character array
         json1.toCharArray(jsonChar1, json1.length()+1);
   
         if  (client.connected()) {
              Serial.print("Publish message: ");
              Serial.println(json1);
              // Publish JSON character array to MQTT topic
             client.publish("alex9ufo/outTopic/RFID/json",jsonChar1);
         }
      } // if ((IDNo != IDNo_buf) || (now - lastMsg > 5000))
   }  // if (mfrc522.PICC_IsNewCardPresent()
  } //========Auto Connect===============================
  //Portal.handleClient();
}   //Loop
//=========================================================




沒有留言:

張貼留言

WOKWI DHT22 & LED , Node-Red + SQLite database

 WOKWI DHT22 & LED , Node-Red + SQLite database Node-Red程式 [{"id":"6f0240353e534bbd","type":"comment&...