Skip to content

Commit

Permalink
Merge pull request #16 from taffarel55/taffarel55/newSugestionModules
Browse files Browse the repository at this point in the history
Sugestao do Modulo 3 + Sugestao e esboço da projeto do 4
  • Loading branch information
freedxmgxd committed Mar 11, 2022
2 parents cb7540b + 4da9973 commit 51cb1e6
Show file tree
Hide file tree
Showing 9 changed files with 328 additions and 0 deletions.
9 changes: 9 additions & 0 deletions Módulo 3/3. Platformio + OTA/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Sugestão:

Mostrar como utilizar o Platformio em um projeto, um bacana de se usar seria como programar o ESP remotamente via OTA!

Esses dois carinhas fazem todo o sentido!

O platformio por trabalhar com um ambiente de dev com mts beneficios, gerenciamento de libs e tal

E o projeto programando via OTA (sem cabo) tem mts benefícios, atualizar o PET Status dentro da caixa de acrílico por exemplo!
5 changes: 5 additions & 0 deletions Módulo 3/4. Protocolo MQTT/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
10 changes: 10 additions & 0 deletions Módulo 3/4. Protocolo MQTT/.vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}
Empty file.
39 changes: 39 additions & 0 deletions Módulo 3/4. Protocolo MQTT/include/README
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

This directory is intended for project header files.

A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.

```src/main.c

#include "header.h"

int main (void)
{
...
}
```

Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.

In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.

Read more about using header files in official GCC documentation:

* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes

https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html
46 changes: 46 additions & 0 deletions Módulo 3/4. Protocolo MQTT/lib/README
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@

This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.

The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").

For example, see a structure of the following two libraries `Foo` and `Bar`:

|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c

and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>

int main (void)
{
...
}

```

PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.

More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html
16 changes: 16 additions & 0 deletions Módulo 3/4. Protocolo MQTT/platformio.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html

[env:nodemcu-32s]
platform = espressif32
board = nodemcu-32s
framework = arduino
monitor_speed = 115200
lib_deps = knolleary/PubSubClient@^2.8
192 changes: 192 additions & 0 deletions Módulo 3/4. Protocolo MQTT/src/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
// Programa: comunicação MQTT com ESP32
// Autor: Pedro Bertoleti
// Alguns comentários adicionados por: Maurício Taffarel (taffarel55)
// https://www.newtoncbraga.com.br/index.php/microcontroladores/143-tecnologia/17117-comunicando-se-via-mqtt-com-o-esp32-mic404.html

/* Headers */
#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h> // Documentação: https://pubsubclient.knolleary.net/api

/* Defines do MQTT */
#define TOPICO_SUBSCRIBE "taffarel55_recebe_informacao"
#define TOPICO_PUBLISH "taffarel55_envia_informacao"
#define ID_MQTT "taffarel55_Cliente_MQTT"

/* Variáveis e constantes globais */
const char *SSID = "HUAWEI-2.4G-Uppx";
const char *PASSWORD = "eBTPrJ4a";

/* Configurações do Broker */
const char *BROKER_MQTT = "broker.hivemq.com";
int BROKER_PORT = 1883;

/* Variáveis e objetos globais */
// https://pubsubclient.knolleary.net/api#PubSubClient1
WiFiClient espClient; // client - the network client to use, for example WiFiClient
PubSubClient MQTT(espClient); // Creates a partially initialised client instance.

// Prototypes
void init_serial(void);
void init_wifi(void);
void init_mqtt(void);
void reconnect_wifi(void);
void mqtt_callback(char *topic, byte *payload, unsigned int length);
void verifica_conexoes_wifi_mqtt(void);

/*
* Implementações das funções
*/
void setup()
{
init_serial();
init_wifi();
init_mqtt();
}

/* Função: inicializa comunicação serial com baudrate 115200 (para fins de monitorar no terminal serial
* o que está acontecendo.
* Parâmetros: nenhum
* Retorno: nenhum
*/
void init_serial()
{
Serial.begin(115200);
}

/* Função: inicializa e conecta-se na rede WI-FI desejada
* Parâmetros: nenhum
* Retorno: nenhum
*/
void init_wifi(void)
{
delay(10);
Serial.println("------ Conexao WI-FI ------");
Serial.print("Conectando-se na rede: ");
Serial.println(SSID);
Serial.println("Aguarde");
reconnect_wifi();
}

/* 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 init_mqtt(void)
{
/* informa a qual broker e porta deve ser conectado */
// https://pubsubclient.knolleary.net/api#PubSubClient1
MQTT.setServer(BROKER_MQTT, BROKER_PORT); // client.setServer("broker.example.com",1883);

/* atribui função de callback (quando qualquer informação do tópico subescrito chega) */
// https://pubsubclient.knolleary.net/api#setCallback
MQTT.setCallback(mqtt_callback); // PubSubClient* setCallback (callback)
}

/* 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
* */

// https://pubsubclient.knolleary.net/api#callback
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;
}
Serial.print("[MQTT] Mensagem recebida: ");
Serial.println(msg);
}

/* 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 reconnect_mqtt(void)
{
while (!MQTT.connected())
{
Serial.print("* Tentando se conectar ao Broker MQTT: ");
Serial.println(BROKER_MQTT);
if (MQTT.connect(ID_MQTT))
{
Serial.println("Conectado com sucesso ao broker MQTT!");
MQTT.subscribe(TOPICO_SUBSCRIBE);
}
else
{
Serial.println("Falha ao reconectar no broker.");
Serial.println("Havera nova tentatica de conexao em 2s");
delay(2000);
}
}
}

/* Função: reconecta-se ao WiFi
* Parâmetros: nenhum
* Retorno: nenhum
*/
void reconnect_wifi()
{
/* 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;

WiFi.begin(SSID, PASSWORD);

while (WiFi.status() != WL_CONNECTED)
{
delay(100);
Serial.print(".");
}

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 verifica_conexoes_wifi_mqtt(void)
{
/* se não há conexão com o WiFI, a conexão é refeita */
reconnect_wifi();
/* se não há conexão com o Broker, a conexão é refeita */
if (!MQTT.connected())
reconnect_mqtt();
}

/* programa principal */
void loop()
{
/* garante funcionamento das conexões WiFi e ao broker MQTT */
verifica_conexoes_wifi_mqtt();

/* Envia frase ao broker MQTT */
// https://pubsubclient.knolleary.net/api#publish
MQTT.publish(TOPICO_PUBLISH, "ESP32 se comunicando com MQTT");
// boolean publish (topic, payload, [length], [retained])

/* keep-alive da comunicação com broker MQTT */
// https://pubsubclient.knolleary.net/api#loop
MQTT.loop();

/* Agurda 1 segundo para próximo envio */
delay(1000);
}
11 changes: 11 additions & 0 deletions Módulo 3/4. Protocolo MQTT/test/README
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

This directory is intended for PlatformIO Unit Testing and project tests.

Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.

More information about PlatformIO Unit Testing:
- https://docs.platformio.org/page/plus/unit-testing.html

0 comments on commit 51cb1e6

Please sign in to comment.