Unable to access a websocket using ESP8266 (Using Arduino IDE) - arduino

I been trying to get my ESP8266 to connect to a websocket, but no luck so far. Things that are ruled out are:
The ESP8266 is connected to WiFi and has access to Internet (checked using a HTTP request).
Not a problem with the socket server, I spun up my own websocket server and it was not hit.
Tried port 80 and 443.
My code is as follows, keeps printing
Not Connected!
:
#include <Arduino.h>
#include "WebSocketClient.h"
#include "ESP8266WiFi.h"
WebSocketClient ws(true);
void setup() {
Serial.begin(115200);
WiFi.begin("SSID", "PASSWORD");
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void loop() {
if (!ws.isConnected()) {
ws.connect("echo.websocket.org", "/", 80);
Serial.println("Not connected!");
} else {
ws.send("hello");
String msg;
if (ws.getMessage(msg)) {
Serial.println(msg);
}
}
delay(500);
}

WebSocketClient ws(true); tries to connect securely and uses WiFiClientSecure in stead of WiFiClient. This will probably require specifying a certificate or some such.
Try WebSocketClient ws(false); to see if that works (tries to force an insecure connection).

Related

ESP32 was connecting earlier but is not connecting to WiFi now with the same code

I'm doing a project where I have to connect to a WiFi network. So, I've used this code for ESP32 to connect to a WiFi network -
#include <Arduino.h>
#include <WiFi.h>
void setup() {
Serial.begin(115200);
WiFi.begin("XYZXYZ", "asdfghjkl");
// Wait for WiFi to be connected
uint32_t notConnectedCounter = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.println("Wifi connecting...");
notConnectedCounter++;
if(notConnectedCounter > 50) { // Reset board if not connected after 5s
Serial.println("Resetting due to Wifi not connecting...");
ESP.restart();
}
}
Serial.print("Wifi connected, IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// put your main code here, to run repeatedly:
}
The code I mentioned above worked well but for some reason, it is not working now. Now when I power the ESP32, it gives out something like (or similar to) this-
}⸮~⸮}⸮n~⸮~ֶ⸮}⸮⸮⸮n⸮~n⸮⸮]⸮⸮⸮⸮⸮⸮D⸮b⸮⸮z⸮}⸮⸮⸮1]⸮⸮}⸮⸮~⸮⸮|⸮⸮~}⸮]⸮}⸮=~]⸮⸮]⸮⸮]⸮]⸮⸮n⸮⸮ ֎UvHX⸮.,⸮⸮a⸮⸮⸮]⸮⸮>]⸮>⸮]⸮]⸮n>⸮⸮⸮>>⸮]⸮⸮>]⸮]⸮⸮6⸮
What can I do to solve this?
Make sure your Serial.begin(11520) speed parameter is the same as Serial Monitor speed parameter value.

How to solve "Connection failed" for D1mini(ESP8266)

I'm trying to use D1 mini to fetch some data from website. I created an API key on Thingspeak ThingHttp. However, the client didn't connect properly. I got "connection failed" from the Serial monitor.
Here is my code. I think they are almost the same as this.
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
WiFiClientSecure client;
#define HOST "api.thingspeak.com"
void setup()
{
const char *ssid = "my_wifi";
const char *password = "qwertyui";
const char *API = "W0B96PD71W3Z245Q";
Serial.begin(115200);
WiFi.mode(WIFI_STA);
delay(100);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
IPAddress ip=WiFi.localIP();
Serial.println(ip);
delay(5000);
Serial.println("finish setup");
}
void loop()
{
delay(5000);
if (!client.connect(HOST, 80))
{
Serial.println(F("Connection failed"));
return;
}
Serial.println("***");
}
And here is what I got from the serial monitor.
WiFi connected
IP address:
192.168.0.53
finish setup
Connection failed
Connection failed
It's obvious that it indeed connected to my wifi correctly, but just unable to connect to the server.
Does anyone know how to fix this? Or are there any crucial step I should set on my D1mini?
(I'm using VSCode instead of Arduino IDE)
You're using the wrong port number.
Port 80 is for unencrypted HTTP.
Port 443 is for HTTPS.
You're using WiFiClientSecure, so presumably you're intending to use HTTPS. HTTPS runs on port 443, not port 80. You'll need to change your code to use 443, or you'll need to use WiFiClient in order to work with port 80 (but make sure the API you're trying to connect to allows access over plain HTTP - most will not).
I highly recommend that you use an existing HTTP client rather than implement the protocol yourself as you'll need to with WiFiClient or WiFiClientSecure, which just provide TCP and encrypted TCP connections. You can find examples of how to use ESP8266HTTPClient in the ESP8266 Arduino core repository.

ESP32 MQTT client stuck at client.subscribe()

I'm trying to connect my ESP32 to mosquitto with MQTTClient but it get stuck when trying to subscribe to any topic and it won't recive messages. I've searched all the afternoon and can't find any solution. I've also tested the broker with MQTTBox and I can subscribe and publish just fine.
Here is the code uploaded to the NodeMCU:
#include <Arduino.h>
#include <MQTTClient.h>
#include "WiFi.h"
#include "secrets.h"
#include <WiFiManager.h>
WiFiClient net = WiFiClient();
MQTTClient client = MQTTClient(256);
void connectMQTT(){
WiFiManager wifiManager;
if(!wifiManager.autoConnect(WIFI_SSID,WIFI_PASSWORD)) {
Serial.println("failed to connect and hit timeout");
//reset and try again, or maybe put it to deep sleep
ESP.restart();
delay(1000);
}
Serial.println("Connected to Wi-Fi");
// Connect to the MQTT broker
client.begin(MQTT_ENDPOINT, MQTT_PORT, net);
// Create a message handler
client.onMessage(messageHandler);
Serial.println("Connecting to MQTT");
while (!client.connect(THINGNAME)) {
Serial.print(".");
delay(100);
}
if(!client.connected()){
Serial.println("MQTT Timeout!");
return;
}
Serial.println("MQTT Connected!");
Serial.println("Subscribing to irtopic");
// Subscribe to topics
client.subscribe("esp32/ir");
Serial.println("");
Serial.println("Success!");
}
void setup() {
Serial.begin(115200);
connectMQTT();
}
And the serial output:
*WM:
*WM: AutoConnect
*WM: Connecting as wifi client...
*WM: Using last saved values, should be faster
*WM: Connection result:
*WM: 3
*WM: IP Address:
*WM: 192.168.0.155
Connected to Wi-Fi
Connecting to MQTT
MQTT Connected!
Subscribing to irtopic

Set parameters of ESP8266 through Arduino

The problem is that I want to execute the code below, but when ESP8266 is shut down, then I start it again, everything is gone.
So, is there a solution that I can make this ESP8266 work the same controlled by my Arduino Uno.
My program blow is to control the GPIO2 through web browser.
Thanks a lot to all of you!!
My Codes:
#include <ESP8266WiFi.h>
#include <aREST.h>
// Create aREST instance
aREST rest = aREST();
// WiFi parameters
const char* ssid = "Protect Big Dragon 4";
const char* password = "18717772056";
// The port to listen for incoming TCP connections
#define LISTEN_PORT 80
// Create an instance of the server
WiFiServer server(LISTEN_PORT);
void setup(void)
{
// Start Serial
Serial.begin(115200);
// Give name and ID to device
rest.set_id("2");
rest.set_name("lamp_control");
// Connect to WiFi
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.println(WiFi.localIP());
}
void loop() {
// Handle REST calls
WiFiClient client = server.available();
if (!client) {
return;
}
while(!client.available()){
delay(1);
}
rest.handle(client);
}
So your ESP8266 loses your code when it is rebooted.
Sounds like the memory is faulty.
Try a different ESP8266 and let us know what occurs.

MQTT on Arduino not working

I'm using Arduino Uno and Wi-Fi shield. I'm trying to implement MQTT protocol for communication and I tried two libraries for Arduino. First one is Knolleary's PubSubClient: http://pubsubclient.knolleary.net/ . I modified original example a little bit to use WiFi module instead of ethernet. Sending works but not every time (sometimes, the message is sent and sometimes not). But receiving via callback function doesn't work at all.
Here is my code:
/*
Basic MQTT example with Authentication
- connects to an MQTT server, providing username
and password
- publishes "hello world" to the desired topic
- subscribes to the desired topic
*/
#include <WiFi.h>
#include <PubSubClient.h>
char ssid[] = "[DELETED]"; // your network SSID (name)
char pass[] = "[DELETED]"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
// Update these with values suitable for your network.
IPAddress server(85, 119, 83, 194);
WiFiClient WifiClient;
void callbackFunc(char* topic, byte* payload, unsigned int length) {
Serial.println("test message received");
/*Serial.println();
Serial.println("=============== MESSAGE RECEIVED ================================");
Serial.print("Topic: ");
Serial.print(topic);
Serial.println();
Serial.println((const char *) payload);*/
}
PubSubClient client(server, 1883, callbackFunc, WifiClient);
void setup()
{
delay(2000);
Serial.begin(9600);
Serial.println("Starting....");
Serial.println("Initializing Wifi...");
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
}
// attempt to connect using WPA2 encryption:
Serial.println("Attempting to connect to WPA network...");
status = WiFi.begin(ssid, pass);
// if you're not connected, stop here:
if (status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// If you are connected, print out success message
else
Serial.println("Connected to network");
if (client.connect("arduinoClient")) {
Serial.println("Connected to server! Sending message...");
client.publish("randy/test","hello world");
client.subscribe("randy/test");
Serial.println("Sent!");
}
else
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
}
void loop()
{
client.loop();
delay(1000);
if (!client.connected())
{
if(!client.connect("arduinoClient"))
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
else
{
client.subscribe("randy/test");
Serial.println("INFO: reconnected!");
}
}
}
As you can see, I'm using http://test.mosquitto.org/ for testing. I'm also using mosquitto on Ubuntu where I'm subscribed to the same topic and from where (another terminal window) I'm publishing to the same topic. Here is the picture of both windows:
As you can see, "hello world" message from Arduino is received successfully (but not every time), and when I publish "bla" message from another window, it's successfully received on mosquitto (on image) but NOT on Arduino. Is there something wrong with my code or? I found similar problem here: Arduino Knolleary PubSubClient will publish messages but can't receive them
It's worth noticing that it keeps getting reconnected all the time. As you can see, in loop() I put a part of code which will connect and subscribe again if connection is lost. On Serial Monitor I get "INFO: Reconnected!" message every 2-3 seconds.
Adafruit library
Then I tried the Adafruit library, but it won't connect at all! I tried with test.mosquitto.org and with io.adafruit.com from their example, but I just keep getting "Connection failed!" error. I tried making many changes and combinations but no luck so far. Once I managed to get "Failed to subscribe" instead of "Connection failed" but this was only once and next time with the same code I get "Connection failed" again.
Here's my code:
/*
Basic MQTT example with Authentication
- connects to an MQTT server, providing username
and password
- publishes "hello world" to the topic "outTopic"
- subscribes to the topic "inTopic"
*/
#include <WiFi.h>
#include <PubSubClient.h>
char ssid[] = "[DELETED]"; // your network SSID (name)
char pass[] = "[DELETED]"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
// Update these with values suitable for your network.
IPAddress server(85, 119, 83, 194);
WiFiClient WifiClient;
void callbackFunc(char* topic, byte* payload, unsigned int length) {
Serial.println("test message received");
/*Serial.println();
Serial.println("=============== MESSAGE RECEIVED ================================");
Serial.print("Topic: ");
Serial.print(topic);
Serial.println();
Serial.println((const char *) payload);*/
}
PubSubClient client(server, 1883, callbackFunc, WifiClient);
void setup()
{
delay(2000);
Serial.begin(9600);
Serial.println("Starting....");
Serial.println("Initializing Wifi...");
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
}
// attempt to connect using WPA2 encryption:
Serial.println("Attempting to connect to WPA network...");
status = WiFi.begin(ssid, pass);
// if you're not connected, stop here:
if (status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// Ff you are connected, print out success message
else
Serial.println("Connected to network");
if (client.connect("arduinoClient")) {
Serial.println("Connected to server! Sending message...");
client.publish("randy/test","hello world");
client.subscribe("randy/test");
Serial.println("Sent!");
}
else
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
}
void loop()
{
client.loop();
delay(1000);
if (!client.connected())
{
if(!client.connect("arduinoClient"))
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
else
{
client.subscribe("randy/test");
Serial.println("INFO: reconnected!");
}
}
}
Any idea what's wrong with those libraries or my code?
As mentioned in the comments
When using example code on public brokers make sure you change the client id to something random as the odds of clashing with somebody else are pretty high. Because client ids have to be unique else they will cause a reconnection storm

Resources