#ifndef HQ_H #define HQ_H #include #include #include "Buffer.h" #include "ca_cert.h" class HQ { public: // Public static function to get the instance of the singleton class static HQ& getInstance() { static HQ instance; // Create a single instance of the class on first call return instance; // Return the single instance on each call } private: // Private constructor and copy constructor to prevent outside instantiation HQ(){ client = new NetworkClientSecure; if(!client) { Serial.printf("Unable to create HTTP client\r\n"); } client->setCACert(ca_cert); client->setHandshakeTimeout(5); } HQ(const HQ&) = delete; Buffer txBuffer=Buffer(4096,'&'); Buffer rxBuffer=Buffer(1024,'\n'); NetworkClientSecure *client; public: unsigned long httpErrors=0; boolean send(const char *s){ Serial.printf("HQ_SEND:%s\r\n",s); return txBuffer.add(s); } template boolean send(const char* format, T arg1, Args... args) { static char msg[1024]; snprintf(msg, 1024, format, arg1, args...); return send(msg); } boolean poll(){ String payload; if(strlen(txBuffer.get())){ payload+=txBuffer.get(); } if(payload.isEmpty()){ return true; } HTTPClient https; https.setTimeout(1000); https.setConnectTimeout(1000); https.addHeader("Content-Type","application/x-www-form-urlencoded"); String url="https://api.ecomotus.co.uk/api/v1/graphite"; Serial.printf("Connecting to %s\r\n",url.c_str()); if(!https.begin(*client, url)) { // HTTPS Serial.printf("HTTP Connection Failed\r\n"); httpErrors++; return false; } int httpCode=https.POST(payload); if(httpCode==200){ txBuffer.clear(); // Read all the lines of the reply from server and print them to Serial boolean command=false; char buff[128]; int totalSize=0; NetworkClient * stream = https.getStreamPtr(); while(stream->available() && totalSize<1000) { size_t size=stream->readBytesUntil('\n',buff,120); totalSize+=size; buff[size]=0; Serial.printf("Response: %s\r\n",buff); if(command==true){ rxBuffer.add(buff); command=false; } if(0==strcmp(buff,"COMMAND")){ command=true; } } Serial.printf("Got %d bytes\r\n",totalSize); }else{ Serial.printf("HTTP Error: %d\r\n",httpCode); httpErrors++; return false; } return true; } }; HQ& hq = HQ::getInstance(); #endif