Last active
January 9, 2020 14:38
-
-
Save luandro/2c34a5711e16e76373619390c8db296b to your computer and use it in GitHub Desktop.
comuREDE firmware for esp8622
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//MESH-UP Trabalho Final | |
//IFRJ Niterói - Turma ARDUINO (manha) - Professor Luiz Felipe | |
//Grupo: Bruno Souza, Felipe Monteiro e Filipe Rimes | |
//Fontes: | |
//#Programa: NodeMCU e MQTT - Controle e Monitoramento IoT | |
//#Autor: Pedro Bertoleti | |
//code write by Moz for YouTube changel LogMaker360, 7-10-2015 | |
//code belongs to this video: https://www.youtube.com/watch?v=jTj1oMyJF_c | |
//KY018 Photo resistor module | |
//https://tkkrlab.nl/wiki/Arduino_KY-018_Photo_resistor_module | |
// reading liquid flow rate using Seeeduino and Water Flow Sensor from Seeedstudio.com | |
// Code adapted by Charles Gantt from PC Fan RPM code written by Crenn @thebestcasescenario.com | |
// http:/themakersworkbench.com http://thebestcasescenario.com http://seeedstudio.com | |
//An example showing how to put ESP8266 into Deep-sleep mode | |
//https://www.losant.com/blog/making-the-esp8266-low-powered-with-deep-sleep | |
//Como utilizar o LED RGB - By Ezequiel Demetras | |
//https://portal.vidadesilicio.com.br/como-utilizar-o-led-rgb-com-arduino/ | |
//Programação do ESP8266 via OTA com wifi | |
//https://www.filipeflop.com/blog/programacao-esp8266-ota-wifi/ | |
//Carrega as bibliotecas | |
#include <ESP8266WiFi.h> // Importa a Biblioteca ESP8266WiFi | |
#include <PubSubClient.h> // Importa a Biblioteca PubSubClient | |
#include <ESP8266mDNS.h> // Importa a Biblioteca BasicOTA | |
#include <WiFiUdp.h> // Importa a Biblioteca BasicOTA | |
#include <ArduinoOTA.h> // Importa a Biblioteca BasicOTA | |
//defines: | |
//defines de id mqtt e tópicos para publicação e subscribe | |
#define TOPICO_SUBSCRIBE "TESTE" //tópico MQTT de escuta | |
#define TOPICO_PUBLISH "AGUA" //tópico MQTT de envio de informações para Broker | |
//IMPORTANTE: recomendamos fortemente alterar os nomes | |
// desses tópicos. Caso contrário, há grandes | |
// chances de você controlar e monitorar o NodeMCU | |
// de outra pessoa. | |
#define ID_MQTT "D1 Mini_AGUA_PROD_v02_Filipe" //id mqtt (para identificação de sessão) | |
//#define ID_MQTT "NodeMCU_AGUA_PROD_v02_Filipe" //id mqtt (para identificação de sessão) | |
//IMPORTANTE: este deve ser único no broker (ou seja, | |
// se um client MQTT tentar entrar com o mesmo | |
// id de outro já conectado ao broker, o broker | |
// irá fechar a conexão de um deles). | |
//Modificado por Filipe | |
//defines - mapeamento de pinos do NodeMCU | |
#define D0 16 | |
#define D1 5 // I2C Bus SCL (clock) | |
#define D2 4 // I2C Bus SDA (data) | |
#define D3 0 | |
#define D4 2 // Same as "LED_BUILTIN", but inverted logic | |
#define D5 14 // SPI Bus SCK (clock) | |
#define D6 12 // SPI Bus MISO | |
#define D7 13 // SPI Bus MOSI | |
#define D8 15 // SPI Bus SS (CS) | |
#define D9 3 // RX0 (Serial console) | |
#define D10 1 // TX0 (Serial console) | |
//Modificado por Filipe - http://autocorerobotica.blog.br/monitoramento-de-ambiente-com-nodemcu/ | |
//Setando a utilizaçâo do LDR à porta ADC A0 do Nodemcu | |
//int ldr = 0; | |
//variável para armazenar a leitura do ldr. | |
//int valorldr = 0; | |
//Modificado por Filipe | |
volatile int NbTopsFan; //measuring the rising edges of the signal | |
int Calc; | |
int hallsensor = 0; //The pin location of the sensor | |
void rpm () //This is the function that the interupt calls | |
{ | |
NbTopsFan++; //This function measures the rising and falling edge of the hall effect sensors signal | |
} | |
// WIFI | |
//const char* SSID = "comuREDE >> Internet Gratis <<"; // SSID / nome da rede WI-FI que deseja se conectar | |
//const char* PASSWORD = ""; // Senha da rede WI-FI que deseja se conectar | |
const char* ssid = "comuREDE >> Internet Gratis <<"; | |
const char* password = ""; | |
// MQTT | |
const char* BROKER_MQTT = "10.62.63.50"; //URL do broker MQTT que se deseja utilizar | |
int BROKER_PORT = 1883; // Porta do Broker MQTT | |
//Login MQTT | |
//Modificado por Filipe em 020818 - https://techtutorialsx.com/2017/04/09/esp8266-connecting-to-mqtt-broker/ | |
//const char* mqttUser = "ljzfyihh"; | |
//const char* mqttPassword = "EoDmU2Nkr9CN"; | |
//Leds Indicativos | |
const int azul = 13; | |
const int verde = 12; | |
const int vermelho = 14; | |
String cor; | |
//Variáveis e objetos globais | |
WiFiClient espClient; // Cria o objeto espClient | |
PubSubClient MQTT(espClient); // Instancia o Cliente MQTT passando o objeto espClient | |
char EstadoSaida = '0'; //variável que armazena o estado atual da saída | |
//Modificado por Filipe - http://autocorerobotica.blog.br/monitoramento-de-ambiente-com-nodemcu/ | |
char EstadoEntrada = '0'; | |
//Prototypes | |
//Implementações das funções | |
//void initSerial(); | |
void initWiFi(); | |
void initMQTT(); | |
void reconectWiFi(); | |
void mqtt_callback(char* topic, byte* payload, unsigned int length); | |
void VerificaConexoesWiFIEMQTT(void); | |
void InitOutput(void); | |
void setup() { | |
Serial.begin(9600); | |
//Leds Indicativos | |
pinMode(azul, OUTPUT); | |
pinMode(verde, OUTPUT); | |
pinMode(vermelho, OUTPUT); | |
Serial.println(" >>> Iniciando..."); | |
WiFi.mode(WIFI_STA); | |
WiFi.begin(ssid, password); | |
while (WiFi.waitForConnectResult() != WL_CONNECTED) { | |
Serial.println("Falha na conexão! Reiniciando..."); | |
vermelhoFuncao(); | |
delay(5000); | |
ESP.restart(); | |
} | |
// Port defaults to 8266 | |
// ArduinoOTA.setPort(8266); | |
// Hostname defaults to esp8266-[ChipID] | |
// ArduinoOTA.setHostname("myesp8266"); | |
// No authentication by default | |
// ArduinoOTA.setPassword("admin"); | |
// Password can be set with it's md5 value as well | |
// MD5(admin) = 21232f297a57a5a743894a0e4a801fc3 | |
// ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3"); | |
//TRADUZIDO: | |
// Porta padrao do ESP8266 para OTA eh 8266 - Voce pode mudar ser quiser, mas deixe indicado! | |
// ArduinoOTA.setPort(8266); | |
// O Hostname padrao eh esp8266-[ChipID], mas voce pode mudar com essa funcao | |
// ArduinoOTA.setHostname("nome_do_meu_esp8266"); | |
// Nenhuma senha eh pedida, mas voce pode dar mais seguranca pedindo uma senha pra gravar | |
// ArduinoOTA.setPassword((const char *)"123"); | |
ArduinoOTA.onStart([]() { | |
String type; | |
if (ArduinoOTA.getCommand() == U_FLASH) | |
type = "sketch"; | |
else // U_SPIFFS | |
type = "filesystem"; | |
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() | |
Serial.println("Atualizando " + type); | |
}); | |
ArduinoOTA.onEnd([]() { | |
Serial.println("\nFim"); | |
}); | |
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { | |
Serial.printf("Progress: %u%%\r", (progress / (total / 100))); | |
}); | |
ArduinoOTA.onError([](ota_error_t error) { | |
Serial.printf("Error[%u]: ", error); | |
if (error == OTA_AUTH_ERROR) Serial.println("Autenticação Falhou"); | |
else if (error == OTA_BEGIN_ERROR) Serial.println("Falha no Início"); | |
else if (error == OTA_CONNECT_ERROR) Serial.println("Falha na Conexão"); | |
else if (error == OTA_RECEIVE_ERROR) Serial.println("Falha na Recepção"); | |
else if (error == OTA_END_ERROR) Serial.println("Falha no Fim"); | |
}); | |
ArduinoOTA.begin(); | |
Serial.println("Pronto"); | |
Serial.print("Endereco IP: "); | |
Serial.println(WiFi.localIP()); | |
//inicializações: | |
InitOutput(); | |
initWiFi(); | |
initMQTT(); | |
/* initSerial(); | |
Serial.setTimeout(2000); | |
while(!Serial) { } | |
Serial.println("Estou acordado."); | |
*/ | |
pinMode(hallsensor, INPUT); //initializes digital pin 2 as an input | |
attachInterrupt(0, rpm, RISING); //and the interrupt is attached | |
// the loop() method runs over and over again, | |
// as long as the Arduino has powers | |
} | |
//Leds Indicativos | |
//Funções responsáveis por executar o brilho selecionado | |
void vermelhoFuncao(){ | |
digitalWrite(azul, LOW); | |
digitalWrite(verde, LOW); | |
digitalWrite(vermelho, HIGH); | |
} | |
void azulFuncao(){ | |
digitalWrite(azul, HIGH); | |
digitalWrite(verde, LOW); | |
digitalWrite(vermelho, LOW); | |
} | |
void verdeFuncao(){ | |
digitalWrite(azul, LOW); | |
digitalWrite(verde, HIGH); | |
digitalWrite(vermelho, LOW); | |
} | |
void verdeApaga(){ | |
digitalWrite(azul, LOW); | |
digitalWrite(verde, LOW); | |
digitalWrite(vermelho, LOW); | |
} | |
void amareloFuncao(){ | |
analogWrite(azul, 0); | |
analogWrite(verde, 50); | |
analogWrite(vermelho, 255); | |
} | |
void roxoFuncao(){ | |
analogWrite(azul, 207); | |
analogWrite(verde, 0); | |
analogWrite(vermelho, 255); | |
} | |
void brancoFuncao(){ | |
digitalWrite(azul, HIGH); | |
digitalWrite(verde, HIGH); | |
digitalWrite(vermelho, HIGH); | |
} | |
//Função: inicializa e conecta-se na rede WI-FI desejada | |
//Parâmetros: nenhum | |
//Retorno: nenhum | |
void initWiFi() | |
{ | |
delay(10); | |
// Serial.println("------Conexao WI-FI------"); | |
// Serial.print("Conectando-se na rede: "); | |
Serial.print("Conectado a rede: "); | |
Serial.println(ssid); | |
amareloFuncao(); | |
Serial.println("Aguarde"); | |
reconectWiFi(); | |
} | |
//Função: inicializa parâmetros de conexão MQTT(endereço do | |
// broker, porta e seta função de callback) | |
//Parâmetros: nenhum | |
//Retorno: nenhum | |
void initMQTT() | |
{ | |
MQTT.setServer(BROKER_MQTT, BROKER_PORT); //informa qual broker e porta deve ser conectado | |
MQTT.setCallback(mqtt_callback); //atribui função de callback (função chamada quando qualquer informação de um dos tópicos subescritos chega) | |
} | |
//Função: função de callback | |
// esta função é chamada toda vez que uma informação de | |
// um dos tópicos subescritos chega) | |
//Parâmetros: nenhum | |
//Retorno: nenhum | |
void mqtt_callback(char* topic, byte* payload, unsigned int length) | |
{ | |
String msg; | |
//obtem a string do payload recebido | |
for(int i = 0; i < length; i++) | |
{ | |
char c = (char)payload[i]; | |
msg += c; | |
} | |
//toma ação dependendo da string recebida: | |
//verifica se deve colocar nivel alto de tensão na saída D0: | |
//IMPORTANTE: o Led já contido na placa é acionado com lógica invertida (ou seja, | |
//enviar HIGH para o output faz o Led apagar / enviar LOW faz o Led acender) | |
if (msg.equals("L")) | |
{ | |
digitalWrite(D0, LOW); | |
EstadoSaida = '1'; | |
} | |
//verifica se deve colocar nivel alto de tensão na saída D0: | |
if (msg.equals("D")) | |
{ | |
digitalWrite(D0, HIGH); | |
EstadoSaida = '0'; | |
} | |
} | |
//Função: reconecta-se ao broker MQTT (caso ainda não esteja conectado ou em caso de a conexão cair) | |
// em caso de sucesso na conexão ou reconexão, o subscribe dos tópicos é refeito. | |
//Parâmetros: nenhum | |
//Retorno: nenhum | |
void reconnectMQTT() | |
{ | |
while (!MQTT.connected()) | |
{ | |
Serial.print("* Tentando se conectar ao Broker MQTT: "); | |
Serial.println(BROKER_MQTT); | |
// if (MQTT.connect(ID_MQTT)) | |
// if (client.connect("ESP8266Client", mqttUser, mqttPassword )) | |
// if (MQTT.connect(ID_MQTT, mqttUser, mqttPassword )) | |
if (MQTT.connect(ID_MQTT)) | |
{ | |
Serial.println("Conectado com sucesso ao broker MQTT!"); | |
// if(!MQTT.connected()){ //Modificado por Filipe em 040818 | |
// verdeFuncao(); | |
// } | |
if(MQTT.connected()){ | |
verdeFuncao(); | |
delay(2000); | |
verdeApaga(); | |
} | |
MQTT.subscribe(TOPICO_SUBSCRIBE); | |
} | |
else | |
{ | |
Serial.println("Falha ao reconectar no broker."); | |
if (WiFi.status() == WL_CONNECTED) amareloFuncao(); | |
else vermelhoFuncao(); | |
Serial.println("Havera nova tentatica de conexao em 2s"); | |
delay(2000); | |
} | |
} | |
} | |
//Função: reconecta-se ao WiFi | |
//Parâmetros: nenhum | |
//Retorno: nenhum | |
void reconectWiFi() | |
{ | |
//se já está conectado a rede WI-FI, nada é feito. | |
//Caso contrário, são efetuadas tentativas de conexão | |
if (WiFi.status() == WL_CONNECTED) | |
return; | |
vermelhoFuncao(); | |
WiFi.begin(ssid, password); // Conecta na rede WI-FI | |
while (WiFi.status() != WL_CONNECTED) | |
{ | |
delay(100); | |
Serial.print("."); | |
vermelhoFuncao(); | |
} | |
Serial.println(); | |
Serial.print("Conectado com sucesso na rede "); | |
Serial.print(ssid); | |
Serial.println("IP obtido: "); | |
Serial.println(WiFi.localIP()); | |
} | |
//Função: verifica o estado das conexões WiFI e ao broker MQTT. | |
// Em caso de desconexão (qualquer uma das duas), a conexão | |
// é refeita. | |
//Parâmetros: nenhum | |
//Retorno: nenhum | |
void VerificaConexoesWiFIEMQTT(void) | |
{ | |
if (!MQTT.connected()) reconnectMQTT(); //se não há conexão com o Broker, a conexão é refeita | |
reconectWiFi(); //se não há conexão com o WiFI, a conexão é refeita | |
} | |
//Modificado por Filipe - http://autocorerobotica.blog.br/monitoramento-de-ambiente-com-nodemcu/ | |
//Função: envia ao Broker o estado atual do input | |
//Parâmetros: nenhum | |
//Retorno: nenhum | |
void EnviaEstadoInputMQTT(void) | |
{ | |
if (Calc < 15) | |
MQTT.publish(TOPICO_PUBLISH, "D"); | |
if (Calc > 16) | |
MQTT.publish(TOPICO_PUBLISH, "L"); | |
Serial.println("Estado do sensor ÁGUA enviado ao broker!"); | |
delay(500); | |
} | |
//Função: inicializa o output em nível lógico baixo | |
//Parâmetros: nenhum | |
//Retorno: nenhum | |
void InitOutput(void) | |
{ | |
//IMPORTANTE: o Led já contido na placa é acionado com lógica invertida (ou seja, | |
//enviar HIGH para o output faz o Led apagar / enviar LOW faz o Led acender) | |
pinMode(D0, OUTPUT); | |
digitalWrite(D0, HIGH); | |
} | |
//programa principal | |
void loop() { | |
ArduinoOTA.handle(); | |
//garante funcionamento das conexões WiFi e ao broker MQTT | |
VerificaConexoesWiFIEMQTT(); | |
// | |
/* | |
//envia o status de todos os outputs para o Broker no protocolo esperado | |
EnviaEstadoOutputMQTT(); | |
*/ | |
// //keep-alive da comunicação com broker MQTT | |
MQTT.loop(); | |
//Modificado por Filipe - | |
//fazer leitura de pino declarado e armazenar em variável | |
// | |
/* | |
valorldr = analogRead(ldr); | |
Serial.println(valorldr); | |
delay(2000); | |
*/ | |
// | |
NbTopsFan = 0; //Set NbTops to 0 ready for calculations | |
sei(); //Enables interrupts | |
delay (500); //Wait 1 second | |
cli(); //Disable interrupts | |
Calc = (NbTopsFan * 60 / 7.5); //(Pulse frequency x 60) / 7.5Q, = flow rate in L/hour | |
Serial.print (Calc, DEC); //Prints the number calculated above | |
Serial.print (" L/hour\r\n"); //Prints "L/hour" and returns a new line | |
// | |
// //Modificado por Filipe - http://autocorerobotica.blog.br/monitoramento-de-ambiente-com-nodemcu/ | |
EnviaEstadoInputMQTT(); | |
delay (59000); | |
//Serial.println("Entrando em deep sleep por 59 segundos"); | |
//ESP.deepSleep(59e6); // 59e6 is 59 microseconds | |
// | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment