upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/main
diff options
context:
space:
mode:
authorYour Name <you@example.com>2026-05-20 02:14:45 +0530
committerYour Name <you@example.com>2026-05-20 02:14:45 +0530
commit899016795c389151e6b486ec470653f5688e5c5f (patch)
tree64b4c732d6f585552fd14df5f47890764c66ac1a /main
parent4f713120dbedd37a3512c2ec1af0766025a59d57 (diff)
feat: merge display-fix — touch driver, keyboard, WiFi setup UI
Squash-merge of feature/display-fix (27 commits): - AXS15231B touch driver with coordinate parsing (touch.c/h) - On-screen keyboard with layout/hit detection (keyboard.c/h) - WiFi setup state machine + config_add_wifi (wifi_setup.c/h) - Web-based WiFi setup via captive portal - Display rotation fix (stride=480), color fixes, DMA byte-swap - WiFi QR code on BOOT and ERROR screens - ERROR state transition after WiFi retries exhausted - Unit tests: test_touch, test_keyboard, test_wifi_setup - Integration test: wifi_setup.mjs - E2E test: wifi-setup.spec.mjs - Per-board hardware locks for flash targets Conflicts resolved: took master for config/cvm/api/main (more current), took display-fix for display/axs15231b (newer fixes).
Diffstat (limited to 'main')
-rw-r--r--main/CMakeLists.txt3
-rw-r--r--main/captive_portal.c368
-rw-r--r--main/captive_portal.h1
-rw-r--r--main/config.h1
-rw-r--r--main/display.c349
-rw-r--r--main/display.h10
-rw-r--r--main/keyboard.c186
-rw-r--r--main/keyboard.h53
-rw-r--r--main/touch.c156
-rw-r--r--main/touch.h29
-rw-r--r--main/wifi_setup.c89
-rw-r--r--main/wifi_setup.h51
12 files changed, 1212 insertions, 84 deletions
diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt
index 2107cf1..9e76f89 100644
--- a/main/CMakeLists.txt
+++ b/main/CMakeLists.txt
@@ -31,6 +31,9 @@ idf_component_register(SRCS "tollgate_main.c"
31 "sw_miner.c" 31 "sw_miner.c"
32 "asic_miner.c" 32 "asic_miner.c"
33 "tollgate_platform.c" 33 "tollgate_platform.c"
34 "touch.c"
35 "keyboard.c"
36 "wifi_setup.c"
34 INCLUDE_DIRS "." 37 INCLUDE_DIRS "."
35 REQUIRES esp_wifi esp_event esp_netif nvs_flash esp_http_server 38 REQUIRES esp_wifi esp_event esp_netif nvs_flash esp_http_server
36 lwip json esp_http_client mbedtls esp-tls log spiffs 39 lwip json esp_http_client mbedtls esp-tls log spiffs
diff --git a/main/captive_portal.c b/main/captive_portal.c
index ea83906..6a8c716 100644
--- a/main/captive_portal.c
+++ b/main/captive_portal.c
@@ -6,6 +6,7 @@
6#include "stratum_proxy.h" 6#include "stratum_proxy.h"
7#include "esp_log.h" 7#include "esp_log.h"
8#include "esp_wifi.h" 8#include "esp_wifi.h"
9#include "esp_netif.h"
9#include "cJSON.h" 10#include "cJSON.h"
10#include "lwip/sockets.h" 11#include "lwip/sockets.h"
11#include "lwip/netdb.h" 12#include "lwip/netdb.h"
@@ -13,6 +14,7 @@
13#include "freertos/task.h" 14#include "freertos/task.h"
14#include <string.h> 15#include <string.h>
15#include <sys/param.h> 16#include <sys/param.h>
17#include <stdio.h>
16 18
17static const char *TAG = "captive_portal"; 19static const char *TAG = "captive_portal";
18static httpd_handle_t s_server = NULL; 20static httpd_handle_t s_server = NULL;
@@ -342,17 +344,19 @@ static esp_err_t redirect_to_portal_handler(httpd_req_t *req)
342 return portal_handler(req); 344 return portal_handler(req);
343} 345}
344 346
345static esp_err_t catchall_handler(httpd_req_t *req) 347static esp_err_t catchall_err_handler(httpd_req_t *req, httpd_err_code_t err)
346{ 348{
347 ESP_LOGI(TAG, "Catchall: GET %s → 302 → http://%s/", req->uri, s_ap_ip_str); 349 if (err == HTTPD_404_NOT_FOUND) {
348 httpd_resp_set_status(req, "302 Found"); 350 ESP_LOGI(TAG, "Catchall 404: GET %s → 302 → http://%s/", req->uri, s_ap_ip_str);
349 351 httpd_resp_set_status(req, "302 Found");
350 char location[64]; 352 char location[64];
351 snprintf(location, sizeof(location), "http://%s/", s_ap_ip_str); 353 snprintf(location, sizeof(location), "http://%s/", s_ap_ip_str);
352 httpd_resp_set_hdr(req, "Location", location); 354 httpd_resp_set_hdr(req, "Location", location);
353 httpd_resp_set_hdr(req, "Connection", "close"); 355 httpd_resp_set_hdr(req, "Connection", "close");
354 httpd_resp_send(req, NULL, 0); 356 httpd_resp_send(req, NULL, 0);
355 return ESP_OK; 357 return ESP_OK;
358 }
359 return ESP_FAIL;
356} 360}
357 361
358static const httpd_uri_t uri_portal = { .uri = "/", .method = HTTP_GET, .handler = portal_handler }; 362static const httpd_uri_t uri_portal = { .uri = "/", .method = HTTP_GET, .handler = portal_handler };
@@ -368,7 +372,338 @@ static const httpd_uri_t uri_success = { .uri = "/success.txt", .method = HTTP_G
368static const httpd_uri_t uri_ncsi = { .uri = "/ncsi.txt", .method = HTTP_GET, .handler = redirect_to_portal_handler }; 372static const httpd_uri_t uri_ncsi = { .uri = "/ncsi.txt", .method = HTTP_GET, .handler = redirect_to_portal_handler };
369static const httpd_uri_t uri_connecttest = { .uri = "/connecttest.txt", .method = HTTP_GET, .handler = redirect_to_portal_handler }; 373static const httpd_uri_t uri_connecttest = { .uri = "/connecttest.txt", .method = HTTP_GET, .handler = redirect_to_portal_handler };
370static const httpd_uri_t uri_wpad = { .uri = "/wpad.dat", .method = HTTP_GET, .handler = redirect_to_portal_handler }; 374static const httpd_uri_t uri_wpad = { .uri = "/wpad.dat", .method = HTTP_GET, .handler = redirect_to_portal_handler };
371static const httpd_uri_t uri_catchall = { .uri = "/*", .method = HTTP_GET, .handler = catchall_handler }; 375
376static const char SETUP_HTML_TEMPLATE[] = \
377"<!DOCTYPE html>"
378"<html><head>"
379"<meta charset='utf-8'>"
380"<meta name='viewport' content='width=device-width, initial-scale=1'>"
381"<title>TollGate Setup</title>"
382"<style>"
383"*{box-sizing:border-box;margin:0;padding:0}"
384"body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;"
385"background:#0a0a0a;color:#fff;display:flex;align-items:center;justify-content:center;"
386"min-height:100vh;padding:20px}"
387".card{background:#1a1a1a;border:1px solid #333;border-radius:16px;padding:32px;"
388"max-width:400px;width:100%;text-align:center}"
389"h1{font-size:24px;margin-bottom:8px;color:#f7931a}"
390".subtitle{color:#888;margin-bottom:20px;font-size:13px}"
391".networks{margin-top:16px;text-align:left}"
392".net-item{background:#252525;border:1px solid #333;border-radius:8px;"
393"padding:12px;margin-bottom:8px;cursor:pointer;display:flex;justify-content:space-between;align-items:center}"
394".net-item:hover{border-color:#f7931a}"
395".net-item:active{background:#333}"
396".net-ssid{font-size:14px}"
397".net-rssi{font-size:11px;color:#888}"
398".net-lock{color:#f7931a;margin-right:4px}"
399".manual{margin-top:12px}"
400"input{width:100%;background:#252525;border:1px solid #333;border-radius:8px;"
401"color:#fff;padding:12px;font-size:14px;margin-bottom:8px;outline:none}"
402"input:focus{border-color:#f7931a}"
403".btn{background:#f7931a;color:#000;border:none;border-radius:8px;padding:14px 28px;"
404"font-size:16px;font-weight:bold;cursor:pointer;width:100%;margin-top:8px}"
405".btn:hover{background:#e8850f}"
406".btn:disabled{background:#333;color:#666;cursor:not-allowed}"
407"#status{margin-top:12px;padding:10px;border-radius:8px;display:none;font-size:13px}"
408"#status.success{display:block;background:#1a472a;color:#4caf50}"
409"#status.error{display:block;background:#471a1a;color:#f44336}"
410"#status.processing{display:block;background:#1a3a47;color:#2196f3}"
411".refresh{background:none;border:1px solid #444;color:#aaa;border-radius:6px;"
412"padding:6px 12px;font-size:12px;cursor:pointer;margin-top:4px}"
413".refresh:hover{border-color:#f7931a;color:#f7931a}"
414"#manualForm{display:none;margin-top:12px}"
415"</style>"
416"</head><body>"
417"<div class='card'>"
418"<h1>TollGate Setup</h1>"
419"<p class='subtitle'>Configure upstream WiFi</p>"
420"<div id='scanStatus'>Scanning...</div>"
421"<div class='networks' id='networkList'></div>"
422"<button class='refresh' onclick='scanWifi()'>Rescan</button>"
423"<button class='refresh' onclick='showManual()'>Manual entry</button>"
424"<div id='manualForm'>"
425"<input id='manualSsid' placeholder='SSID'>"
426"<input id='manualPass' type='password' placeholder='Password'>"
427"<button class='btn' onclick='connectManual()'>Connect</button>"
428"</div>"
429"<div id='passwordForm' style='display:none'>"
430"<p style='margin:12px 0 8px;text-align:left' id='selectedNetwork'></p>"
431"<input id='wifiPass' type='password' placeholder='WiFi password'>"
432"<button class='btn' onclick='connectSelected()'>Connect</button>"
433"</div>"
434"<div id='status'></div>"
435"</div>"
436"<script>"
437"const apIp='__AP_IP__';"
438"let selectedSsid='';"
439"function showStatus(msg,type){const s=document.getElementById('status');"
440"s.textContent=msg;s.className=type;}"
441"function scanWifi(){"
442"document.getElementById('scanStatus').textContent='Scanning...';"
443"document.getElementById('networkList').innerHTML='';"
444"fetch('/wifi/scan').then(r=>r.json()).then(aps=>{"
445"document.getElementById('scanStatus').textContent=aps.length+' networks found';"
446"const list=document.getElementById('networkList');"
447"aps.forEach(ap=>{"
448"const div=document.createElement('div');"
449"div.className='net-item';"
450"const lock=ap.secured?'<span class=net-lock>&#128274;</span>':'';"
451"div.innerHTML='<span class=net-ssid>'+lock+ap.ssid+'</span>"
452"<span class=net-rssi>'+ap.rssi+' dBm</span>';"
453"div.onclick=()=>selectNetwork(ap.ssid,ap.secured);"
454"list.appendChild(div);"
455"});"
456"}).catch(e=>{document.getElementById('scanStatus').textContent='Scan failed';});"
457"}"
458"function selectNetwork(ssid,secured){"
459"selectedSsid=ssid;"
460"document.getElementById('selectedNetwork').textContent='Connect to: '+ssid;"
461"document.getElementById('passwordForm').style.display='block';"
462"document.getElementById('scanStatus').style.display='none';"
463"document.getElementById('networkList').style.display='none';"
464"document.querySelector('.refresh').style.display='none';"
465"if(!secured){connectSelected();}"
466"}"
467"function showManual(){"
468"document.getElementById('manualForm').style.display='block';"
469"}"
470"function connectSelected(){"
471"const pass=document.getElementById('wifiPass').value;"
472"doConnect(selectedSsid,pass);"
473"}"
474"function connectManual(){"
475"const ssid=document.getElementById('manualSsid').value.trim();"
476"const pass=document.getElementById('manualPass').value;"
477"if(!ssid){showStatus('Enter SSID','error');return;}"
478"doConnect(ssid,pass);"
479"}"
480"function doConnect(ssid,pass){"
481"showStatus('Connecting to '+ssid+'...','processing');"
482"fetch('/wifi/connect',{method:'POST',headers:{'Content-Type':'application/json'},"
483"body:JSON.stringify({ssid:ssid,password:pass})})"
484".then(r=>r.json()).then(d=>{"
485"if(d.ok){showStatus('Connected! Device is restarting...','success');}"
486"else{showStatus('Failed: '+(d.error||'unknown'),'error');}"
487"}).catch(e=>{showStatus('Connection error','error');});"
488"}"
489"scanWifi();"
490"</script>"
491"</body></html>";
492
493static char *template_replace(const char *tpl, const char *key, const char *val) {
494 const char *p;
495 size_t klen = strlen(key);
496 size_t vlen = strlen(val);
497 size_t tlen = strlen(tpl);
498 size_t extra = 0;
499 p = tpl;
500 while ((p = strstr(p, key)) != NULL) {
501 extra += vlen - klen;
502 p += klen;
503 }
504 size_t out_size = tlen + extra + 1;
505 char *out = malloc(out_size);
506 if (!out) return NULL;
507 char *dst = out;
508 p = tpl;
509 while (*p) {
510 const char *found = strstr(p, key);
511 if (found) {
512 memcpy(dst, p, found - p);
513 dst += found - p;
514 memcpy(dst, val, vlen);
515 dst += vlen;
516 p = found + klen;
517 } else {
518 strcpy(dst, p);
519 dst += strlen(p);
520 break;
521 }
522 }
523 *dst = '\0';
524 return out;
525}
526
527static bool is_setup_available(void) {
528 const tollgate_config_t *cfg = tollgate_config_get();
529 return cfg->network_count == 0;
530}
531
532static esp_err_t setup_page_handler(httpd_req_t *req) {
533 if (!is_setup_available()) {
534 httpd_resp_set_status(req, "302 Found");
535 char location[64];
536 snprintf(location, sizeof(location), "http://%s/", s_ap_ip_str);
537 httpd_resp_set_hdr(req, "Location", location);
538 httpd_resp_send(req, NULL, 0);
539 return ESP_OK;
540 }
541
542 httpd_resp_set_type(req, "text/html");
543 char *html = template_replace(SETUP_HTML_TEMPLATE, "__AP_IP__", s_ap_ip_str);
544 if (!html) {
545 httpd_resp_send_500(req);
546 return ESP_OK;
547 }
548 httpd_resp_send(req, html, strlen(html));
549 free(html);
550 return ESP_OK;
551}
552
553static esp_err_t wifi_scan_handler(httpd_req_t *req) {
554 esp_wifi_disconnect();
555 vTaskDelay(pdMS_TO_TICKS(300));
556
557 wifi_scan_config_t scan_cfg = {0};
558 scan_cfg.scan_type = WIFI_SCAN_TYPE_ACTIVE;
559 scan_cfg.scan_time.active.min = 100;
560 scan_cfg.scan_time.active.max = 300;
561 esp_err_t ret = esp_wifi_scan_start(&scan_cfg, true);
562 if (ret != ESP_OK) {
563 httpd_resp_set_type(req, "application/json");
564 httpd_resp_send(req, "[]", 2);
565 return ESP_OK;
566 }
567
568 uint16_t ap_count = 0;
569 esp_wifi_scan_get_ap_num(&ap_count);
570 if (ap_count > 20) ap_count = 20;
571 wifi_ap_record_t aps[20];
572 esp_wifi_scan_get_ap_records(&ap_count, aps);
573
574 for (int i = 0; i < (int)ap_count - 1; i++) {
575 for (int j = i + 1; j < (int)ap_count; j++) {
576 if (aps[j].rssi > aps[i].rssi) {
577 wifi_ap_record_t tmp = aps[i];
578 aps[i] = aps[j];
579 aps[j] = tmp;
580 }
581 }
582 }
583
584 cJSON *root = cJSON_CreateArray();
585 for (int i = 0; i < (int)ap_count; i++) {
586 if (aps[i].ssid[0] == '\0') continue;
587 cJSON *ap = cJSON_CreateObject();
588 cJSON_AddStringToObject(ap, "ssid", (const char *)aps[i].ssid);
589 cJSON_AddNumberToObject(ap, "rssi", aps[i].rssi);
590 cJSON_AddBoolToObject(ap, "secured", aps[i].authmode != WIFI_AUTH_OPEN);
591 cJSON_AddItemToArray(root, ap);
592 }
593
594 char *json = cJSON_PrintUnformatted(root);
595 httpd_resp_set_type(req, "application/json");
596 httpd_resp_send(req, json, strlen(json));
597 cJSON_free(json);
598 cJSON_Delete(root);
599
600 const tollgate_config_t *cfg = tollgate_config_get();
601 if (cfg->network_count > 0) {
602 wifi_config_t wifi_cfg;
603 if (tollgate_config_get_wifi(&wifi_cfg) == ESP_OK) {
604 esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg);
605 esp_wifi_connect();
606 }
607 }
608
609 return ESP_OK;
610}
611
612static esp_err_t wifi_connect_handler(httpd_req_t *req) {
613 int content_len = req->content_len;
614 if (content_len <= 0 || content_len > 1024) {
615 httpd_resp_set_type(req, "application/json");
616 httpd_resp_send(req, "{\"ok\":false,\"error\":\"invalid request\"}", HTTPD_RESP_USE_STRLEN);
617 return ESP_OK;
618 }
619
620 char *body = malloc(content_len + 1);
621 if (!body) {
622 httpd_resp_send_500(req);
623 return ESP_OK;
624 }
625 int total = 0;
626 while (total < content_len) {
627 int r = httpd_req_recv(req, body + total, content_len - total);
628 if (r <= 0) { free(body); httpd_resp_send_500(req); return ESP_OK; }
629 total += r;
630 }
631 body[total] = '\0';
632
633 cJSON *json = cJSON_Parse(body);
634 free(body);
635 if (!json) {
636 httpd_resp_set_type(req, "application/json");
637 httpd_resp_send(req, "{\"ok\":false,\"error\":\"invalid JSON\"}", HTTPD_RESP_USE_STRLEN);
638 return ESP_OK;
639 }
640
641 cJSON *ssid_item = cJSON_GetObjectItem(json, "ssid");
642 cJSON *pass_item = cJSON_GetObjectItem(json, "password");
643 if (!ssid_item || !cJSON_IsString(ssid_item)) {
644 cJSON_Delete(json);
645 httpd_resp_set_type(req, "application/json");
646 httpd_resp_send(req, "{\"ok\":false,\"error\":\"missing ssid\"}", HTTPD_RESP_USE_STRLEN);
647 return ESP_OK;
648 }
649
650 const char *ssid = ssid_item->valuestring;
651 const char *password = (pass_item && cJSON_IsString(pass_item)) ? pass_item->valuestring : "";
652
653 esp_err_t err = tollgate_config_add_wifi(ssid, password);
654 if (err != ESP_OK) {
655 cJSON_Delete(json);
656 httpd_resp_set_type(req, "application/json");
657 httpd_resp_send(req, "{\"ok\":false,\"error\":\"save failed\"}", HTTPD_RESP_USE_STRLEN);
658 return ESP_OK;
659 }
660
661 wifi_config_t wifi_cfg = {0};
662 strncpy((char *)wifi_cfg.sta.ssid, ssid, sizeof(wifi_cfg.sta.ssid) - 1);
663 strncpy((char *)wifi_cfg.sta.password, password, sizeof(wifi_cfg.sta.password) - 1);
664 wifi_cfg.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
665 esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg);
666 esp_wifi_connect();
667
668 cJSON_Delete(json);
669
670 httpd_resp_set_type(req, "application/json");
671 httpd_resp_send(req, "{\"ok\":true}", HTTPD_RESP_USE_STRLEN);
672 return ESP_OK;
673}
674
675static esp_err_t wifi_status_handler(httpd_req_t *req) {
676 wifi_ap_record_t ap_info;
677 bool connected = (esp_wifi_sta_get_ap_info(&ap_info) == ESP_OK);
678
679 cJSON *root = cJSON_CreateObject();
680 cJSON_AddBoolToObject(root, "connected", connected);
681
682 if (connected) {
683 esp_netif_t *netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
684 if (netif) {
685 esp_netif_ip_info_t ip_info;
686 if (esp_netif_get_ip_info(netif, &ip_info) == ESP_OK) {
687 char ip_str[16];
688 snprintf(ip_str, sizeof(ip_str), IPSTR, IP2STR(&ip_info.ip));
689 cJSON_AddStringToObject(root, "ip", ip_str);
690 }
691 }
692 cJSON_AddStringToObject(root, "ssid", (const char *)ap_info.ssid);
693 }
694
695 char *json = cJSON_PrintUnformatted(root);
696 httpd_resp_set_type(req, "application/json");
697 httpd_resp_send(req, json, strlen(json));
698 cJSON_free(json);
699 cJSON_Delete(root);
700 return ESP_OK;
701}
702
703static const httpd_uri_t uri_setup = { .uri = "/setup", .method = HTTP_GET, .handler = setup_page_handler };
704static const httpd_uri_t uri_wifi_scan = { .uri = "/wifi/scan", .method = HTTP_GET, .handler = wifi_scan_handler };
705static const httpd_uri_t uri_wifi_connect = { .uri = "/wifi/connect", .method = HTTP_POST, .handler = wifi_connect_handler };
706static const httpd_uri_t uri_wifi_status = { .uri = "/wifi/status", .method = HTTP_GET, .handler = wifi_status_handler };
372 707
373esp_err_t captive_portal_start(const char *ap_ip_str) 708esp_err_t captive_portal_start(const char *ap_ip_str)
374{ 709{
@@ -377,7 +712,6 @@ esp_err_t captive_portal_start(const char *ap_ip_str)
377 712
378 httpd_config_t config = HTTPD_DEFAULT_CONFIG(); 713 httpd_config_t config = HTTPD_DEFAULT_CONFIG();
379 config.max_uri_handlers = 20; 714 config.max_uri_handlers = 20;
380 config.uri_match_fn = httpd_uri_match_wildcard;
381 715
382 esp_err_t ret = httpd_start(&s_server, &config); 716 esp_err_t ret = httpd_start(&s_server, &config);
383 if (ret != ESP_OK) { 717 if (ret != ESP_OK) {
@@ -398,7 +732,15 @@ esp_err_t captive_portal_start(const char *ap_ip_str)
398 httpd_register_uri_handler(s_server, &uri_ncsi); 732 httpd_register_uri_handler(s_server, &uri_ncsi);
399 httpd_register_uri_handler(s_server, &uri_connecttest); 733 httpd_register_uri_handler(s_server, &uri_connecttest);
400 httpd_register_uri_handler(s_server, &uri_wpad); 734 httpd_register_uri_handler(s_server, &uri_wpad);
401 httpd_register_uri_handler(s_server, &uri_catchall); 735 httpd_register_uri_handler(s_server, &uri_setup);
736 ret = httpd_register_uri_handler(s_server, &uri_wifi_scan);
737 ESP_LOGI(TAG, "Registered /wifi/scan: %s", esp_err_to_name(ret));
738 ret = httpd_register_uri_handler(s_server, &uri_wifi_connect);
739 ESP_LOGI(TAG, "Registered /wifi/connect: %s", esp_err_to_name(ret));
740 ret = httpd_register_uri_handler(s_server, &uri_wifi_status);
741 ESP_LOGI(TAG, "Registered /wifi/status: %s", esp_err_to_name(ret));
742
743 httpd_register_err_handler(s_server, HTTPD_404_NOT_FOUND, catchall_err_handler);
402 744
403 ESP_LOGI(TAG, "Captive portal started on port 80"); 745 ESP_LOGI(TAG, "Captive portal started on port 80");
404 return ESP_OK; 746 return ESP_OK;
diff --git a/main/captive_portal.h b/main/captive_portal.h
index 06eb860..e02a4ce 100644
--- a/main/captive_portal.h
+++ b/main/captive_portal.h
@@ -7,5 +7,6 @@
7esp_err_t captive_portal_start(const char *ap_ip_str); 7esp_err_t captive_portal_start(const char *ap_ip_str);
8void captive_portal_stop(void); 8void captive_portal_stop(void);
9httpd_handle_t captive_portal_get_server(void); 9httpd_handle_t captive_portal_get_server(void);
10bool captive_portal_is_setup_available(void);
10 11
11#endif 12#endif
diff --git a/main/config.h b/main/config.h
index 50f7efb..3092306 100644
--- a/main/config.h
+++ b/main/config.h
@@ -105,5 +105,6 @@ esp_err_t tollgate_config_init(void);
105const tollgate_config_t *tollgate_config_get(void); 105const tollgate_config_t *tollgate_config_get(void);
106esp_err_t tollgate_config_get_wifi(wifi_config_t *wifi_config); 106esp_err_t tollgate_config_get_wifi(wifi_config_t *wifi_config);
107esp_err_t tollgate_config_get_next_wifi(wifi_config_t *wifi_config); 107esp_err_t tollgate_config_get_next_wifi(wifi_config_t *wifi_config);
108esp_err_t tollgate_config_add_wifi(const char *ssid, const char *password);
108 109
109#endif 110#endif
diff --git a/main/display.c b/main/display.c
index 2b6cc88..ccd08b7 100644
--- a/main/display.c
+++ b/main/display.c
@@ -2,7 +2,10 @@
2#include "axs15231b.h" 2#include "axs15231b.h"
3#include "qrcoded.h" 3#include "qrcoded.h"
4#include "font.h" 4#include "font.h"
5#include "nucula_wallet.h"
6#include "config.h"
5#include "esp_log.h" 7#include "esp_log.h"
8#include "esp_wifi.h"
6#include "freertos/FreeRTOS.h" 9#include "freertos/FreeRTOS.h"
7#include "freertos/task.h" 10#include "freertos/task.h"
8#include <string.h> 11#include <string.h>
@@ -12,15 +15,36 @@
12static const char *TAG = "display"; 15static const char *TAG = "display";
13 16
14#define QR_CYCLE_MS 5000 17#define QR_CYCLE_MS 5000
18#define RENDER_INTERVAL_MS 2000
19
20#define COLOR_BG 0x0000
21#define COLOR_WHITE 0xFFFF
22#define COLOR_CYAN 0x07FF
23#define COLOR_YELLOW 0xFFE0
24#define COLOR_GREEN 0x07E0
25#define COLOR_ORANGE 0xFD20
26#define COLOR_RED 0xF800
27#define COLOR_DIM 0x8410
15 28
16static volatile display_state_t s_state = DISPLAY_BOOT; 29static volatile display_state_t s_state = DISPLAY_BOOT;
17static char s_ap_ssid[32] = ""; 30static char s_ap_ssid[32] = "";
18static char s_portal_url[256] = ""; 31static char s_portal_url[256] = "";
32static char s_mint_url[256] = "";
33static char s_wifi_status[32] = "starting...";
19static int s_active_clients = 0; 34static int s_active_clients = 0;
20static uint64_t s_wallet_balance = 0; 35static uint64_t s_wallet_balance = 0;
36static int s_price_per_step = 0;
21static bool s_initialized = false; 37static bool s_initialized = false;
22static int64_t s_last_qr_switch = 0; 38static int64_t s_last_qr_switch = 0;
23static display_qr_mode_t s_qr_mode = DISPLAY_QR_WIFI; 39static display_qr_mode_t s_qr_mode = DISPLAY_QR_WIFI;
40static int s_last_payment_sats = 0;
41static int64_t s_last_allotment_ms = 0;
42
43static uint16_t wallet_color(void) {
44 if (s_wallet_balance == 0) return COLOR_RED;
45 if (s_wallet_balance < 100) return COLOR_YELLOW;
46 return COLOR_GREEN;
47}
24 48
25static int qr_version_from_strlen(int len) { 49static int qr_version_from_strlen(int len) {
26 if (len <= 17) return 1; 50 if (len <= 17) return 1;
@@ -59,10 +83,60 @@ static int escape_wifi_field(const char *src, char *dst, int dst_size) {
59 return di; 83 return di;
60} 84}
61 85
86static void extract_domain(const char *url, char *out, int out_size) {
87 const char *start = url;
88 if (strncmp(url, "https://", 8) == 0) start = url + 8;
89 else if (strncmp(url, "http://", 7) == 0) start = url + 7;
90 strncpy(out, start, out_size - 1);
91 out[out_size - 1] = '\0';
92 char *slash = strchr(out, '/');
93 if (slash) *slash = '\0';
94}
95
62static void build_wifi_qr_string(char *out, int out_size) { 96static void build_wifi_qr_string(char *out, int out_size) {
63 char escaped_ssid[64]; 97 char escaped_ssid[64];
64 escape_wifi_field(s_ap_ssid, escaped_ssid, sizeof(escaped_ssid)); 98 escape_wifi_field(s_ap_ssid, escaped_ssid, sizeof(escaped_ssid));
65 snprintf(out, out_size, "WIFI:S:%s;T:nopass;;", escaped_ssid); 99 const tollgate_config_t *cfg = tollgate_config_get();
100 if (strlen(cfg->ap_password) > 0) {
101 char escaped_pass[128];
102 escape_wifi_field(cfg->ap_password, escaped_pass, sizeof(escaped_pass));
103 snprintf(out, out_size, "WIFI:S:%s;T:WPA;P:%s;;", escaped_ssid, escaped_pass);
104 } else {
105 snprintf(out, out_size, "WIFI:S:%s;T:nopass;;", escaped_ssid);
106 }
107}
108
109static void render_qr_at(const char *text, int x_off, int y_off, int max_w, int max_h) {
110 int len = strlen(text);
111 int version = qr_version_from_strlen(len);
112 int px = qr_pixel_size(len);
113
114 uint16_t buf_size = qrcode_getBufferSize(version);
115 uint8_t *qr_buf = (uint8_t *)malloc(buf_size);
116 if (!qr_buf) return;
117
118 QRCode qrcode;
119 if (qrcode_initText(&qrcode, qr_buf, version, ECC_LOW, text) != 0) {
120 free(qr_buf);
121 return;
122 }
123
124 int qr_px_w = qrcode.size * px;
125 int qr_px_h = qrcode.size * px;
126 int cx = x_off + (max_w - qr_px_w) / 2;
127 int cy = y_off + (max_h - qr_px_h) / 2;
128 if (cx < 0) cx = 0;
129 if (cy < 0) cy = 0;
130
131 for (int y = 0; y < qrcode.size; y++) {
132 for (int x = 0; x < qrcode.size; x++) {
133 bool mod = qrcode_getModule(&qrcode, x, y);
134 uint16_t color = mod ? COLOR_WHITE : COLOR_BG;
135 axs15231b_fill_rect(cx + x * px, cy + y * px, px, px, color);
136 }
137 }
138
139 free(qr_buf);
66} 140}
67 141
68void display_render_text(int x, int y, const char *text, uint16_t fg, uint16_t bg, int scale) { 142void display_render_text(int x, int y, const char *text, uint16_t fg, uint16_t bg, int scale) {
@@ -98,99 +172,206 @@ void display_render_text(int x, int y, const char *text, uint16_t fg, uint16_t b
98 } 172 }
99} 173}
100 174
101static void render_qr_at(const char *text, int x_off, int y_off, int max_w, int max_h) {
102 int len = strlen(text);
103 int version = qr_version_from_strlen(len);
104 int px = qr_pixel_size(len);
105
106 uint16_t buf_size = qrcode_getBufferSize(version);
107 uint8_t *qr_buf = (uint8_t *)malloc(buf_size);
108 if (!qr_buf) {
109 ESP_LOGE(TAG, "Failed to allocate QR buffer");
110 return;
111 }
112
113 QRCode qr;
114 if (qrcode_initText(&qr, qr_buf, version, ECC_LOW, text) != 0) {
115 ESP_LOGE(TAG, "QR generation failed");
116 free(qr_buf);
117 return;
118 }
119
120 int qr_px_w = qr.size * px;
121 int qr_px_h = qr.size * px;
122 int cx = x_off + (max_w - qr_px_w) / 2;
123 int cy = y_off + (max_h - qr_px_h) / 2;
124 if (cx < 0) cx = 0;
125 if (cy < 0) cy = 0;
126
127 for (int y = 0; y < qr.size; y++) {
128 for (int x = 0; x < qr.size; x++) {
129 bool mod = qrcode_getModule(&qr, x, y);
130 uint16_t color = mod ? 0xFFFF : 0x0000;
131 axs15231b_fill_rect(cx + x * px, cy + y * px, px, px, color);
132 }
133 }
134
135 free(qr_buf);
136}
137
138void display_render_qr(const char *text) { 175void display_render_qr(const char *text) {
139 int screen_w = axs15231b_get_width(); 176 int screen_w = axs15231b_get_width();
140 int screen_h = axs15231b_get_height(); 177 int screen_h = axs15231b_get_height();
141 axs15231b_fill_screen(0x0000); 178 axs15231b_fill_screen(COLOR_BG);
142 render_qr_at(text, 0, 0, screen_w, screen_h); 179 render_qr_at(text, 0, 0, screen_w, screen_h);
143 axs15231b_flush(); 180 axs15231b_flush();
144} 181}
145 182
146static void render_boot_screen(void) { 183static void render_boot_screen(void) {
147 axs15231b_fill_screen(0x0000); 184 int screen_w = axs15231b_get_width();
148 display_render_text(140, 100, "TollGate", 0xF79F, 0x0000, 3); 185 axs15231b_fill_screen(COLOR_BG);
149 display_render_text(140, 140, "starting...", 0xB5B6, 0x0000, 2); 186
187 char qr_text[320];
188 build_wifi_qr_string(qr_text, sizeof(qr_text));
189 render_qr_at(qr_text, 0, 10, screen_w, 220);
190
191 const char *title = "TollGate";
192 int title_w = strlen(title) * 8 * 2;
193 display_render_text((screen_w - title_w) / 2, 240, title, COLOR_CYAN, COLOR_BG, 2);
194
195 int status_w = strlen(s_wifi_status) * 8;
196 display_render_text((screen_w - status_w) / 2, 268, s_wifi_status, COLOR_YELLOW, COLOR_BG, 1);
197
198 snprintf(qr_text, sizeof(qr_text), "SSID: %s", s_ap_ssid);
199 int ssid_w = strlen(qr_text) * 8;
200 display_render_text((screen_w - ssid_w) / 2, 295, qr_text, COLOR_DIM, COLOR_BG, 1);
201
202 const char *hint = "Scan QR to connect";
203 int hint_w = strlen(hint) * 8;
204 display_render_text((screen_w - hint_w) / 2, 315, hint, COLOR_DIM, COLOR_BG, 1);
205
150 axs15231b_flush(); 206 axs15231b_flush();
151} 207}
152 208
153static void render_ready_screen(void) { 209static void render_ready_screen(void) {
154 axs15231b_fill_screen(0x0000);
155
156 int screen_w = axs15231b_get_width(); 210 int screen_w = axs15231b_get_width();
157 int screen_h = axs15231b_get_height(); 211 int text_area_y = 330;
158 int text_area_y = screen_h - 55; 212 axs15231b_fill_screen(COLOR_BG);
159 213
160 char qr_text[320]; 214 char qr_text[320];
161 const char *label;
162
163 if (s_qr_mode == DISPLAY_QR_WIFI) { 215 if (s_qr_mode == DISPLAY_QR_WIFI) {
164 build_wifi_qr_string(qr_text, sizeof(qr_text)); 216 build_wifi_qr_string(qr_text, sizeof(qr_text));
165 label = "Scan to connect";
166 } else { 217 } else {
167 strncpy(qr_text, s_portal_url, sizeof(qr_text) - 1); 218 strncpy(qr_text, s_portal_url, sizeof(qr_text) - 1);
168 qr_text[sizeof(qr_text) - 1] = '\0'; 219 qr_text[sizeof(qr_text) - 1] = '\0';
169 label = "Portal URL";
170 } 220 }
171 221
172 render_qr_at(qr_text, 0, 0, screen_w, text_area_y - 5); 222 render_qr_at(qr_text, 0, 5, screen_w, text_area_y - 10);
223
224 int y = text_area_y;
225 char line[48];
226
227 if (s_qr_mode == DISPLAY_QR_WIFI) {
228 snprintf(line, sizeof(line), "Scan to connect");
229 display_render_text(10, y, line, COLOR_CYAN, COLOR_BG, 1);
230 y += 16;
231
232 snprintf(line, sizeof(line), "SSID: %s", s_ap_ssid);
233 display_render_text(10, y, line, COLOR_WHITE, COLOR_BG, 1);
234 y += 16;
235 } else {
236 snprintf(line, sizeof(line), "Portal URL");
237 display_render_text(10, y, line, COLOR_CYAN, COLOR_BG, 1);
238 y += 16;
239
240 char domain[48];
241 extract_domain(s_mint_url, domain, sizeof(domain));
242 snprintf(line, sizeof(line), "Mint: %.30s", domain);
243 display_render_text(10, y, line, COLOR_ORANGE, COLOR_BG, 1);
244 y += 16;
245 }
246
247 snprintf(line, sizeof(line), "%d sats/min", s_price_per_step);
248 display_render_text(10, y, line, COLOR_ORANGE, COLOR_BG, 1);
249 y += 16;
250
251 snprintf(line, sizeof(line), "Wallet: %llu sats", (unsigned long long)s_wallet_balance);
252 display_render_text(10, y, line, wallet_color(), COLOR_BG, 1);
253 y += 16;
254
255 if (s_active_clients > 0) {
256 snprintf(line, sizeof(line), "Clients: %d", s_active_clients);
257 display_render_text(10, y, line, COLOR_GREEN, COLOR_BG, 1);
258 }
259
260 axs15231b_flush();
261}
262
263static void render_setup_pending_screen(void) {
264 int screen_w = axs15231b_get_width();
265 axs15231b_fill_screen(COLOR_BG);
173 266
174 display_render_text(10, text_area_y, label, 0xB5B6, 0x0000, 2); 267 char qr_text[320];
268 build_wifi_qr_string(qr_text, sizeof(qr_text));
269 render_qr_at(qr_text, 0, 5, screen_w, 280);
175 270
271 int y = 290;
176 char line[64]; 272 char line[64];
273
274 const char *title = "WiFi Setup";
275 int tw = strlen(title) * 8;
276 display_render_text((screen_w - tw) / 2, y, title, COLOR_CYAN, COLOR_BG, 1);
277 y += 20;
278
177 snprintf(line, sizeof(line), "SSID: %s", s_ap_ssid); 279 snprintf(line, sizeof(line), "SSID: %s", s_ap_ssid);
178 display_render_text(10, text_area_y + 20, line, 0xB5B6, 0x0000, 2); 280 display_render_text(10, y, line, COLOR_WHITE, COLOR_BG, 1);
281 y += 18;
282
283 const char *hint1 = "1. Connect to WiFi above";
284 display_render_text(10, y, hint1, COLOR_DIM, COLOR_BG, 1);
285 y += 16;
286
287 const char *hint2 = "2. Open browser, go to:";
288 display_render_text(10, y, hint2, COLOR_DIM, COLOR_BG, 1);
289 y += 18;
290
291 const tollgate_config_t *cfg = tollgate_config_get();
292 snprintf(line, sizeof(line), "http://%s/setup", cfg->ap_ip_str);
293 display_render_text(10, y, line, COLOR_YELLOW, COLOR_BG, 1);
294 y += 22;
295
296 const char *hint3 = "3. Configure upstream WiFi";
297 display_render_text(10, y, hint3, COLOR_DIM, COLOR_BG, 1);
179 298
180 axs15231b_flush(); 299 axs15231b_flush();
181} 300}
182 301
183static void render_payment_screen(void) { 302static void render_payment_screen(void) {
184 axs15231b_fill_screen(0x07E0); 303 int screen_w = axs15231b_get_width();
185 display_render_text(140, 100, "Paid!", 0x0000, 0x07E0, 3); 304 axs15231b_fill_screen(COLOR_BG);
186 display_render_text(130, 140, "Access granted", 0x0000, 0x07E0, 2); 305
306 axs15231b_fill_rect(0, 190, screen_w, 50, COLOR_GREEN);
307 const char *msg = "ACCESS GRANTED";
308 int msg_w = strlen(msg) * 8 * 2;
309 display_render_text((screen_w - msg_w) / 2, 202, msg, COLOR_WHITE, COLOR_GREEN, 2);
310
311 char line[48];
312
313 snprintf(line, sizeof(line), "Paid: %d sats", s_last_payment_sats);
314 int lw = strlen(line) * 8;
315 display_render_text((screen_w - lw) / 2, 270, line, COLOR_WHITE, COLOR_BG, 1);
316
317 int64_t secs = s_last_allotment_ms / 1000;
318 if (secs >= 60) {
319 snprintf(line, sizeof(line), "Time: %lld min", (long long)(secs / 60));
320 } else {
321 snprintf(line, sizeof(line), "Time: %lld sec", (long long)secs);
322 }
323 lw = strlen(line) * 8;
324 display_render_text((screen_w - lw) / 2, 290, line, COLOR_WHITE, COLOR_BG, 1);
325
326 snprintf(line, sizeof(line), "Wallet: %llu sats", (unsigned long long)s_wallet_balance);
327 lw = strlen(line) * 8;
328 display_render_text((screen_w - lw) / 2, 320, line, wallet_color(), COLOR_BG, 1);
329
187 axs15231b_flush(); 330 axs15231b_flush();
188} 331}
189 332
190static void render_error_screen(void) { 333static void render_error_screen(void) {
191 axs15231b_fill_screen(0xF800); 334 int screen_w = axs15231b_get_width();
192 display_render_text(120, 100, "No upstream", 0xFFFF, 0xF800, 3); 335 axs15231b_fill_screen(COLOR_BG);
193 display_render_text(130, 140, "Check config", 0xFFFF, 0xF800, 2); 336
337 char qr_text[320];
338 build_wifi_qr_string(qr_text, sizeof(qr_text));
339 render_qr_at(qr_text, 0, 5, screen_w, 150);
340
341 axs15231b_fill_rect(0, 160, screen_w, 36, COLOR_RED);
342 const char *msg = "NO UPSTREAM";
343 int msg_w = strlen(msg) * 8 * 2;
344 display_render_text((screen_w - msg_w) / 2, 170, msg, COLOR_WHITE, COLOR_RED, 2);
345
346 char line[64];
347 int lw;
348 int y = 210;
349
350 const char *l1 = "Internet unavailable";
351 lw = strlen(l1) * 8;
352 display_render_text((screen_w - lw) / 2, y, l1, COLOR_WHITE, COLOR_BG, 1);
353 y += 20;
354
355 const char *l3 = "AP still active";
356 lw = strlen(l3) * 8;
357 display_render_text((screen_w - lw) / 2, y, l3, COLOR_GREEN, COLOR_BG, 1);
358 y += 20;
359
360 snprintf(line, sizeof(line), "SSID: %s", s_ap_ssid);
361 lw = strlen(line) * 8;
362 display_render_text((screen_w - lw) / 2, y, line, COLOR_DIM, COLOR_BG, 1);
363 y += 20;
364
365 const tollgate_config_t *cfg = tollgate_config_get();
366 snprintf(line, sizeof(line), "http://%s/setup", cfg->ap_ip_str);
367 lw = strlen(line) * 8;
368 display_render_text((screen_w - lw) / 2, y, line, COLOR_YELLOW, COLOR_BG, 1);
369 y += 16;
370
371 const char *hint = "Scan QR to connect";
372 lw = strlen(hint) * 8;
373 display_render_text((screen_w - lw) / 2, y, hint, COLOR_DIM, COLOR_BG, 1);
374
194 axs15231b_flush(); 375 axs15231b_flush();
195} 376}
196 377
@@ -200,6 +381,14 @@ static void display_task(void *pvParameters) {
200 while (1) { 381 while (1) {
201 display_state_t state = s_state; 382 display_state_t state = s_state;
202 383
384 if (state == DISPLAY_READY) {
385 int64_t now = (int64_t)xTaskGetTickCount() * portTICK_PERIOD_MS;
386 if ((now - s_last_qr_switch) >= QR_CYCLE_MS) {
387 s_qr_mode = (s_qr_mode == DISPLAY_QR_WIFI) ? DISPLAY_QR_PORTAL : DISPLAY_QR_WIFI;
388 s_last_qr_switch = now;
389 }
390 }
391
203 switch (state) { 392 switch (state) {
204 case DISPLAY_BOOT: 393 case DISPLAY_BOOT:
205 render_boot_screen(); 394 render_boot_screen();
@@ -209,21 +398,18 @@ static void display_task(void *pvParameters) {
209 break; 398 break;
210 case DISPLAY_PAYMENT_RECEIVED: 399 case DISPLAY_PAYMENT_RECEIVED:
211 render_payment_screen(); 400 render_payment_screen();
212 vTaskDelay(pdMS_TO_TICKS(2000)); 401 vTaskDelay(pdMS_TO_TICKS(3000));
213 s_state = DISPLAY_READY; 402 s_state = DISPLAY_READY;
214 break; 403 break;
215 case DISPLAY_ERROR: 404 case DISPLAY_ERROR:
216 render_error_screen(); 405 render_error_screen();
217 break; 406 break;
407 case DISPLAY_SETUP_PENDING:
408 render_setup_pending_screen();
409 break;
218 } 410 }
219 411
220 int64_t now = (int64_t)xTaskGetTickCount() * portTICK_PERIOD_MS; 412 vTaskDelay(pdMS_TO_TICKS(RENDER_INTERVAL_MS));
221 if (state == DISPLAY_READY && (now - s_last_qr_switch) >= QR_CYCLE_MS) {
222 s_qr_mode = (s_qr_mode == DISPLAY_QR_WIFI) ? DISPLAY_QR_PORTAL : DISPLAY_QR_WIFI;
223 s_last_qr_switch = now;
224 }
225
226 vTaskDelay(pdMS_TO_TICKS(1000));
227 } 413 }
228} 414}
229 415
@@ -239,7 +425,7 @@ esp_err_t display_init(void) {
239 s_initialized = true; 425 s_initialized = true;
240 s_last_qr_switch = (int64_t)xTaskGetTickCount() * portTICK_PERIOD_MS; 426 s_last_qr_switch = (int64_t)xTaskGetTickCount() * portTICK_PERIOD_MS;
241 427
242 xTaskCreatePinnedToCore(display_task, "display", 16384, NULL, 2, NULL, 1); 428 xTaskCreatePinnedToCore(display_task, "display", 24576, NULL, 2, NULL, 1);
243 429
244 ESP_LOGI(TAG, "Display initialized"); 430 ESP_LOGI(TAG, "Display initialized");
245 return ESP_OK; 431 return ESP_OK;
@@ -250,7 +436,9 @@ void display_set_state(display_state_t state) {
250} 436}
251 437
252void display_update(const char *ap_ssid, int active_clients, 438void display_update(const char *ap_ssid, int active_clients,
253 uint64_t wallet_balance, const char *portal_url) { 439 uint64_t wallet_balance, const char *portal_url,
440 const char *mint_url, int price_per_step,
441 const char *wifi_status) {
254 if (ap_ssid) { 442 if (ap_ssid) {
255 strncpy(s_ap_ssid, ap_ssid, sizeof(s_ap_ssid) - 1); 443 strncpy(s_ap_ssid, ap_ssid, sizeof(s_ap_ssid) - 1);
256 s_ap_ssid[sizeof(s_ap_ssid) - 1] = '\0'; 444 s_ap_ssid[sizeof(s_ap_ssid) - 1] = '\0';
@@ -259,6 +447,29 @@ void display_update(const char *ap_ssid, int active_clients,
259 strncpy(s_portal_url, portal_url, sizeof(s_portal_url) - 1); 447 strncpy(s_portal_url, portal_url, sizeof(s_portal_url) - 1);
260 s_portal_url[sizeof(s_portal_url) - 1] = '\0'; 448 s_portal_url[sizeof(s_portal_url) - 1] = '\0';
261 } 449 }
450 if (mint_url) {
451 strncpy(s_mint_url, mint_url, sizeof(s_mint_url) - 1);
452 s_mint_url[sizeof(s_mint_url) - 1] = '\0';
453 }
454 if (wifi_status) {
455 strncpy(s_wifi_status, wifi_status, sizeof(s_wifi_status) - 1);
456 s_wifi_status[sizeof(s_wifi_status) - 1] = '\0';
457 }
458 if (price_per_step > 0) s_price_per_step = price_per_step;
262 s_active_clients = active_clients; 459 s_active_clients = active_clients;
263 s_wallet_balance = wallet_balance; 460 s_wallet_balance = wallet_balance;
264} 461}
462
463void display_notify_payment(int amount_sats, int64_t allotment_ms) {
464 s_last_payment_sats = amount_sats;
465 s_last_allotment_ms = allotment_ms;
466 s_wallet_balance = nucula_wallet_balance();
467 display_set_state(DISPLAY_PAYMENT_RECEIVED);
468}
469
470void display_notify_wifi_connected(const char *ip) {
471 (void)ip;
472}
473
474void display_notify_wifi_disconnected(void) {
475}
diff --git a/main/display.h b/main/display.h
index 407521b..ecb76b6 100644
--- a/main/display.h
+++ b/main/display.h
@@ -9,7 +9,8 @@ typedef enum {
9 DISPLAY_BOOT, 9 DISPLAY_BOOT,
10 DISPLAY_READY, 10 DISPLAY_READY,
11 DISPLAY_PAYMENT_RECEIVED, 11 DISPLAY_PAYMENT_RECEIVED,
12 DISPLAY_ERROR 12 DISPLAY_ERROR,
13 DISPLAY_SETUP_PENDING
13} display_state_t; 14} display_state_t;
14 15
15typedef enum { 16typedef enum {
@@ -20,7 +21,12 @@ typedef enum {
20esp_err_t display_init(void); 21esp_err_t display_init(void);
21void display_set_state(display_state_t state); 22void display_set_state(display_state_t state);
22void display_update(const char *ap_ssid, int active_clients, 23void display_update(const char *ap_ssid, int active_clients,
23 uint64_t wallet_balance, const char *portal_url); 24 uint64_t wallet_balance, const char *portal_url,
25 const char *mint_url, int price_per_step,
26 const char *wifi_status);
27void display_notify_payment(int amount_sats, int64_t allotment_ms);
28void display_notify_wifi_connected(const char *ip);
29void display_notify_wifi_disconnected(void);
24void display_render_text(int x, int y, const char *text, uint16_t fg, uint16_t bg, int scale); 30void display_render_text(int x, int y, const char *text, uint16_t fg, uint16_t bg, int scale);
25void display_render_qr(const char *text); 31void display_render_qr(const char *text);
26 32
diff --git a/main/keyboard.c b/main/keyboard.c
new file mode 100644
index 0000000..d16135f
--- /dev/null
+++ b/main/keyboard.c
@@ -0,0 +1,186 @@
1#include "keyboard.h"
2#include <string.h>
3
4static const char *s_alpha_lower[] = {
5 "qwertyuiop",
6 "asdfghjkl",
7 "\001zxcvbnm\b",
8 "\002\003\004"
9};
10
11static const char *s_alpha_upper[] = {
12 "QWERTYUIOP",
13 "ASDFGHJKL",
14 "\001ZXCVBNM\b",
15 "\002\003\004"
16};
17
18static const char *s_numsym[] = {
19 "1234567890",
20 "-/:;()$&@\"",
21 "\001.,?!'\\b",
22 "\002\003\004"
23};
24
25#define CTRL_SHIFT '\001'
26#define CTRL_LAYER '\002'
27#define CTRL_SPACE '\003'
28#define CTRL_DONE '\004'
29#define CTRL_BS '\b'
30
31static kb_layout_t s_layout = {
32 .key_w = 28,
33 .key_h = 36,
34 .key_gap = 2,
35 .start_y = 70,
36 .screen_w = 320,
37 .row_count = 4,
38};
39
40void kb_state_init(kb_state_t *st) {
41 if (!st) return;
42 memset(st, 0, sizeof(*st));
43 st->layer = KB_ALPHA_LOWER;
44 st->reveal = false;
45}
46
47void kb_set_layout(const kb_layout_t *layout) {
48 if (layout) s_layout = *layout;
49}
50
51const kb_layout_t *kb_get_layout(void) {
52 return &s_layout;
53}
54
55static const char **get_layer(kb_layer_t layer) {
56 switch (layer) {
57 case KB_ALPHA_UPPER: return s_alpha_upper;
58 case KB_NUMSYM: return s_numsym;
59 default: return s_alpha_lower;
60 }
61}
62
63int kb_get_row_keys(int row, kb_layer_t layer, const char **keys_out) {
64 if (row < 0 || row >= s_layout.row_count) {
65 *keys_out = NULL;
66 return 0;
67 }
68 const char **layer_rows = get_layer(layer);
69 const char *row_str = layer_rows[row];
70 *keys_out = row_str;
71 return (int)strlen(row_str);
72}
73
74static int row_x_offset(int row, int total_keys) {
75 int kw = s_layout.key_w;
76 int gap = s_layout.key_gap;
77 int total_w = total_keys * kw + (total_keys - 1) * gap;
78 int margin = (s_layout.screen_w - total_w) / 2;
79 if (margin < 2) margin = 2;
80 switch (row) {
81 case 0: return margin;
82 case 1: return margin + kw / 2;
83 case 2: return margin + kw;
84 case 3: return margin;
85 default: return margin;
86 }
87}
88
89static int key_width_at(int row, int col, int total_keys) {
90 int kw = s_layout.key_w;
91 if (row == 3) {
92 int gap = s_layout.key_gap;
93 int margin = row_x_offset(3, total_keys);
94 int available = s_layout.screen_w - margin * 2;
95 int side_w = (available - gap) / 4;
96 if (col == 0) return side_w;
97 if (col == total_keys - 1) return side_w;
98 return available - side_w * 2 - gap * 2;
99 }
100 return kw;
101}
102
103kb_result_t kb_hit_test(int tx, int ty, kb_layer_t layer) {
104 kb_result_t result = {KB_ACTION_NONE, 0};
105 int sy = s_layout.start_y;
106 int kw = s_layout.key_w;
107 int kh = s_layout.key_h;
108 int gap = s_layout.key_gap;
109
110 if (ty < sy || ty >= sy + s_layout.row_count * (kh + gap)) {
111 return result;
112 }
113
114 int row = (ty - sy) / (kh + gap);
115 if (row < 0 || row >= s_layout.row_count) return result;
116
117 const char *row_str;
118 int total_keys = kb_get_row_keys(row, layer, &row_str);
119 if (total_keys == 0) return result;
120
121 int x_off = row_x_offset(row, total_keys);
122 int cx = x_off;
123
124 for (int col = 0; col < total_keys; col++) {
125 int key_w = key_width_at(row, col, total_keys);
126 if (tx >= cx && tx < cx + key_w) {
127 char c = row_str[col];
128 if (c == CTRL_SHIFT) {
129 result.action = KB_ACTION_SHIFT;
130 } else if (c == CTRL_LAYER) {
131 result.action = KB_ACTION_LAYER;
132 } else if (c == CTRL_SPACE) {
133 result.action = KB_ACTION_SPACE;
134 result.ch = ' ';
135 } else if (c == CTRL_DONE) {
136 result.action = KB_ACTION_DONE;
137 } else if (c == CTRL_BS) {
138 result.action = KB_ACTION_BACKSPACE;
139 } else {
140 result.action = KB_ACTION_CHAR;
141 result.ch = c;
142 }
143 return result;
144 }
145 cx += key_w + gap;
146 }
147
148 return result;
149}
150
151void kb_apply(kb_state_t *st, kb_result_t result) {
152 if (!st || result.action == KB_ACTION_NONE) return;
153
154 switch (result.action) {
155 case KB_ACTION_CHAR:
156 if (st->cursor < KB_INPUT_MAX) {
157 st->input[st->cursor++] = result.ch;
158 st->input[st->cursor] = '\0';
159 }
160 break;
161 case KB_ACTION_BACKSPACE:
162 if (st->cursor > 0) {
163 st->cursor--;
164 st->input[st->cursor] = '\0';
165 }
166 break;
167 case KB_ACTION_SHIFT:
168 if (st->layer == KB_ALPHA_LOWER) st->layer = KB_ALPHA_UPPER;
169 else if (st->layer == KB_ALPHA_UPPER) st->layer = KB_ALPHA_LOWER;
170 break;
171 case KB_ACTION_LAYER:
172 if (st->layer == KB_NUMSYM) st->layer = KB_ALPHA_LOWER;
173 else st->layer = KB_NUMSYM;
174 break;
175 case KB_ACTION_SPACE:
176 if (st->cursor < KB_INPUT_MAX) {
177 st->input[st->cursor++] = ' ';
178 st->input[st->cursor] = '\0';
179 }
180 break;
181 case KB_ACTION_DONE:
182 break;
183 default:
184 break;
185 }
186}
diff --git a/main/keyboard.h b/main/keyboard.h
new file mode 100644
index 0000000..9c4118f
--- /dev/null
+++ b/main/keyboard.h
@@ -0,0 +1,53 @@
1#ifndef KEYBOARD_H
2#define KEYBOARD_H
3
4#include <stdint.h>
5#include <stdbool.h>
6
7#define KB_INPUT_MAX 64
8
9typedef enum {
10 KB_ALPHA_LOWER,
11 KB_ALPHA_UPPER,
12 KB_NUMSYM
13} kb_layer_t;
14
15typedef enum {
16 KB_ACTION_NONE = 0,
17 KB_ACTION_CHAR,
18 KB_ACTION_SHIFT,
19 KB_ACTION_BACKSPACE,
20 KB_ACTION_DONE,
21 KB_ACTION_LAYER,
22 KB_ACTION_SPACE
23} kb_action_t;
24
25typedef struct {
26 char input[KB_INPUT_MAX + 1];
27 int cursor;
28 bool reveal;
29 kb_layer_t layer;
30} kb_state_t;
31
32typedef struct {
33 kb_action_t action;
34 char ch;
35} kb_result_t;
36
37typedef struct {
38 int key_w;
39 int key_h;
40 int key_gap;
41 int start_y;
42 int screen_w;
43 int row_count;
44} kb_layout_t;
45
46void kb_state_init(kb_state_t *st);
47void kb_set_layout(const kb_layout_t *layout);
48const kb_layout_t *kb_get_layout(void);
49int kb_get_row_keys(int row, kb_layer_t layer, const char **keys_out);
50kb_result_t kb_hit_test(int tx, int ty, kb_layer_t layer);
51void kb_apply(kb_state_t *st, kb_result_t result);
52
53#endif
diff --git a/main/touch.c b/main/touch.c
new file mode 100644
index 0000000..a28d13e
--- /dev/null
+++ b/main/touch.c
@@ -0,0 +1,156 @@
1#include "touch.h"
2#include "esp_log.h"
3#include "driver/i2c_master.h"
4#include "driver/gpio.h"
5#include "freertos/FreeRTOS.h"
6#include "freertos/task.h"
7#include <string.h>
8
9static const char *TAG = "touch";
10
11static i2c_master_bus_handle_t s_bus = NULL;
12static i2c_master_dev_handle_t s_dev = NULL;
13static bool s_initialized = false;
14static int s_rotation = 0;
15
16static const uint8_t s_read_cmd[11] = {
17 0xb5, 0xab, 0xa5, 0x5a, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00
18};
19
20void touch_parse_raw(const uint8_t *data, touch_point_t *pt) {
21 memset(pt, 0, sizeof(*pt));
22
23 if (!data || data[0] != 0 || data[1] == 0 || data[1] > 1) {
24 pt->touched = false;
25 return;
26 }
27
28 uint16_t raw_x = ((data[2] & 0x0F) << 8) | data[3];
29 uint16_t raw_y = ((data[4] & 0x0F) << 8) | data[5];
30
31 if (raw_x > TOUCH_MAX_X) raw_x = TOUCH_MAX_X;
32 if (raw_y > TOUCH_MAX_Y) raw_y = TOUCH_MAX_Y;
33
34 pt->x = raw_x;
35 pt->y = raw_y;
36 pt->touched = true;
37}
38
39esp_err_t touch_init(void) {
40 if (s_initialized) return ESP_OK;
41
42 gpio_config_t rst_conf = {
43 .pin_bit_mask = (1ULL << TOUCH_RST_PIN),
44 .mode = GPIO_MODE_OUTPUT,
45 .pull_up_en = GPIO_PULLUP_DISABLE,
46 .pull_down_en = GPIO_PULLDOWN_DISABLE,
47 .intr_type = GPIO_INTR_DISABLE,
48 };
49 gpio_config(&rst_conf);
50
51 gpio_set_level(TOUCH_RST_PIN, 0);
52 vTaskDelay(pdMS_TO_TICKS(200));
53 gpio_set_level(TOUCH_RST_PIN, 1);
54 vTaskDelay(pdMS_TO_TICKS(200));
55
56 i2c_master_bus_config_t bus_cfg = {
57 .i2c_port = I2C_NUM_0,
58 .sda_io_num = TOUCH_SDA_PIN,
59 .scl_io_num = TOUCH_SCL_PIN,
60 .clk_source = I2C_CLK_SRC_DEFAULT,
61 .glitch_ignore_cnt = 7,
62 .intr_priority = 0,
63 .trans_queue_depth = 0,
64 .flags = {
65 .enable_internal_pullup = 1,
66 .allow_pd = 0,
67 },
68 };
69
70 esp_err_t ret = i2c_new_master_bus(&bus_cfg, &s_bus);
71 if (ret != ESP_OK) {
72 ESP_LOGE(TAG, "Failed to create I2C bus: %s", esp_err_to_name(ret));
73 return ret;
74 }
75
76 i2c_device_config_t dev_cfg = {
77 .dev_addr_length = I2C_ADDR_BIT_LEN_7,
78 .device_address = TOUCH_I2C_ADDR,
79 .scl_speed_hz = 400000,
80 .scl_wait_us = 0,
81 .flags = {
82 .disable_ack_check = 0,
83 },
84 };
85
86 ret = i2c_master_bus_add_device(s_bus, &dev_cfg, &s_dev);
87 if (ret != ESP_OK) {
88 ESP_LOGE(TAG, "Failed to add I2C device: %s", esp_err_to_name(ret));
89 i2c_del_master_bus(s_bus);
90 s_bus = NULL;
91 return ret;
92 }
93
94 s_initialized = true;
95 ESP_LOGI(TAG, "Touch initialized (I2C addr 0x%02X)", TOUCH_I2C_ADDR);
96 return ESP_OK;
97}
98
99bool touch_read(touch_point_t *pt) {
100 if (!s_initialized || !s_dev || !pt) {
101 if (pt) pt->touched = false;
102 return false;
103 }
104
105 esp_err_t ret = i2c_master_transmit(s_dev, s_read_cmd, sizeof(s_read_cmd), 100);
106 if (ret != ESP_OK) {
107 pt->touched = false;
108 return false;
109 }
110
111 uint8_t data[8] = {0};
112 ret = i2c_master_receive(s_dev, data, sizeof(data), 100);
113 if (ret != ESP_OK) {
114 pt->touched = false;
115 return false;
116 }
117
118 touch_parse_raw(data, pt);
119
120 if (pt->touched && s_rotation != 0) {
121 uint16_t raw_x = pt->x;
122 uint16_t raw_y = pt->y;
123 switch (s_rotation) {
124 case 1:
125 pt->x = raw_y;
126 pt->y = TOUCH_MAX_X - raw_x;
127 break;
128 case 2:
129 pt->x = TOUCH_MAX_X - raw_x;
130 pt->y = TOUCH_MAX_Y - raw_y;
131 break;
132 case 3:
133 pt->x = TOUCH_MAX_Y - raw_y;
134 pt->y = raw_x;
135 break;
136 }
137 }
138
139 return pt->touched;
140}
141
142void touch_set_rotation(int rotation) {
143 s_rotation = rotation;
144}
145
146void touch_deinit(void) {
147 if (s_dev) {
148 i2c_master_bus_rm_device(s_dev);
149 s_dev = NULL;
150 }
151 if (s_bus) {
152 i2c_del_master_bus(s_bus);
153 s_bus = NULL;
154 }
155 s_initialized = false;
156}
diff --git a/main/touch.h b/main/touch.h
new file mode 100644
index 0000000..b9e3ccd
--- /dev/null
+++ b/main/touch.h
@@ -0,0 +1,29 @@
1#ifndef TOUCH_H
2#define TOUCH_H
3
4#include "esp_err.h"
5#include <stdint.h>
6#include <stdbool.h>
7
8#define TOUCH_SDA_PIN 4
9#define TOUCH_SCL_PIN 8
10#define TOUCH_RST_PIN 12
11#define TOUCH_INT_PIN 11
12#define TOUCH_I2C_ADDR 0x3B
13#define TOUCH_MAX_X 319
14#define TOUCH_MAX_Y 479
15
16typedef struct {
17 uint16_t x;
18 uint16_t y;
19 bool touched;
20} touch_point_t;
21
22esp_err_t touch_init(void);
23bool touch_read(touch_point_t *pt);
24void touch_deinit(void);
25void touch_set_rotation(int rotation);
26
27void touch_parse_raw(const uint8_t *data, touch_point_t *pt);
28
29#endif
diff --git a/main/wifi_setup.c b/main/wifi_setup.c
new file mode 100644
index 0000000..b2669e9
--- /dev/null
+++ b/main/wifi_setup.c
@@ -0,0 +1,89 @@
1#include "wifi_setup.h"
2#include <string.h>
3
4void wifi_setup_init(wifi_setup_t *setup) {
5 if (!setup) return;
6 memset(setup, 0, sizeof(*setup));
7 setup->state = SETUP_SCAN;
8 setup->selected_ap = -1;
9}
10
11void wifi_setup_set_aps(wifi_setup_t *setup, const wifi_ap_info_t *aps, int count) {
12 if (!setup || !aps) return;
13 if (count > WIFI_SETUP_MAX_APS) count = WIFI_SETUP_MAX_APS;
14 memcpy(setup->aps, aps, count * sizeof(wifi_ap_info_t));
15 setup->ap_count = count;
16 setup->list_scroll = 0;
17 setup->state = SETUP_LIST;
18}
19
20int wifi_setup_visible_count(const wifi_setup_t *setup) {
21 if (!setup) return 0;
22 int remaining = setup->ap_count - setup->list_scroll;
23 if (remaining > WIFI_SETUP_MAX_VISIBLE) remaining = WIFI_SETUP_MAX_VISIBLE;
24 return remaining < 0 ? 0 : remaining;
25}
26
27const wifi_ap_info_t *wifi_setup_get_visible(const wifi_setup_t *setup, int idx) {
28 if (!setup || idx < 0 || idx >= wifi_setup_visible_count(setup)) return NULL;
29 return &setup->aps[setup->list_scroll + idx];
30}
31
32setup_state_t wifi_setup_handle_select(wifi_setup_t *setup, int list_idx) {
33 if (!setup || setup->state != SETUP_LIST) return setup ? setup->state : SETUP_CANCELLED;
34 if (list_idx < 0 || list_idx >= wifi_setup_visible_count(setup)) return setup->state;
35
36 int real_idx = setup->list_scroll + list_idx;
37 setup->selected_ap = real_idx;
38 strncpy(setup->selected_ssid, setup->aps[real_idx].ssid, WIFI_SETUP_SSID_LEN - 1);
39 setup->selected_ssid[WIFI_SETUP_SSID_LEN - 1] = '\0';
40 setup->state = SETUP_PASSWORD;
41 return setup->state;
42}
43
44setup_state_t wifi_setup_handle_connect(wifi_setup_t *setup) {
45 if (!setup || setup->state != SETUP_PASSWORD) return setup ? setup->state : SETUP_CANCELLED;
46 setup->state = SETUP_CONNECTING;
47 return setup->state;
48}
49
50setup_state_t wifi_setup_handle_connect_result(wifi_setup_t *setup, bool success, const char *ip) {
51 if (!setup) return SETUP_CANCELLED;
52 if (setup->state != SETUP_CONNECTING) return setup->state;
53
54 if (success) {
55 setup->state = SETUP_SUCCESS;
56 if (ip) {
57 strncpy(setup->connect_ip, ip, sizeof(setup->connect_ip) - 1);
58 setup->connect_ip[sizeof(setup->connect_ip) - 1] = '\0';
59 }
60 setup->connect_failed_auth = false;
61 } else {
62 setup->state = SETUP_FAILED;
63 setup->connect_failed_auth = true;
64 setup->connect_ip[0] = '\0';
65 }
66 return setup->state;
67}
68
69setup_state_t wifi_setup_handle_cancel(wifi_setup_t *setup) {
70 if (!setup) return SETUP_CANCELLED;
71 setup->state = SETUP_CANCELLED;
72 return setup->state;
73}
74
75setup_state_t wifi_setup_handle_retry(wifi_setup_t *setup) {
76 if (!setup) return SETUP_CANCELLED;
77 if (setup->state != SETUP_FAILED) return setup->state;
78 setup->state = SETUP_PASSWORD;
79 setup->connect_failed_auth = false;
80 return setup->state;
81}
82
83setup_state_t wifi_setup_handle_change_network(wifi_setup_t *setup) {
84 if (!setup) return SETUP_CANCELLED;
85 if (setup->state != SETUP_FAILED) return setup->state;
86 setup->state = SETUP_LIST;
87 setup->connect_failed_auth = false;
88 return setup->state;
89}
diff --git a/main/wifi_setup.h b/main/wifi_setup.h
new file mode 100644
index 0000000..17712d5
--- /dev/null
+++ b/main/wifi_setup.h
@@ -0,0 +1,51 @@
1#ifndef WIFI_SETUP_H
2#define WIFI_SETUP_H
3
4#include "esp_err.h"
5#include <stdint.h>
6#include <stdbool.h>
7
8#define WIFI_SETUP_MAX_APS 20
9#define WIFI_SETUP_MAX_VISIBLE 8
10#define WIFI_SETUP_SSID_LEN 33
11#define WIFI_SETUP_PASS_LEN 64
12
13typedef enum {
14 SETUP_SCAN,
15 SETUP_LIST,
16 SETUP_PASSWORD,
17 SETUP_CONNECTING,
18 SETUP_SUCCESS,
19 SETUP_FAILED,
20 SETUP_CANCELLED
21} setup_state_t;
22
23typedef struct {
24 char ssid[WIFI_SETUP_SSID_LEN];
25 int rssi;
26 bool secured;
27} wifi_ap_info_t;
28
29typedef struct {
30 setup_state_t state;
31 wifi_ap_info_t aps[WIFI_SETUP_MAX_APS];
32 int ap_count;
33 int list_scroll;
34 int selected_ap;
35 char selected_ssid[WIFI_SETUP_SSID_LEN];
36 char connect_ip[16];
37 bool connect_failed_auth;
38} wifi_setup_t;
39
40void wifi_setup_init(wifi_setup_t *setup);
41void wifi_setup_set_aps(wifi_setup_t *setup, const wifi_ap_info_t *aps, int count);
42int wifi_setup_visible_count(const wifi_setup_t *setup);
43const wifi_ap_info_t *wifi_setup_get_visible(const wifi_setup_t *setup, int idx);
44setup_state_t wifi_setup_handle_select(wifi_setup_t *setup, int list_idx);
45setup_state_t wifi_setup_handle_connect(wifi_setup_t *setup);
46setup_state_t wifi_setup_handle_connect_result(wifi_setup_t *setup, bool success, const char *ip);
47setup_state_t wifi_setup_handle_cancel(wifi_setup_t *setup);
48setup_state_t wifi_setup_handle_retry(wifi_setup_t *setup);
49setup_state_t wifi_setup_handle_change_network(wifi_setup_t *setup);
50
51#endif