can't connect esp8266 device to azure IoT hub - azure

I am trying to connect a esp8266(esp-12e node mcu 1.0) to azure iot hub with code written in arduino. I've created a iot hub and a device using symmetric key authentication. Using the PubSubClient along with WifiClientSecure library to provide a secure mqtt connection(port 8883). generated a SAS token for the device. can't seem to connect to azure and keep getting mqtt disconnected error (-1). Oh and have the azure Baltimore CyberTrust Root CA downloaded and added
#define AZURE
//#define AWS
#ifdef AZURE
#include "secretsAzure.h"
#elif defined(AWS)
#include "secretsAws.h"
#endif
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#include <PubSubClient.h>
BearSSL::WiFiClientSecure net;
BearSSL::X509List cert(cacert);
PubSubClient client(net);
void connectToWiFi()
{
Serial.print("connecting to wifi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(1000);
}
Serial.println("ok!");
}
void connectToMqtt()
{
Serial.print("MQTT connecting ");
while (!client.connected())
{
if (client.connect(THINGNAME, USER, SAS_TOKEN))
{
Serial.println("connected!");
if (!client.subscribe(MQTT_SUB_TOPIC))
Serial.println(client.state());
}
else
{
Serial.print("failed ");
Serial.println(client.state());
delay(5000);
}
}
}
void setup()
{
pinMode(MYPIN, OUTPUT);
Serial.begin(115200);
WiFi.hostname(THINGNAME);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
connectToWiFi();
net.setTrustAnchors(&cert);
client.setServer(MQTT_HOST, MQTT_PORT);
delay(5000);
connectToMqtt();
}
unsigned long lastMillis = 0;
void loop()
{
if (!client.connected())
connectToMqtt();
else
{
client.loop();
if (millis() - lastMillis > 5000)
{
lastMillis = millis();
//sendData();
}
}
}

Related

MH-z19 giving -1 value after some time

I'm trying make an mqtt co2 sensor for home assistant. And I got it to work, but only for a couple of hours. At some point it starts giving me -1 values instead of the proper co2 value. What could this be?
Below my code:
#include <Arduino.h>
#include <Mhz19.h>
#include <SoftwareSerial.h>
SoftwareSerial softwareSerial(D3, D4);
Mhz19 sensor;
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "ID";
const char* password = "pw";
const char* MQTT_BROKER = "192.168.1.25";//"test.mosquitto.org";
int mqttPort = 1883;
const char* mqttUser ="mqtt-user";
const char* mqttPassword ="pw";
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(100);
// Connect to Wi-Fi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("Connected to Wi-Fi");
}
void reconnect() {
// Loop until connected
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect("Test1", mqttUser, mqttPassword )) {
Serial.println("Connected to MQTT");
} else {
Serial.print("Failed MQTT connection with state: ");
Serial.println(client.state());
// Re-try in 3 seconds
delay(3000);
}
}
// Once connected, publish an announcement, and subscribe
client.publish("sensor/test", "Hello from ...");
client.subscribe("sensor/test");
}
void setup() {
Serial.begin(115200);
setup_wifi(); // Connect to Wi-Fi network
client.setServer(MQTT_BROKER, mqttPort);
//client.setCallback(callback);
reconnect(); // Connect to MQTT broker
softwareSerial.begin(9600);
sensor.begin(&softwareSerial);
sensor.setMeasuringRange(Mhz19MeasuringRange::Ppm_5000);
sensor.enableAutoBaseCalibration();
Serial.println("Preheating..."); // Preheating, 3 minutes
while (!sensor.isReady()) {
delay(50);
}
Serial.println("Sensor Ready...");
}
void loop() {
if (!client.connected()) { reconnect(); }
//client.publish("Time", ctime(&now));
auto carbonDioxide = sensor.getCarbonDioxide();
if (carbonDioxide >= 0) {
Serial.println(String(carbonDioxide) + " ppm");
}
char co2String[8];
dtostrf(carbonDioxide, 1,0, co2String);
//Serial.println(co2String);
client.publish("Floating/climate/CO2", co2String);
delay(2000);
}
I also tried flashing it via ESPHome, but then I run into issues from UART. The chip doesn't work propperly as long as the sensor is connected to it.
The sensor may not be receiving enough current. Try connecting the sensor directly to a separate breadboard power supply. The sensor seems to have a warm up time. Try waiting for longer with the independent power supply connected. I hope this will solve your issue.
Thank You,
Naveen PS

ESP8266 not connected in Azure Iot Hub, return state -2

I'm trying to connect my ESP8266 to Azure Hub IoT, but I'm not getting it. I've already followed examples and I get the return rc = -2.
I use https://github.com/knolleary/pubsubclient libary.
I used the library example and other examples and nothing being able to connect to Azure Hub IoT.
Error this line
client.connect(dispositivo, usuario_mqtt, senha_mqtt)
My code
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
const char* nome_wifi = "M11";
const char* senha_wifi = "035954159";
const char* broker = "tiedt-tech-iot-hub.azure-devices.net";
const char* dispositivo = "esp-quarto";
const char* usuario_mqtt = "tiedt-tech-iot-hub.azure-devices.net/esp-quarto";
const char* senha_mqtt = "SharedAccessSignature sr=tiedt-tech-iot-hub.azure-devices.net%2Fdevices%2Fesp-quarto&sig=uM6iZTBylAcNHa4%2F4GYxPcAwMUfMAljCx5zvHyx3m%2BE%3D&se=1647197049";
const char* topico = "devices/esp-quarto/messages/events/";
WiFiClientSecure espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
conectarWifi();
}
void conectarWifi(){
Serial.print("Conectando na rede");
WiFi.begin(nome_wifi, senha_wifi);
while(WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi Conectado");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void conectarMQTT() {
Serial.println("Conectando no broker");
client.setServer(broker, 8883);
while(!client.connected()) {
if (client.connect(dispositivo, usuario_mqtt, senha_mqtt)){
Serial.println("Conectado no broker");
}
else {
Serial.print("Falha na conexão com o broker, rc= ");
Serial.print(client.state());
Serial.println("");
delay(5000);
}
}
}
void loop(){
if (!client.connected()){
conectarMQTT();
}
}
Since late last year, there is an official Arduino SDK for ESP8266 boards. You can find it here, it comes with an example that I can confirm works.
It takes care of some of the heavy lifting, and uses the same WifiClientSecure and PubSubClient classes of your implementation.

Can't send anything to Azure IoT hub

I am working on a project where I need to send data from an Arduino sensor to Azure IoT hub via MQTT SIMCOM SIM7000E.
The device connects fine however when it comes to sending anything it fails. I think it may be the way I've configured my credentials?
IP: "hub.azure-devices.net"
Client: "Sensor_0001"
Username: "hub.azure-devices.net/Sensor_0001/?api-version=2018-06-30"
Key: "SharedAccessSignature sr=Hub.azure-devices.net%2Fdevices%2FSensor_0001&sig=****"
Topic: "Hub/devices/Sensor_0001/messages/events"
I am very new to this and would appreciate any help or suggestions.
Thanks
#include <Wire.h>
#include <DFRobot_SIM7000.h>
#include "Adafruit_FONA.h"
#include <SoftwareSerial.h>
#define serverIP "EEWHub.azure-devices.net"
#define IOT_CLIENT "EEW_Sensor_0001"
#define IOT_USERNAME "EEWHub.azure-devices.net/EEW_Sensor_0001/?api-version=2018-06-30"
#define IOT_KEY "SharedAccessSignature sr=EEWHub.azure-devices.net%2Fdevices%2FEEW_Sensor_0001&sig=ayW2DcT3YOJGQK6Ch8hEJyNF7MIaT%2BukyfJY03J1Y%2BM%3D&se=1632246687"
#define IOT_TOPIC "devices/EEW_Sensor_0001/messages/events/"
#define PIN_TX 7
#define PIN_RX 8
SoftwareSerial mySerial(PIN_RX, PIN_TX);
DFRobot_SIM7000 sim7000;
void simconnect() {
Serial.begin(115200);
while (!Serial);
sim7000.begin(mySerial);
Serial.println("Turn ON SIM7000......");
if (sim7000.turnON()) { //Turn ON SIM7000
Serial.println("Turn ON !");
}
delay(10000);
Serial.println("Set baud rate......");
while (1) {
if (sim7000.setBaudRate(19200)) { //Set SIM7000 baud rate from 115200 to 19200 reduce the baud rate to avoid distortion
Serial.println("Set baud rate:19200");
break;
} else {
Serial.println("Fail to set baud rate");
delay(1000);
}
}
Serial.println("Attaching service......");
while (1) {
if (sim7000.attachService()) { //Open the connection
Serial.println("Attach service");
break;
} else {
Serial.println("Fail to Attach service");
delay(1000);
}
}
}
void loop() {
String sendData;
Serial.print("Connect to :");
Serial.println(serverIP);
if (sim7000.openNetwork(TCP, serverIP, 8883)) { //Connect to server
Serial.println("Connected !");
} else {
Serial.println("Failed to connect");
return;
}
delay(200);
Serial.print("Connect to : ");
Serial.println(IOT_USERNAME);
if (sim7000.mqttConnect(IOT_CLIENT, IOT_USERNAME, IOT_KEY)) { //MQTT connect request
Serial.println("Connected !");
} else {
Serial.println("Failed to connect");
return;
}
delay(200);
Serial.println("Input data end with CRLF : ");
sendData = readSerial(sendData);
Serial.print("Send data : ");
Serial.print(sendData);
Serial.println(" ......");
if (sim7000.mqttPublish(IOT_TOPIC, sendData)) { //Send data to topic
Serial.println("Send OK");
} else {
Serial.println("Failed to send");
return;
}
delay(200);
Serial.println("Close connection......");
if (sim7000.closeNetwork()) { //Close connection
Serial.println("Close connection !");
} else {
Serial.println("Fail to close connection !");
return;
}
delay(2000);
}
String readSerial(String result) {
int i = 0;
while (1) {
while (Serial.available() > 0) {
char inChar = Serial.read();
if (inChar == '\n') {
result += '\0';
while (Serial.read() >= 0);
return result;
}
if (i == 50) {
Serial.println("The data is too long");
result += '\0';
while (Serial.read() >= 0);
return result;
}
if (inChar != '\r') {
result += inChar;
i++;
}
}
}
}
It looks like your topic is not correct. Try the following:
devices/Sensor_0001/messages/events/
Have a look at this doc for more details.
The following screen snippet shows the MQTTBox client example:
Update:
I have tested connectivity from your example and the following screen shows a result:

Reconnection to mqtt broker fails when using own mosquitto broker on AWS EC2 ubuntu Instance

I was using mosquito's test mqtt broker before (i.e. test.mosquitto.org) on my esp8266 with reconnection code i.e. if connection is broken due to router reset then it will reconnect to broker when internet is back. And its working fine. I had used same code with Cloud Mqtt broker and it was working perfectly too. But now when I hosted my own mosquitto broker like in this tutorial MQTT broker on AWS EC2 it stopped reconnecting after router reset. Below is my code on ESP8266:-
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* topic = "someTopic";
String clientId = "randomClientId";
const char* mqttServer = "xxxxxxxxxxxxxxx.compute.amazonaws.com";
const int mqttPort = 1883;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
lastReconnectAttempt = 0;
delay(500);
}
boolean reconnect() {
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
client.subscribe(topic);
}
return client.connected();
}
void loop() {
if (!client.connected())
{
long now = millis();
if (now - lastReconnectAttempt > 5000)
{
lastReconnectAttempt = now;
if (reconnect())
{
lastReconnectAttempt = 0;
}
}
} else
{
client.loop();
}
}
Please let me know if someone knows the reason of this.

Cannot set hostname for ESP8266

I am facing a problem, as setting host name for my ESP8266 is not working. Even though when I'm trying to connect through default host name "ESP_xxxx", it's not working.
Actually when I upload my code with my mobile hotspot SSID and password then it's working fine, but as soon as I gave the SSID and password of my router then it's not working.
Here's my code (setup part):
#include <ESP8266WiFi.h>
const char* ssid = "xxxxxx";
const char* password = "xxxxxx";
int ledPin = 13; // GPIO13
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.hostname("xyz");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
Serial.println(WiFi.hostname());
}
Try this:
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
//
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h" //https://github.com/tzapu/WiFiManager
void configModeCallback (WiFiManager *myWiFiManager)
{
Serial.println("Entered config mode");
Serial.println(WiFi.softAPIP());
Serial.println(myWiFiManager->getConfigPortalSSID());
}
//
void setup()
{
Serial.begin(115200);
//
WiFiManager wifiManager;
WiFi.hostname("myhostname");
//
//wifiManager.resetSettings();
//
//
wifiManager.setAPCallback(configModeCallback);
if (!wifiManager.autoConnect("myhostname"))
{
Serial.println("failed to connect and hit timeout");
// reset
ESP.reset();
delay(1000);
}
//
Serial.println("connected...yeey :)");
}
void loop()
{
//
}
Stumbled upon this issue and below is the code which works for me.
WiFi.disconnect(true);
WiFi.begin(ssid, password);
WiFi.setHostname(device);`
Also came across below code, with this line the module is not receiving any IP. Hence deleted it.
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
Running on Arduino 1.8.15 and esp8266 board version 3.0.1
Try using mDNS instead.
Include the mDNS library
#include <ESP8266mDNS.h>
Then in the setup after you connected to WiFi, start mDNS like this.
if (!MDNS.begin("your-desired-hostname")) {
Serial.println("Error setting up MDNS responder!");
}

Resources