ESP8266 not connecting to websocket server - websocket

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

Related

WebSocketServer on ESP32 DevkitC V4 Issue

I'm developing a simple mobile robot controlled by a custom web application hosted on ESP32. The communication protocol that is used is WebSocket. I had a code that was working but after some break, I can't make it run properly again... most likely I changed something accidentally or I don't understand some code parts. The logs in SerialPort suggest that the program connects to the WiFi, it gets data (HTML files) from Flash memory and the server is started under some particular IP. However, when I try to access the server IP nothing is given in response. I pasted my .ino code down below, I can also add HTML and .js files if needed. The data folder is ofc uploaded to the flash memory. For now I just want to host that page on a server and access it, the code is not supposed to do anything else for now. I'm going crazy because of that issue. Does anyone see some mistake or misconception?
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "SPIFFS.h"
#include <Arduino_JSON.h>
// Network credentials
const char *ssid = "mySSID";
const char *password = "myCredentials";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
// Create a WebSocket object
AsyncWebSocket ws("/ws");
// Placeholder for messages from the clients
String message = "";
void initFS()
{
if (!SPIFFS.begin())
{
Serial.println("An error has occurred while mounting SPIFFS");
}
else
{
Serial.println("SPIFFS mounted successfully");
}
}
// Initialise WiFi
void initWiFi()
{
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
void handleWebSocketMessage(void *arg, uint8_t *data, size_t len)
{
AwsFrameInfo *info = (AwsFrameInfo *)arg;
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT)
{
data[len] = 0;
message = (char *)data;
}
}
void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len)
{
switch (type)
{
case WS_EVT_CONNECT:
Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket client #%u disconnected\n", client->id());
break;
case WS_EVT_DATA:
handleWebSocketMessage(arg, data, len);
break;
case WS_EVT_PONG:
case WS_EVT_ERROR:
break;
}
}
void initWebSocket()
{
Serial.println("I'm Inside!");
ws.onEvent(onEvent);
server.addHandler(&ws);
}
void setup()
{
Serial.begin(115200);
Serial.println("Initialising SPIFFS");
initFS();
Serial.println("Initialising WiFi");
initWiFi();
Serial.println("Initialising WebSocket");
initWebSocket();
// Web Server Root URL
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(SPIFFS, "/index.html", "text/html"); });
server.serveStatic("/", SPIFFS, "/");
// Start server
server.begin();
Serial.println("Starting Server");
}
void loop()
{
ws.cleanupClients();
}
Update:
I created a different, very simple sketch just to have a look if it might work and it doesn't. It connects to the WiFi according to the logs but I'm getting timed out when I try to access the server IP address Down below is the code that I used for the second sketch:
#include <WiFi.h>
#include <WebServer.h>
//SSID and Password to the local WiFi
const char* ssid = "ssid";
const char* password = "password";
WebServer server(80);
String webpage = "<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>Document</title></head><body> <h1> Test! </h1></body></html>";
//Function to initialise the connection with local WiFi
void InitWiFi()
{
WiFi.begin(ssid, password);
Serial.println("Trying to connect to the WiFi with SSID: " + String(ssid) + "..");
while(WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected to the WiFi with the IP address: ");
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(115200);
InitWiFi();
//Initialising WebServer
server.on("/", []() {
server.send(200, "text\html", webpage);
});
delay(1000);
server.begin();
Serial.println("Server started");
}
void loop() {
server.handleClient();
}

MQTT Websocket Arduino Uno with SIM7600

I'm created a program to connect an Arduino Uno to a MQTT broker.
With the code that you can see below, I can connect to the broker, for testing I use HiveMQ with a plain TCP connection, everything go more or less well.
But for the final broker I'm going to use Websockets secure (wss) and I cant find how to do it.
I read that "I should wrap the client with the websocket", like is made here, the problem is that all the libraries I found use WiFiClientSecure.h
Do you know any way to do this? Any library or example to use a GSM board to connect using websocket to MQTT?
//DEFINITION
#define TINY_GSM_MODEM_SIM7600 //have to be before the include
#define Terminal Serial
#define SIM7600RX_PIN 2
#define SIM7600TX_PIN 3
#define SIM7600PWR_PIN 5
//GPRS credentials
const char apn[] = "";
const char gprsUser[] = "";
const char gprsPass[] = "";
//MQTT
const char* broker = "broker.hivemq.com";
const char* topic = "/testPablo/init";
const char* topiclstWill = "/testPablo/last";
const int mqttPort = 1883;
uint32_t lastReconnectAttempt = 0;
//INCLUDE LIBRARIES
#include <SoftwareSerial.h>
#include <TinyGsmClient.h>
#include <PubSubClient.h>
//VARIABLE
SoftwareSerial SIM7600(SIM7600RX_PIN, SIM7600TX_PIN);
TinyGsm modem(SIM7600);
TinyGsmClient client(modem);
PubSubClient mqtt(client);
//Function
void activateSIM7600(){
Terminal.println("Starting 4G Module...");
pinMode(SIM7600PWR_PIN, OUTPUT);
digitalWrite(SIM7600PWR_PIN,HIGH);
delay(15000); //wait SIM7600 to start
Terminal.println("wait...");
}
bool connectNetwork(){
Terminal.print("Connecting to network...");
modem.gprsConnect(apn, gprsUser, gprsPass);
Terminal.print("Waiting for network...");
if (!modem.waitForNetwork()) {
Terminal.println(" fail");
delay(5000);
return false;
}
Terminal.println(" success");
if (modem.isNetworkConnected()) {
Terminal.println("Network connected");
}
}
void configureSIM7600(){
SIM7600.begin(115200);
modem.init();
String modemInfo = modem.getModemInfo();
Terminal.print("Modem Info: ");
Terminal.println(modemInfo);
connectNetwork();
}
void mqttCallback(char* topic, byte* payload, unsigned int len) {
Terminal.print("Message arrived [");
}
void configureMQTT(){
// MQTT Broker setup
mqtt.setServer(broker, 1883);
mqtt.setCallback(mqttCallback);
}
boolean mqttConnect() {
Terminal.print("Connecting to ");
Terminal.print(broker);
// Connect to MQTT Broker
boolean status = mqtt.connect("GsmClientTest");
//authenticate MQTT:
//boolean status = mqtt.connect("GsmClientName", "mqtt_user", "mqtt_pass");
if (status == false) {
Terminal.println(" fail");
return false;
}
Terminal.println(" success");
mqtt.publish(topic, "GsmClientTest started");
//mqtt.subscribe(topicLed);
return mqtt.connected();
}
void setup() {
Terminal.begin(115200);
delay(10);
activateSIM7600();
configureSIM7600();
configureMQTT();
Terminal.println("Finish configuration");
}
void loop() {
if (!mqtt.connected()) {
Terminal.println("=== MQTT NOT CONNECTED ===");
uint32_t t = millis(); // Reconnect every 10 seconds
if (t - lastReconnectAttempt > 10000L) {
lastReconnectAttempt = t;
if (mqttConnect()) {
lastReconnectAttempt = 0;
}
}
delay(100);
return;
}
mqtt.loop();
}
You want an Arduino to connect to a broker, in most cases this is done by using ports 1883 or 8883 (secured).
WebSockets are needed if you want to connect to a web client such as a browser and this is done in most cases over ports 8080, 8081 an alike.
If I've understood the README for the library you've linked to you need to use the TinyGsmClient instance instead of the WifiClientSecure
Something like:
TinyGsmClient client(modem);
WebSocketClient250 wsClient(client, host, port);
WebSocketStreamClient wsStreamClient(wsClient, path);
PubSubClient mqtt(wsStreamClient);
This should work for the unsecured version

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.

esp8266 based project using xampp

I've tried uploading the below code into NodeMCU for sending data into MySQL using Xampp Webserver. I want to send values from sensors to the MySQL database through ESP8266. This is the code I have tried
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#define sensorPin1 analogRead(A0)
WiFiServer server(301);
const char *ssid = "internet";
const char *pass = "abcdefghi";
const char* host = "x.x.x.x";
byte mac[6];
WiFiClient client;
MySQL_Connection conn((Client *)&client);
char INSERT_SQL[] = "INSERT INTO test.tester(id,sensor) VALUES ('', %d)";
char query[128];
IPAddress server_addr(x,x,x,x); // MySQL server IP
char user[] = "root"; // MySQL user
char password[] = ""; // MySQL password
void setup() {
Serial.begin(9600);
delay(10);
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
WiFi.macAddress(mac);
Serial.print("MAC: ");
Serial.print(mac[5],HEX);
Serial.print(":");
Serial.print(mac[4],HEX);
Serial.print(":");
Serial.print(mac[3],HEX);
Serial.print(":");
Serial.print(mac[2],HEX);
Serial.print(":");
Serial.print(mac[1],HEX);
Serial.print(":");
Serial.println(mac[0],HEX);
Serial.println("");
Serial.print("Assigned IP: ");
Serial.print(WiFi.localIP());
Serial.println("");
Serial.println("Connecting to database");
while (conn.connect(server_addr, 3306, user, password) != true) {
delay(5);
Serial.print ( "." );
}
Serial.println("");
Serial.println("Connected to SQL Server!");
}
void loop() {
int sensor = sensorPin1;
delay(10000); //10 sec
sprintf(query, INSERT_SQL, sensor);
Serial.println("Data Recorded.");
Serial.println(query);
MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
cur_mem->execute(query);
delete cur_mem;
}
But when I execute this program, the chip is getting connected to WiFi but is is not getting connected to the database.
Any solutions please!?

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.

Resources