-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAPI.cpp
More file actions
692 lines (623 loc) · 26.9 KB
/
Copy pathAPI.cpp
File metadata and controls
692 lines (623 loc) · 26.9 KB
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
#include "API.h"
#include "GlobalState.h"
#include "DeviceState.h"
#include "Display.h"
#include "Log.h"
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#include <Preferences.h>
// External references to main.cpp
extern StateManager deviceState;
extern MultiChannelConfig multiChannelConfig;
extern ProductLabels productLabels;
extern BitcoinData bitcoinData;
extern NetworkStatus networkStatus;
extern String lnbitsServer;
extern String deviceId;
extern String currency;
extern bool labelsLoadedSuccessfully;
extern bool labelsValidationAttempted;
extern ExtensionConfig extensionConfig;
#ifdef BOARD_JC3248W535C
extern T35AmbientConfig t35AmbientConfig;
extern ProductSelectState productSelectState;
#endif
// External constants from main.cpp
const unsigned long LABEL_UPDATE_INTERVAL = 300000; // 5 minutes
// Retry backoff for failed label fetches
static unsigned long lastFetchAttempt = 0;
static const unsigned long RETRY_BACKOFF = 30000; // 30 seconds between retries
static bool apiPathLoaded = false; // NVS path loaded only once per boot
// Load persisted apiPath from NVS (called first time fetchSwitchLabels runs)
static void loadApiPathIfNeeded() {
if (apiPathLoaded) return;
apiPathLoaded = true;
Preferences prefs;
prefs.begin("zapbox", true); // read-only
String saved = prefs.getString("apiPath", "");
prefs.end();
if (saved.length() > 0 && (saved == "zapbox" || saved == "bitcoinswitch")) {
extensionConfig.apiPath = saved;
Serial.println("[LABELS] Loaded saved extension path from NVS: " + saved);
}
}
#if ENABLE_BITCOIN_DATA
const unsigned long BTC_UPDATE_INTERVAL = 300000; // 5 minutes
const unsigned long BTC_ERROR_RETRY_INTERVAL = 60000; // 1 minute retry for errors
static bool btcDataHasError = false; // Track if last BTC fetch had errors
// External function declarations from main.cpp
extern void btctickerScreen();
extern void updateBtctickerValues(); // Partial update function
#endif
/**
* Fetch switch labels and configuration from LNbits server.
*/
void fetchSwitchLabels()
{
loadApiPathIfNeeded();
if (lnbitsServer.length() == 0 || deviceId.length() == 0) {
Serial.println("[LABELS] Cannot fetch labels - server or deviceId not configured");
lastFetchAttempt = millis(); // apply backoff so this doesn't spam every loop tick
return;
}
// SAFETY: Abort if WiFi is being torn down for config mode.
// configMode() sets CONFIG_MODE on Core 0 before WiFi.disconnect();
// if we start an HTTPS request while WiFi is shutting down, the SSL
// stack will crash with LoadProhibited.
if (deviceState.isInState(DeviceState::CONFIG_MODE)) {
Serial.println("[LABELS] Skipping fetch - CONFIG_MODE active");
return;
}
// Update last attempt time to prevent rapid retries
lastFetchAttempt = millis();
HTTPClient http;
// Try primary extension path. On 404 or connection error, try the other extension.
// Detected path is persisted in NVS so restarts go directly to the right path.
String url = "https://" + lnbitsServer + "/" + extensionConfig.apiPath + "/api/v1/public/" + deviceId;
Serial.println("[LABELS] Fetching switch configurations from: " + url);
http.begin(url);
http.setTimeout(4000);
int httpCode = http.GET();
// Auto-detect extension path: try fallback on 404 or any connection error
bool shouldTryFallback = (httpCode == 404) || (httpCode <= 0);
if (shouldTryFallback) {
String fallbackPath = (extensionConfig.apiPath == "bitcoinswitch") ? "zapbox" : "bitcoinswitch";
Serial.println("[LABELS] " + extensionConfig.apiPath + (httpCode == 404 ? " returned 404" : " connection error") + " - trying fallback: " + fallbackPath);
http.end();
url = "https://" + lnbitsServer + "/" + fallbackPath + "/api/v1/public/" + deviceId;
Serial.println("[LABELS] Fetching switch configurations from: " + url);
http.begin(url);
http.setTimeout(5000);
httpCode = http.GET();
if (httpCode == 200) {
extensionConfig.apiPath = fallbackPath;
Serial.println("[LABELS] Auto-detected extension: /" + fallbackPath + "/api/v1/ (saved for payments)");
// Persist so next boot uses the correct path directly
Preferences prefs;
prefs.begin("zapbox", false);
prefs.putString("apiPath", fallbackPath);
prefs.end();
}
}
if (httpCode == 200) {
String payload = http.getString();
Serial.println("[LABELS] Received response: " + payload);
// Parse JSON response
JsonDocument doc;
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
// Extract currency from response (optional field – not all extensions send it)
const char* currencyChar = doc["currency"];
if (currencyChar != nullptr) {
String oldCurrency = currency;
currency = String(currencyChar);
currency.toUpperCase(); // Ensure uppercase for display and API calls
LOG_INFO("LABELS", "Currency set by server: " + currency +
(oldCurrency != currency ? " (was: " + oldCurrency + ")" : ""));
} else {
// Server did not include a currency field – keep the current value (default: USD).
// This is normal for extensions that don't configure currency per-device.
LOG_INFO("LABELS", "No currency in API response – using: " + currency);
}
// Clear existing labels and durations (all PRODUCT_LABELS_MAX slots)
for (int i = 0; i < PRODUCT_LABELS_MAX; i++) {
productLabels.labels[i] = "";
productLabels.durations[i] = 0;
}
// Extract labels from switches array
JsonArray switches = doc["switches"];
for (JsonObject switchObj : switches) {
int pin = switchObj["pin"];
const char* labelChar = switchObj["label"];
String labelStr = (labelChar != nullptr) ? String(labelChar) : "";
int pinDuration = switchObj["duration"].as<int>(); // Action time in ms (0 if not set)
// Store label and duration based on pin number using array index (0-11)
int pinIndex = getPinIndex(pin);
if (pinIndex >= 0 && pinIndex < PRODUCT_LABELS_MAX) {
productLabels.labels[pinIndex] = labelStr;
productLabels.durations[pinIndex] = pinDuration;
Serial.println("[LABELS] Pin " + String(pin) + " label: " + labelStr + " duration: " + String(pinDuration) + " ms");
}
}
Serial.println("[LABELS] Successfully fetched and cached all labels");
labelsLoadedSuccessfully = true; // Mark labels as successfully loaded
labelsValidationAttempted = true; // Mark validation as completed
productLabels.lastUpdate = millis(); // Update timestamp
// WebSocket connection is valid - device config exists on server
// This is the ONLY place where we confirm WebSocket after validation
Serial.println("[LABELS] Device config validated - confirming WebSocket connection");
networkStatus.confirmed.websocket = true;
#if ENABLE_BITCOIN_DATA
// Mark BTC data as stale so the periodic updater in loop() refreshes it
// without blocking here. Calling fetchBitcoinData() inline caused setup()
// to stall for 20+ s on SSL timeouts, preventing touch from responding.
bitcoinData.lastUpdate = 0;
Serial.println("[LABELS] BTC update scheduled (will fetch at next ticker cycle)");
if (multiChannelConfig.btcTickerActive) {
Serial.println("[LABELS] Ticker active - refreshing display");
btctickerScreen();
}
#endif
} else {
Serial.println("[LABELS] JSON parsing failed: " + String(error.c_str()));
}
} else {
Serial.printf("[LABELS] HTTP request failed with code: %d\n", httpCode);
// HTTP 404 means the bitcoinswitch instance was deleted on the server
// This is a critical configuration error - invalidate WebSocket connection
if (httpCode == 404) {
Serial.println("[LABELS] ERROR: Device not found (404) - tried /bitcoinswitch/ and /zapbox/ paths.");
Serial.println("[LABELS] The configured device ID does not exist on the server.");
Serial.println("[LABELS] Marking WebSocket as unconfirmed to trigger error LED pattern.");
networkStatus.confirmed.websocket = false;
labelsValidationAttempted = true; // Mark validation as completed (failed)
labelsLoadedSuccessfully = false;
}
// Other HTTP errors (500, timeout, etc.) - could be temporary
else if (httpCode < 0) {
Serial.println("[LABELS] Connection error - could not reach server (will retry soon)");
labelsValidationAttempted = true; // Mark as attempted so startup doesn't hang
labelsLoadedSuccessfully = false;
} else if (httpCode >= 500) {
Serial.println("[LABELS] Server error - may be temporary, will retry");
labelsValidationAttempted = true;
labelsLoadedSuccessfully = false;
}
}
http.end();
}
#if ENABLE_BITCOIN_DATA
/**
* Fetch Bitcoin price and block height from external APIs (sequential).
*/
void fetchBitcoinData()
{
// SAFETY: Abort immediately if WiFi is being torn down for config mode.
// configMode() calls WiFi.disconnect(true) on Core 0; if we start an HTTPS
// request on Core 1 at the same time the SSL/WiFi stack is freed underneath
// us, the result is a LoadProhibited crash (EXCVADDR ~0x130).
if (deviceState.isInState(DeviceState::CONFIG_MODE)) {
Serial.println("[BTC] Skipping fetch - CONFIG_MODE active");
return;
}
// Concurrency guard: the initial fetch runs as an async task while the
// periodic updater in loop() may also call this function. Two parallel TLS
// sessions waste ~100 KB heap. If a fetch appears stuck (router drops the
// SSL handshake without RST), allow a new attempt after 90 s anyway.
static volatile bool fetchInProgress = false;
static volatile unsigned long fetchStartedAt = 0;
if (fetchInProgress && (millis() - fetchStartedAt) < 90000) {
Serial.println("[BTC] Skipping fetch - previous fetch still in progress");
// Arm the caller backoff too — otherwise updateBitcoinTicker() retries
// (and logs) on every single loop iteration while the fetch hangs.
lastFetchAttempt = millis();
return;
}
fetchInProgress = true;
fetchStartedAt = millis();
Serial.println("[BTC] Fetching Bitcoin data...");
// Update last fetch attempt time for backoff
lastFetchAttempt = millis();
HTTPClient http;
// Own TLS client so the SSL handshake timeout can be bounded: the default
// is 120 s, and consumer routers have been observed to silently drop the
// handshake — the fetch then hangs for the better part of a minute.
WiFiClientSecure secureClient;
secureClient.setInsecure(); // same trust model as http.begin(url)
secureClient.setHandshakeTimeout(10); // seconds
// mempool.space /api/v1/prices supports: USD, EUR, GBP, CAD, CHF, AUD, JPY
// Using uppercase currency codes as returned by the API.
String currencyUpper = currency;
currencyUpper.toUpperCase();
// Fetch BTC price from mempool.space — same server as block height fetch
bool priceOk = false;
http.begin(secureClient, "https://mempool.space/api/v1/prices");
http.setConnectTimeout(5000);
http.setTimeout(8000);
if (http.GET() == 200) {
JsonDocument doc;
if (!deserializeJson(doc, http.getString())) {
long price = doc[currencyUpper] | 0L;
if (price > 0) {
bitcoinData.price = String(price);
priceOk = true;
} else {
Serial.println("[BTC] Currency '" + currencyUpper + "' not in mempool.space prices — keeping last value");
}
}
}
http.end();
delay(200); // SSL cleanup delay
// Second guard: config mode might have been triggered while the first
// HTTP call was running. Don't start a new SSL connection if WiFi is gone.
if (deviceState.isInState(DeviceState::CONFIG_MODE)) {
Serial.println("[BTC] Aborting mid-fetch - CONFIG_MODE active");
fetchInProgress = false;
return;
}
// Fetch block height from mempool.space — keep last known value on failure
bool blockOk = false;
http.begin(secureClient, "https://mempool.space/api/blocks/tip/height");
http.setConnectTimeout(5000);
http.setTimeout(8000);
if (http.GET() == 200) {
String val = http.getString();
val.trim();
if (val.length() > 0) {
bitcoinData.blockHigh = val;
blockOk = true;
}
}
http.end();
// If price failed but block succeeded: retry price once. The block fetch just established
// a connection to mempool.space so the router's connection-tracking entry is now warm —
// the retry usually succeeds immediately where the first cold attempt was dropped.
if (!priceOk && blockOk && !deviceState.isInState(DeviceState::CONFIG_MODE)) {
delay(300);
Serial.println("[BTC] Price failed, block OK — retrying price (connection now warm)...");
http.begin(secureClient, "https://mempool.space/api/v1/prices");
http.setConnectTimeout(5000);
http.setTimeout(8000);
if (http.GET() == 200) {
JsonDocument doc2;
if (!deserializeJson(doc2, http.getString())) {
long price = doc2[currencyUpper] | 0L;
if (price > 0) { bitcoinData.price = String(price); priceOk = true; }
}
}
http.end();
if (priceOk) Serial.println("[BTC] Price retry succeeded: " + bitcoinData.price);
else Serial.println("[BTC] Price retry also failed — keeping last value: " + bitcoinData.price);
}
Serial.println("[BTC] Source: mempool.space");
if (!priceOk) Serial.println("[BTC] Price fetch failed — keeping last value: " + bitcoinData.price);
if (!blockOk) Serial.println("[BTC] Block fetch failed — keeping last value: " + bitcoinData.blockHigh);
Serial.println("[BTC] Price: " + bitcoinData.price + " " + currency);
Serial.println("[BTC] Block height: " + bitcoinData.blockHigh);
// Retry sooner if either request failed; stale display values are preserved
btcDataHasError = (!priceOk || !blockOk);
if (btcDataHasError) {
Serial.println("[BTC] ERROR detected - will retry in 1 minute instead of 5 minutes");
}
bitcoinData.lastUpdate = millis();
fetchInProgress = false;
}
/**
* Periodically update Bitcoin ticker display.
*/
void updateBitcoinTicker()
{
// Run when the BTC ticker screen is active OR when numeric product selection
// needs the block height refreshed on the main screen.
bool needsUpdate = multiChannelConfig.btcTickerActive;
#ifdef BOARD_JC3248W535C
if (t35AmbientConfig.numericSelect &&
deviceState.isInState(DeviceState::PRODUCT_SELECTION) &&
!productSelectState.panelActive && !productSelectState.qrActive) {
needsUpdate = true;
}
#endif
if (!needsUpdate || deviceState.isInState(DeviceState::ERROR_RECOVERABLE) || deviceState.isInState(DeviceState::CONFIG_MODE) || deviceState.isInState(DeviceState::HELP_SCREEN)) {
return;
}
unsigned long currentTime = millis();
// Use the short interval if the last fetch had errors OR no data has ever
// been loaded (e.g. the initial async fetch hung on a dropped SSL
// handshake) — otherwise the "Loading..." placeholders would sit on the
// ticker for the full 5-minute interval.
bool noDataYet = (bitcoinData.price == "Loading...");
unsigned long updateInterval = (btcDataHasError || noDataYet) ? BTC_ERROR_RETRY_INTERVAL : BTC_UPDATE_INTERVAL;
// Check if it's time for an update and enforce backoff for failed attempts
if (currentTime - bitcoinData.lastUpdate >= updateInterval) {
// Enforce 30-second backoff between failed BTC fetch attempts
if ((currentTime - lastFetchAttempt) < RETRY_BACKOFF) {
return; // Too soon - skip this attempt
}
Serial.println("[BTC] Update interval reached, fetching new data...");
unsigned long lastUpdateBefore = bitcoinData.lastUpdate;
fetchBitcoinData();
// Refresh the display ONLY if the fetch actually completed (it may have
// been skipped while another fetch is in progress) AND we're STILL on the
// ticker screen. Partial update to reduce flicker.
if (bitcoinData.lastUpdate != lastUpdateBefore &&
!deviceState.isInState(DeviceState::SCREENSAVER) && !deviceState.isInState(DeviceState::DEEP_SLEEP)) {
if (multiChannelConfig.btcTickerActive && !deviceState.isInState(DeviceState::PRODUCT_SELECTION)) {
updateBtctickerValues(); // Partial update instead of btctickerScreen()
Serial.println("[BTC] Values updated (partial refresh - reduced flicker)");
}
#ifdef BOARD_JC3248W535C
if (t35AmbientConfig.numericSelect &&
deviceState.isInState(DeviceState::PRODUCT_SELECTION) &&
!productSelectState.panelActive && !productSelectState.qrActive) {
updateProductSelectBlockHeight();
Serial.println("[BTC] Block height updated on product selection screen");
}
#endif
}
}
}
#endif // ENABLE_BITCOIN_DATA
/**
* Periodically update switch labels from server.
*/
void updateSwitchLabels()
{
// Skip if in error/config/help modes
if (deviceState.isInState(DeviceState::ERROR_RECOVERABLE) || deviceState.isInState(DeviceState::CONFIG_MODE) || deviceState.isInState(DeviceState::HELP_SCREEN)) {
return;
}
unsigned long currentTime = millis();
// Check if labels failed to load initially or if it's time for periodic update
if (!labelsLoadedSuccessfully || (currentTime - productLabels.lastUpdate >= LABEL_UPDATE_INTERVAL)) {
// Enforce backoff delay between retry attempts to prevent SSL memory exhaustion
if ((currentTime - lastFetchAttempt) < RETRY_BACKOFF) {
return; // Too soon - skip this attempt
}
if (!labelsLoadedSuccessfully) {
Serial.println("[LABELS] Labels not loaded successfully, retrying...");
} else {
Serial.println("[LABELS] Periodic update interval reached, fetching labels...");
}
fetchSwitchLabels();
}
}
// ============================================================================
// MINI-POS API (Touch 3.5 — amount entry → invoice via zapbox_extension)
// ============================================================================
extern void updateLightningQR(const String& lnurlStr);
/**
* POST /<apiPath>/api/v1/pos/invoice
* Header: X-Api-Key: <wallet invoice key>
* Body: {"amount": 5.00, "currency": "EUR", "device_id": "<22-char-id>"}
* Response: {"payment_hash": "...", "payment_request": "lnbc..."}
*/
bool requestMiniPosInvoice(const String &amountStr)
{
if (lnbitsServer.length() == 0 || deviceId.length() == 0) {
miniPosState.infoMsg = "No server configured";
return false;
}
if (miniPosConfig.invoiceKey.length() == 0) {
miniPosState.infoMsg = "No invoice key";
return false;
}
HTTPClient http;
String url = "https://" + lnbitsServer + "/" + extensionConfig.apiPath
+ "/api/v1/pos/invoice";
LOG_INFO("MiniPoS", "Requesting invoice: " + amountStr + " " + miniPosConfig.currency);
http.begin(url);
http.addHeader("Content-Type", "application/json");
http.addHeader("X-Api-Key", miniPosConfig.invoiceKey);
http.setConnectTimeout(5000);
http.setTimeout(10000);
// The device tells the server which relay pin to fire on settlement — its
// primary channel CH01 (PIN_RELAY_CH01). This keeps the GPIO mapping entirely
// on the device: the extension no longer hard-codes a Mini-PoS pin, so a
// re-map of the channel layout needs no server-side change.
String body = String("{\"amount\":") + amountStr
+ ",\"currency\":\"" + miniPosConfig.currency + "\""
+ ",\"device_id\":\"" + deviceId + "\""
+ ",\"pin\":" + String(PIN_RELAY_CH01) + "}";
int httpCode = http.POST(body);
if (httpCode != 200) {
String resp = http.getString();
http.end();
LOG_ERROR("MiniPoS", String("Invoice HTTP ") + String(httpCode) + " - " + resp);
miniPosState.infoMsg = (httpCode < 0) ? String("Connection failed")
: "Server error " + String(httpCode);
return false;
}
String resp = http.getString();
http.end();
JsonDocument doc;
if (deserializeJson(doc, resp)) {
LOG_ERROR("MiniPoS", "Invoice response JSON parse error");
miniPosState.infoMsg = "Bad response";
return false;
}
const char *hash = doc["payment_hash"];
const char *bolt11 = doc["payment_request"];
if (!hash || !bolt11 || strlen(bolt11) == 0) {
LOG_ERROR("MiniPoS", "Invoice response missing fields");
miniPosState.infoMsg = "Bad response";
return false;
}
LOG_INFO("MiniPoS", String("BOLT11 length: ") + String(strlen(bolt11)) + " chars");
miniPosState.paymentHash = String(hash);
miniPosState.amountLine = amountStr + " " + miniPosConfig.currency;
miniPosState.invoicePending = true;
miniPosState.invoiceCreatedAt = millis();
// BOLT11 into the QR/NFC buffer ("lightning:" prefix added automatically)
updateLightningQR(String(bolt11));
LOG_INFO("MiniPoS", "Invoice created: " + miniPosState.paymentHash);
return true;
}
/**
* GET /<apiPath>/api/v1/pos/invoice/last?device_id=<id>
* Header: X-Api-Key: <wallet invoice key>
* Response: {"amount": 23.5, "currency": "EUR"} or {"amount": null}
*/
bool fetchMiniPosLastPay(String &amountOut)
{
amountOut = "";
if (lnbitsServer.length() == 0 || deviceId.length() == 0 ||
miniPosConfig.invoiceKey.length() == 0) {
return false;
}
HTTPClient http;
String url = "https://" + lnbitsServer + "/" + extensionConfig.apiPath
+ "/api/v1/pos/invoice/last?device_id=" + deviceId;
http.begin(url);
http.addHeader("X-Api-Key", miniPosConfig.invoiceKey);
http.setConnectTimeout(5000);
http.setTimeout(7000);
int httpCode = http.GET();
if (httpCode != 200) {
http.end();
LOG_WARN("MiniPoS", String("Last-pay HTTP ") + String(httpCode));
return false;
}
String resp = http.getString();
http.end();
JsonDocument doc;
if (deserializeJson(doc, resp)) return false;
if (doc["amount"].isNull()) return false;
float amount = doc["amount"];
if (miniPosConfig.decimal) {
char buf[16];
snprintf(buf, sizeof(buf), "%.2f", amount);
amountOut = String(buf);
} else {
amountOut = String((long)amount);
}
// Keep within the 7-char entry limit
if (amountOut.length() > 7) amountOut = amountOut.substring(0, 7);
LOG_INFO("MiniPoS", "Last paid amount: " + amountOut);
return true;
}
/**
* Authy (LNURL-auth): GET /<apiPath>/api/v1/auth/<deviceId>?pin=&duration=
* The extension creates a fresh single-use k1 and returns the bech32 auth
* LNURL plus the action it expects ("auth" in normal operation, "register"
* while a teach session is open). On success the LNURL is placed in the QR/NFC
* buffer. The k1 is single-use with a short TTL, so the caller refreshes it
* periodically. No API key needed — the endpoint only hands out a challenge.
* Response: {"lnurl": "lnurl1...", "k1": "<hex>", "action": "auth|register"}
*/
bool requestAuthLnurl(String *actionOut, int *httpOut)
{
if (actionOut) *actionOut = "";
if (httpOut) *httpOut = 0;
if (lnbitsServer.length() == 0 || deviceId.length() == 0) {
LOG_WARN("Authy", "Cannot fetch auth LNURL - server or deviceId not configured");
return false;
}
HTTPClient http;
String url = "https://" + lnbitsServer + "/" + extensionConfig.apiPath
+ "/api/v1/auth/" + deviceId
+ "?pin=" + String(authyConfig.authPin)
+ "&duration=" + String(authyConfig.authDuration);
http.begin(url);
http.setConnectTimeout(5000);
http.setTimeout(10000);
int httpCode = http.GET();
if (httpOut) *httpOut = httpCode;
if (httpCode != 200) {
http.end();
LOG_ERROR("Authy", String("Auth LNURL HTTP ") + String(httpCode));
return false;
}
String resp = http.getString();
http.end();
JsonDocument doc;
if (deserializeJson(doc, resp)) {
LOG_ERROR("Authy", "Auth LNURL JSON parse error");
return false;
}
const char *lnurl = doc["lnurl"];
if (!lnurl || strlen(lnurl) == 0) {
LOG_ERROR("Authy", "Auth LNURL response missing lnurl");
return false;
}
const char *action = doc["action"];
if (actionOut && action) *actionOut = String(action);
// Store as "lightning:<lnurl1...>" — the NT3H2111 NFC tag writes this value
// as a Lightning URI so phones can tap-to-open. The QR renderer uppercases
// it locally before calling qrcode_initText(), enabling alphanumeric mode
// (fits ~511 chars in v8 ECC_LOW) instead of binary mode (only ~193 bytes).
String nfcUri = "lightning:" + String(lnurl);
strncpy(lightningConfig.lightning, nfcUri.c_str(), sizeof(lightningConfig.lightning) - 1);
lightningConfig.lightning[sizeof(lightningConfig.lightning) - 1] = '\0';
LOG_INFO("Authy", String("Auth LNURL ready (action=") + String(action ? action : "?") + ")");
return true;
}
// Ring-Login: verify NTAG 424 DNA tap (server does the CMAC check, triggers relay)
bool requestNfcAuth(const String &externalId, const String &p, const String &c,
const String &pin, String *errorOut)
{
if (errorOut) *errorOut = "";
if (lnbitsServer.length() == 0 || deviceId.length() == 0) {
if (errorOut) *errorOut = "Not configured";
return false;
}
String url = "https://" + lnbitsServer + "/" + extensionConfig.apiPath
+ "/api/v1/nfc/auth/" + deviceId
+ "?external_id=" + externalId
+ "&p=" + p + "&c=" + c
+ "&auth_pin=" + String(authyConfig.authPin)
+ "&auth_duration=" + String(authyConfig.authDuration);
if (pin.length() > 0) url += "&pin=" + pin;
HTTPClient http;
http.begin(url);
http.setConnectTimeout(5000);
http.setTimeout(10000);
int code = http.GET();
String resp = http.getString();
http.end();
LOG_INFO("NFC-Auth", String("HTTP ") + code + " resp=" + resp.substring(0, 60));
if (code != 200) {
// Try to extract reason from error body
JsonDocument edoc;
if (!deserializeJson(edoc, resp)) {
const char *detail = edoc["detail"];
if (detail && errorOut) *errorOut = String(detail);
}
if (errorOut && errorOut->isEmpty()) *errorOut = "HTTP " + String(code);
return false;
}
JsonDocument doc;
if (deserializeJson(doc, resp)) {
if (errorOut) *errorOut = "Parse error";
return false;
}
const char *status = doc["status"];
if (!status || String(status) != "OK") {
const char *reason = doc["reason"];
if (errorOut) *errorOut = reason ? String(reason) : "Unknown error";
return false;
}
return true;
}
// Ring-Login teach: enrol a card (server validates via tagid, stores in allowlist)
bool requestNfcTeach(const String &externalId, const String &p, const String &c)
{
if (lnbitsServer.length() == 0 || deviceId.length() == 0) return false;
String url = "https://" + lnbitsServer + "/" + extensionConfig.apiPath
+ "/api/v1/nfc/teach/" + deviceId
+ "?external_id=" + externalId
+ "&p=" + p + "&c=" + c;
HTTPClient http;
http.begin(url);
http.setConnectTimeout(5000);
http.setTimeout(10000);
int code = http.GET();
String resp = http.getString();
http.end();
LOG_INFO("NFC-Teach", String("HTTP ") + code + " resp=" + resp.substring(0, 60));
if (code != 200) return false;
JsonDocument doc;
if (deserializeJson(doc, resp)) return false;
const char *status = doc["status"];
return status && String(status) == "OK";
}