ERR_CONNECTION_REFUSED when communicating with my ESP8266 over WiFi - networking

Derived from the following code.
I uploaded that code to my ESP8266 and it's all good and okay when I communicate with it with my laptop while my laptop is connected to my network with a LAN cable.
The problem is: when I try to communicate with the ESP with my laptop or phone over Wi-Fi I get ERR_CONNECTION_REFUSED though they rarely work and communicate. I tried another phone another router, and did a factory reset to my router, and all the same.
I know that there is an option in the router that is called AP Isolation and it's been checked and it's disabled.
My question is: What could possibly be the reason for this error ERR_CONNECTION_REFUSED when I communicate with ESP8266 with that code?
If someone could help me I would be pleased as I am stuck in this situation.
The ESP code (same as the link):
#include <ESP8266WiFi.h>
const char* ssid = "*****";
const char* password = "*******";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
Serial.println();
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" connected");
server.begin();
Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());
}
// prepare a web page to be send to a client (web browser)
// the connection will be closed after completion of the response
// the page will be refreshed automatically every 5 sec
String prepareHtmlPage() {
String htmlPage = String("HTTP/1.1 200 OK\r\n") +
"Content-Type: text/html\r\n" +
"Connection: close\r\n" +
"Refresh: 5\r\n" + "\r\n" +
"<!DOCTYPE HTML>" + "<html>" +
"Analog input: " + String(analogRead(A0)) +
"</html>" + "\r\n";
return htmlPage;
}
void loop() {
WiFiClient client = server.available();
// wait for a client (web browser) to connect
if (client) {
Serial.println("\n[Client connected]");
while (client.connected()) {
// read line by line what the client (web browser) is requesting
if (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
// wait for end of client's request, that is marked with an empty line
if (line.length() == 1 && line[0] == '\n') {
client.println(prepareHtmlPage());
break;
}
}
}
delay(1); // give the web browser time to receive the data
// close the connection:
client.stop();
Serial.println("[Client disconnected]");
}
}

I hope its not too late and it helps someone in need.
You need to do 2 things
Before WiFi.begin(), you need to add
WiFi.mode(WIFI_STA);
Second, you need to
#include <ESP8266mDNS.h>
in setup()
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
and in loop()
MDNS.update();
Lastly, do not forget to add the following in every server response. Else, you will hit CORS error.
server.sendHeader("Access-Control-Allow-Origin", "*");
Please dont forget to add supporting libraries. Let me know if it works. Demo code would look like the below
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* ssid = "<your SSID>";
const char* password = "<your WIFI Password>>";
int serverPort = 80;
int boardBaud = 115200;
ESP8266WebServer server(serverPort);
void handleRoot() {
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/html", "<h1>Hello World</h1>");
}
void handleNotFound() {
if (server.method() == HTTP_OPTIONS)
{
server.sendHeader("Access-Control-Allow-Origin", "*");
server.sendHeader("Access-Control-Max-Age", "10000");
server.sendHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS");
server.sendHeader("Access-Control-Allow-Headers", "*");
server.send(204);
}
else
{
server.send(404, "text/plain", "Error");
}
}
void setup(void) {
Serial.begin(boardBaud);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void) {
server.handleClient();
MDNS.update();
}

Related

ESP8266Httpclient & WiFIClient(Secure) - connection fails both with HTTPS and HTTP

I'm trying to connect to a server, both using ESP8266Httpclient and WiFiClient(Secure), but no matter what I do the connection fails.
WiFiClient(Secure) version:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
const char* ssid = "wifi";
const char* password = "pass";
WiFiClientSecure client;
char server[64] = "website.domain", url[64] = "/path/to/data";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED) yield();
}
void loop() {
if (!client.connect(server, 443)) Serial.println("Connection failed");
else {
Serial.println("Connection success");
}
}
This always prints "Connection failed", no matter what combination I try: I tried connecting with port 80 and 443, using WiFiClient and WiFiClientSecure, adding and removing "http(s)://" from the server, they all return "Connection failed".
ESP8266Httpclient version:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#ifndef STASSID
#define STASSID "wifi"
#define STAPSK "pass"
#endif
void setup() {
Serial.begin(115200);
WiFi.begin(STASSID, STAPSK);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// wait for WiFi connection
if ((WiFi.status() == WL_CONNECTED)) {
WiFiClientSecure client;
HTTPClient http;
Serial.print("[HTTP] begin...\n");
http.begin(client, "https://website.domain/path/to/data", 443);
http.addHeader("Content-Type", "application/json");
Serial.print("[HTTP] POST...\n");
int httpCode = http.POST("{\"points\":[{\"lat\":mylat,\"lng\":mylng}],\"fuelType\":\"1-x\",\"priceOrder\":\"asc\"}");
if (httpCode > 0) {
Serial.printf("[HTTP] POST... code: %d\n", httpCode);
Serial.println("Redirect location: " + http.getLocation());
//if (httpCode == HTTP_CODE_OK) {
const String& payload = http.getString();
Serial.println("received payload:\n<<");
Serial.println(payload);
Serial.println(">>");
//}
} else Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
http.end();
}
delay(10000);
}
This snippet behaves differently: if I connect to http://website.domain/path/to/data I get HTTP code 301 (moved permanently), which returns location https://website.domain/path/to/data.
If I then change the endpoint to https://website.domain/path/to/data, it returns error -1 (connection failed). I tried every combination in this code as well: port 80 and 443, with and without http(s)://, WiFiClient and WiFiClientSecure, nothing worked. I might be overlooking something very simple, or this might not be possible at all.
Thanks to Juraj for the suggestion to put client.setInsecure(). I thought I'd already done that, but you actually need to call it after you create the client and before you pass it to httpclient. That way it'll actually be set as insecure. Thanks again Juraj.

HTTP get Request using ESP8266

Why I am unable to send get request. It always response 400.The URL are okay there is no problem in it. Actually I need to send data using get request. I have tried my best to find the solution but I didn't get any idea about it. Please anyone can help me with the code
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>//this header is used to send get request and see response
#include <WiFiClient.h>
const char* ssid = "myssid";
const char* password = "mypswd";
String host_url="https://api-test.technofield.net";
String url1="/api/data?token=TEST_TOKEN_123&data=";
int httpPort=80;
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password); //Connect to my WiFi router
Serial.println("");
Serial.print("Connecting"); //initiall step just displaying connecting
// Wait for connection
while (WiFi.status() != WL_CONNECTED) { //the llop wiil execute till wifi is not connected
delay(500);
Serial.print(".");
}
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);// connected to given ssid
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
}
void loop(){
if(WiFi.status()==WL_CONNECTED){ //we will perform action if wifi is connected
HTTPClient http; //intialize object of HTTPclient which is importent
String data="Sunil Kumar Yadav";
//String token="TEST_TOKEN_123";
url1=url1+data;
//full APi url is created you can manipulate those above data and token vaiable.
http.begin(host_url,httpPort,url1);//specify the request,begin the request
int httpCode=http.GET(); //Send the request
// if (httpCode>0){ //lets see the response from server
// String payload = http.getString();//store response on payload variable
// Serial.print("==============");//just for seperating the wifi connection status and server response
// Serial.println(payload);//print the response payload
// }
Serial.print(httpCode);
http.end();//if there is begin there will be end ,it will Close the connection
}
delay(500); //send the request in every 2sec, you can change it according to your need
//you can also specify the time so that it will be easy to identify on which time data is send
}
Following is the output:
301
==============<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx</center>
</body>
</html>
I dont know how to solve this.
There's one (of several) example how to do this with HTTPs here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecure.h>
const char* ssid = "myssid";
const char* password = "mypswd";
String url = "https://api-test.technofield.net/api/data?token=TEST_TOKEN_123&data=";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
WiFiClientSecure client;
client.setInsecure();
HTTPClient https;
String data = "Sunil%20Kumar%20Yadav";
String fullUrl = url + data;
Serial.println("Requesting " + fullUrl);
if (https.begin(client, fullUrl)) {
int httpCode = https.GET();
Serial.println("============== Response code: " + String(httpCode));
if (httpCode > 0) {
Serial.println(https.getString());
}
https.end();
} else {
Serial.printf("[HTTPS] Unable to connect\n");
}
}
delay(5000);
}
import WiFiClientSecure.h
note how I set client.setInsecure(); which you shouldn't in your real code, rather us the root certificate of your end point as shown here https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino#L29
you should URL-encode the data parameter like so String data = "Sunil%20Kumar%20Yadav"

ESP8266 EEPROM or FLASH Error: Succesfully connecting to Wifi with false credentials

I am building a small sensor based on the ESP8266. For setting up wifi I host a small webserver, where the user can enter the credentials.
In the setup routine I load the credentials and try to connect to wifi. If the connection fails, the esp creates an AP and the user can enter new credentials.
I got some strange behaviour. Because when I remove the credentials, the esp nevertheless connects successfully to the wifi. But the 'serial.print()' don't show any credentials.
Maybe its a problem with the EEPROM or FLASH I have no idea. I could reproduce this behaviour on several ESPs.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
ESP8266WebServer server(80);
const char *soft_ap_ssid = "Connect Sensor to MCU";
const char *soft_ap_password = "MySensor";
char ssid[32] = "";
char password[32] = "";
bool wifi_status;
void setup()
{
Serial.begin(115200);
Serial.println();
delay(10);
load_credentials();
wifi_status = setup_wifi(5);
if (!wifi_status)
{
setup_soft_ap();
setup_server();
}
}
void loop()
{
if (!wifi_status)
{
server.handleClient();
}
else
{
Serial.println("Doing Sensor stuff");
delay(2000);
// Remove exsting credentials
for( int i = 0; i < sizeof(ssid); i++ ){
ssid[i] = (char)0;
password[i] = (char)0;
}
save_credentials();
}
}
/*
############## Gernerische Code ########### TODO LIB
*/
bool setup_wifi(int timeout)
{
int timeout_ctr = 0;
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password); //Connect to the WiFi network
while ((WiFi.status() != WL_CONNECTED) && (timeout_ctr < timeout))
{
delay(500);
Serial.println("...");
timeout_ctr++;
}
if (WiFi.status())
{
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //Print the local IP
}
else
{
Serial.println("Connection to MCU failed, setting up AP.");
}
return (WiFi.status() == WL_CONNECTED);
}
void setup_soft_ap()
{
Serial.println();
Serial.println("Creating WiFi AP...");
WiFi.softAP(soft_ap_ssid, soft_ap_password);
Serial.print("AP \"");
Serial.print(soft_ap_ssid);
Serial.println("\" is online.");
Serial.print("IP address: ");
Serial.println(WiFi.softAPIP());
Serial.println();
}
void setup_server()
{
server.on("/", handle_root); //Associate the landingpage function to the path
server.on("/submit", handle_submit); //Associate the handler function to the path
server.begin(); //Start the server
Serial.println("Server listening");
}
void handle_root()
{
const char *landingpage = "<html><head> <title>ESP8266 Demo</title> <style></style></head><body> <h1>Sensor einrichten</h1> <p> Eingabe der Wifi Daten </p><form action='/submit' method='post'> <input type='text' name='ssid' placeholder='Wifi SSID'> <input type='text' name='pw' placeholder='Wifi Password'> <input type='submit' value='Submit'> </form></body></html>";
server.send(200, "text/html", landingpage);
}
void handle_submit()
{
if (server.args() > 0)
{
Serial.println("POST:");
Serial.println(server.arg("ssid"));
Serial.println(server.arg("pw"));
server.arg("ssid").toCharArray(ssid, sizeof(ssid) - 1);
server.arg("pw").toCharArray(password, sizeof(password) - 1);
Serial.println("credentials:");
Serial.println(ssid);
Serial.println(password);
save_credentials();
}
server.sendHeader("Location", String("/"), true);
server.send(302, "text/plain", "");
}
void load_credentials()
{
EEPROM.begin(512);
EEPROM.get(0, ssid);
EEPROM.get(0 + sizeof(ssid), password);
char ok[2 + 1];
EEPROM.get(0 + sizeof(ssid) + sizeof(password), ok);
EEPROM.end();
if (String(ok) != String("OK"))
{
ssid[0] = 0;
password[0] = 0;
}
Serial.println("Recovered credentials:");
Serial.println(ssid);
Serial.println(password);
}
/** Store WLAN credentials to EEPROM */
void save_credentials()
{
EEPROM.begin(512);
EEPROM.put(0, ssid);
EEPROM.put(0 + sizeof(ssid), password);
char ok[2 + 1] = "OK";
EEPROM.put(0 + sizeof(ssid) + sizeof(password), ok);
EEPROM.commit();
EEPROM.end();
}
By default, the ESP8266 Arduino SDK saves its wifi configuration in flash memory.
This is documented but not called out clearly.
You'll need to call Wifi.persistent() to get the ESP to not save the credentials. This doesn't seem to be called out clearly in a lot of ESP Arduino Core writeups that I've seen.
Try this:
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.persistent(false);
WiFi.begin(ssid, password); //Connect to the WiFi network
while ((WiFi.status() != WL_CONNECTED) && (timeout_ctr < timeout))
You'll probably want to write a bad set of credentials to flash before you update your code to tell the SDK to stop saving them, otherwise I think it will keep using the last saved set. The alternative is to wipe the sector of flash on your ESP where the credentials are stored, which is a lot more work.
There's some documentation on WiFi.persistent() here - which appears to be incorrect - I believe this call operates the way I described (passing false just doesn't store the credentials at all).
If your project is going to be restarting frequently (like going in and out of deep sleep often) I'd definitely use WiFi.persistent(false) to avoid wear on the flash.

Sending GET Request with NodeMCU ESP8266

I'm trying to send a standard http GET request to my website using the NodeMCU example client code however for some reason it is not working.
If I type into my browser: snackrefill.com/GetData.php?username=aaaa&pin=bbbb&cost=cccc then it will successfully connect with the php script and save a data base entry.
The problem is that when I try to do the same using the NodeMCU module it does not work. it seems to be connecting to WiFi and the server just fine but when it sends the request nothing seems to happen.
Am I structuring my request wrong?
#include <ESP8266WiFi.h>
const char* ssid = "BELL473";
const char* password = "XXXXXXX";
const char* host = "ns8451.hostgator.com";
void setup() {
Serial.begin(115200);
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); //works!
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
int value = 0;
void loop() {
delay(5000);
++value;
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) { //works!
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/GetData.php";
url += "?username=";
url += "aaaa";
url += "&pin=";
url += "bbbb";
url += "&cost=";
url += "cccc";
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
Serial.println();
Serial.println("closing connection");
}
The reason it was not sending was because the host was wrong, i was pointing to my website nameserver when i should have pointed it to the regular website name. I changed const char* host = "ns8451.hostgator.com"; to const char* host = "snackrefill.com"; and now it works!

Message is not publishing to ESP8266 from IBM Bluemix

I have programmed to my ESP8266 and subscribed one topic to keep listening messages. This is my graphical view of injecting message to IBM Iot node.
This is my settings of inject view
This is my settings of IBM Iot node.
Here are my logs at Serial Monitor, it is connected and subscribed to cmd channel
So far so good, When I am trying to inject a message to my IBM Iot node then it is not publishing a message, as it is not reaching on serial monitor and no log on debug view. here you can see
Here is source code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/releases/tag/v2.3
const char* ssid = "shiv";
const char* password = "manmohan#12345";
#define ORG "2kafk4"
#define DEVICE_TYPE "ESP8266"
#define DEVICE_ID "5CCF7FEED6F0"
#define TOKEN "opKF7v3#8jRM*mGkb_"
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char topic[] = "iot-2/cmd/test/fmt/String";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int payloadLength) {
Serial.print("callback invoked for topic: "); Serial.println(topic);
for (int i = 0; i < payloadLength; i++) {
Serial.print((char)payload[i]);
}
}
PubSubClient client(server, 1883, callback, wifiClient);
void setup() {
Serial.begin(115200);
Serial.println();
wifiConnect();
mqttConnect();
}
void loop() {
if (!client.loop()) {
mqttConnect();
}
}
void wifiConnect() {
Serial.print("Connecting to "); Serial.print(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("nWiFi connected, IP address: "); Serial.println(WiFi.localIP());
}
void mqttConnect() {
if (!client.connected()) {
Serial.print("Reconnecting MQTT client to "); Serial.println(server);
while (!client.connect(clientId, authMethod, token)) {
Serial.print(".");
delay(500);
}
initManagedDevice();
Serial.println();
}
}
void initManagedDevice() {
if (client.subscribe(topic)) {
Serial.println("subscribe to cmd OK");
} else {
Serial.println("subscribe to cmd FAILED");
}
}
I tried to check cloud foundry logs using cf command, here it is https://pastebin.com/dfMaS1Gd
Can anyone hint me what I am doing wrong ? Thanks in advance.
Confirm the device type is correctly specified in your node configuration. Currently the screenshot show 0.16.2 which doesn't seem to match the device type you registered and what is specified in your code.

Resources