AfRApay/AfRApay.MateCard/src/utils.cpp
2023-02-06 02:37:36 +01:00

80 lines
2.6 KiB
C++

#include <Arduino.h>
#include <WiFiClient.h>
#include <HTTPClient.h>
String byteArrayAsHexString(byte *buffer, byte bufferSize) {
String s = "";
for (byte i = 0; i < bufferSize; i++) {
s += (buffer[i] < 0x10 ? "0" : "");
s += String(buffer[i], HEX);
}
return s;
}
unsigned long cooldownSecondsRemaining(unsigned long timeout, unsigned long timer) {
return (timeout - (millis() - timer)) / 1000 + 1;
}
String splitString(String data, char separator, int index) {
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++) {
if (data.charAt(i) == separator || i == maxIndex) {
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i + 1 : i;
}
}
return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}
String cardLink(WiFiClient *wifi, HTTPClient *http, String apiUrl, String cardId) {
String finalRequestUrl = apiUrl + "/api/card/link?card=" + cardId;
http->begin(*wifi, finalRequestUrl.c_str());
int httpResponseCode = http->GET();
if (httpResponseCode == 200) {
String payload = http->getString();
http->end();
return payload;
}
http->end();
if (httpResponseCode > 0) {
return String("E:HTTP Error ") + httpResponseCode;
}
return String("E:Internal Error ") + httpResponseCode;
}
String cardBalance(WiFiClient *wifi, HTTPClient *http, String apiUrl, String cardId) {
String finalRequestUrl = apiUrl + "/api/card/balance?card=" + cardId;
http->begin(*wifi, finalRequestUrl.c_str());
int httpResponseCode = http->GET();
if (httpResponseCode == 200) {
String payload = http->getString();
http->end();
return payload;
}
http->end();
if (httpResponseCode > 0) {
return String("E:HTTP Error ") + httpResponseCode;
}
return String("E:Internal Error ") + httpResponseCode;
}
String cardTransaction(WiFiClient *wifi, HTTPClient *http, String apiUrl, String cardId, String amount) {
String finalRequestUrl = apiUrl + "/api/card/transaction?card=" + cardId + "&amount=" + amount;
http->begin(*wifi, finalRequestUrl.c_str());
int httpResponseCode = http->GET();
if (httpResponseCode == 200) {
String payload = http->getString();
http->end();
return payload;
}
http->end();
if (httpResponseCode > 0) {
return String("E:HTTP Error ") + httpResponseCode;
}
return String("E:Internal Error ") + httpResponseCode;
}