Advertisement
Guest User

Untitled

a guest
Jun 18th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.10 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3. #include <BlynkSimpleEsp8266.h>
  4. #include <WiFiClientSecure.h>
  5. #include <SPI.h>
  6. #include <MFRC522.h>
  7.  
  8.  
  9.  
  10. #define BLYNK_PRINT Serial
  11.  
  12. #define D0 16
  13. #define D1 5
  14. #define D2 4
  15. #define D3 0
  16. #define D4 2
  17. #define D5 14
  18. #define D6 12
  19. #define D7 13
  20. #define D8 15
  21. #define D9 3
  22. #define D10 1
  23.  
  24. WiFiClient client;
  25.  
  26. int libera = 0;
  27.  
  28. /*
  29. //Wifi Arruda
  30. char ssid[] = "brisa-484946";
  31. char pass[] = "hlr046f3";
  32. */
  33.  
  34.  
  35. //Wifi 4x
  36. char ssid[] = "Redmi";
  37. char pass[] = "12345678";
  38.  
  39.  
  40. /*
  41. //wifi Rhuan
  42. char ssid[] = "brisa-485118";
  43. char pass[] = "nhih5zei";
  44. */
  45.  
  46. /*
  47. //WiFi Willian
  48. char ssid[] = "brisa-136570";
  49. char pass[] = "dufnz7tf";
  50. */
  51. MFRC522 mfrc522(D4, D3); // Create MFRC522 instance.
  52. int statuss = 0;
  53. int out = 0;
  54.  
  55.  
  56. //============== cloudmqtt ===================//
  57. PubSubClient psClient(client);
  58. const char* mqttServer = "m14.cloudmqtt.com"; // endereço do seu servidor cloudmqtt
  59. const int mqttPort = 13622; // porta cloudmqtt
  60. const char* mqttUser = "bdsmhayc"; //nome de usuario cloudmqtt
  61. const char* mqttPassword = "lj5yHr1o6v6v"; // senha cloudmqtt
  62. void callback(char* topic, byte* payload, unsigned int length); //prototipo da funcao para ser chamada dentro do setup() o corpo da funcao esta mais embaixo
  63.  
  64.  
  65. //============= pushbullet ===============//
  66. const char* host = "api.pushbullet.com";
  67. const int httpsPort = 443;
  68. //const char* PushBulletAPIKEY = "o.iZSbVRUcs2WAvQTuWQfTBDdM9uBlNdKR"; //Chave do Rhuan
  69. const char* PushBulletAPIKEY = "o.AuIPPIgHEu8eoIYfzgZZRCe9XmtrRyic";
  70.  
  71.  
  72.  
  73. //========= ThingSpeak ==========//
  74. const char* TS_SERVER = "api.thingspeak.com";
  75. //String TS_API_KEY ="7G5M4S0FUZF9S0OC"; //Rhuan
  76. String TS_API_KEY = "OTAXWFEUKPYACY0X"; //Willian
  77.  
  78.  
  79.  
  80. //================ Blynk ==================//
  81. char auth[] = "227a5ae01f044e5086b34214067c90d5"; //Auth Token Bylink Willian
  82. //char auth[] = "dcd3b6114e61432b840ab702702a72d2"; //Auth Token Blynk Rhuan
  83.  
  84.  
  85.  
  86. BLYNK_CONNECTED() {
  87. Blynk.syncAll();
  88. }
  89. int but0, but1, but2, but3; // Variaveis que recebem os valores dos BOTOES VIRTUAIS do Blynk para pausar os sensores
  90. int sensorPin = A0;
  91. int sensor1 = D1;
  92. int sensor2 = D2;
  93. int sensor3 = D8;
  94.  
  95. int sensorValue1 = 0; //potenciomentro
  96. int sensorValue2 = 0; //temperatura
  97. int sensorValue3 = 0; //luminosidade
  98.  
  99. BLYNK_WRITE(V0) { //Esse botão vai bloquear o sensoriamento
  100. but0 = param.asInt(); //but0 recebendo o valor da Porta Virtual 0
  101. }
  102.  
  103. BLYNK_WRITE(V1) {
  104. but1 = param.asInt(); //but1 recebendo o valor da Porta Virtual 1
  105. }
  106. BLYNK_WRITE(V2) {
  107. but2 = param.asInt(); //but2 recebendo o valor da Porta Virtual 2
  108. }
  109. BLYNK_WRITE(V3) {
  110. but3 = param.asInt(); //but2 recebendo o valor da Porta Virtual 3
  111. }
  112.  
  113.  
  114.  
  115. BlynkTimer timer;
  116.  
  117.  
  118.  
  119.  
  120. void setup()
  121. {
  122. //Blynk.virtualWrite(V0, 1);
  123. pinMode(sensor1, OUTPUT);
  124. pinMode(sensor2, OUTPUT);
  125. pinMode(sensor3, OUTPUT);
  126.  
  127. Serial.begin(115200);
  128. Blynk.begin(auth, ssid, pass);
  129. Serial.println();
  130. Serial.print("connecting to ");
  131. Serial.println(ssid);
  132. WiFi.mode(WIFI_STA);
  133. WiFi.begin(ssid, pass);
  134. while (WiFi.status() != WL_CONNECTED) {
  135. delay(500);
  136. Serial.print(".");
  137. }
  138. Serial.println("");
  139. Serial.println("WiFi connected");
  140. //Serial.print("IP address: "); Serial.println(WiFi.localIP());
  141. //Serial.print("MAC: "); Serial.println(WiFi.macAddress());
  142. //Serial.print("Gateway:"); Serial.println(WiFi.gatewayIP());
  143. //Serial.print("AP MAC:"); Serial.println(WiFi.BSSIDstr());
  144.  
  145. notificar("Programa Iniciou");
  146.  
  147.  
  148. psClient.setServer(mqttServer, mqttPort);
  149. psClient.setCallback(callback);
  150. while (!psClient.connected()) {
  151. Serial.println("Connecting to MQTT...");
  152.  
  153. if (psClient.connect("ESP8266Client", mqttUser, mqttPassword )) {
  154.  
  155. Serial.println("connected to MQTT");
  156.  
  157. } else {
  158. Serial.print("failed with state ");
  159. Serial.print(psClient.state());
  160. delay(500);
  161.  
  162. }
  163. }
  164.  
  165. psClient.publish("liga", "desliga");
  166. psClient.subscribe("SENSOR");
  167.  
  168. Serial.println("----------------------------------------");
  169. Serial.println();
  170.  
  171. }
  172.  
  173.  
  174.  
  175. //FUNLÃO QUE ENVIA A NOTIFICAÇÃO PARA O PUSHBULLET
  176. void notificar(String message) {
  177. // Use WiFiClientSecure class to create TLS connection
  178. WiFiClientSecure client;
  179. Serial.print("connecting to ");
  180. Serial.println(host);
  181. if (!client.connect(host, httpsPort)) {
  182. Serial.println("connection failed");
  183. return;
  184. }
  185.  
  186. String url = "/v2/pushes";
  187. String messagebody = "{\"type\": \"note\", \"title\": \"Trabalho IoT\", \"body\": \""+message+"\"}\r\n";
  188. //messagebody += String(message);
  189. //messagebody += "\"}\r\n";
  190.  
  191. client.print(String("POST ") + url + " HTTP/1.1\r\n" +
  192. "Host: " + host + "\r\n" +
  193. "Authorization: Bearer " + PushBulletAPIKEY + "\r\n" +
  194. "Content-Type: application/json\r\n" +
  195. "Content-Length: " +
  196. String(messagebody.length()) + "\r\n\r\n");
  197. client.print(messagebody);
  198.  
  199. Serial.println("Requisicao enviada, verifique o celular");
  200. }
  201.  
  202.  
  203. void lerDados() {
  204. if (but0 != 0) {
  205. libera = 0; //Se o botao 0 for apertado libera recebe 0 e a funcao liberaRFI() eh chamada, consequentemente o sensoriamente eh bloaqueado
  206. Blynk.virtualWrite(V0, 1);
  207. }
  208. if (libera == 0) {
  209. Blynk.virtualWrite(V0, 1);
  210. but0 = 1;
  211. } else if (libera == 1) {
  212. Blynk.virtualWrite(V0, 0);
  213. but0 = 0;
  214. }
  215.  
  216. delay(100);
  217.  
  218. if (but1 != 0) { // Lê os valores do sensor 1 se o Botão Virtual 1 no Blynk estiver ativo
  219. digitalWrite(sensor1, HIGH); //passa corrente para o sensor 1
  220. sensorValue1 = analogRead(sensorPin);
  221. Serial.print("Temperatura: ");
  222. Serial.println(sensorValue1);
  223. digitalWrite(sensor1, LOW); //Desliga a corrente do sensor 1 para começar a passar para o proximo sensor
  224. } else { //Se o botão não estiver ativo a variavel do valor lido recebe zero o sensor eh pausado
  225. sensorValue1 = 0;
  226. Serial.println("Temperatura: Pausado");
  227. digitalWrite(sensor1, LOW); //Se o botao no Blynk estiver desligado nao eh passada corrente para o sensor
  228. }
  229. delay(100);
  230.  
  231.  
  232. if (but2 != 0) { // Lê os valores do sensor 2 se o Botão Virtual 2 no Blynk estiver ativo
  233. digitalWrite(sensor2, HIGH);
  234. sensorValue2 = analogRead(sensorPin);
  235. Serial.print("Potenciômetro: ");
  236. Serial.println(sensorValue2);
  237. digitalWrite(sensor2, LOW);
  238. } else { //Se o botão não estiver ativo a variavel do valor lido recebe zero o sensor eh pausado
  239. sensorValue2 = 0;
  240. digitalWrite(sensor2, LOW);
  241. Serial.println("Potenciômetro: Pausado");
  242. }
  243.  
  244. delay(100);
  245.  
  246.  
  247. if (but3 != 0) { //Lê os valores do sensor 3 se o Botão Virtual 3 no Blynk estiver ativo
  248. digitalWrite(sensor3, HIGH);
  249. sensorValue3 = analogRead(sensorPin);
  250. Serial.print("Luminosidade: ");
  251. Serial.println(sensorValue3);
  252. digitalWrite(sensor3, LOW);
  253. } else { //Se o botão não estiver ativo a variavel do valor lido recebe zero o sensor eh pausado
  254. sensorValue3 = 0;
  255. Serial.println("Luminosidade: Pausado");
  256. digitalWrite(sensor3, LOW);
  257. }
  258. delay(500);
  259. }
  260.  
  261. //float temp = sensorValue1;
  262. //float potenciometro = sensorValue2;
  263. //float luminosidade = sensorValue3;
  264.  
  265.  
  266.  
  267.  
  268. //FUNÇÃO QUE ENVIA OS DADOS PARA O APLICATIVO BLYNK
  269. void enviaBlynk() {
  270.  
  271. //Os botoes virtuais do Blynk estao utilizando as portas viruais 1, 2 e 3.
  272. //Para o valores do grafico que eh exibido no proprio aplicativo foram utilizadas as portas viruais 4, 5 e 6
  273.  
  274. Blynk.virtualWrite(V4, sensorValue1); //Envia os dados do sensor 1 para a porta Vitual 4
  275. Blynk.virtualWrite(V5, sensorValue2); //Envia os dados do sensor 1 para a porta Vitual 5
  276. Blynk.virtualWrite(V6, sensorValue3); //Envia os dados do sensor 1 para a porta Vitual 6
  277. }
  278.  
  279.  
  280.  
  281. //FUNÇÃO QUE ENVIA OS VALORES PARA O THINGSPEAK
  282. //Funcao tirada das aulas praticas da disciplina de IoT
  283. void enviaThingSpeak(int sensorValue1, int sensorValue2, int sensorValue3)
  284. {
  285. WiFiClient client;
  286.  
  287. if (client.connect(TS_SERVER, 80)) { // use ip 184.106.153.149 or api.thingspeak.com
  288. Serial.println("WiFi Client connected ");
  289.  
  290. String postStr = TS_API_KEY;
  291. postStr += "&field1=";
  292. postStr += String(sensorValue1);
  293. postStr += "&field2=";
  294. postStr += String(sensorValue2);
  295. postStr += "&field3=";
  296. postStr += String(sensorValue3);
  297.  
  298. postStr += "\r\n\r\n";
  299.  
  300.  
  301. client.print("POST /update HTTP/1.1\n");
  302. client.print("Host: api.thingspeak.com\n");
  303. client.print("Connection: close\n");
  304. client.print("X-THINGSPEAKAPIKEY: " + TS_API_KEY + "\n");
  305. client.print("Content-Type: application/x-www-form-urlencoded\n");
  306. client.print("Content-Length: ");
  307. client.print(postStr.length());
  308. client.print("\n\n");
  309. client.print(postStr);
  310.  
  311. }//end if
  312.  
  313. client.stop();
  314. delay(500);
  315.  
  316. }
  317.  
  318.  
  319.  
  320. //FUNCAO QUE DESLIGA OU LIGA OS SENSORES DE ACORDO COM A MENSAGEM RECEBIDA DO CLOUDMQTT
  321. void callback(char* topic, byte* payload, unsigned int length) {
  322.  
  323. Serial.print("Mensagem recebida no topico: ");
  324. Serial.println(topic);
  325.  
  326. Serial.print("Mensagem:");
  327. for (int i = 0; i < length; i++) {
  328. Serial.print((char)payload[i]);
  329. String msg;
  330. //obtem a string do payload recebido
  331. for (int i = 0; i < length; i++)
  332. {
  333. char c = (char)payload[i];
  334. msg += c;
  335. }
  336. Serial.println();
  337.  
  338.  
  339. //verifica se deve colocar nivel alto de tensão na saída se enviar L e digito, ou nivel baixo se enviar D e digito no topíco SENSOR
  340. if (msg.equals("L1"))
  341. {
  342. Blynk.virtualWrite(V1, 1); //liga o Botao Virtual 1 do Blynk
  343. but1 = 1; //Ativa o sensor 1 na funcao lerDados()
  344. notificar("Sensor 1 ligado pelo CloudMQTT");
  345. }
  346. if (msg.equals("D1"))
  347. {
  348. but1 = 0; //Pausa o sensor na funcao lerDados()
  349. Blynk.virtualWrite(V1, 0); //desliga o Botao Virtual 1 do Blynk
  350. notificar("Sensor 1 desligado pelo CloudMQTT");
  351. }
  352. if (msg.equals("L2"))
  353. {
  354. but2 = 1; //Ativa o sensor 2 na funcao lerDados()
  355. Blynk.virtualWrite(V2, 1); //liga o Botao Virtual 2 do Blynk
  356. notificar("Sensor 2 ligado pelo CloudMQTT");
  357. }
  358. if (msg.equals("D2"))
  359. {
  360. but2 = 0; //Pausa o sensor 2 na funcao lerDados()
  361. Blynk.virtualWrite(V2, 0); //desliga o Botao Virtual 2 do Blynk
  362. notificar("Sensor 2 desligado pelo CloudMQTT");
  363. }
  364.  
  365. if (msg.equals("L3"))
  366. {
  367. but3 = 1; //Ativa o sensor 3 na funcao lerDados()
  368. Blynk.virtualWrite(V3, 1); //liga o Botao Virtual 3 do Blynk
  369. notificar("Sensor 3 ligado pelo CloudMQTT");
  370. }
  371. if (msg.equals("D3"))
  372. {
  373. but3 = 0; //Pausa o sensor 3 na funcao lerDados()
  374. Blynk.virtualWrite(V3, 0); //desliga o Botao Virtual 3 do Blynk
  375. notificar("Sensor 3 desligado pelo CloudMQTT");
  376. }
  377.  
  378.  
  379. // Liga todos os sensores se enviar LT no topico SENSOR
  380. if (msg.equals("LT"))
  381. {
  382. //Ativa todos os sensores na funcao lerDados()
  383. but1 = 1;
  384. but2 = 1;
  385. but3 = 1;
  386. //liga todos Botos Virtuais do Blynk
  387. Blynk.virtualWrite(V1, 1);
  388. Blynk.virtualWrite(V2, 1);
  389. Blynk.virtualWrite(V3, 1);
  390. notificar("Todos os sensores foram ligados pelo CloudMQTT");
  391. }
  392.  
  393. // Desliga todos os sensores se enviar DT com o topico SENSOR
  394. if (msg.equals("DT"))
  395. {
  396. //Pausa todos os sensores na funcao lerDados
  397. but1 = 0;
  398. but2 = 0;
  399. but3 = 0;
  400. //Desliga todos os botoes Virtuais do Blynk
  401. Blynk.virtualWrite(V1, 0);
  402. Blynk.virtualWrite(V2, 0);
  403. Blynk.virtualWrite(V3, 0);
  404. notificar("Todos os sensores foram desligados pelo CloudMQTT");
  405. }
  406.  
  407. //Bloqueia o sensores com o RFID
  408. if (msg.equals("B"))
  409. {
  410. notificar("Os sensores foram bloqueados pelo CloudMQTT! Aproxime o Cartão RFID para desbloquear!!!");
  411. libera = 0;
  412. Blynk.virtualWrite(V0, 1);
  413. but0 = 1;
  414. }
  415. }
  416.  
  417. delay(500);
  418. Serial.println();
  419. Serial.println("=================");
  420.  
  421. }
  422.  
  423.  
  424.  
  425.  
  426. //======= FUNCAO PARA DESBLOQUAR O SENSORIAMENTO PELO RFID ===========//
  427. //Adaptada do site: http://www.instructables.com/id/MFRC522-RFID-Reader-Interfaced-With-NodeMCU/
  428. void liberaRFID() {
  429.  
  430. //Enquanto estiver bloqueado o botao Virtual 0 permanecerá ligado
  431. if (libera == 0) {
  432. Blynk.virtualWrite(V0, 1);
  433. but0 = 0;
  434. }
  435. SPI.begin(); // Initiate SPI bus
  436. mfrc522.PCD_Init(); // Initiate MFRC522
  437.  
  438. // Procura por cartoes
  439. if ( ! mfrc522.PICC_IsNewCardPresent())
  440. {
  441. return;
  442. }
  443.  
  444. // Seleciona apenas um dos cartoes, caso haja mais de um
  445. if ( ! mfrc522.PICC_ReadCardSerial())
  446. {
  447. return;
  448. }
  449.  
  450. Serial.println();
  451. Serial.print("UID tag : ");
  452. String content = "";
  453. byte letter;
  454.  
  455. for (byte i = 0; i < mfrc522.uid.size; i++) {
  456. Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
  457. Serial.print(mfrc522.uid.uidByte[i], HEX);
  458. content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
  459. content.concat(String(mfrc522.uid.uidByte[i], HEX));
  460. }
  461.  
  462. content.toUpperCase();
  463.  
  464. Serial.println();
  465.  
  466. if (content.substring(1) == "3E 52 B4 79") //change UID of the card that you want to give access
  467. {
  468. Serial.println("Acesso Liberado!!! ");
  469. Serial.println("Bem vindo!");
  470. libera = 1;
  471. Blynk.virtualWrite(V0, 0); //Quando for desbloqueado o botao virtual 0 sera desligado
  472. but0 == 0;
  473. Serial.println();
  474.  
  475. notificar("Sensores desbloqueados");
  476.  
  477. //statuss = 1;
  478. } else {
  479. Serial.println("Acesso Negado!!! ");
  480. Serial.println("Tente Novamente!!! ");
  481. Blynk.virtualWrite(V0, 1);
  482. but0 == 1;
  483. libera = 0;
  484. delay(500);
  485. }
  486.  
  487. }
  488.  
  489.  
  490.  
  491.  
  492. void loop()
  493. {
  494. liberaRFID();
  495. while (libera != 0) {
  496. Blynk.run();
  497. psClient.loop();
  498. lerDados();
  499.  
  500. //Enviamos os dados lidos para o Blynk
  501. timer.setInterval(1000L, enviaBlynk);
  502. //Serial.println("Dados enviados para o Thingspeak");
  503.  
  504. //Enviamos os dados lidos para o ThingSpeak
  505. enviaThingSpeak(sensorValue1, sensorValue2, sensorValue3);
  506. //Serial.println("Dados enviados para o Thingspeak");
  507.  
  508. //timer.run();
  509.  
  510. Serial.println("----------------------------------------");
  511. }
  512.  
  513. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement