WifiClient not connecting to XAMPP server - http

I'm working with a NodeMCU "ESP8266" with a pulse sensor and I want to send analog data to my database on a XAMPP server.
I used this code for the WiFi client:
#include <ESP8266WiFi.h>
const char* ssid = "tabark";
const char* password = "tabarekghassan";
int value;
const char* host = "http://localhost/mysql0.php?value"+ value;
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);
/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
would try to act as both a client and an access-point and could cause
network-issues with your other WiFi-devices on your WiFi-network. */
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
delay(5000);
value=analogRead(A0);
Serial.print(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)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/input/";
url += "&value=";
url += value;
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");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
// 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();
Serial.println("closing connection");
}
And I used this for the database:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$value = $_GET["value"];
$conn = mysql_connect($servername, $username, $password);
if ($conn) {
echo "Connected successfully";
}
else {
echo "connection failed";
}
$conndb = mysql_select_db('database', $conn);
echo "<br>";
$sql_insert ="insert into pulsesensor(value) values ('$value')";
if($sql_insert){
echo "insert successfull";
}
else {
echo "insert failed";
}
echo "<br>";
$result = mysql_query($sql_insert);
if($result){
echo "insert successfull";
}
else {
echo "insert failed" . mysql_error($result);
}
?>
When I put the value in the URL the value is saved in the database, but it's not working and I got this result:
So what to do?

It seems like you are making an unallowed opperation:
const char* host = "http://localhost/mysql0.php?value"+ value;

Related

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.

Not able to send data from nodeMCU-8266 to localhost (database)

When I try to send data from nodemcu it shows -1, refer bellow image
[serial monitor][1]
[1]: https://i.stack.imgur.com/3IokX.jpg
you can see my ip address
[ip address][2]
[2]: https://i.stack.imgur.com/srNo1.jpg
my post code
<?php
//Creates new record as per request
//Connect to database
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "sensor";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Database Connection failed: " . $conn->connect_error);
} else{
echo "success"."<br>";}
//Get current date and time
date_default_timezone_set('Asia/Kolkata');
$d = date("Y-m-d");
//echo " Date:".$d."<BR>";
$t = date("H:i:s");
if(!empty($_POST['sensor1']) || !empty($_POST['sensor2']))
{
$sensorData1 = $_POST['sensor1'];
$sensorData2 = $_POST['sensor2'];
$sensorData3 = $_POST['sensor3'];
$sensorData4 = $_POST['sensor4'];
$sensorData5 = $_POST['sensor5'];
$sensorData6 = $_POST['sensor6'];
$sensorData7 = $_POST['sensor7'];
$sql = "INSERT INTO logs (sensor1, sensor2,sensor3,sensor4,sensor5,sensor6,sensor7, Date, Time)
VALUES ('".$sensorData1."', '".$sensorData2."', '".$sensorData3."', '".$sensorData4."',
'".$sensorData5."', '".$sensorData6."', '".$sensorData7."', '".$d."', '".$t."')";
if ($conn->query($sql) === TRUE) {
echo "OK";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
and my Arduino code
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
const char *ssid = "mcu"; //ENTER YOUR WIFI ssid
const char *password = "123456789"; //ENTER YOUR WIFI password
void setup() {
connectWifi();
}
void loop() {
HTTPClient http; //Declare object of class HTTPClient
String sensorData1,sensorData2,sensorData3,sensorData4,sensorData5,sensorData6,sensorData7, postData;
sensorData1="High";
sensorData2="High";
sensorData3="High";
sensorData4="High";
sensorData5="High";
sensorData6="High";
sensorData7="High";
//Post Data
postData = "&sensor1=" + sensorData1 + "&sensor2=" + sensorData2+ "&sensor3=" + sensorData3+
"&sensor4=" + sensorData4+ "&sensor5=" + sensorData5+ "&sensor6=" + sensorData6+ "&sensor7=" +
sensorData7;
http.begin("http://192.168.137.1/esp8266/postData.php"); //change the ip to your
computer ip address
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type
header
int httpCode = http.POST(postData); //Send the request
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
http.end(); //Close connection
delay(500); //Post Data at every 5 seconds
}
//function to connect to wifi
void connectWifi(){
delay(1000);
Serial.begin(115200);
WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect)
delay(1000);
WiFi.mode(WIFI_STA); //This line hides the viewing of ESP as wifi hotspot
WiFi.begin(ssid, password); //Connect to your WiFi router
Serial.println("");
Serial.print("Connecting");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//If connection successful show IP address in serial monitor
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
}
can you fin where is the mistake or missing part
I am using php version: 7.4.10

How to post to a MS-teams webhook from Esp8266?

I have an ESP8266 and want to send messages to a MS-Teams channel. In the future I want to send temperature data but for now I am okay with whatever.
Right now I can connect to the host but it will not send any data to the team and it gives no error.
It works without any problems from Postman and the webhook also works from Python.
Here is my code:
#include "ESP8266HTTPClient.h"
#include "ESP8266WiFi.h"
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>
void setup() {
Serial.begin(9600); //Serial connection
WiFi.begin("", ""); //WiFi connection
while (WiFi.status() != WL_CONNECTED) { //Wait for the WiFI connection completion
delay(500);
Serial.println("Waiting for connection");
}
}
void MicrosoftTeams() {
char host[] = "outlook.office.com"; //Specify request destination";
WiFiClient client;
if (client.connect(host, 443)) {
Serial.println("connected");
String url = "/webhook/Webhookcode";
char json[] = "{ \"#context\":
\"https://schema.org/extensions\",\"#type\":
\"MessageCard\",\"themeColor\": \"0072C6\",\"title\":
\"meddelande\",\"text\": \"Hello!!\"}";
int len = strlen(json);
String Output = "POST " + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Content-Type: application/json\r\n" +
"User-Agent: arduino/1.0\r\n" +
"Content-Length: " + len + "\r\n" +
"\r\n" +
json + "\n";
client.print(Output);
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
}
}
void loop() {
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
MicrosoftTeams();
} else {
Serial.println("Error in WiFi connection");
}
delay(30000); //Send a request every 30 seconds
}
Update:
Ive tested the following function and it works in this test example but not the real case. If i change the WiFiClient to WiFiClientSecure everything stops working.
void WifiCliwaySecure()
{
//Work
WiFiClient client;
const int httpPort = 80;
// //Doenst work
// WiFiClientSecure client;
// const int httpPort = 443;
char host[] = "ptsv2.com";
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
String url = "/t/erzs7-1555484154/post";
Serial.print("Requesting POST: ");
// Send request to the server:
String data = "{ \"title\": \"meddelande\",\"text\": \"Hallå alla bk!!\"}";
client.print(String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Content-Length: " + data.length() + "\r\n" +
"Content-Type: application/json\r\n" +
"\r\n" +
data +
"\r\n");
Serial.print("url Send");
delay(500); // Can be changed
if (client.connected()) {
client.stop(); // DISCONNECT FROM THE SERVER
}
Serial.println();
Serial.println("closing connection");
}
By 2021, you should do the following:
#include <WiFi.h>
#include <HTTPClient.h>
void notifyTeams() {
// === Check WiFi connection status
if (WiFi.status()== WL_CONNECTED) {
HTTPClient http;
// == The incoming webhooks as given by Microsoft Teams
String url = "https://XXXXX.webhook.office.com/webhookb2/YYYYY/IncomingWebhook/ZZZZ/AAAA";
http.begin(url);
http.addHeader("Content-Type", "application/json");
// Send request to the server:
String data = "{ \"title\": \"Slug’s here!\", \"text\": \"Quickly go catch her!\"}";
int httpResponseCode = http.POST(data);
if(httpResponseCode>0) {
// === Get the response to the request
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
}
else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end();
}
else {
Serial.println("Error in WiFi connection");
}
}

Firebase cloud function POST HTTPS Request from ESP8266

I want to connect to an url of a cloud function but isn´t working. someone can see the error? I´m working with an ESP8266 from arduino IDE. I try sending a POST request by postman and it function perfectly, I don´t understan what is the problem with the conection, i always try to connect with out the https and only with http and again in the esp8266 didn´t wotk but in postman does works fine, I do not understant why is this problem
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
const char* ssid = "My wifi";
const char* password = "My Password";
const char* host = "https://us-central1-sensores4bad6.cloudfunctions.net/actualizar";
void setup() {
Serial.begin(9600);
delay(10);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
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);
WiFiClientSecure client;
const int httpPort = 443;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
client.print(String("POST ") + host + " 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;
}
}
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}
Try removing the s in https. So:
const char* host = "http://us-central1-sensores4bad6.cloudfunctions.net/actualizar";
instead of
const char* host = "https://us-central1-sensores4bad6.cloudfunctions.net/actualizar";

How to use esp8266WiFi Library GET request to obtain info from a website

I'm working on the ESP8266 ESP-01 WiFi module programmed with Arduino IDE to send GET request to a URL and read the contents.
Trying to modify the below code which uses the ESP8266WiFi library, I'm not clear what to replace for host. Should i put my URL in host or something else?
Also how to edit the line.
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
#include <ESP8266WiFi.h>
const char* ssid = "your-ssid";
const char* password = "your-password";
const char* host = "data.sparkfun.com";
const char* streamId = "....................";
const char* privateKey = "....................";
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);
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)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/input/";
url += streamId;
url += "?private_key=";
url += privateKey;
url += "&value=";
url += value;
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");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
// 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();
Serial.println("closing connection");
}
Your line client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); is OK. You don't need to change it.
For host you have to provide domain name or IP address. Eg. const char* host = "example.com";.
Example
If you want to get http://stackoverflow.com/questions/39707504/how-to-use-esp8266wifi-library-get-request-to-obtain-info-from-a-website you should have:
const char* host = "stackoverflow.com";
String url = "/questions/39707504/how-to-use-esp8266wifi-library-get-request-to-obtain-info-from-a-website";

Resources