Skip to content

Commit

Permalink
Done implementing Realtime Postgres Changes
Browse files Browse the repository at this point in the history
  • Loading branch information
jhagas committed Jul 19, 2024
1 parent b2b45fa commit 1d5a099
Show file tree
Hide file tree
Showing 6 changed files with 303 additions and 415 deletions.
77 changes: 0 additions & 77 deletions examples/combined-example/combined-example.ino

This file was deleted.

106 changes: 31 additions & 75 deletions examples/realtime-postgresChanges/realtime-postgresChanges.ino
Original file line number Diff line number Diff line change
@@ -1,94 +1,50 @@
#include <Arduino.h>
#include <ArduinoJson.h>
#include <ESP_Supabase.h>
#include <ESP_Supabase_Realtime.h>

#if defined(ESP8266)
#include <ESP8266WiFi.h>
#else
#include <WiFi.h>
#endif

enum DEBUGTYPES {
DEBUG_ERROR,
DEBUG_INFO,
DEBUG_MOTOR,
DEBUG_VERBOSE,
DEBUG_LED,
DEBUG_FEED,
DEBUG_SYNC
};
SupabaseRealtime realtime;

typedef enum DEBUGTYPES DEBUGTYPES;
void DevicesTableHandler(String result)
{
JsonDocument doc;
deserializeJson(doc, result);


DEBUGTYPES APP_DEBUG_LEVEL[4] = {
DEBUG_ERROR,
DEBUG_FEED,
DEBUG_INFO,
DEBUG_SYNC
};

void DEBUG_PRINT(String str, DEBUGTYPES debuglevel) {
for (int i = 0; i < 4; i++) {
if (APP_DEBUG_LEVEL[i] == debuglevel) {
Serial.println(String(APP_DEBUG_LEVEL[i]) + " " + str);
return;
}
}

return;
}


void wifiConnected() {
DEBUG_PRINT("WiFi Connected: " + WiFi.SSID(), DEBUG_INFO);
DEBUG_PRINT("IP Address: ", DEBUG_INFO);
DEBUG_PRINT(String(WiFi.localIP()), DEBUG_INFO);
// Example of what you can do with the result
String state = doc["state"];
Serial.println(state);
}

bool waitForWifi(int timeout = 0, String method = "") {
int cnt = 0;
ProgressBar status = ProgressBar(timeout);
DEBUG_PRINT("", DEBUG_INFO);

DEBUG_PRINT("Attempting Connection: " + method, DEBUG_INFO);
status.start();

while (WiFi.status() != WL_CONNECTED) {
delay(500);
status.step();
cnt++;

if (cnt >= timeout && timeout > 0) {
status.end();
return false;
}
}
status.end();

return true;
}

Supabase db;

void DevicesTableHandler(JsonDocument result) {
serializeJson(result, Serial);
}

void setup() {
void setup()
{
Serial.begin(9600);

WiFi.begin("ssid", "password");
if (waitForWifi(50, ".ENV")) {
wifiConnected();
};

db.setupRealtime(SUPABASEURL, SUPABASEANONKEY);
int numqueries = 0;
SUPABASEQuery queries[numqueries] = {};
db.realtime.addEntry("Devices", "*", queries, numqueries, DevicesTableHandler);
while (WiFi.status() != WL_CONNECTED)
{
delay(100);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");

realtime.begin("https://project.supabase.co", "apikey");
realtime.login_email("email", "password"); // Only if you activate RLS in your Supabase Postgres Table

// Parameter 1 : Table name
// Parameter 2 : Event type ("*" | "INSERT" | "UPDATE" | "DELETE")
// Parameter 3 : Filter
// Please read : https://supabase.com/docs/guides/realtime/postgres-changes?queryGroups=language&language=js#available-filters
// empty string if you don't want to filter the result
// Parameter 4 : Callback function, how to handle the result (message)
realtime.listen("table", "*", "", DevicesTableHandler);
}

void loop() {
db.realtime.loop();
void loop()
{
realtime.loop();
}
54 changes: 54 additions & 0 deletions src/ESP-Supabase-Realtime.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#ifndef ESP_Supabase_Realtime_h
#define ESP_Supabase_Realtime_h

#include <Arduino.h>
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>
#include <WebSocketsClient.h>

#if defined(ESP8266)
#include <ESP8266HTTPClient.h>
#elif defined(ESP32)
#include <HTTPClient.h>
#else
#error "This library is not supported for your board! ESP32 and ESP8266"
#endif

class SupabaseRealtime
{
private:
WebSocketsClient webSocket;

String key;
String hostname;

String phone_or_email;
String password;
String data;
String loginMethod;
String USER_TOKEN = "";
bool useAuth;
int _login_process();
unsigned int authTimeout = 0;
unsigned long loginTime;

const char *config = "{\"event\":\"phx_join\",\"topic\":\"realtime:ESP\",\"payload\":{\"config\":{\"postgres_changes\":[{\"event\":\"abcdfeghijklmbopq\",\"schema\":\"public\",\"table\":\"abcdfeghijklmbopq\"}]}},\"ref\":\"sentRef\"}";
unsigned int last_ms = millis();
const char *jsonRealtimeHeartbeat = R"({"event": "heartbeat","topic": "phoenix","payload": {},"ref": "sentRef"})";
const char *tokenConfig = R"({"topic": "realtime:ESP","event": "access_token","payload": {
"access_token": ""
},"ref": "sendRef"})";

void processMessage(uint8_t *payload, void (*func)(String));
void webSocketEvent(WStype_t type, uint8_t *payload, size_t length, String configJSON, void (*func)(String));

public:
SupabaseRealtime() {}
void begin(String hostname, String key);
void listen(String table, String event, String filter, void (*func)(String));
void loop();
int login_email(String email_a, String password_a);
int login_phone(String phone_a, String password_a);
};

#endif
61 changes: 5 additions & 56 deletions src/ESP-Supabase.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
#include <Arduino.h>
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>
#include <WebSocketsClient.h>

#if defined(ESP8266)
#include <ESP8266HTTPClient.h>
Expand All @@ -14,82 +13,32 @@
#error "This library is not supported for your board! ESP32 and ESP8266"
#endif

struct SupabaseQuery
{
String key;
String comparator;
String value;
};

class SupabaseRealtimeTableEntry
{
private:
WiFiClientSecure client;
WebSocketsClient webSocket;
std::function<void(JsonDocument)> handleEvent; // Changed to std::function
String jsonRealtimeConfig;
String key;
String hostname;

public:
void setupHandler(std::function<void(JsonDocument)> handler);

SupabaseRealtimeTableEntry(String key, String hostname)
{
hostname.replace("https://", "");
this->key = key;
this->hostname = hostname;
}

void setupListener(String table, String event, SupabaseQuery queries[], int numqueries);
void processMessage(uint8_t *payload, size_t length, JsonDocument result);
void webSocketEvent(WStype_t type, uint8_t *payload, size_t length);
void loop();
};

class SupabaseRealtime
{
private:
String hostname;
String key;
// Define an array to store SUPABASERealtimeTableEntry objects
std::vector<SupabaseRealtimeTableEntry> entries;

public:
SupabaseRealtime(){}
void setupConnection(String hostname, String key);
// Function to add a SUPABASERealtimeTableEntry object to the array
void addEntry(String table, String event, SupabaseQuery queries[], int numqueries, std::function<void(JsonDocument)> handler);\
void loop();
};

class Supabase
{
private:
String hostname;
String key;
String USER_TOKEN;

String url_query;

WiFiClientSecure client;
HTTPClient https;

bool useAuth;
unsigned long loginTime;
String phone_or_email;
String password;
String data;
String loginMethod;
String filter;

unsigned int authTimeout = 0;

void _check_last_string();
int _login_process();
unsigned int authTimeout = 0;
unsigned long loginTime;

public:
SupabaseRealtime realtime;
bool useAuth;
String USER_TOKEN;

Supabase() {}
~Supabase() {}

Expand Down
Loading

0 comments on commit 1d5a099

Please sign in to comment.