#include <FFat.h>
#include "wifi.h"
#include <WiFiClientSecure.h>
#include <Wire.h>
#include "RTClib.h"
#include "files.h"
char laikas[20] = "YYYY-MM-DD hh:mm:ss";
//#include "certs.h"
RTC_DS1307 rtc;
#include "sensor.h"
DateTime now;
char jwt[943];
uint32_t iat, jwtexp;
void setup() {
Serial.begin(115200);
setupDS18B20();
Wire.begin(21,20);
if (! rtc.begin()) Serial.println("Couldn't find RTC");
wifiset();
//configTime(3600*2, 3600*1, "pool.ntp.org");
Serial.printf("Time: %s\n", rtc.now().toString(laikas));
if (!FFat.begin(true,"/ft",10,"fat")) {
Serial.println("FFat Mount Failed");
return;
} else Serial.println("FFat mounted.");
WiFiClientSecure *cln = new WiFiClientSecure;
const char* server = "identitytoolkit.googleapis.com";
//cln->setCACert(root_ca);
//cln->setCACert(root_ca2);
cln->setInsecure();
String reqt = "{ \"email\": \"[email protected]\", \"password\":\"123456789\",\"returnSecureToken\":true}";
String urlt = "/v1/accounts:signInWithPassword?key=AIzaSyDozinTFHn9REYox0W2kiJc1cOQRpcxaRo";
//identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyDozinTFHn9REYox0W2kiJc1cOQRpcxaRo
Serial.print("Getting token from password.. " + String(server));
bool skiptoken = true;
if (skiptoken || !cln->connect(server, 443)) {
Serial.print(" .. FAILED!\n");
} else { Serial.print(" ..connected .. ");
String req = "POST "+urlt+ " HTTP/1.1\r\n"
"Host: " + String(server) + "\r\n"
"User-Agent: ESP \r\n"
"Accept: application/json\r\n"
"Content-Type: application/json\r\n"
"Content-Length: " + String(reqt.length()) + "\r\n"
"\r\n" + reqt + "\r\n";
cln->print(req);
while (cln->connected()) {
String line = cln->readStringUntil('\n');
if (line == "\r") {
break;
}
}
while (cln->available()) {
String c = cln->readStringUntil('\n');
if (c.indexOf("idToken")>0) {
Serial.printf(" token received, length %i.\n", c.length()-12);
//Serial.println(c);
strncpy(jwt, c.substring(12,c.length()-2).c_str(), sizeof(jwt)-1);
} //else {Serial.println("idToken NOT found"); }
}
cln->stop();
File f = FFat.open("/data.txt", FILE_APPEND);
now = rtc.now();
f.println(now.unixtime());
Serial.println("Token " + String(jwt).substring(610,620) + " will expire at " + now.toString(laikas));
f.println(jwt);
f.close();
}
}
void loop() {
//DeviceAddress tAddr;
//sensors.requestTemperatures();
//float temperatureC = 1;//DS18B20.getTempCByIndex(0);
//float temperatureF = sensors.getTempFByIndex(0);
//for (int i=0; i<devices;i++) {
//Serial.printf("\nTemperature #%i: %3.f\n", i, getTemperature(tAddr[i]));
//DS18B20.requestTemperatures();
//}
sensor();
//Serial.println("ºC");
//sensors.getAddress(tAddr, 0);
//for (uint8_t j = 0; j < 8; j++) Serial.printf("%02X", tAddr[j]);
//Serial.printf(", resolution: %i ]\n", sensors.getResolution(tAddr));
delay(10);
}