T-DEV-811/IOT/lib/API/src/API.cpp

81 lines
2.2 KiB
C++
Raw Normal View History

2023-03-27 17:42:17 +02:00
#include "../include/API.h"
2023-03-28 16:05:36 +02:00
API::API(String user, String password, String host, bool https = true){
this->user = user;
this->password = password;
this->serveurHost = host;
this->https = https;
this->token = "";
this->client = new WiFiEspClient();
}
bool API::wifiBegin(String wifiId, String wifiPass, Stream* espSerial){
WiFi.init(espSerial);
// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
2023-04-03 11:09:44 +02:00
Serial.println("WiFi shield not present");//FIXME: rm debug
return false;
}
// attempt to connect to WiFi network
int status = WL_IDLE_STATUS; // the Wifi radio's status
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");//FIXME: rm debug
Serial.println(wifiId);//FIXME: rm debug
status = WiFi.begin(wifiId.c_str(), wifiPass.c_str());
}
return true;
2023-03-27 17:42:17 +02:00
}
JSONVar* API::connect(){
2023-04-03 12:06:39 +02:00
JSONVar* sortie =nullptr;
JSONVar data;
data["identity"] = this->user;
data["password"] = this->password;
String StrData = JSONVar::stringify(data);
if(this->https){
if (!this->client->connectSSL(this->serveurHost.c_str(), 443)) {
Serial.println("NOT Connected to server");
2023-04-03 12:06:39 +02:00
return sortie;
}
this->client->println("POST /api/collections/users/auth-with-password HTTP/1.1");
this->client->println("Host: iot.epi.cb85.software");
this->client->println("Content-Type: application/json");
this->client->println("Content-Length: " + String(StrData.length()));
this->client->println();
this->client->println(StrData);
this->client->println("Connection: close");
this->client->println();
2023-04-03 12:06:39 +02:00
}else{
//TODO: implement http (no 's') request
}
2023-04-03 12:06:39 +02:00
while (!client->available()) {
}
String responce = "";
while (client->available()) {
responce += (char)client->read();
}
String str = responce.substring(responce.indexOf("{"),responce.lastIndexOf("}")+1);
sortie = new JSONVar(JSONVar::parse(str));
this->token = JSONVar::stringify((*sortie)["token"]);
this->token = this->token.substring(1,this->token.length()-1);
Serial.println(this->token);
2023-03-27 17:42:17 +02:00
return sortie;
}