Read Value from URL with ESP8266 - arduino-uno

my friend made a google script, and gave me this link: https://script.google.com/macros/s/AKfycbxxWwU59sp_rF9C6phVIFSdLF6IIM83hFRWUrrJyVI8TdY6F-t1/exec
If you click you will se "52" in your browser.
Now I want to create a script in Arduino that can receive this value and use it in order to adjust the amount of light of a LED (code below is without LED part).
I wrote a code:
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiClientSecure.h>
const char* ssid = "TabletS3";
const char* password = "123456789";
//https://script.google.com/macros/s/AKfycbxxWwU59sp_rF9C6phVIFSdLF6IIM83hFRWUrrJyVI8TdY6F-t1/exec
WiFiServer server(80);
//String GAS_ID = "AKfycbxxWwU59sp_rF9C6phVIFSdLF6IIM83hFRWUrrJyVI8TdY6F-t1"; // Replace by your GAS service id
const char* host = "script.google.com";
const int httpsPort = 443;
const char* fingerprint = "46 B2 C3 44 9C 59 09 8B 01 B6 F8 BD 4C FB 00 74 91 2F EF F6";
WiFiClientSecure client;
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void loop() {
String url = "https://script.google.com/macros/s/AKfycbxxWwU59sp_rF9C6phVIFSdLF6IIM83hFRWUrrJyVI8TdY6F-t1/exec";
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
//"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Connection: close\r\n\r\n");
Serial.println("Response:");
while (client.connected())
{
String line = client.readStringUntil('\r');
Serial.print(line);
client.flush();
}
delay(10000);
}
but I can't read value "52" on Serial Monitor.
Where is the mistake?
Thanks in advance,
RR
After your insight I tried this:
#include <ESP8266WiFi.h>
//#include <DNSServer.h>
//#include <ESP8266WebServer.h>
//#include <WiFiClientSecure.h>
const char* ssid = "TabletS3";
const char* password = "123456789";
//https://script.google.com/macros/s/AKfycbxxWwU59sp_rF9C6phVIFSdLF6IIM83hFRWUrrJyVI8TdY6F-t1/exec
//WiFiServer server(80);
//String GAS_ID = "AKfycbxxWwU59sp_rF9C6phVIFSdLF6IIM83hFRWUrrJyVI8TdY6F-t1"; // Replace by your GAS service id
const char* host = "script.google.com";
const int httpsPort = 443;
const char* fingerprint = "46 B2 C3 44 9C 59 09 8B 01 B6 F8 BD 4C FB 00 74 91 2F EF F6";
WiFiClientSecure client;
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void loop() {
String url = "https://script.google.com/macros/s/AKfycbxxWwU59sp_rF9C6phVIFSdLF6IIM83hFRWUrrJyVI8TdY6F-t1/exec";
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Connection: close\r\n\r\n");
Serial.println("request sent");
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
Serial.println("headers received");
break;
}
}
String line = client.readStringUntil('\n');
if (line.startsWith("{\"state\":\"success\"")) {
Serial.println("esp8266/Arduino CI successfull!");
} else {
Serial.println("esp8266/Arduino CI has failed");
}
Serial.println("reply was:");
Serial.println("==========");
Serial.println(line);
Serial.println("==========");
Serial.println("closing connection");
delay(10000);
}
But doesn't catch nothing

Related

Arduino How to POST a request to a HTTPS with ArduinoHttpClient

I'm pretty new on Arduino. I'm using ArduinoHttpClient and need to POST a request in secure way (https://).
I'm not able to define the https:// on the serverName passed to HttpClient(ethernetClient, serverName, webServerPort).
When I use serverName = url (ssl9083.websiteseguro.com or 179.188.19.74) with port 443 the board hangs and after sometime returns -3 on httpClient.responseStatusCode().
I'm using Arduino Uno R3 with Ethernet Shield W5100.
I'd appreciate any help. Below the code.
Thank you in advance.
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <ArduinoHttpClient.h>
//UDP Variables
#define UDP_PACKET_SIZE 80 //UDP size
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress localIp(192, 168, 1, 9);
unsigned int localPort = 8888; // local port to listen on
char packetBuffer[UDP_PACKET_SIZE]; // buffer to hold incoming packet,
EthernetUDP Udp; // An EthernetUDP instance to let us send and receive packets over UDP
//Http Variables
// Environment = P, H, D
char ENV[1] = {'H'};
const char* devServerName = "192.168.1.105";
const char* homServerName = "179.188.19.74";
//const char* homServerName = "https://ssl9083.websiteseguro.com/cfbinformatica"; Port 80 - NOK Frooze
//const char* homServerName = "https://ssl9083.websiteseguro.com"; Port 80 - NOK Frooze
//const char* homServerName = "ssl9083.websiteseguro.com/cfbinformatica"; Port 80 - NOK Frooze
//const char* homServerName = "ssl9083.websiteseguro.com"; Port 80 - OK conectou e retornou 404
//const char* homServerName = "179.188.19.74"; Port 80 OK conectou e retornou 404 - Port 443 retornou -3
const char* prdServerName = "ssl9083.websiteseguro.com/cfbinformatica";
String measurementServiceInsertMeasurement = "/MeasurementService.svc/InsertMeasurement";
String postInsertMeasurement = "/MeasurementService.svc/InsertMeasurement";
String serverName;
int webServerPort;
EthernetClient ethernetClient;
String authUserUid;
String userValidationUidCredentials;
void setup() {
setupSerial();
setupEthernetUDP();
setupHttp();
}
void setupSerial() {
// Open 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
}
}
void setupEthernetUDP() {
// start the Ethernet
Ethernet.begin(mac, localIp);
Serial.print("IP: ");
Serial.println(Ethernet.localIP());
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Etn shield notFnd");
while (1);
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Cable notConn");
while (1);
}
// start UDP
Udp.begin(localPort);
Serial.println("UDP init OK");
delay(5000);
}
void setupHttp() {
// Your Domain name with URL path or IP address with path
switch(ENV[0]) {
case 'P' :
serverName = prdServerName;
webServerPort = 443;
postInsertMeasurement = "/housemeterprd" + measurementServiceInsertMeasurement;
break;
case 'H' :
serverName = homServerName;
webServerPort = 443;
postInsertMeasurement = "/cfbinformatica/housemeterhom" + measurementServiceInsertMeasurement;
break;
default :
serverName = devServerName;
webServerPort = 80;
postInsertMeasurement = "/housemeterdev" + measurementServiceInsertMeasurement;
}
authUserUid = "Mg==";
userValidationUidCredentials = "PlUfGKwdXKmcF7HEoEPFu5QqGA3w52ukaUsIp5gOOlOXX928fermbxvGNsfbVr4Q";
Serial.println("HTTP init OK");
}
void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i=0; i < 4; i++) {
Serial.print(remote[i], DEC);
if (i < 3) {
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(Udp.remotePort());
readPackage();
processPackage();
}
delay(10);
}
void readPackage() {
// read the packet into packetBufffer
Udp.read(packetBuffer, UDP_PACKET_SIZE);
Serial.println("Contents:");
Serial.println(packetBuffer);
}
void processPackage() {
switch(packetBuffer[0]) {
case 'A' :
handleAckMsg();
break;
case 'E' :
handleErrorMsg();
break;
default :
handleDataMsg();
}
}
void handleAckMsg() {
}
void handleErrorMsg() {
}
void handleDataMsg() {
String meterMAC;
meterMAC = convertToString(packetBuffer+35, 12);
String measurementValue;
measurementValue = convertToString(packetBuffer+20, 15);
String postData = "{\"meterMAC\":\"" + meterMAC + "\",\"measurementValue\":" + measurementValue +"}";
sendHttpPostDataMsg(&postData);
replyBack();
}
void sendHttpPostDataMsg(String *postData) {
Serial.print(serverName);
Serial.println(" Server ");
Serial.print(webServerPort);
Serial.println(" port ");
Serial.print(postInsertMeasurement);
Serial.println(" Url");
String data = *postData;
Serial.print(data);
Serial.println(" data ");
Serial.print(data.length());
Serial.println(" data length ");
HttpClient httpClient = HttpClient(ethernetClient, serverName, webServerPort);
httpClient.beginRequest();
httpClient.post(postInsertMeasurement);
httpClient.sendHeader("Content-Type", "application/json;charset=utf-8");
httpClient.sendHeader("Content-Length", data.length());
httpClient.sendHeader("Accept", "application/json");
httpClient.sendHeader("AuthUserUid", authUserUid);
httpClient.sendHeader("AuthUserValidationUid", userValidationUidCredentials);
httpClient.sendHeader("DeviceLanguage", "English");
httpClient.sendHeader("AuthUserProfile", "user");
httpClient.beginBody();
httpClient.print(data);
httpClient.endRequest();
int statusCode = httpClient.responseStatusCode();
String response = httpClient.responseBody();
httpClient.flush();
httpClient.stop();
Serial.print(statusCode);
Serial.println(" Http ret code");
Serial.print("Response: ");
Serial.println(response);
}
void replyBack() {
// send a reply to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(packetBuffer);
Udp.endPacket();
}
String convertToString(char* arr, int size)
{
int i;
String s = "";
for (i = 0; i < size; i++) {
s = s + arr[i];
}
return s;
}
here the results of the http call:
21:30:49.179 -> IP: 192.168.1.9
21:30:49.179 -> UDP init OK
21:30:54.226 -> HTTP init OK
21:31:05.891 -> Received packet of size 47
21:31:05.891 -> From 192.168.1.32, port 58412
21:31:05.937 -> Contents:
21:31:05.937 -> 000000000000000010330000000017.9090DEADBEEFFEED
21:31:05.985 -> 179.188.19.74 Server
21:31:06.031 -> 443 port
21:31:06.031 -> /cfbinformatica/housemeterhom/MeasurementService.svc/InsertMeasurement Url
21:31:06.125 -> {"meterMAC":"DEADBEEFFEED","measurementValue":0000000017.9090} data
21:31:06.172 -> 62 data length
21:32:07.214 -> -3 Http ret code
21:32:07.214 -> Response:

Why have I connection failed when I try to connect to my localhost?

I have an esp32 with one sensor(BMP280) connected and one database where I want to storage three parameters: temperature, atmospheric pressure and altitude. The database is on localhost with 8080 port. I cannot to connect at my localhost and I have connection failed. I have tried to put at host the ip address 0.0.0.0 or localhost:8080 and it doesn't work. What is the problem?
I attach my code below:
#include <BMP280_DEV.h>
#include <WiFi.h>
float temperature, pressure, altitude;
BMP280_DEV bmp280;
const char * ssid = "*******";
const char * password = "*********";
const char * host = "127.0.0.1";
const int port = 8080;
const int watchdog = 5000;
unsigned long previousMillis = millis();
void init_wifi() {
//We start by connecting to a Wi-Fi network
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 setup() {
Serial.begin(115200);
bmp280.begin(BMP280_I2C_ALT_ADDR);
//bmp280.setPresOversampling(OVERSAMPLING_X4);
//bmp280.setTempOversampling(OVERSAMPLING_X1);
//bmp280.setIIRFilter(IIR_FILTER_4);
bmp280.setTimeStandby(TIME_STANDBY_2000MS);
bmp280.startNormalConversion();
init_wifi();
}
void loop() {
if (bmp280.getMeasurements(temperature, pressure, altitude)) {
Serial.print(temperature);
Serial.print(F("*C "));
Serial.print(pressure);
Serial.print(F("hPa "));
Serial.print(altitude);
Serial.println(F("m"));
delay(20000);
}
unsigned long currentMillis = millis();
if (currentMillis - previousMillis > watchdog) {
previousMillis = currentMillis;
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("Connection Failed");
return;
}
String url = "/test_bmp280/index.php?temp=";
url += temperature;
url += "&pres=";
url += pressure;
url += "&alt=";
url += altitude;
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;
}
}
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
}
}

esp8266 NodeMCU client cant connect to esp8266 NodeMCU server with static ip

Hello...
My code is working perfect with using dynamic IP's, the LED is connected to server and a push button is connected to client, it work perfect with dynamic IP's addresses of both devices. But when i make static IP addresses, the client can not connect to server, and it always says connection failed.
Client code is:
#include <ESP8266WiFi.h>
//IPAddress staticIP612_61(192,168,100,59);
//IPAddress gateway612_61(192,168,100,1);
//IPAddress subnet612_61(255,255,255,0);
const char* ssid = "GravixarATD"; // Your wifi Name
const char* password = "TheRedMonster79"; // Your wifi Password
const char * host = "192.168.100.23"; // IP Server
const int httpPort = 80;
const char* Commands; // The command variable that is sent to the server
int button = 5; // push button is connected
bool btn_press = true; // The variable to detect the button has been pressed
int con = 0; // Variables for mode
void setup() {
// put your setup code here, to run once:
pinMode(button, INPUT_PULLUP); // initialize the pushbutton pin as an input:
Serial.begin(115200); // initialize serial:
Serial.println("");
Serial.println("Client-------------------------------");
Serial.print("Connecting to Network");
WiFi.mode(WIFI_STA); // Mode Station
WiFi.begin(ssid, password); // Matching the SSID and Password
delay(1000);
// Waiting to connect to wifi
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("Successfully Connecting");
Serial.println("Status : Connected");
//WiFi.config(staticIP612_61, gateway612_61, subnet612_61);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("-------------------------------------");
Serial.println("");
}
void loop() {
// put your main code here, to run repeatedly:
if (digitalRead(button) == LOW) {
Serial.println("Client-------------------------------");
Serial.print("Send Command = ");
if (btn_press == true){
if (con >= 2) {
con=0;
}
con++;
switch (con){
case 1:
Commands="LED_On";
Serial.println(Commands);
send_commands();
break;
case 2:
Commands="LED_Off";
Serial.println(Commands);
send_commands();
break;
}
btn_press = false;
}
}
else {
btn_press = true;
}
delay(100);
}
void send_commands(){
Serial.println("Sending command...");
Serial.println("Don't press the button for now...");
Serial.println("");
Serial.print("Connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, httpPort)) {
Serial.println("Connection failed");
return;
}
// We now create a URI for the request
Serial.print("Requesting URL : ");
Serial.println(Commands);
// This will send the request to the server
client.print(String("GET ") + Commands + " 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;
}
}
Serial.print("Server Reply = ");
// 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("Now you can press the button ...");
Serial.println("-------------------------------------");
Serial.println("");
}
Server code is:
#include <ESP8266WiFi.h>
//IPAddress staticIP612_60(192,168,100,60);
//IPAddress gateway612_60(192,168,100,1);
//IPAddress subnet612_60(255,255,255,0);
int led = 5; // the pin the LED is connected to
const char* ssid = "GravixarATD"; // Your wifi Name
const char* password = "TheRedMonster79"; // Your wifi Password
const char* Commands_Reply; // The command variable that is sent to the client
const char * host = "192.168.100.21"; // IP Client
WiFiServer server(80);
void setup() {
// put your setup code here, to run once:
pinMode(led, OUTPUT); // Declare the LED as an output
Serial.begin(115200); // initialize serial:
delay(10);
Serial.println("");
Serial.println("Server-------------------------------");
Serial.print("Configuring access point");
WiFi.begin(ssid, password);
// Waiting to connect to wifi
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// WiFi.config(staticIP612_60, gateway612_60, subnet612_60);
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
Serial.println("-------------------------------------");
Serial.println("");
}
void loop() {
// put your main code here, to run repeatedly:
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("Server-------------------------------");
Serial.println("New client");
Serial.print("From client = ");
while(!client.available()){
delay(1);
}
// Read the first line of the request -------------------------------------
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
//Command LED -------------------------------------------------------------
if (req.indexOf("LED_On") != -1){
Commands_Reply = "LED Status : On";
Serial.print("Server send = ");
Serial.println(Commands_Reply);
client.print(String("GET ") + Commands_Reply + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
digitalWrite(led, HIGH);
}
else if (req.indexOf("LED_Off") != -1){
Commands_Reply = "LED Status : Off";
Serial.print("Server send = ");
Serial.println(Commands_Reply);
client.print(String("GET ") + Commands_Reply + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
digitalWrite(led, LOW);
}
else {
Serial.println("invalid request");
client.stop();
return;
}
client.flush();
Serial.println("Client disonnected");
Serial.println("-------------------------------------");
Serial.println("");
}
NOTE I have commented all the static IP lines, when i comment them and using dynamic ips, client connect to server perfectly and when i use static ips instead of dynamic ips client fails to connect with server. any help will be appreciated.

How do I make an HTTPS request with SIM900 (Arduino)

I try to make an HTTPS GET request and make an HTTPS POST request with the data recieved... I am using an arduino UNO with the library GSM_GPRS_GPS_Shield_GSMSHIELD and the GSM GPRS shield SIM900. Here is my current code below:
//include libs
#include "SIM900.h"
#include "inetGSM.h"
#include <SoftwareSerial.h>
InetGSM inet;
//data holder
int par1 = -1;
int par2 = -1;
void setup() {
Serial.begin(9600);
Serial.println("BEGIN");
boolean started = false;
SIM900power();
//initialize the SIM900
if (gsm.begin(2400)){
Serial.println("READY");
started=true;
}else Serial.println("IDLE");
//connect it to the network
if(started){
if (inet.attachGPRS("free", "", ""))
Serial.println("ATTACHED");
else Serial.println("ERROR");
delay(1000);
gsm.SimpleWriteln("AT+CIFSR");
delay(3000);
gsm.WhileSimpleRead();
//GET request
char * json = "";
while(strlen(json) < 4){
delay(2000);
char msg[200] = "";
Serial.println(inet.httpGET("my.site.com", 80, "/somethingToGet?param=1", msg, 200));
//interpret Json
char * msg_tmp = msg;
json = strstr (msg_tmp, "[{");
}
if(json != ""){
const byte posPar1 = (int)(strstr(json, "par1") - json) + 7;
const byte posPar2 = (int)(strstr(json, "par2") - json) + 7;
if(json[posPar1] != 'u')
par1 = extractNum(json, posPar1);
if(json[posPar2] != 'u')
par2 = extractNum(json, posPar2);
}
if(json == "" || par1 == -1 || par2 == -1){
SIM900power();
Serial.println("A JSON ERROR OCCURED");
while(1){}}
}
};
void loop() {
aPostRequest();
while(1){}
};
void SIM900power()
{
digitalWrite(9, HIGH);
delay(1000);
digitalWrite(9, LOW);
delay(8000);
}
//extract the data from the Json string
int extractPar(char * json, byte pos){
int num = 0;
while (json[pos] != '"'){
num = json[pos]-'0' + num * 10;
pos++;
}
return num;
}
//POST request
void aPostRequest(){
if( par1 != -1 && par2 != -1){
boolean dataFound = true;
while(dataFound){
delay(2000);
char params[100];
snprintf(params, 100, "par1=%d&par2=%d", par1,par2);
char msg[200] = "";
dataFound = (inet.httpPOST("my.site.com ", 80, "/something", params , msg, 200) == 0);
}
}
}
I have two web sites, an HTTP one for my tests and the other one in HTTPS. As you can imagine, it's working on my HTTP one.
I don't know how to solve this problem but I think I need to do some tricky things with certificates in the library... can somebody help?
PS: if you want to test the code, you need to uncomment the HTTPPOST() function in the file inetGSM.h of the library. You can edit the functions httpGET() and HTTPPOST() in the file inetGSM.cpp.
UPDATE
There is the library code for the GET function below (httpPOST() works the same) :
int InetGSM::httpGET(const char* server, int port, const char* path, char* result, int resultlength)
{
boolean connected=false;
int n_of_at=0;
int length_write;
char end_c[2];
end_c[0]=0x1a;
end_c[1]='\0';
/*
Status = ATTACHED.
if(gsm.getStatus()!=GSM::ATTACHED)
return 0;
*/
while(n_of_at<3) {
if(!connectTCP(server, port)) {
#ifdef DEBUG_ON
Serial.println("DB:NOT CONN");
#endif
n_of_at++;
} else {
connected=true;
n_of_at=3;
}
}
if(!connected) return 0;
gsm.SimpleWrite("GET ");
gsm.SimpleWrite(path);
gsm.SimpleWrite(" HTTP/1.0\r\nHost: ");
gsm.SimpleWrite(server);
gsm.SimpleWrite("\r\n");
gsm.SimpleWrite("User-Agent: Arduino");
gsm.SimpleWrite("\r\n\r\n");
gsm.SimpleWrite(end_c);
switch(gsm.WaitResp(10000, 10, "SEND OK")) {
case RX_TMOUT_ERR:
return 0;
break;
case RX_FINISHED_STR_NOT_RECV:
return 0;
break;
}
delay(50);
#ifdef DEBUG_ON
Serial.println("DB:SENT");
#endif
int res = gsm.read(result, resultlength);
//gsm.disconnectTCP();
//int res=1;
return res;
}
I have already tried to change the HTTP/1.0 for HTTPS/1.0, but nothing appends.
UPDATE 2
I redirected my request through my HTTP server because I still have not found an answer, if someone could answer for those who could be blocked!
I was trying to make a HTTPS request to a Lambda function that i coded in AWS. The function had to send a json body from a WEMOS D1 mini via a POST to AWS. TBH, I don't know, if this will solve your Issue on your Controller, but it might be worth trying :)
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#ifndef STASSID
#define STASSID "<yourWiFiSSID>"
#define STAPSK "<yourWifiPW>"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "<the host link here (has to look like **google.com** important, dont add the route here) >";
const int httpsPort = 443;
const String data = "<Json Object here e.g -> **{\"temperature\": 20.5, \"humidity\": 60}**>";
// Use web browser to view and copy
// SHA1 fingerprint of the certificate
const char fingerprint[] PROGMEM = "5F F1 60 31 09 04 3E F2 90 D2 B0 8A 50 38 04 E8 37 9F BC 76";
void setup() {
Serial.begin(115200);
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());
// Use WiFiClientSecure class to create TLS connection
WiFiClientSecure client;
Serial.print("connecting to ");
Serial.println(host);
Serial.printf("Using fingerprint '%s'\n", fingerprint);
client.setFingerprint(fingerprint);
client.setInsecure();
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
return;
}
String url = "<your route here e.g **/photos/test**> ";
Serial.print("requesting URL: ");
Serial.println(url);
client.print(String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n"+
"Content-Length: " + data.length() + "\r\n" +
"Content-Type: application/json;charset=UTF-8\r\n\r\n"+
data +"\r\n");
Serial.println("request sent");
//READ INCOMING HTML
uint8_t * _buffer = new uint8_t[128];
String line = "";
if (client.connected()) {
int actualLength = client.read(_buffer, 128);
// If it fails for whatever reason
if(actualLength <= 0)
{
return;
}
// Concatenate the buffer content to the final response string
// I used an arduino String for convenience
// but you can use strcat or whatever you see fit
//TRANSFORM EVERY CHAR FROM INCOMING HTML
line += String((char*)_buffer).substring(0, actualLength);
if (line == "\r") {
Serial.println("headers received");
}
}
Serial.print("Line: ");
Serial.println(line);
if (line.startsWith("{\"state\":\"success\"")) {
Serial.println("esp8266/Arduino CI successfull!");
} else {
Serial.println("esp8266/Arduino CI has failed");
}
Serial.println("reply was:");
Serial.println("==========");
Serial.println(line);
Serial.println("==========");
Serial.println("closing connection");
}
void loop() {
}
I really hope this might have helped someone.

Whats the purpose of "num" in arduinoWebSockets?

Whats the purpose of num in webSocket.sendTXT(num, "Connected"); or at any other place its used in the code, what function does it serve? Because it doesn't ever get defined as anything anywhere, but it is required to
be passed as a function argument for it to work.
In void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) it's set as a function parameter.
Links2004/arduinoWebSockets Library
/*
* WebSocketServer_LEDcontrol.ino
*
* Created on: 26.11.2015
*
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Hash.h>
#define LED_RED 15
#define LED_GREEN 12
#define LED_BLUE 13
#define USE_SERIAL Serial
ESP8266WiFiMulti WiFiMulti;
ESP8266WebServer server = ESP8266WebServer(80);
WebSocketsServer webSocket = WebSocketsServer(81);
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
USE_SERIAL.printf("[%u] Disconnected!\n", num);
break;
case WStype_CONNECTED: {
IPAddress ip = webSocket.remoteIP(num);
USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
// send message to client
webSocket.sendTXT(num, "Connected");
}
break;
case WStype_TEXT:
USE_SERIAL.printf("[%u] get Text: %s\n", num, payload);
if(payload[0] == '#') {
// we get RGB data
// decode rgb data
uint32_t rgb = (uint32_t) strtol((const char *) &payload[1], NULL, 16);
analogWrite(LED_RED, ((rgb >> 16) & 0xFF));
analogWrite(LED_GREEN, ((rgb >> 8) & 0xFF));
analogWrite(LED_BLUE, ((rgb >> 0) & 0xFF));
}
break;
}
}
void setup() {
//USE_SERIAL.begin(921600);
USE_SERIAL.begin(115200);
//USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
for(uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
pinMode(LED_RED, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_BLUE, OUTPUT);
digitalWrite(LED_RED, 1);
digitalWrite(LED_GREEN, 1);
digitalWrite(LED_BLUE, 1);
WiFiMulti.addAP("SSID", "passpasspass");
while(WiFiMulti.run() != WL_CONNECTED) {
delay(100);
}
// start webSocket server
webSocket.begin();
webSocket.onEvent(webSocketEvent);
if(MDNS.begin("esp8266")) {
USE_SERIAL.println("MDNS responder started");
}
// handle index
server.on("/", []() {
// send index.html
server.send(200, "text/html", "<html><head><script>var connection = new WebSocket('ws://'+location.hostname+':81/', ['arduino']);connection.onopen = function () { connection.send('Connect ' + new Date()); }; connection.onerror = function (error) { console.log('WebSocket Error ', error);};connection.onmessage = function (e) { console.log('Server: ', e.data);};function sendRGB() { var r = parseInt(document.getElementById('r').value).toString(16); var g = parseInt(document.getElementById('g').value).toString(16); var b = parseInt(document.getElementById('b').value).toString(16); if(r.length < 2) { r = '0' + r; } if(g.length < 2) { g = '0' + g; } if(b.length < 2) { b = '0' + b; } var rgb = '#'+r+g+b; console.log('RGB: ' + rgb); connection.send(rgb); }</script></head><body>LED Control:<br/><br/>R: <input id=\"r\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" /><br/>G: <input id=\"g\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" /><br/>B: <input id=\"b\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" /><br/></body></html>");
});
server.begin();
// Add service to MDNS
MDNS.addService("http", "tcp", 80);
MDNS.addService("ws", "tcp", 81);
digitalWrite(LED_RED, 0);
digitalWrite(LED_GREEN, 0);
digitalWrite(LED_BLUE, 0);
}
void loop() {
webSocket.loop();
server.handleClient();
}
Looking at the library's source code, it reveals that it's a client id, so you can differentiate between multiple clients, that are connected at the same time.
/*
* send text data to client
* #param num uint8_t client id
* #param payload uint8_t *
* #param length size_t
* #param headerToPayload bool (see sendFrame for more details)
* #return true if ok
*/
bool WebSocketsServer::sendTXT(uint8_t num, uint8_t * payload, size_t length, bool headerToPayload) {
if(num >= WEBSOCKETS_SERVER_CLIENT_MAX) {
return false;
}
if(length == 0) {
length = strlen((const char *) payload);
}
WSclient_t * client = &_clients[num];
if(clientIsConnected(client)) {
return sendFrame(client, WSop_text, payload, length, false, true, headerToPayload);
}
return false;
}

Resources