Can't connect NodeMCU to websockets server - websocket

I am working on a project in which I need to connect NodeMCU to an online WebSocket Node.js server. The server is using socket.io. Now I am using a WebsocketsClient.h library in NodeMCU to connect to the server. I have confirmed that it is connecting to WiFi properly.
This is the code of NodeMCU:
#include <Arduino.h>
#include <SPI.h>
#include <Ethernet.h>
#include <WebSocketsClient.h>
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#ifdef DEBUG_ESP_PORT
#define DEBUG_MSG(...) DEBUG_ESP_PORT.printf( __VA_ARGS__ )
#else
#define DEBUG_MSG(...)
#endif
WebSocketsClient webSocket;
WiFiClient client;
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
switch(type) {
case WStype_CONNECTED:
{
Serial.print("[WSc] Connected to url: ");
Serial.println((char *)payload);
// send message to server when Connected
webSocket.sendTXT("Connected");
}
break;
case WStype_DISCONNECTED:
Serial.println("[WSc] Disconnected!\n");
Serial.print("Type: ");
Serial.println(type);
break;
case WStype_TEXT:
Serial.print("[WSc] get text: ");
Serial.println((char *)payload);
// send message to server
// webSocket.sendTXT("message here");
break;
case WStype_BIN:
Serial.print("[WSc] get binary length: ");
Serial.println(length);
// hexdump(payload, length);
// send data to server
// webSocket.sendBIN(payload, length);
break;
}
}
int led = 13;
char *ssid1 = "Rishab's Galaxy M31";
char *pass1 = "ciqk4548";
char *ssid2 = "dugar 4g";
char *pass2 = "rishab0430";
char path[] = "/";
char host[] = "robota-lock.herokuapp.com";
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(115200);
Serial.println("Starting up...");
DEBUG_MSG("bootup...\n");
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
// Disconnect from an AP if it was previously connected
// WiFi.disconnect();
Serial.println("Connecting WiFi ");
WiFi.begin(ssid2, pass2);
Serial.print("connecting.");
while(WiFi.status() != WL_CONNECTED){
digitalWrite(LED_BUILTIN, HIGH);
delay(125);
digitalWrite(LED_BUILTIN, LOW);
delay(125);
digitalWrite(LED_BUILTIN, HIGH);
delay(125);
digitalWrite(LED_BUILTIN, LOW);
delay(125);
Serial.print(".");
}
Serial.println("");
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("connected");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
WiFi.setAutoReconnect(true);
WiFi.persistent(true);
delay(100);
digitalWrite(LED_BUILTIN, LOW);
Serial.print("Starting Socket Connection...");
webSocket.beginSSL(host, 81);
webSocket.onEvent(webSocketEvent);
}
void loop()
{
delay(3000);
webSocket.loop();
DEBUG_MSG("loop %d\n", millis());
// delay(3000);
}
Now as you can see I am currently using Port 81. Whenever I use port 81 or 83, I get the same error:
23:06:59.419 -> BSSL:connect: Unable to connect TCP socket
23:06:59.419 -> loop 309059
23:07:02.912 -> [WSc] Disconnected!
And whenever I use 443 or 80 as Port, I get the following error:
23:11:17.769 -> loop 117716
23:11:21.279 -> [WSc] Disconnected!
23:11:21.279 ->
23:11:21.279 -> Type: 1
23:11:21.604 -> BSSL:_connectSSL: start connection
23:11:21.604 -> BSSL:Connection *will* fail, no authentication method is setup
23:11:36.650 -> BSSL:_run_until: Timeout
23:11:36.650 -> BSSL:_wait_for_handshake: failed
23:11:36.650 -> BSSL:Couldn't connect. Error = 'Unknown error code.'
Either way, I cannot get it to connect to NodeMCU. Please help.

Related

ESP8266 not connecting to websocket server

I have created and deployed a websocket to the heroku. I am able to use the websocket on postman but I can't connect it with my node mcu. I could connect the node mcu to the wifi but not with the websocket.
I am not sure about the port number which should be used for begin() method for websocketsclient object.
Below is my code to connect with my websocket:
#include "ESP8266WiFi.h"
#include "WebSocketsClient.h"
// WiFi parameters to be configured
const char* ssid = "<wifi_ssid>"; // Write here your router's username
const char* password = "<password>"; // Write here your router's passward
int LED_STATUS = 0;
const char* host = "<project_name>.herokuapp.com";
const uint16_t port = 3000;
const char* url = "/";
WebSocketsClient webSocketsClient = WebSocketsClient();
void handleMessage(char * message){
Serial.println("message...");
Serial.println(message);
}
void webSocketCallback(WStype_t type, uint8_t * payload, size_t length){
toggleLED();
switch(type){
case WStype_DISCONNECTED:
offLED();
break;
case WStype_TEXT:
onLED();
handleMessage((char*) payload);
break;
case WStype_CONNECTED:
default:
onLED();
break;
}
}
void toggleLED(){
LED_STATUS = (LED_STATUS + 1)%2;
digitalWrite(LED_BUILTIN, LED_STATUS);
}
void offLED(){
LED_STATUS = 1;
digitalWrite(LED_BUILTIN, LED_STATUS);
}
void onLED(){
LED_STATUS = 0;
digitalWrite(LED_BUILTIN, LED_STATUS);
}
void setup(void)
{
Serial.begin(9600);
// Connect to WiFi
WiFi.begin(ssid, password);
//setting the led pin
pinMode(LED_BUILTIN, OUTPUT);
// while wifi not connected yet, print '.'
// then after it connected, get out of the loop
while (WiFi.status() != WL_CONNECTED) {
toggleLED();
delay(500);
Serial.print(".");
}
//WiFi connected, IP address
Serial.println("");
Serial.println("WiFi connected");
Serial.println(WiFi.localIP());
offLED();
//websocket connection
webSocketsClient.begin(host, port, url);
webSocketsClient.onEvent(webSocketCallback);
webSocketsClient.setReconnectInterval(5000);
}
void loop() {
// Nothing
webSocketsClient.loop();
}
Solutions(few mistakes in the code):
Since my websocket supports secured connection : wss, so instead of begin() need to use beginSSL()
since wss is used, port number for secured connections is 443

esp8266 NodeMCU client cant connect to esp8266 NodeMCU server with static ip

Hello...
My code is working perfect with using dynamic IP's, the LED is connected to server and a push button is connected to client, it work perfect with dynamic IP's addresses of both devices. But when i make static IP addresses, the client can not connect to server, and it always says connection failed.
Client code is:
#include <ESP8266WiFi.h>
//IPAddress staticIP612_61(192,168,100,59);
//IPAddress gateway612_61(192,168,100,1);
//IPAddress subnet612_61(255,255,255,0);
const char* ssid = "GravixarATD"; // Your wifi Name
const char* password = "TheRedMonster79"; // Your wifi Password
const char * host = "192.168.100.23"; // IP Server
const int httpPort = 80;
const char* Commands; // The command variable that is sent to the server
int button = 5; // push button is connected
bool btn_press = true; // The variable to detect the button has been pressed
int con = 0; // Variables for mode
void setup() {
// put your setup code here, to run once:
pinMode(button, INPUT_PULLUP); // initialize the pushbutton pin as an input:
Serial.begin(115200); // initialize serial:
Serial.println("");
Serial.println("Client-------------------------------");
Serial.print("Connecting to Network");
WiFi.mode(WIFI_STA); // Mode Station
WiFi.begin(ssid, password); // Matching the SSID and Password
delay(1000);
// Waiting to connect to wifi
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("Successfully Connecting");
Serial.println("Status : Connected");
//WiFi.config(staticIP612_61, gateway612_61, subnet612_61);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("-------------------------------------");
Serial.println("");
}
void loop() {
// put your main code here, to run repeatedly:
if (digitalRead(button) == LOW) {
Serial.println("Client-------------------------------");
Serial.print("Send Command = ");
if (btn_press == true){
if (con >= 2) {
con=0;
}
con++;
switch (con){
case 1:
Commands="LED_On";
Serial.println(Commands);
send_commands();
break;
case 2:
Commands="LED_Off";
Serial.println(Commands);
send_commands();
break;
}
btn_press = false;
}
}
else {
btn_press = true;
}
delay(100);
}
void send_commands(){
Serial.println("Sending command...");
Serial.println("Don't press the button for now...");
Serial.println("");
Serial.print("Connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, httpPort)) {
Serial.println("Connection failed");
return;
}
// We now create a URI for the request
Serial.print("Requesting URL : ");
Serial.println(Commands);
// This will send the request to the server
client.print(String("GET ") + Commands + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: Close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
Serial.print("Server Reply = ");
// Read all the lines of the reply from server and print them to Serial
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println("Now you can press the button ...");
Serial.println("-------------------------------------");
Serial.println("");
}
Server code is:
#include <ESP8266WiFi.h>
//IPAddress staticIP612_60(192,168,100,60);
//IPAddress gateway612_60(192,168,100,1);
//IPAddress subnet612_60(255,255,255,0);
int led = 5; // the pin the LED is connected to
const char* ssid = "GravixarATD"; // Your wifi Name
const char* password = "TheRedMonster79"; // Your wifi Password
const char* Commands_Reply; // The command variable that is sent to the client
const char * host = "192.168.100.21"; // IP Client
WiFiServer server(80);
void setup() {
// put your setup code here, to run once:
pinMode(led, OUTPUT); // Declare the LED as an output
Serial.begin(115200); // initialize serial:
delay(10);
Serial.println("");
Serial.println("Server-------------------------------");
Serial.print("Configuring access point");
WiFi.begin(ssid, password);
// Waiting to connect to wifi
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// WiFi.config(staticIP612_60, gateway612_60, subnet612_60);
// 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("-------------------------------------");
Serial.println("");
}
void loop() {
// put your main code here, to run repeatedly:
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("Server-------------------------------");
Serial.println("New client");
Serial.print("From client = ");
while(!client.available()){
delay(1);
}
// Read the first line of the request -------------------------------------
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
//Command LED -------------------------------------------------------------
if (req.indexOf("LED_On") != -1){
Commands_Reply = "LED Status : On";
Serial.print("Server send = ");
Serial.println(Commands_Reply);
client.print(String("GET ") + Commands_Reply + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
digitalWrite(led, HIGH);
}
else if (req.indexOf("LED_Off") != -1){
Commands_Reply = "LED Status : Off";
Serial.print("Server send = ");
Serial.println(Commands_Reply);
client.print(String("GET ") + Commands_Reply + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
digitalWrite(led, LOW);
}
else {
Serial.println("invalid request");
client.stop();
return;
}
client.flush();
Serial.println("Client disonnected");
Serial.println("-------------------------------------");
Serial.println("");
}
NOTE I have commented all the static IP lines, when i comment them and using dynamic ips, client connect to server perfectly and when i use static ips instead of dynamic ips client fails to connect with server. any help will be appreciated.

Arduino web socket autoreconnect

I am using 2 esp8266, both connected to same network. Esp1 send some data to esp2 using websocket. So basically esp2 connect to esp1 websocket and read data.
My problem is that if esp1 is restarted, after is up again, esp2 does not connect anymore to it and needs restart to connect
This is code I am using on esp2
#include <ESP8266WiFi.h>
#include <WebSocketsClient.h>
#include <ESP8266WebServer.h>
#include <SoftwareSerial.h>
#define USE_SERIAL Serial
#define LEDS 0 //Status led
WebSocketsClient webSocket;
SoftwareSerial COM(5, 4);
long previousMillis = 0;
long interval = 50;
String data;
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
yield();
break;
case WStype_CONNECTED: {
webSocket.sendTXT("Connected");
}
yield();
break;
case WStype_TEXT:
if(payload[0] == '#') {
uint32_t dataz = (uint32_t) strtol((const char *) &payload[1], NULL, 10);
if (dataz < 99911) {
data = "0" + String(dataz);
}
else {
data = String(dataz);
}
}
yield();
if (data.length() == 6 ) {
COM.print('<'); // start marker
COM.print(data);
COM.println('>'); // end marker
}
break;
}
}
void setup() {
pinMode(LEDS, OUTPUT);
digitalWrite(LEDS, LOW);
for(uint8_t t = 4; t > 0; t--) {
delay(1000);
}
WiFi.mode(WIFI_STA);
WiFi.begin("xxx", "xxx");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
}
// server address, port and URL
webSocket.begin("192.168.0.30", 81, "/");
// event handler
webSocket.onEvent(webSocketEvent);
// use HTTP Basic Authorization this is optional remove if not needed
//webSocket.setAuthorization("user", "Password");
// try ever 5000 again if connection has failed
webSocket.setReconnectInterval(5000);
digitalWrite(LEDS, HIGH);
}
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
webSocket.loop();
}
}
I would need some help to make it reconnect when the esp1 is available again after was disconnected
Thank you very much
webSocket.loop(); should be outside of if statement.

nodeMCU connect refused with XMAPP localhost

My project is about using nodeMCU measure value from sensor DHT11 and sent value to database Mysql. I use xampp for server. I cannot sent value to database.
nodeMCU can read value and sent value.But HTTP GET is fail.And return connect refused. I think maybe have problems with port for listening.
this is my code
#include <Arduino.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include "DHT.h"
#define DHTPIN 2 // what digital pin the DHT22 is conected to
#define DHTTYPE DHT11 // there are multiple kinds of DHT sensors
DHT dht(DHTPIN, DHTTYPE);
ESP8266WiFiMulti WiFiMulti;
const char* ssid = "something";
const char* password = "something";
int EP =5;
void setup() {
Serial.begin(115200);
pinMode(EP, INPUT);
for (uint8_t t = 4; t > 0; t--) {
Serial.printf("[SETUP] WAIT %d...\n", t);
Serial.flush();
delay(1000);
}
WiFiMulti.addAP(ssid, password); // ssid , password
randomSeed(50);
}
int timeSinceLastRead = 0;
void loop() {
if ((WiFiMulti.run() == WL_CONNECTED)) {
HTTPClient http;
float temp = dht.readTemperature();
float humi = dht.readHumidity();
long meas =TP_init();
Serial.println(WiFi.localIP());
//int temp = random(25,35);
String url = "localhost:8012/add2.php?temp="+String(temp)+"&humi="+String(humi)+"&meas=0";
Serial.println(url);
http.begin(url); //HTTP
int httpCode = http.GET();
if (httpCode > 0) {
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(3000);
}
long TP_init(){
delay(10);
long meas=pulseIn (EP, HIGH); //wait for the pin to get HIGH and returns measurement
return meas;
}
I changed Apache port from 80 to 8012
I use PHPMyadmin for store database . File php's name add2.php for insert value from sensor DHT11
enter image description here
This is result from serial port.
String url = "localhost should be replaced with String url = "<IP-address-of-your-webserver> as the webserver clearly isn't running on the ESP8266.

Arduino callback stops working when there is a new connection to MQTT broker

First time posting on here, I am hoping somebody will be able to give me some help with an annoying problem I a having.
I am trying to control an Arduino through MQTT with websockets this all works fine until a new connection to the broker is made, the Arduino then does not respond to the callbacks.
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 123);
const char* server = "192.168.0.30";
char message_buff[100];
// defines and variable for sensor/control mode
#define MODE_OFF 0 // not sensing light, LED off
#define MODE_ON 1 // not sensing light, LED on
#define MODE_SENSE 2 // sensing light, LED controlled by software
int senseMode = 0;
unsigned long time;
EthernetClient ethClient;
PubSubClient mqttClient(ethClient);
void callback(char* topic, byte* payload, unsigned int length) {
int i = 0;
for (int i=0;i<length;i++) {
message_buff[i] = payload[i];
}
String msgString = String(message_buff);
Serial.println("Payload: " + msgString);
if (msgString.equals("onn")){
senseMode = MODE_ON;
}else if(msgString.equals("off")){
senseMode = MODE_OFF;
}
}
void reconnect() {
// Loop until we're reconnected
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (mqttClient.connect("arduinoClient")) {
Serial.println("connected");
// Once connected, publish an announcement...
mqttClient.publish("test","AR1 Connected");
// ... and resubscribe
mqttClient.subscribe("test");
} else {
Serial.print("failed, rc=");
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
Serial.begin(9600);
pinMode(7, OUTPUT);
mqttClient.setServer(server, 1883);
mqttClient.setCallback(callback);
Ethernet.begin(mac, ip);
// Allow the hardware to sort itself out
delay(1500);
}
void loop()
{
if (!mqttClient.connected()) {
reconnect();
}
switch (senseMode) {
case MODE_OFF:
// light should be off
digitalWrite(7, LOW);
break;
case MODE_ON:
// light should be on
digitalWrite(7, HIGH);
break;
}
mqttClient.loop();
}
Outputs:
Attempting MQTT connection...failed, rc= try again in 5 seconds
Attempting MQTT connection...connected
Payload: onn
Payload: off
Payload: JTPA.CONNECTED
Payload: onnA.CONNECTED
Payload: offA.CONNECTED
Any help would be much appreciated.
Thanks.
As thrashed out in the comments the problem here is that you are using the same MQTT client ID for all instances. This will not work as every client needs a unique id and the broker will disconnect duplicates.
You need a way to generate a unique id, this question on the Arduino site has some hints on how to do this.

Resources