Skip to content

Instantly share code, notes, and snippets.

@alexastrum
Last active July 29, 2020 22:19
Show Gist options
  • Save alexastrum/070c853f1173b22382d56052b0e62179 to your computer and use it in GitHub Desktop.
Save alexastrum/070c853f1173b22382d56052b0e62179 to your computer and use it in GitHub Desktop.
#define WIFI_SSID ""
#define WIFI_PASSWORD ""
// Firebase
#define DEVICE_ID "TestDevice"
#define PROJECT_ID ""
#include <ArduinoHttpClient.h>
bool firebaseDatabasePut(String path, DynamicJsonDocument jsonDoc, String idToken = "") {
String jsonStr;
serializeJson(jsonDoc, jsonStr);
displayStatus("Saving to RTDB: " + path + " = " + jsonStr);
String host = String(PROJECT_ID) + ".firebaseio.com";
WiFiSSLClient wifiClient;
HttpClient httpClient = HttpClient(wifiClient, host, 443);
String url = "/" + path + ".json";
if (idToken != "") {
url = url + "?auth=" + idToken;
}
httpClient.put(url, "application/json", jsonStr);
int statusCode = httpClient.responseStatusCode();
String response = httpClient.responseBody();
if (statusCode != 200) {
displayError(String(statusCode) + " " + response);
return false;
}
displayStatus("Saved to RTDB.");
return true;
}
#include "config.h"
#include "display.h"
#include "wifi.h"
#include "json.h"
#include "firebase_database.h"
void setup()
{
setupDisplay();
setupWiFi();
}
void loop()
{
DynamicJsonDocument json(1024);
json["hello"] = "world";
firebaseDatabasePut(DEVICE_ID, json);
displaySuspend("All done!");
}
#include <ArduinoJson.h>
/**
* Converts a String into a JsonDocument of correct size.
* In case of error, the returned `jsonDoc.isNull()` will be true.
*/
DynamicJsonDocument toJsonDocument(String str, int size = 0) {
if (size == 0) {
size = JSON_OBJECT_SIZE(1) + str.length();
}
DynamicJsonDocument jsonDoc(str.length() * 2);
DeserializationError error = deserializeJson(jsonDoc, str);
if (error) {
displayError("JSON " + String(error.c_str()) + ": " + str);
jsonDoc.clear();
}
return jsonDoc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment