Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds threshold to switch as an option #13

Merged
merged 2 commits into from
Jul 21, 2023
Merged

Adds threshold to switch as an option #13

merged 2 commits into from
Jul 21, 2023

Conversation

arcbtc
Copy link
Member

@arcbtc arcbtc commented Jul 8, 2023

No description provided.

@arbadacarbaYK
Copy link

arbadacarbaYK commented Jul 9, 2023

🫠😬😂
"
I've reviewed the provided code, and I noticed a few potential issues:
Here's a summary of all the changes made to the code:

  1. Added missing semicolon at the end of the line thresholdSum = thresholdSum + payment_amount; to fix a compilation error.
  2. Corrected the variable name in the line DeserializationError error = deserializeJson(doc, input); to payloadStr to match the intended variable.
  3. Added missing semicolon at the end of the line payloadStr.replace("'", '"'); to fix a compilation error.
  4. Added a break statement after the WStype_TEXT case in the switch statement inside the webSocketEvent function for proper flow control.
  5. increases the StaticJsonDocument size to 4096 to provide more space for deserializing larger JSON payloads.
  6. improved error-handling

"

#include <WiFi.h>
#include <FS.h>
#include <SPIFFS.h>
#include <ArduinoJson.h>
#include <WebSocketsClient.h>

fs::SPIFFSFS &FlashFS = SPIFFS;
#define FORMAT_ON_FAIL true
#define PARAM_FILE "/elements.json"

////////////////////////////////

String wallet;
int threshold = 0;
int thresholdSum = 0;
int thresholdPin = 0;
int thresholdTime = 0;

/////////////////////////////////

// Access point variables
String payloadStr;
String password;
String serverFull;
String lnbitsServer;
String ssid;
String wifiPassword;
String deviceId;
String dataId;
String lnurl;

bool paid;
bool down = false;

WebSocketsClient webSocket;

struct KeyValue {
String key;
String value;
};

const int MAX_CONNECTION_ATTEMPTS = 5;
const int CONNECTION_RETRY_INTERVAL = 2000; // milliseconds

void setup()
{
Serial.begin(115200);
pinMode(2, OUTPUT);

FlashFS.begin(FORMAT_ON_FAIL);

// get the saved details and store in global variables
if (!readFiles()) {
Serial.println("Error reading files. Retry in a moment...");
delay(CONNECTION_RETRY_INTERVAL);
ESP.restart();
}

connectToWiFi();

connectToWebSocket();
}

void loop() {
while (!WiFi.isConnected()) {
Serial.println("Failed to connect to WiFi. Retrying...");
delay(CONNECTION_RETRY_INTERVAL);
connectToWiFi();
}

digitalWrite(2, LOW);
payloadStr = "";
delay(2000);
while (!paid) {
webSocket.loop();
if (paid) {
if (threshold == 0) {
pinMode(getValue(payloadStr, '-', 0).toInt(), OUTPUT);
digitalWrite(getValue(payloadStr, '-', 0).toInt(), HIGH);
delay(getValue(payloadStr, '-', 1).toInt());
digitalWrite(getValue(payloadStr, '-', 0).toInt(), LOW);
} else {
StaticJsonDocument<4096> doc; // Increase the size here
DeserializationError error = deserializeJson(doc, payloadStr);
if (error) {
Serial.println("Error parsing JSON. Ignoring payload...");
break; // Skip processing and continue to the next iteration
}
JsonObject payment = doc.as();
int payment_amount = payment["amount"];
thresholdSum = thresholdSum + payment_amount;
if (threshold >= thresholdSum) {
pinMode(thresholdPin, OUTPUT);
digitalWrite(thresholdPin, HIGH);
delay(thresholdTime);
digitalWrite(thresholdPin, LOW);
}
}
}
}
Serial.println("Paid");
paid = false;
}

//////////////////HELPERS///////////////////

String getValue(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]) : "";
}

bool readFiles()
{
File paramFile = FlashFS.open(PARAM_FILE, "r");
if (!paramFile) {
return false; // Error reading file
}

StaticJsonDocument<1500> doc;
DeserializationError error = deserializeJson(doc, paramFile.readString());
paramFile.close();

if (error) {
Serial.println("Error parsing JSON in file. Retry in a moment...");
return false; // Error parsing JSON
}

const JsonObject maRoot0 = doc[0];
const char *maRoot0Char = maRoot0["value"];
password = maRoot0Char;
Serial.println(password);

const JsonObject maRoot1 = doc[1];
const char *maRoot1Char = maRoot1["value"];
ssid = maRoot1Char;
Serial.println(ssid);

const JsonObject maRoot2 = doc[2];
const char *maRoot2Char = maRoot2["value"];
wifiPassword = maRoot2Char;
Serial.println(wifiPassword);

const JsonObject maRoot3 = doc[3];
const char *maRoot3Char = maRoot3["value"];
serverFull = maRoot3Char;
lnbitsServer = serverFull.substring(5, serverFull.length() - 33);
deviceId = serverFull.substring(serverFull.length() - 22);

const JsonObject maRoot4 = doc[4];
const char *maRoot4Char = maRoot4["value"];
lnurl = maRoot4Char;
Serial.println(lnurl);

return true; // Successfully read and parsed the file
}

void connectToWiFi()
{
WiFi.begin(ssid.c_str(), wifiPassword.c_str());
int connectionAttempts = 0;
while (WiFi.status() != WL_CONNECTED && connectionAttempts < MAX_CONNECTION_ATTEMPTS) {
Serial.println("Connecting to WiFi...");
delay(CONNECTION_RETRY_INTERVAL);
connectionAttempts++;
}

if (WiFi.status() != WL_CONNECTED) {
Serial.println("Failed to connect to WiFi. Retry in a moment...");
delay(CONNECTION_RETRY_INTERVAL);
ESP.restart();
}
}

void connectToWebSocket()
{
if (threshold != 0) {
Serial.println(lnbitsServer + "/api/v1/ws/" + wallet);
webSocket.beginSSL(lnbitsServer, 443, "/api/v1/ws/" + wallet);
} else {
Serial.println(lnbitsServer + "/api/v1/ws/" + deviceId);
webSocket.beginSSL(lnbitsServer, 443, "/api/v1/ws/" + deviceId);
}

webSocket.onEvent(webSocketEvent);
webSocket.setReconnectInterval(1000);
}

//////////////////WEBSOCKET///////////////////

void webSocketEvent(WStype_t type, uint8_t* payload, size_t length) {
switch (type) {
case WStype_DISCONNECTED:
Serial.printf("[WSc] Disconnected!\n");
break;
case WStype_CONNECTED:
{
Serial.printf("[WSc] Connected to url: %s\n", payload);

    // send message to server when Connected
    webSocket.sendTXT("Connected");
  }
  break;
case WStype_TEXT:
  payloadStr = (char*)payload;
  if (threshold != 0) {
    payloadStr.replace("'", "\"");
  }
  paid = true;
  break;
case WStype_ERROR:
case WStype_FRAGMENT_TEXT_START:
case WStype_FRAGMENT_BIN_START:
case WStype_FRAGMENT:
case WStype_FRAGMENT_FIN:
  break;

}
}

@pieterjm
Copy link

Several issues:

  • Lots of compilation errors (missing semi colons)
  • Undeclared timer variable
  • The threshold variable is set to 0 in the sketch, but logic to change the value is absent
  • Code that triggers loading configuration is absent

@arcbtc arcbtc merged commit 99c1a9a into main Jul 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants