-
Notifications
You must be signed in to change notification settings - Fork 0
/
LNChecker.cpp
309 lines (256 loc) · 9.77 KB
/
LNChecker.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <WebSocketsClient.h>
#include <Arduino_JSON.h>
#include "LNChecker.h"
#include "gpio.h"
String payloadStr;
bool paid = false;
bool setupDone = false;
WebSocketsClient webSocket;
extern LNBCard myLNBcard;
/////////////////////////////////////////////////////////////////
/////////////////////// LNBITS stuff ////////////////////////////
/////////////////////////////////////////////////////////////////
/************** WEBSOCKET EVENT *****************/
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);
webSocket.sendTXT("Connected"); // send message to server when Connected
break;
case WStype_TEXT:
payloadStr = (char*)payload;
payloadStr.replace(String("'"), String('"'));
payloadStr.toLowerCase();
Serial.println("Received data from socket: " + payloadStr);
paid = true;
case WStype_ERROR:
case WStype_FRAGMENT_TEXT_START:
case WStype_FRAGMENT_BIN_START:
case WStype_FRAGMENT:
case WStype_FRAGMENT_FIN:
break;
}
}
/*********************** SETUP LNBITS Socket *******************/
void setupLNBitsChecker(void){
Serial.println("[CHECKER] Starting checker in LNBits Checker Mode");
Serial.println("Connecting to websocket: ws://" + myLNBcard.Settings.LNURLServer + String(DEFAULT_API_URL) + myLNBcard.Settings.LNURLWallet);
webSocket.beginSSL(myLNBcard.Settings.LNURLServer, 443, String(DEFAULT_API_URL) + myLNBcard.Settings.LNURLWallet);
webSocket.onEvent(webSocketEvent);
webSocket.setReconnectInterval(1000);
}
/*********** LNBITS CHECKER ****************/
void checkLNURL(void){
webSocket.loop();
//client.poll();
if(paid){
Serial.println("Paid");
doBoltNotification();
paid = false;
}
}
/////////////////////////////////////////////////////////////////
/////////////////////// LNDHUB stuff ////////////////////////////
/////////////////////////////////////////////////////////////////
String refresh_token = "";
String access_token = "";
String login_auth = "";
String password_auth = "";
String server_url = "";
String LNHUBServer = "";
String api_path = "";
void setupLNDHubChecker(void){
Serial.println("[CHECKER] Starting checker in LNDHub Checker Mode");
String uri = myLNBcard.Settings.LNDHUBuri;
//PARSE LNDHUB URI
//Extraer credenciales
int atIndex = uri.indexOf('@');
String credentials = uri.substring(9,atIndex);
login_auth = credentials.substring(0,credentials.indexOf(":"));
password_auth = credentials.substring(credentials.indexOf(":")+1);
//Extraer la url del server
server_url = uri.substring(atIndex+1);
int protocolEndIndex = server_url.indexOf("://") + 3; // Saltar el protocolo (http, https, etc.)
int serverEndIndex = server_url.indexOf('/', protocolEndIndex); // Encontrar el final del servidor
if (serverEndIndex == -1) { // Si no hay más '/' después del servidor
serverEndIndex = server_url.length();
}
LNHUBServer = server_url.substring(protocolEndIndex, serverEndIndex); // Extraer el servidor
if (serverEndIndex < server_url.length()) {
api_path = server_url.substring(serverEndIndex); // Extraer la API, si existe
if (api_path.endsWith("/")) api_path = api_path.substring(0, api_path.length() - 1);
} else {
api_path = ""; // Si no hay API en la URL
}
Serial.println("LNDHub credentials: "+ credentials + "\r\nLNDHub login_auth: " + login_auth + "\r\nLNDHub password_auth: " + password_auth);
Serial.println("Server url: "+ LNHUBServer + "\r\nLNDHub api_path: " + api_path);
}
/****************** DO FIRST AUTHORIZATION ****************/
bool doAuth(){
WiFiClientSecure client;
client.setInsecure();
if (!client.connect(LNHUBServer.c_str(), 443)){
Serial.println("Client error connect LNHUB");
return false;
}
Serial.println("\r\n\r\n---------------- CONNECTED TO LNHUB >> GET auth ----------");
//String url = "/lndhub/auth"; //api_path + "/auth"; //"/auth?type=auth";
String url = api_path + "/auth"; //"/auth?type=auth";
String rBody = String("{\r\n") +
"\"login\": \"" + login_auth + "\",\r\n" +
"\"password\": \"" + password_auth + "\"\r\n" +
"}\r\n";
String request = String("POST ") + url + " HTTP/1.1\r\n" +
//HEADER PART
"Host: " + LNHUBServer + "\r\n" +
"User-Agent: ESP32\r\n" +
"Content-Type: application/json\r\n" +
"Content-Length: " + String(rBody.length()) + "\r\n" +
"Accept: */*\r\n" +
"Cache-Control: no-cache\r\n" +
"Connection: keep-alive\r\n\r\n" +
//BODY PART
rBody;
Serial.println(request);
client.print(request);
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
break;
}
if (line == "\r") {
break;
}
}
String line = client.readString();
Serial.println(line);
JSONVar myObject = JSON.parse(line);
// JSON.typeof(jsonVar) can be used to get the type of the var
if (JSON.typeof(myObject) == "undefined") {
Serial.println("Parsing input failed!");
return false;
}
//Obtain token vars and replace ["] character
refresh_token = JSON.stringify(myObject["refresh_token"]);
access_token = JSON.stringify(myObject["access_token"]);
refresh_token.remove(0,1); //remove first character
access_token.remove(0,1); //remove first character
refresh_token.remove(refresh_token.length()-1,1); //remove last character
access_token.remove(access_token.length()-1,1); //remove last character
Serial.println("Current access_token: " + access_token);
return true;
}
/*********** CHECK LNDHUB BALANCE ***************/
unsigned long checkBalance(void){
WiFiClientSecure client;
client.setInsecure();
Serial.println("Connecting to LNDHUB at " + String(LNHUBServer) + " ...");
unsigned long charBalance = 0;
try {
if (!client.connect(LNHUBServer.c_str(), 443)){
return -1;
}
Serial.println("\r\n\r\n---------------- CONNECTED TO LNHUB >> GET BALANCE ----------");
String url = api_path + "/balance";
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + LNHUBServer + "\r\n" +
"Authorization: Bearer " + access_token +" \r\n" +
"User-Agent: ESP32\r\n" +
"Accept: */*\r\n" +
"Cache-Control: no-cache\r\n" +
"Connection: keep-alive\r\n\r\n");
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
break;
}
if (line == "\r") {
break;
}
}
String line = client.readString();
Serial.println(line);
JSONVar myObject = JSON.parse(line);
// JSON.typeof(jsonVar) can be used to get the type of the var
if (JSON.typeof(myObject) == "undefined") {
Serial.println("Parsing input failed!");
return -1;
}
// Convierte el valor JSONVar a String primero
String balanceStr = JSON.stringify(myObject["BTC"]["AvailableBalance"]);
Serial.println("Current balance: " + String(balanceStr));
char *endPtr;
charBalance = strtoul(balanceStr.c_str(), &endPtr, 10);
}catch(...){
Serial.println("Failed to read balance ");
}
return charBalance;
}
/*********** LNDHUB CHECKER ****************/
bool authDone=false;
unsigned long currentBalance = 0;
void checkLNDHub(void){
Serial.println("[checkLNDHub] Checking LNDHub Balance AuthDone[" + String(authDone) + "]");
if(!authDone){
authDone = doAuth();
if(authDone) currentBalance = checkBalance();
}
else{
unsigned long newBalance = checkBalance();
if(newBalance != currentBalance) {
doBoltNotification();
currentBalance = newBalance;
}
}
}
/////////////////////////////////////////////////////////////////
///////////////// Checker generic functions /////////////////////
/////////////////////////////////////////////////////////////////
/****************** SETUP CHECKER *****************/
void setupChecker(void){
myLNBcard.isLNBitsWallet = myLNBcard.Settings.LNURLWallet.length() > 4; //Means we have a non 0 or a valid address
Serial.println("[CHECKER] setup");
if(myLNBcard.isLNBitsWallet) setupLNBitsChecker();
else setupLNDHubChecker();
setupDone = true;
}
void doBoltNotification(void){
myLNBcard.isStripBlocked = true; //Block other processes update strip leds
switch(myLNBcard.Settings.BoltEffect){
case 1: blinkBoltLeds(0); break;
case 2: rainbowBolt(6); break;
case 3: snakeBolt(6); break;
default: blinkBoltLeds(0); break;
}
myLNBcard.isStripBlocked = false; //Allow other processes update strip leds
}
void runChecker(void *name){
Serial.println("[CHECKER] started");
int countChecks = 0;
while (1)
{
if ((WiFi.status() == WL_CONNECTED)&&(setupDone)){
if(myLNBcard.isLNBitsWallet) {
if(countChecks++>600){ Serial.println(">> Checker LNBITs working - waiting payments "); countChecks=0;} //EveryMinute is print
//LNBITS stuff
checkLNURL();
vTaskDelay(100 / portTICK_PERIOD_MS);
}
else{
//LNDHUB stuff - every 5 seconds
Serial.println(">> Checker LNDHUB ");
checkLNDHub();
doQueryLed();
vTaskDelay(5000 / portTICK_PERIOD_MS);
}
}else{
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
}