ESP8266 GET request not working - http

I am trying to send data from an Arduino Uno using ESP8266 to Firebase via PHP. The connection between the Firebase DB and PHP seems to be fine since I can manually send data to it through my browser. However, I am not able to send data from the Arduino to PHP.
Here is the Arduino code:
#include "SoftwareSerial.h"
String ssid ="xxxx";
String password="xxxx";
String server = "firstfirebase.000webhostapp.com"; // www.example.com
String uri = "/firebaseTest.php";// our example is /esppost.php
SoftwareSerial esp(2, 3);// RX, TX
void setup() {
esp.begin(9600);
Serial.begin(9600);
reset();
connectWifi();
}
void reset() {
esp.println("AT+RST");
delay(1000);
if(esp.find("OK"))
Serial.println("Module Reset");
}
void connectWifi() {
String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
esp.println(cmd);
delay(4000);
if(esp.find("OK")) {
Serial.println("Connected!");
} else {
connectWifi();
Serial.println("Cannot connect to wifi");
}
}
void loop() {
httppost();
delay(1000);
}
void httppost () {
esp.println("AT+CIPSTART=\"TCP\",\"firstfirebase.000webhostapp.com\",80");//start a TCP connection.
if( esp.find("OK")) {
Serial.println("TCP connection ready");
}
delay(1000);
String getRequest = "GET firebaseTest.php?arduino_data=56.00 HTTP/1.1\r\nHost: firstfirebase.000webhostapp.com\r\n\r\n";
String sendCmd = "AT+CIPSEND";//determine the number of caracters to be sent.
esp.print(sendCmd);
esp.println(getRequest.length() );
delay(500);
if(esp.find(">")) {
Serial.println("Sending..");
esp.print(getRequest+"\r\n\r\n");
delay(500);
esp.println("AT+CIPSTATUS");
if( esp.find("SEND OK")) {
Serial.println("Packet sent");
while (esp.available()) {
String tmpResp = esp.readString();
Serial.println(tmpResp);
}
// close the connection
esp.println("AT+CIPCLOSE");
}
}
}
Here is a screenshot of the serial monitor:

You are missing a / in front of your path.
It should be:
String getRequest = "GET /firebaseTest.php?arduino_data=56.00 HTTP/1.1\r\nHost: firstfirebase.000webhostapp.com\r\n\r\n";

The user Agent it is very important:
AT+CIPSTART="TCP","somedomain.it",80
AT+CIPSEND=EXACT NUMBER OF GET REQ
GET /Arduino/ciao.php HTTP/1.1\r\n
Host: 192.168.0.111\r\n
User-Agent: wget/1.12\r\n\r\n

Related

Communication between Postman and Arduino

I plan to send from a server a POST request to my Arduino Uno WiFi Rev2. More correctly, when the server sends this request a servomotor controlled by the Arduino should start moving. Right now, I'm using Postman to try and connect with the Arduino but I can't get it to work. So first I connect the Arduino to WiFi using my smartphone as a hotspot. This should be the unit's IP address, right?
I then try to send a POST request to this IP but it doesn't work. I'm also unsure which port number I should use, so I have just been trying with the standard ones (80, 4430, etc).
What am I doing wrong and how should I proceed?
EDIT: Here is my code.
#include <SPI.h>
#include <Servo.h>
#include <WiFiNINA.h>
char ssid[] = "MyNetwork"; // The network SSID
char pass[] = "testtest"; // The network password
int status = WL_IDLE_STATUS; // The Wifi radio's connection status
Servo servo_9; // Initializes the servomotor
WiFiServer server(80); // Server socket
//WiFiClient client;
WiFiClient client = server.available();
void setup() {
// Connects the servomotor to pin 9
servo_9.attach(9, 500, 2500);
// Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // Wait for serial port to connect. Needed for native USB port only
}
enable_WiFi();
connect_WiFi();
server.begin();
printCurrentNet();
printWifiData();
}
void loop() {
// Check the network connection once every 10 seconds:
delay(10000);
client = server.available();
if(client){
printWEB();
}
}
void enable_WiFi(){
// Check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
// Don't continue
while (true);
}
// Check if the latest Firmware version is installed
String fv = WiFi.firmwareVersion();
if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
Serial.println("Please upgrade the firmware");
}
}
void connect_WiFi(){
// Attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
// Wait 10 seconds for connection:
delay(10000);
}
// Now the arduino is connected, so print out the data:
Serial.print("You're connected to the network: ");
Serial.println();
}
void printCurrentNet() {
// Print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// Print the MAC address of the router you're attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print("BSSID: ");
printMacAddress(bssid);
// Print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("Signal strength (RSSI): ");
Serial.println(rssi);
// Print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print("Encryption Type: ");
Serial.println(encryption, HEX);
Serial.println();
}
void printWifiData() {
Serial.println("Your board's IP and MAC address: ");
// Print your board's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// Print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
printMacAddress(mac);
Serial.println();
}
// Find the MAC adress for your Arduino board
void printMacAddress(byte mac[]) {
for (int i = 5; i >= 0; i--) {
if (mac[i] < 16) {
Serial.print("0");
}
Serial.print(mac[i], HEX);
if (i > 0) {
Serial.print(":");
}
}
Serial.println();
}
void printWEB() {
if (client) { // if you get a client,
Serial.println("new client"); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// The HTTP response ends with another blank line:
client.println();
// break out of the while loop:
break;
}
else { // if you got a newline, then clear currentLine:
currentLine = "";
}
}
else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// close the connection:
client.stop();
Serial.println("client disconnected");
}
}
void servomotorGate(){
int position = 0;
for (position = 0; position <= 90; position += 1) {
servo_9.write(position);
Serial.println("Opening the gate");
}
delay(5000); // Wait for 5000 millisecond(s)
for (position = 90; position >= 0; position -= 1) {
servo_9.write(position);
Serial.println("Closing the gate");
}
}
I added the server client to listen for connections. However, the main reason why I couldn't connect to my IP address with Postman was that I was trying to get WiFi from my phone as a hotspot. I guess there is a problem with the port forwarding when using a hotspot. In the end, I solved the issue by connecting to a normal router WiFi network.

HTTP POST request-GSM Arduino

I've MKR GSM 1400 with sim and antenna, I want to send data to the KAA cloud by HTTP POST request.
By using cURL I've succeded to send data to the cloud using thise code
curl --location --request POST 'https://connect.cloud.kaaiot.com:443/kp1/<app-version-name>/dcx/<endpoint-token>/json' \
--data-raw '[
{
"temperature": 23,
"humidity": 48
}
]
Based on this I've written this code so far but I'm not sure what I'm missing for it to work :
#include <ArduinoHttpClient.h>
#include <MKRGSM.h>
#include <ArduinoJson.h>
const char PINNUMBER[] = "";
const char GPRS_APN[] = "";
const char GPRS_LOGIN[] = "";
const char GPRS_PASSWORD[] = "";
const String TOKEN = ""; // Deleted for security purpose
const String APP_VERSION = ""; // Deleted for security purpose
const unsigned long fiveSeconds = 1 * 5 * 1000UL;
static unsigned long lastPublish = 0 - fiveSeconds;
int temp;
GSMClient client;
GPRS gprs;
GSM gsmAccess;
char server[] = "connect.cloud.kaaiot.com";
char path[] = "/";
int port = 443;
HttpClient httpClient = HttpClient(client, server, port);
void setup() {
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Starting GSM connection...");
// connection state
boolean connected = false;
// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with the APN, login and password
while (!connected) {
if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &&
(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
connected = true;
} else {
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, port)) {
Serial.println("connected");
} else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
}
void loop() {
if (client.connect(server, port)) {
unsigned long now = millis();
if (now - lastPublish >= fiveSeconds) {
lastPublish += fiveSeconds;
temp = random(18, 23);
Serial.print("temperature = ");
Serial.println(temp);
String queryString = String(" \"temperature\": ) + String(temp) ");
String topic = "/kp1/" + APP_VERSION + "/dcx/" + TOKEN + "/json";
httpClient.println("POST https://" + String(server) + ":" + String(port) + String(topic) + " HTTP/1.1");
Serial.println("POST https://" + String(server) + ":" + String(port) + String(topic) + " HTTP/1.1");
httpClient.println("Connection: close");
httpClient.println(); // end HTTP header
// send HTTP body
httpClient.print("{ \"temperature\": ");
httpClient.print(temp);
httpClient.print("}");
//httpClient.println(queryString);
}
} else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
delay(3000); // Wait for 3 seconds to post again
}
On Serial monitor it shows that I've connected to the server.

ERR_CONNECTION_REFUSED when communicating with my ESP8266 over WiFi

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();
}

Send data periodically as a server to my client in arduino ESP8226

I'm using NodeMCU board to communicate a laptop through WiFi. Basic communication is ok with a code like this:
void loop (){
WiFiClient client = server.available();
if (client) {
while (client.connected()){
client.println(Data_mem[0]);
delay(2000);
}
client.stop(); // tarminates the connection with the client
}
}
But when I want to send data a Timer Tick, it seems the client couldn't connect to me.
void setup(){
....
//Initialize Ticker every 40ms
Data_Rec.attach_ms(40, 40ms_Data );
}
void 40ms_Data (){
WiFiClient client = server.available();
Serial.println("40ms_Data A");
if (client) {
Serial.println("40ms_Data B");
if (client .connected()){
Serial.println("40ms_Data C");
client.println(40ms_Data [0]);
}
else{
client.stop();
}
}
}
I arduino serial monitor, i see only this:
40ms_Data A \r\n
40ms_Data A \r\n
....
So, could anyone help me? maybe it a problem of WiFiClient deceleration in a non-forever loop (like example 1). But I have no idea to fix it.
According to M.R.'s idea, this is my complete new code:
#include <ESP8266WiFi.h>
#include <Ticker.h>
/* Put your SSID & Password */
const char* ssid = "NodeMCU"; // Enter SSID here
const char* password = "12345678"; //Enter Password here
/* Put IP Address details */
IPAddress local_ip(192,168,1,1);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
WiFiServer server(80);
const int CLIENT_TIMEOUT = 2000;
Ticker Data_Rec;
bool Sending_40ms_Start_Flag = false;
void setup() {
Serial.begin(115200);
pinMode(D0, OUTPUT);
WiFi.softAP(ssid, password);
WiFi.softAPConfig(local_ip, gateway, subnet);
delay(100);
server.begin();
Serial.println("HTTP server started");
Data_Rec.attach_ms(500, flag_enable);//500ms is for test
}
void flag_enable(){
//Read FPGA Data from SPI
//...
Sending_40ms_Start_Flag = true;
}
void loop(){
WiFiClient client = server.available();
if (client) {
while(client.connected()){
Serial.println("40ms_Data B");
if (Sending_40ms_Start_Flag){
client.println("Server listening.\r");
Sending_40ms_Start_Flag = false;
}
delay(1);//without this delay, ESP would be reset(because it cannot handle background processes)
}
// else{
// client.stop();
// }
}
}
This code worked. But the server RST the TCP connection after sending one,two or tree "Server listening." as Wireshark shows: Wireshark Capture
What is probable cause of TCP Reset from ESP?
Besides that some syntax errors in your code:
A good solution is to create a static pointer object from client and pass it as an argument to ms40_Data function:
void ms40_Data(WiFiClient *client)
{
Serial.println("40ms_Data A");
if (*client)
{
Serial.println("40ms_Data B");
if (client->connected())
{
Serial.println("40ms_Data C");
//client.println(40ms_Data [0]);
}
else
{
client->stop();
}
}
}
void setup()
{
...
// create a static object from WiFiClient
static WiFiClient client = server.available();
//Initialize Ticker every 40ms
Data_Rec.attach_ms(40, ms40_Data, &client);
}
void loop()
{
}
Another solution is, you can set a flag inside your ticker and then call your ms40_Data function:
bool start_40ms_Data = false;
void ms40_Data()
{
static WiFiClient client = server.available();
Serial.println("40ms_Data A");
if (client)
{
Serial.println("40ms_Data B");
if (client.connected())
{
Serial.println("40ms_Data C");
//client.println(40ms_Data [0]);
}
else
{
client.stop();
}
}
}
void flag_enable()
{
start_40ms_Data = true;
}
void setup()
{
...
//Initialize Ticker every 40ms
Data_Rec.attach_ms(40, flag_enable);
}
void loop()
{
if (start_40ms_Data)
{
ms40_Data();
start_40ms_Data = false;
}
}
The point is to adding this to setup function:
WiFi.mode(WIFI_AP);
Full explanation: Here
Thank you,

Linkit One crashed after few hours while sending post

I'm bought a Linkit One last week and I'm trying to send http post (JSON) request to my remote server via sim card from the Linkit One board.
It all seems working fine but after couple hours those request stopped arriving to my server.
this is my code :
#include <LGPRS.h>
#include <LGPRSClient.h>
#include <LGPRSServer.h>
char server[] = "myserver.com";
int port = 80;
String object = "";
String Location = "";
int objSize;
String objLength;
LGPRSClient client;
void setup() {
Serial.begin(115200);
while (!LGPRS.attachGPRS("internet.golantelecom.net.il", "", "")) {
delay(500);
}
}
void loop() {
object = "value=test";
sendHttpRequest(object);
delay(5000);
}
void sendHttpRequest(String object) {
objSize = object.length();
objLength = String(objSize);
int timeOut = 0;
int index = 0;
String response = "";
if (client.connect(server, port)) {
// FOR THE CONSOLE :
Serial.println(F("POST /index.php HTTP/1.1"));
Serial.print(F("Host: "));
Serial.println(server);
Serial.println(F("Content-Type: application/x-www-form-urlencoded"));
Serial.print(F("Content-Length: "));
Serial.println(objLength);
Serial.println();
Serial.println(object);
Serial.println();
// FOR THE SERVER :
client.println(F("POST /index.php HTTP/1.1"));
client.print(F("Host: "));
client.println(server);
client.println(F("Content-Type: application/x-www-form-urlencoded"));
client.print(F("Content-Length: "));
client.println(objLength);
client.println();
client.println(object);
client.println();
}
else Serial.println("connection failed");
while (client.connected()) {
if (client.available() > 0) {
char value = client.read();
if(String(value) == "{" || index) {
response += String(value);
index++;
if(String(value) == "}") index = 0;
}
}
if (!client.connected() || timeOut == 35000) {
Serial.print("Server Response: ");
Serial.println(response);
Serial.println();
client.stop();
}
timeOut++;
}
}
And this is the log from the server :
http://s11.postimg.org/f6oriqj37/image.png
Please help me to figure out what is going on here..
thanks!
A new version of LinkIt ONE SDK v1.1 was released on 2/18/2015. You can try to download the latest version of SDK from this link, and update the firmware on the board accordingly. The companion firmware of LinkIt ONE SDK v2.0 is v1.1.05. Hope this resolves your issue.

Resources