ESP8266 is not getting connected to my deployed websocket on heroku - node.js

I have deployed a nodejs websocket on heroku. But my ESP8266 cannot get connected to that websocket. Before deploying that websocket on heroku, i tried it out locally and it worked pretty well. ESP8266 also got connected to it without any error. Then I made some changes in nodejs socket (before deploying) in order to run it on heroku. i just don't understand what's wrong with this esp8266 code
ESP8266's Code
#include <ESP8266WiFi.h>
#include <WebSocketClient.h>
boolean handshakeFailed = 0;
String data = "";
char path[] = "/"; //identifier of this device
const char *ssid = ""; //<-------------------this was entered correctly. Wifi connection was successful. websocket connection got failed
const char *password = ""; // <-------------------this was entered correctly. Wifi connection was successful. websocket connection got failed
char *host = "example.herokuapp.com"; //replace this ip address with the ip address of your Node.Js server
const int espport = 3000;
WebSocketClient webSocketClient;
unsigned long previousMillis = 0;
unsigned long currentMillis;
unsigned long interval = 300; //interval for sending data to the websocket server in ms
// Use WiFiClient class to create TCP connections
WiFiClient client;
void setup()
{
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
delay(1000);
wsconnect();
// wifi_set_sleep_type(LIGHT_SLEEP_T);
}
void loop()
{
if (client.connected())
{
currentMillis = millis();
webSocketClient.getData(data);
if (data.length() > 0)
{
Serial.println(data);
//*************send log data to server in certain interval************************************
//currentMillis=millis();
if (abs(currentMillis - previousMillis) >= interval)
{
previousMillis = currentMillis;
data = (String)analogRead(A0); //read adc values, this will give random value, since no sensor is connected.
//For this project we are pretending that these random values are sensor values
webSocketClient.sendData(data); //send sensor data to websocket server
}
}
else
{
}
delay(5);
}
}
void wsconnect()
{
// Connect to the websocket server
if (client.connect(host, espport))
{
Serial.println("WebSocket Connected");
}
else
{
Serial.println("Connection failed.");
delay(1000);
if (handshakeFailed)
{
handshakeFailed = 0;
ESP.restart();
}
handshakeFailed = 1;
}
// Handshake with the server
webSocketClient.path = path;
webSocketClient.host = host;
if (webSocketClient.handshake(client))
{
Serial.println("Handshake successful");
}
else
{
Serial.println("Handshake failed.");
delay(4000);
if (handshakeFailed)
{
handshakeFailed = 0;
ESP.restart();
}
handshakeFailed = 1;
}
}

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.

Http get request using Arduino and Azure mobile services

I have hooked up my arduino with Azure mobile services and http post request is working fine where I am able to send data from sensor. But when using a http get request to access data from the tables, I am landing up with this data whereas I should be getting a json data in the Serial Window.
X-cache-Lookup: MISS from Webmaster:8080
Here is the code that is on my Arduino. I have no idea where I am wrong.
#include <ArduinoJson.h>
#include <SPI.h>
#include <Ethernet.h>
#define RESPONSE_JSON_DATA_LINENNO 10
// Ethernet shield MAC address (sticker in the back)
byte mac[] = { 0xA4, 0x5D, 0x36, 0x6A, 0xE1, 0xE1 };
int qq=0;
const char* server= "avirup.azure-mobile.net";
const char* table_name= "iottest";
const char* ams_key="rkIEUqVlFrgtmqNeMmaamgUQywwMjE42";
char stat;
EthernetClient client;
char fin='0';
char buffer[64];
int charIndex=0;
StaticJsonBuffer<200> jsonbuffer;
void send_request()
{
Serial.println("\nconnecting...");
if (client.connect(server, 80)) {
Serial.print("sending ");
// GET URI
sprintf(buffer, "GET /tables/%s HTTP/1.1", table_name);
Serial.println(buffer);
client.println(buffer);
// Host header
sprintf(buffer, "Host: %s", server);
client.println(buffer);
// Azure Mobile Services application key
sprintf(buffer, "X-ZUMO-APPLICATION: %s", ams_key);
client.println(buffer);
// JSON content type
client.println("Content-Type: application/json");
//POST body
sprintf(buffer, "", "");
//Content length
client.print("Content-Length: ");
client.println(strlen(buffer));
Serial.print("Content length: ");
Serial.println(strlen(buffer));
// End of headers
client.println();
// Request body
client.println(buffer);
}
else {
Serial.
println("connection failed");
}
}
/*
** Wait for response
*/
void wait_response()
{
while (!client.available()) {
if (!client.connected()) {
return;
}
}
}
/*
** Read the response and dump to serial
*/
// Read the response and dump to serial
void read_response()
{
int jsonStringLength;
int jsonBufferCntr=0;
int numline=RESPONSE_JSON_DATA_LINENNO;
//Ignore the response except for the 10th line
while (client.available()) {
char c = client.read();
if (c == '\n')
{
numline -=1;
}
else
{
if (numline == 0 )
{
//Capture the 10th line in the response
//To do: Could be more deterministic about this:
// Expect certain content, checks and balances etc.
buffer[jsonBufferCntr++] = c;
buffer[jsonBufferCntr] = '\0';
}
}
}
Serial.println("Received:");
Serial.println(buffer);
Serial.println("");
}
/*
** Close the connection
*/
void parse()
{
//char json[] = "{\"id\":\"34CCC60D-15D2-4B53-AB8E-FF3745FDC945\",\"control\":1}";
JsonObject& root = jsonbuffer.parseObject(buffer);
if(!root.success())
{
Serial.println("PARSING FAILED!!!");
return;
}
//fin= root["control"][0];
int f= root["control"][0];
Serial.println("Decoded: ");
Serial.println(f);
}
void end_request()
{
client.stop();
}
/*
** Arduino Setup
*/
void setup()
{
pinMode(13,OUTPUT);
digitalWrite(13,LOW);
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect.
}
if (Ethernet.begin(mac) == 0) {
Serial.println("ethernet failed");
for (;;) ;
}
// give the Ethernet shield a second to initialize:
delay(1000);
}
/*
** Arduino Loop
*/
void loop()
{
send_request();
wait_response();
read_response();
end_request();
delay(1000);
}

Resources