Unknown behviour for library Wificlientsecure in ESP32 - arduino

We are having an issue with the library wificlientsecure and we are using ESP32.
There are two functions in our library:
void HttpDownstreamClient::subscriptionCreate(char* user, char* password, char* URL, char* device_ID, char* context , char* SubName, char* API, char* type_Filter, char* fragments_To_Copy) {
#if defined(ARDUINO_ARCH_ESP32)
base64ESP(user, password);
#else
base64(user,password)
#endif
//Serial.println(_base64);
StaticJsonDocument<400> root;
root["context"] = context;
if(context == "mo"){
if(device_ID != NULL){
JsonObject source = root.createNestedObject("source");
source["id"] = device_ID;
}else{
Serial.println("Please enter the device ID");
}
}
//JsonObject source = root.createNestedObject("source");
//source["id"] = device_ID;
root["subscription"] = SubName;
JsonObject subFilter = root.createNestedObject("subscriptionFilter");
if (*type_Filter != NULL) {
subFilter["typeFilter"] = type_Filter;
} else {}
JsonArray apis = subFilter.createNestedArray("apis");
apis.add(API);
if (fragments_To_Copy != NULL) {
JsonArray fragtocopy = root.createNestedArray("fragmentsToCopy");
fragtocopy.add(fragments_To_Copy);
} else {}
String body2send = "";
serializeJsonPretty(root, body2send);
//Serial.println(body2send);
if (_networkClient->connect(URL, 443)) {
Serial.println("Connected to the server to create subscription");
// Make a HTTP request:
_networkClient->println("POST /notification2/subscriptions HTTP/1.1");
_networkClient->print("Host: ");
_networkClient->println(URL);
_networkClient->println("Content-Type: application/json");
_networkClient->print("Content-Length: ");
_networkClient->println(body2send.length());
_networkClient->println("Accept: application/json");
_networkClient->print("Authorization: Basic ");
_networkClient->print(\_base64);
_networkClient->println();
_networkClient->println();
_networkClient->println(body2send);
} else {
Serial.println("Connection fail!");
}
while (_networkClient->available() == 0) {
Serial.println("Waiting message from server");
yield();
}
while (_networkClient->available()) {
char c = _networkClient->read();
Serial.print(c);
}
}
void HttpDownstreamClient::tokenCreatePassword(char* user, char* password, char* URL, char* Subname, char* Suber, int expiretime) {
#if defined(ARDUINO_ARCH_ESP32)
base64ESP(user, password);
#else
base64(user,password)
#endif
Serial.print("The subscription is associated with the Subscripter: ");
Serial.println(Suber);
StaticJsonDocument<150> root;
root["subscriber"] = Suber;
root["subscription"] = Subname;
root["expiresInMinutes"] = expiretime;
String body2send = "";
serializeJsonPretty(root, body2send);
//Serial.println(body2send);
if (_networkClient->connect(URL, 443)) {
Serial.println("Connected to the server");
// Make a HTTP request:
_networkClient->println("POST /notification2/token HTTP/1.1");
_networkClient->print("Host: ");
_networkClient->println(URL);
Serial.println(URL);
_networkClient->print("Authorization: Basic ");
_networkClient->println(_base64);
Serial.println(_base64);
_networkClient->println("Content-Type: application/json");
_networkClient->print("Content-Length: ");
_networkClient->println(body2send.length());
Serial.println(body2send.length());
_networkClient->println("Accept: application/json");
_networkClient->println();
_networkClient->println(body2send);
}
while (_networkClient->available() == 0) {
Serial.println("Waiting message from server");
Serial.print(".");
yield();
}
String msg = "";
while (_networkClient->available()) {
char c = _networkClient->read();
msg += c;
}
Serial.println("debug!!!");
Serial.println(msg);
}
.h file is
#ifndef HttpDownstream_h
#define HttpDownstream_h
#include "Arduino.h"
#include <ArduinoJson.h>
#include <string.h>
#include <Client.h>
//#include <Base64.h>
#if defined(ARDUINO_ARCH_ESP32)
#include <base64.h>
#else
#include <Base64.h>
#endif
class HttpDownstreamClient{
private:
String _token;
char* _base64;
//char* _msgToken;
//String _deviceID;
#if defined(ARDUINO_ARCH_ESP32)
//Base64 encoder for ESP32
void base64ESP(char* username, char* password);
#else
//Base64 encoder for none ESP32 board
void base64(char\ username, char* password);
#endif
public:
Client* _networkClient;
HttpDownstreamClient(Client& networkClient);
//Delete the already existed subscription
void subscriptionDelete(char* user, char* password,char* URL, char* context,char* source);
//Create subscription
void subscriptionCreate(char* user, char* password, char* URL, char* device_ID,char* context ,char\* SubName, char* API,char* typeFilter, char* fragmentsToCopy);
//Create token
void tokenCreate(char* URL, char* Subname, char* Suber, int expiretime);
//Create token by giving password
void tokenCreatePassword(char* user, char* password, char* URL, char* Subname, char* Suber, int expiretime);
//Open WSS
void connectWSS(char* URL,char* Suber);
};
#endif
In the .ino file:
void setup()
{
Serial.begin(115200);
delay(10);
wifisecure.setInsecure();
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 5 seconds for connection:
delay(5000);
}
Serial.println("Connected to WiFi");
c8yclient.subscriptionCreate(username,password,host, device_id,"mo" ,SubscriptionName, APIs,typeFilter,fragmentsToCopy);
c8yclient.tokenCreatePassword(username,password,host, SubscriptionName, SubscriberName, expiretime);
}
I can confirm that the function subscriptionCreate() has been successfully sent out. However, the second function doesn't work as I expected. The given result is as following:
Attempting to connect to SSID: MagentaWLAN-MYHU
Connected to WiFi
Stored Based64 string is: 123456789fkcxxnfh
Connected to the server to create subscription
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
Waiting message from server
HTTP/1.1 201 Created
Date: Fri, 18 Nov 2022 21:35:00 GMT
Content-Type: application/vnd.com.nsn.cumulocity.subscription+json;charset=UTF-8;ver=0.9
Content-Length: 317
Connection: keep-alive
Cache-Control: no-cache,no-store,must-revalidate
Pragma: no-cache
Expires: -1
Location: https://t1664801559.cumulocity.com/notification2/subscriptions/783859
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000; includeSubDomains
{"subscriptionFilter":{"apis":["measurements"]},"context":"mo","self":"https://t1664801559.cumulocity.com/notification2/subscriptions/783859%22,%22subscription%22:%22NotificationV2Test28%22,%22id%22:%22783859%22,%22source%22:%7B%22name%22:%22Temperature #1","self":"https://t1664801559.cumulocity.com/inventory/managedObjects/13225%22,%22id%22:%2213225"}}
Connected to the server to request token!
123456789fkcxxnfh
debug!!!
However, if I only use the function tokenCreatePassword(). The following result will be given:
Attempting to connect to SSID: MagentaWLAN-MYHU
Connected to WiFi
Stored Based64 string is: 123456789sjcnz123456cnmz
The subscription is associated with the Subscripter: Test2Sub1
Connected to the server
yingzheliutest2.cumulocity.com
123465789eqeqw
105
Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.Waiting message from server
.debug!!!
HTTP/1.1 200 OK
Date: Fri, 18 Nov 2022 21:45:51 GMT
Content-Type: application/json
Content-Length: 576
Connection: keep-alive
Cache-Control: no-cache,no-store,must-revalidate
Pragma: no-cache
Expires: -1
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000; includeSubDomains
{"token":"eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJUZXN0MlN1YjEiLCJ0b3BpYyI6InQxNjY0ODAxNTU5L3JlbG5vdGlmL05vdGlmaWNhdGlvblYyVGVzdDI4IiwianRpIjoiNjAwMDExYzMtY2JhYS00MWE4LWFmYmYtZGZhYzgzNTQyYWM1IiwiaWF0IjoxNjY4ODA3OTUxLCJleHAiOjE2Njg4NzM5NTF9.FqXPF62liyIigECNqKnKHUyjTDeGmlBoO3HHwEGLw167b0ix1o4eDC0D1VzFKkggiwN7Mbnr3EsWOmsfkQ3nR7smNAqhGF976YAKjIfmWrARiTDgaiSULQCc5Odq1vvuN-O8o1BB2CsafdV5a1n5W1t2Bf9zzgfkZjQTsIe-Ojj6A_DyqUviwvJ5QnVi4VF9BANDMiiNZtocsfwpz2-S8gWqosGgi704Je8_EaS5xdoRYtR1W3EuDPLhRCea4m39iU4n0S97lkJd52xLDkwil4ZVF7xHBvrW6Zy3krf3wIgVwKfRAOmoy3_lnpPCaZ1oi0oqqg0SznchDGxJe7L_Sw"}
It seems like that the following part in tokenCreatePassword() has never been activated when tokenCreatePassword() and subscriptionCreate() are put together:
_networkClient-\>println("POST /notification2/token HTTP/1.1");
_networkClient-\>print("Host: ");
_networkClient-\>println(URL);
Serial.println(URL);
_networkClient-\>print("Authorization: Basic ");
_networkClient-\>println(\_base64);
Serial.println(\_base64);
_networkClient-\>println("Content-Type: application/json");
_networkClient-\>print("Content-Length: ");
_networkClient-\>println(body2send.length());
Serial.println(body2send.length());
_networkClient-\>println("Accept: application/json");
_networkClient-\>println();
_networkClient-\>println(body2send);
Where does this issue come from? How could this two functiones perform quite well individually and not compatible with each?
Many thanks in advance!
I tried to use them seperately and that worked.

Related

How to read chunked http response in ESP32

Basically I want to develop code for sending a GET request to an API using ESP32 (Arduino framework).
However the HTTP response is going to be very large (JSON object), hence I have used the transfer encoding: chunked
header. My question is how to read and process the chunked response, the below code gives an the following
error:
Connecting to WiFi..
Connected to the WiFi network
-11
Error on HTTP request
-11
This error does not occour if the header is not added
#include<Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = ""; // my access point
const char* password = ""; //my password
const String URL = ""; //the api url
void setup() {
Serial.begin(115200);
delay(4000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
//sw.begin(115200);
}
void loop() {
if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
HTTPClient http;
http.begin(URL); //Specify the URL
http.addHeader("Transfer-Encoding", "Chunked"); // for getting chunked data
int httpCode = http.GET(); //Make the request
if (httpCode > 0) { //Check for the returning code
String payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
}
else {
Serial.println(httpCode);
Serial.println("Error on HTTP request");
}
http.end();
}
delay(10000);
}

GPRS module sendTCPData returns 403 Forbidden server error

I'm trying to fetch data from web server using Arduino Uno. I'm using SIM800L module to connect via GPRS. Following is the code I used to connect to web server.
#include <gprs.h>
#include <SoftwareSerial.h>
char http_cmd[] = "GET canopussl.com/info.php HTTP/1.1\r\n\r\n";
char buffer[512];
GPRS gprs;
void setup() {
Serial.begin(9600);
while(!Serial);
Serial.println("GPRS - HTTP Connection Test...");
gprs.preInit();
while(0 != gprs.init()) {
delay(1000);
Serial.println("init error");
}
while(!gprs.join("dialogbb")) { //change "cmnet" to your own APN
Serial.println("Error joining GPRS network");
delay(2000);
}
// successful DHCP
Serial.print("IP Address is ");
Serial.println(gprs.getIPAddress());
Serial.println("Init success, connecting to canopussl.com ...");
if(0 == gprs.connectTCP("canopussl.com", 80)) {
Serial.println("Successfully connected to canopussl.com!");
}else{
Serial.println("connect error");
while(1);
}
Serial.println("waiting to fetch...");
if(0 == gprs.sendTCPData(http_cmd))
{
gprs.serialDebug();
}
gprs.closeTCP();
gprs.shutTCP();
Serial.println("close");
}
void loop() {
}
The output was this.
GPRS - HTTP Connection Test...
IP Address is 10.84.3.49
Init success, connecting to canopussl.com ...
Successfully connected to canopussl.com!
waiting to fetch...
HTTP/1.0 403 Forbidden
Cache-Control: no-cache
Connection: close
Content-Type: text/html
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
CLOSED
How I have to modify the HTTP header to receive the normal output from server?
You are not sending the mandatory Host header.
Your HTTP request should look like:
char http_cmd[] = "GET /info.php HTTP/1.1\r\nHost: canopussl.com\r\n\r\n";

Arduino Uno+ESP01 module HTTP request issue

I have been working with my Arduino Uno board and ESP01 module. My goal is to send an HTTP request to a remote server and fetch the last entry of a remote data base. This entry is the state of a remote toggle button which can be modified through a web page located on a remote server. I'm using AT commands.
To check the state of the toggle button HTTP requests are sent every second from Arduino Uno.
The Arduino sketch that I wrote configures the ESP01, connects it to wifi, and sends the HTTP request.
Arduino sketch:
#include <SoftwareSerial.h>
SoftwareSerial SerialESP8266(2,3); // RX, TX
String server = "someServer";
String cadena=""; //to store HTTP request
void setup() {
SerialESP8266.begin(9600);
Serial.begin(9600);
SerialESP8266.setTimeout(5000);
//checking the ESP8266 response
SerialESP8266.println("AT");
if(SerialESP8266.find("OK"))
Serial.println("AT OK");
else
Serial.println("Error on ESP8266");
//ESP8266 in STA mode.
SerialESP8266.println("AT+CWMODE=1");
if(SerialESP8266.find("OK"))
Serial.println("ESP8266 on STATION mode...");
//Connecting to wifi
SerialESP8266.println("AT+CWJAP=\"mySSID\",\"somePassword\"");
Serial.println("Connnecting...");
SerialESP8266.setTimeout(10000); //waiting for connection
if(SerialESP8266.find("OK"))
Serial.println("WIFI OK");
else
Serial.println("Unable to connect...");
SerialESP8266.setTimeout(2000);
//Disable multiple connections
SerialESP8266.println("AT+CIPMUX=0");
if(SerialESP8266.find("OK"))
Serial.println("Multiple connections disabled");
}
void loop() {
SerialESP8266.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");
//connecting to server
if(SerialESP8266.find("OK")) {
Serial.println();
Serial.println();
Serial.println();
Serial.println("Server connection successful...");
//Armamos el encabezado de la peticion http
String peticionHTTP= "GET /readLast.php";
peticionHTTP=peticionHTTP+" HTTP/1.1\r\n";
peticionHTTP=peticionHTTP+"Host: someserver\r\n\r\n";
peticionHTTP=peticionHTTP+"Host: localhost\r\n\r\n";
//Sending the length of the HTTP request
SerialESP8266.print("AT+CIPSEND=");
SerialESP8266.println(peticionHTTP.length());
//waiting for ">" for sending HTTP request
if(SerialESP8266.find(">")) {
//we can send the HTTP request when > is displayed
Serial.println("Sending HTTP request. . .");
SerialESP8266.println(peticionHTTP);
if(SerialESP8266.find("SEND OK")) {
Serial.println("HTTP request sent...:");
Serial.println();
Serial.println("On stand by...");
boolean fin_respuesta=false;
long tiempo_inicio=millis();
cadena="";
while(fin_respuesta==false) {
while(SerialESP8266.available()>0) {
char c=SerialESP8266.read();
Serial.write(c);
cadena.concat(c); //store the request string on "cadena"
}
//terminate if "cadena" length is greater than 3500
if(cadena.length()>3500) {
Serial.println("The request exceeded the maximum length...");
SerialESP8266.println("AT+CIPCLOSE");
if( SerialESP8266.find("OK"))
Serial.println("Connection terminated...");
fin_respuesta=true;
}
if((millis()-tiempo_inicio)>10000) {
//Terminate if connection time exceeded the maximum
Serial.println("Connection time exceeded...");
SerialESP8266.println("AT+CIPCLOSE");
if( SerialESP8266.find("OK"))
Serial.println("Connection terminated");
fin_respuesta=true;
}
if(cadena.indexOf("CLOSED")>0) {
Serial.println();
Serial.println("String OK, connection terminated");
fin_respuesta=true;
}
}
} else {
Serial.println("error on HTTP request.....");
}
}
} else {
Serial.println("Unable to find the server....");
}
delay(1000); //1 second delay before new loop
}
The HTTP requests (GET request) is handled by readLast.php on the server, which connects to the database and returns the last state of the toggle button. Two states are possible: encender (TURN ON) or apagar (TURN OFF).
readLast.php
<?php
$servername = "host";
$username = "user"; // username for your database
$password = "password";
$dbname = "database"; // Name of database
$now = new DateTime();
$CRLF = "\n\r";
$conn = mysqli_connect("localhost", "user", "password");
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
$con_result = mysqli_select_db($conn,"database");
if(!$con_result) {
die('Could not connect to specific database: ' . mysqli_error($conn));
}
$result = mysqli_query($conn, "SELECT accion from `datatable` where id = (select MAX(id) from datatable)");
if (!$result) {
die('Invalid query: ' . mysqli_error($conn));
}
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "accion=" . $row["accion"];
}
mysqli_close($conn);
?>
The first HTTP request returns the state of toggle button correctly. But the next HTTP requests return BAD HTTP REQUEST:
IPD,298:HTTP/1.1 200 OK
Date: Fri, 01 Dec 2017 01:40:56 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Server: awex
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Request-ID: cf44e42dbd53cb7cb5456e4b70e3399d
10
accion: encender
+IPD,5:0
+IPD,428:HTTP/1.1 400 Bad Request
Date: Fri, 01 Dec 2017 01:40:56 GMT
Content-Type: text/html
Content-Length: 170
Connection: close
Server: awex
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Request-ID: d8ffa7b4eece5d1e88c7786fea5ace9f
<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>openresty</center>
</body>
</html>
CLOSED
What I am doing wrong?
I had the same problem, but was able to fix it with:
while(SerialESP8266.available()>0) {
char c=SerialESP8266.read();
Serial.write(c);
cadena.concat(c); //store the request string on "cadena"
if (cadena.length() > 50) cadena = "";
}
The problem is due to the limit of string.indexof();
Max characters supported are 170, anything larger will not work.

Wemos D1 404 Not Found - but it is there

I am trying to connect my Wemos D1 to a website to get some data, but I am getting a 404 Not Found Error. I made sure that the url is correct, but I am stilling getting errors. I looked at the errors in the log, but they are empty.
#include <ESP8266WiFi.h>
const char* ssid = "SSID"; // SSID of local network
const char* password = "xxxxx"; // Password on network
String APIKEY = "xxxx";
WiFiClient client;
char servername[]="notreal.com"; // fake host for sample
String result;
int readKey;
int count;
int cursorPosition;
int button;
int x = 0;
void setup() {
//Setup Serial
Serial.begin(9600);
//Connecting to server and get current temperature and set temperature
lcd.print(" Connecting");
Serial.println("Connecting");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("NOT CONNECTED");
lcd.setCursor(cursorPosition,2);
lcd.print(".");
cursorPosition++;
}
getData();
//Serial.println("Connected");*/
delay(1000);
}
void loop() {
//Do Something
}
void getData() //client function to send/receive GET request data.
{
if (client.connect(servername, 80)) { //starts client connection, checks for connection
client.println("GET /data/getData.php?API="+APIKEY);
client.println("HTTP/1.1");
client.println("Host: notreal.com");
client.println("Connection: close");
client.println();
}
else {
Serial.println("connection failed"); //error message if no client connect
Serial.println();
}
while(client.connected() && !client.available()) delay(1); //waits for data
while (client.connected() || client.available()) { //connected or data available
char c = client.read(); //gets byte from ethernet buffer
result = result+c;
}
client.stop(); //stop client
result.replace('[', ' ');
result.replace(']', ' ');
Serial.println(result);
}
This is what I get in the serial:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /nest/getTemp.php was not found on this server.</p>
<p>Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.</p>
</body></html>
This is in the error log:
[host.com] [Fri Aug 05 03:57:33 2016] [error] [client 24.28.29.44] client denied by server configuration: /home/domains/host.com/.htaccess
I checked the server setting and according to support, everything should be set for remote access.

Arduino Getting Data From Web Page

I'm trying to connect my Arduino uno + Ethernet shield to a php script that gets a value from a database and then is sent back which then is displayed on a serial monitor. It works, it connects successfully and i get the value sent back however I'm having trouble displaying it on the serial monitor. It should just display what the server sends however it doesn't. Any one can help?
The Serial Output : It should just output "The Value", however there are numbers that shouldn't be there. If i output this to a LCD monitor i can't have them numbers present.
connecting...
connected
HTTP/1.1 200 OK
Server: cloudflare-nginx
Date: Sat, 04 Jan 2014 15:36:51 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: close
Set-Cookie: __cfduid=dcef101052b82760c1a2de019e6b076141388849811461; expires=Mon, 23-Dec-2019 23:50:00 GMT; path=/; domain=.linku.biz; HttpOnly
X-Powered-By: PHP/5.3.27
CF-RAY: e7901b6dec606e2
4
The
5
Value
0
disconnecting.
PHP Script
<?php
echo 'The Value';
?>
Arduino Script
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "www.linku.biz"; // name address for Google (using DNS)
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,0,177);
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
client.println("GET /arduino.php HTTP/1.1");
client.println("Host: www.linku.biz");
client.println("Connection: close");
client.println();
}
else {
// kf you didn't get a connection to the server:
Serial.println("connection failed");
}
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
while(true);
}
}
Don't know if this helps, but notice that the numbers are the count of available chars which are read out. 4 "The " and 5 "value"
I would expect that client.available returns the 4 and 5 values just after those chars are received. How they got converted to ASCI "4" and "5" and printed, I have no idea.
I parse data by this code
String readString;
//gets byte from ethernet buffer
readString += client.read(); //places captured byte in
//parse readString for request
index = readString.indexOf("text"); //finds location of first "text"
data_want = readString.substring(index+some char, index+some char); //captures data String
Serial.println(data_wand);

Resources