U-BLOX NINA W106 ACESSANDO THINGSTREAM.IO - SSL
O objetivo deste BLOG é mostrar um exemplo em ARDUINO (Platformio) que permite o NINA W106 se comunicar com um servidor MQTT da U-BLOX (mqtt.thingstream.io) via WIFI, pela porta 8883 (SSL).
O programa vai publicar um dado (Random) no ThingStream e obtê-lo novamente via CALLBACK.
Utilize a programação clássica com Sockets do Arduino!
Utilize a programação clássica com Sockets do Arduino!
MQTT
Para os dispositivos de Internet das Coisas (IoT), a conexão com a Internet é um requisito. A conexão com a Internet permite que os dispositivos trabalhem entre si e com serviços de backend. O protocolo de rede subjacente da Internet é o TCP/IP. Desenvolvido com base na pilha TCP/IP, o MQTT (Message Queue Telemetry Transport) tornou-se o padrão para comunicações de IoT.
Implementa também SSL e SN-MQTT
Adquirimos então os seguintes componentes
-Botão de RESET;
-Botão de Modo BOOTLOADER (W106);
-Plugável no PROTOBOARD;
-Acesso às várias GPIOS;
Pequena
1) Baixe e instale o Visual Studio Code
2) Execute o Visual Studio Code
3) Na opção EXTENSIONS (canto esquerdo), procure por PlatformIO e Instale. Aguarde!
4) Uma vez instalado o PlatformIO, vá em PIO Home e crie um Novo Projeto e digite os parâmetros abaixo e então Finish
Aguarde alguns minutos para instalação do SDK. A instalação do SDK ficará em
C:\Users\USER\.platformio>
e os fontes em
C:\Users\USER\Documents\PlatformIO\Projects\pisca\src\main.cpp
5) Na opção EXPLORER você verá o projeto e o código fonte (Arduino Sintax).
6) Observe o arquivo Platformio.ini que foi criado, você pode futuramente mudar para aceitar outro tipo de framework, como exemplo, Arduino.
[env:nina_w10]
platform = espressif32
board = nina_w10
framework = arduino
lib_deps = knolleary/pubsubclient
#board_build.partitions = src/minimal.csv (original para W102)
upload_speed = 921600
Abra o exemplo
Altere config-example.h
/*
WiFi config
*/
const char *WLAN_SSID[] = {"Andreia Oi Miguel 2.4G"};
const char *WLAN_PASS[] = {"xxxxxxxx"};
const int NUM_WLANS = 1; //number of Wifi Options
/*
MQTT settings ThingStream
Topic to Store the Efento Data
*/
const char *MQTT_PREFIX_TOPIC = "esp32-sniffer/";
const char *MQTT_ANNOUNCE_TOPIC = "/status";
const char *MQTT_CONTROL_TOPIC = "/control";
const char *MQTT_BLE_TOPIC = "/ble";
const int MQTT_PORT = 8883; //if you use SSL //1883 no SSL
// GOT FROM ThingsStream!
const char *MQTT_SERVER = "mqtt.thingstream.io";
const char *MQTT_USER = "xxxxxxxxxxxxxxxxxxxxxxxxxx;
const char *MQTT_PASS = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char *MQTT_CLIENT_ID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
Com os dados obtidos do THINGSTREAM
Código final
/*
* Hardware target:
* NINA W106
*
* IDE setup:
* Board: ESP32 Dev Module
* CPU frequency: 240MHz (WiFi/BT)
* Flash frequency: 80MHz
* Flash size: 2MB (16Mb)
* Partition scheme: Huge App (1,5MB No OTA/<1MB SPIFFS)
*
*
* TODO:
* #minival.csv (Para NINA W102)
* #Name, Type, SubType, Offset, Size, Flags
* #nvs, data, nvs, 0x9000, 0x5000,
* #otadata, data, ota, 0xe000, 0x2000,
* #app0, app, ota_0, 0x10000, 0x180000,
* #spiffs, data, spiffs, 0x190000, 0x70000,
*
*
*/
/*
SSL
*/
#include <WiFiClientSecure.h>
/*
NO SSL
#include <WiFi.h>
*/
#include <WiFiUdp.h>
#include <WiFiMulti.h>
#include <PubSubClient.h>
#include <Arduino.h>
#define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00) >> 8) + (((x)&0xFF) << 8))
/*
* configuration includes passwords/etc
* include separately to not leak private information
*/
#include "config-example.h"
/*
* globals
*/
String topic;
uint8_t mac[6];
String my_mac;
/*
blink-per-message housekeeping
*/
int nBlinks = 0;
bool led_state = 1;
bool in_blink = false;
unsigned long last_blink = 0;
//SSL
WiFiClientSecure wifi; //wifiSecure
/*
No SSL
WifiClient wifi;
*/
WiFiMulti wifiMulti; // use multiple wifi options
PubSubClient mqtt(wifi); //wifiSecure
void check_mqtt();
/*
* Given a byte array of length (n), return the ASCII hex representation
* and properly zero pad values less than 0x10.
* String(0x08, HEX) will yield '8' instead of the expected '08' string
*/
String hexToStr(uint8_t* arr, int n)
{
String result;
for (int i = 0; i < n; ++i) {
if (arr[i] < 0x10) {result += '0';}
result += String(arr[i], HEX);
}
return result;
}
/*
This function send Random numbers to ThingStream
*/
void Send_Mqtt_Data()
{
//Publish if mqtt connected
if (mqtt.connected())
{
//Mount Json do Publish
String msg = "{";
msg.reserve(256);
msg.concat("\"MAC\":\"");
msg.concat(String(WiFi.macAddress()));
msg.concat("\",");
msg.concat("\"TMP\":\"");
msg.concat(String(random(20,40)));
msg.concat("\",");
// trim the final comma to ensure valid JSON
if (msg.endsWith(",")) {
msg.remove(msg.lastIndexOf(","));
}
msg.concat("}");
Serial.println("Publish json Data to MQTT");
Serial.println(msg);
mqtt.beginPublish(topic.c_str(), msg.length(), false);
mqtt.print(msg.c_str());;
Serial.println("Done");
//Make the Led blinks
nBlinks += 1;
}
}
/*
* Called whenever a payload is received from a subscribed MQTT topic
*/
void mqtt_receive_callback(char* topic, byte* payload, unsigned int length) {
Serial.print("ThingStream MQTT-receive [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
/*
Switch on the LED if an 1 was received as first character
*/
if ((char)payload[0] == '1') {
led_state = 0;
} else {
led_state = 1;
}
/*
this will effectively be a half-blink, forcing the LED to the
requested state
*/
nBlinks += 1;
}
/*
* Check WiFi connection, attempt to reconnect.
* This blocks until a connection is (re)established.
*/
void check_wifi()
{
if (WiFi.status() != WL_CONNECTED) {
Serial.print("WiFi connection lost, reconnecting");
while (wifiMulti.run() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
}
/*
* Check the MQTT connection state and attempt to reconnect.
* If we do reconnect, then subscribe to MQTT_CONTROL_TOPIC and
* make an announcement to MQTT_ANNOUNCE_TOPIC with the WiFi SSID and
* local IP address.
*/
void check_mqtt()
{
if (mqtt.connected()) { return; }
// reconnect
Serial.print("ThingStream MQTT reconnect...");
// Attempt to connect
int connect_status = mqtt.connect(MQTT_CLIENT_ID, MQTT_USER, MQTT_PASS,
(MQTT_PREFIX_TOPIC + my_mac + MQTT_ANNOUNCE_TOPIC).c_str(),2, false,"");
if (connect_status) {
Serial.println("connected");
Serial.println();
/*
Subscribe if you want, to receive some CALL BACK
*/
Serial.println("Subscribed to topic ");
Serial.println(topic.c_str());
mqtt.subscribe(topic.c_str());
} else {
Serial.print("failed, rc=");
Serial.println(mqtt.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
/*
Start
*/
void setup() {
Serial.begin(9600);
Serial.println();
Serial.println("Mqtt ThingStream");
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, led_state);
/*
* setup WiFi
*/
//WiFi.mode(WIFI_STA);
for (int i=0; i<NUM_WLANS; i++) {
wifiMulti.addAP(WLAN_SSID[i], WLAN_PASS[i]);
}
WiFi.macAddress(mac);
my_mac = hexToStr(mac, 6); //To use to Topic, without ":"
Serial.print("MAC: ");
Serial.println(String(WiFi.macAddress()));
while (wifiMulti.run() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
//if you use SSL
wifi.setCACert(root_ca);
/*
* setup MQTT
*/
mqtt.setServer(MQTT_SERVER, MQTT_PORT);
mqtt.setCallback(mqtt_receive_callback);
topic = MQTT_PREFIX_TOPIC + my_mac + MQTT_BLE_TOPIC;
Serial.println("********************");
Serial.println(topic);
Serial.println("********************");
}
/*
Loop
*/
void loop() {
/*
Check all connections, wifi, mqtt
*/
check_wifi();
check_mqtt();
/*
Alive
*/
mqtt.loop();
// Handle blinking without using delay()
unsigned long now = millis();
if (nBlinks > 0) {
if (now - last_blink >= BLINK_MS) {
last_blink = now;
if (in_blink) { // then finish
digitalWrite(LED_PIN, led_state);
nBlinks--;
in_blink = false;
} else {
digitalWrite(LED_PIN, !led_state);
in_blink = true;
}
}
}
Send_Mqtt_Data();
delay(1000);
}
}Compile o programa e pressione o botão para gravar (reset/boot)
Abra a serial e veja ser publicado dados em um Tópico e o CallBack
Servidor MQTT THINGSTREAM recebendo dados do Tópico do NINA W106
Certificado
/*
Certificate
if you use SSL
*/
const char root_ca[] = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" \
"ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" \
"b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" \
"MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" \
"b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" \
"ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" \
"9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" \
"IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n" \
"VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n" \
"93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\n" \
"jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" \
"AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" \
"A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" \
"U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" \
"N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\n" \
"o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" \
"5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" \
"rqXRfboQnoZsG4q5WTP468SQvvG5\n" \
"-----END CERTIFICATE-----\n";
https://www.u-blox.com/en/docs/UBX-17056481
https://www.u-blox.com/sites/default/files/NINA-B3_DataSheet_%28UBX-17052099%29.pdf
https://github.com/khoih-prog/WiFiNINA_Generic
https://developer.ibm.com/br/articles/iot-mqtt-why-good-for-iot/
https://www.u-blox.com/sites/default/files/NINA-B3_DataSheet_%28UBX-17052099%29.pdf
https://github.com/khoih-prog/WiFiNINA_Generic
https://developer.ibm.com/br/articles/iot-mqtt-why-good-for-iot/
Sobre a SMARTCORE
A SmartCore fornece módulos para comunicação wireless, biometria, conectividade, rastreamento e automação.
Nosso portfólio inclui modem 2G/3G/4G/NB-IoT/Cat.M, satelital, módulos WiFi, Bluetooth, GNSS / GPS, Sigfox, LoRa, leitor de cartão, leitor QR code, mecanismo de impressão, mini-board PC, antena, pigtail, LCD, bateria, repetidor GPS e sensores.
Mais detalhes em www.smartcore.com.br
Nenhum comentário:
Postar um comentário