2026-10-09 00:27:51 +02:00

419 lines
14 KiB
C++

#include <Tactility/app/wificonnect/WifiConnect.h>
#include <Tactility/Tactility.h>
#include <app/event.h>
#include <app/manager.h>
#include <app/manifest.h>
#include <app/scheduler.h>
#include <app/start.h>
#include <lvgl_window_manager/window_manager.h>
#include <wifi/wifi_settings.h>
#include <lvgl/lvgl.h>
#include <lvgl/theme.h>
#include <lvgl/widgets/card.h>
#include <lvgl/widgets/spinner.h>
#include <lvgl/widgets/toolbar.h>
#include <tactility/check.h>
#include <tactility/device.h>
#include <tactility/drivers/wifi.h>
#include <tactility/log.h>
#include <lvgl.h>
#include <cstring>
namespace tt::app::wificonnect {
constexpr auto* TAG = "WifiConnect";
extern const ::AppManifest manifest;
namespace {
struct Context {
uint32_t appInstanceId;
std::string initialSsid;
std::string initialPassword;
bool connecting = false;
bool connectionError = false;
// The access point of the pending connection attempt, saved when it succeeds and rememberAp is set
WifiApSettings pendingAp;
bool rememberAp = false;
lv_obj_t* ssid_textarea = nullptr;
lv_obj_t* ssid_error = nullptr;
lv_obj_t* password_textarea = nullptr;
lv_obj_t* password_error = nullptr;
lv_obj_t* connect_button = nullptr;
lv_obj_t* remember_checkbox = nullptr;
lv_obj_t* connecting_spinner = nullptr;
lv_obj_t* connection_error = nullptr;
// Set once in appMain() before subscribing, left null if this device has no WiFi driver
Device* wifiDevice = nullptr;
WifiEventSubscription wifiEventSub {};
};
void updateView(Context* ctx);
void resetErrors(Context* ctx);
void setLoading(Context* ctx, bool loading);
void onBackPressed(lv_event_t* event) {
auto* ctx = static_cast<Context*>(lv_event_get_user_data(event));
app_event_emit_close(ctx->appInstanceId);
}
void onWifiEvent(Context* ctx, WifiEvent event) {
bool shouldClose = false;
lvgl_lock();
if (event.type == WIFI_EVENT_TYPE_STATION_CONNECTION_RESULT) {
if (event.connection_error == WIFI_STATION_CONNECTION_ERROR_NONE) {
if (ctx->connecting) {
ctx->connecting = false;
shouldClose = true;
if (ctx->rememberAp) {
// Dispatch it, so file IO doesn't block the UI
getMainDispatcher().dispatch([ap = ctx->pendingAp] {
if (wifi_settings_save(&ap) != ERROR_NONE) {
LOG_E(TAG, "Failed to store credentials");
}
});
}
}
} else {
if (ctx->connecting) {
ctx->connecting = false;
ctx->connectionError = true;
updateView(ctx);
}
}
}
updateView(ctx);
lvgl_unlock();
if (shouldClose) {
app_event_emit_close(ctx->appInstanceId);
}
}
void resetErrors(Context* ctx) {
lv_obj_set_hidden(ctx->password_error, true);
lv_obj_set_hidden(ctx->ssid_error, true);
lv_obj_set_hidden(ctx->connection_error, true);
}
void setLoading(Context* ctx, bool loading) {
if (loading) {
lv_obj_set_hidden(ctx->connect_button, true);
lv_obj_set_hidden(ctx->connecting_spinner, false);
lv_obj_add_state(ctx->password_textarea, LV_STATE_DISABLED);
lv_obj_add_state(ctx->ssid_textarea, LV_STATE_DISABLED);
lv_obj_add_state(ctx->remember_checkbox, LV_STATE_DISABLED);
} else {
lv_obj_set_hidden(ctx->connect_button, false);
lv_obj_set_hidden(ctx->connecting_spinner, true);
lv_obj_remove_state(ctx->password_textarea, LV_STATE_DISABLED);
lv_obj_remove_state(ctx->ssid_textarea, LV_STATE_DISABLED);
lv_obj_remove_state(ctx->remember_checkbox, LV_STATE_DISABLED);
}
}
void updateView(Context* ctx) {
if (ctx->connect_button == nullptr) {
// Buried (e.g. this window's own connecting state closed it, or a future dialog opens on top)
return;
}
if (ctx->connectionError) {
setLoading(ctx, false);
resetErrors(ctx);
lv_label_set_text(ctx->connection_error, "Connection failed");
lv_obj_set_hidden(ctx->connection_error, false);
}
}
void onConnectPressed(lv_event_t* event) {
auto* ctx = static_cast<Context*>(lv_event_get_user_data(event));
ctx->connectionError = false;
resetErrors(ctx);
const char* ssid = lv_textarea_get_text(ctx->ssid_textarea);
size_t ssid_len = strlen(ssid);
if (ssid_len > WIFI_SETTINGS_SSID_LIMIT) {
LOG_E(TAG, "SSID too long");
lv_label_set_text(ctx->ssid_error, "SSID too long");
lv_obj_set_hidden(ctx->ssid_error, false);
return;
}
const char* password = lv_textarea_get_text(ctx->password_textarea);
size_t password_len = strlen(password);
if (password_len > WIFI_SETTINGS_PASSWORD_LIMIT) {
LOG_E(TAG, "Password too long");
lv_label_set_text(ctx->password_error, "Password too long");
lv_obj_set_hidden(ctx->password_error, false);
return;
}
bool store = lv_obj_get_state(ctx->remember_checkbox) & LV_STATE_CHECKED;
setLoading(ctx, true);
// Lengths were validated above
WifiApSettings settings {};
strcpy(settings.ssid, ssid);
strcpy(settings.password, password);
settings.channel = 0;
settings.auto_connect = WIFI_SETTINGS_AUTO_CONNECT_DEFAULT; // No UI yet, so use global setting
ctx->connecting = true;
ctx->pendingAp = settings;
ctx->rememberAp = store;
getMainDispatcher().dispatch([settings] {
Device* wifi_device = nullptr;
if (device_get_first_by_type(&WIFI_TYPE, &wifi_device) != ERROR_NONE) {
LOG_W(TAG, "No WiFi device found");
return;
}
error_t result = wifi_set_radio_on(wifi_device);
if (result == ERROR_NONE) {
result = wifi_station_connect(wifi_device, settings.ssid, settings.password, settings.channel);
}
if (result != ERROR_NONE) {
LOG_E(TAG, "Failed to connect (%s)", error_to_string(result));
}
device_put(wifi_device);
});
}
void createBottomButtons(Context* ctx, lv_obj_t* parent) {
auto* button_container = lv_obj_create(parent);
lv_obj_set_width(button_container, LV_PCT(100));
lv_obj_set_height(button_container, LV_SIZE_CONTENT);
lv_obj_set_style_pad_all(button_container, 0, LV_STATE_DEFAULT);
lv_obj_set_style_pad_gap(button_container, 4, LV_STATE_DEFAULT);
lv_obj_set_style_border_width(button_container, 0, LV_STATE_DEFAULT);
lv_obj_set_style_bg_opa(button_container, LV_OPA_TRANSP, LV_STATE_DEFAULT);
// "[x] Remember [Connect]", with everything centered vertically
lv_obj_set_flex_flow(button_container, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(button_container, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
ctx->remember_checkbox = lv_checkbox_create(button_container);
lv_checkbox_set_text(ctx->remember_checkbox, "Remember");
lv_obj_add_state(ctx->remember_checkbox, LV_STATE_CHECKED);
ctx->connecting_spinner = lvgl_spinner_create(button_container);
lv_obj_set_hidden(ctx->connecting_spinner, true);
ctx->connect_button = lv_btn_create(button_container);
auto* connect_label = lv_label_create(ctx->connect_button);
lv_label_set_text(connect_label, "Connect");
lv_obj_add_event_cb(ctx->connect_button, onConnectPressed, LV_EVENT_SHORT_CLICKED, ctx);
}
// Runs with the LVGL lock already held, possibly on another app's thread - see
// WindowDestroyWidgetsFn's warnings. Must stay lock-free: only nulls pointers.
void destroyWidgets(void* userData) {
auto* ctx = static_cast<Context*>(userData);
ctx->ssid_textarea = nullptr;
ctx->ssid_error = nullptr;
ctx->password_textarea = nullptr;
ctx->password_error = nullptr;
ctx->connect_button = nullptr;
ctx->remember_checkbox = nullptr;
ctx->connecting_spinner = nullptr;
ctx->connection_error = nullptr;
}
/** A transparent row: "Title [content]" */
lv_obj_t* createRow(lv_obj_t* parent, const char* title) {
auto* row = lv_obj_create(parent);
lv_obj_set_size(row, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_all(row, 0, LV_STATE_DEFAULT);
lv_obj_set_style_border_width(row, 0, LV_STATE_DEFAULT);
lv_obj_set_style_bg_opa(row, LV_OPA_TRANSP, LV_STATE_DEFAULT);
lv_obj_set_scrollable(row, false);
auto* label = lv_label_create(row);
lv_label_set_text(label, title);
lv_obj_set_flex_grow(label, 1);
return row;
}
/** A hidden label in the theme's error colour */
lv_obj_t* createErrorLabel(lv_obj_t* parent) {
auto* label = lv_label_create(parent);
lv_obj_set_width(label, LV_PCT(100));
lv_label_set_long_mode(label, LV_LABEL_LONG_MODE_WRAP);
// The monochrome theme has no error colour
if (!lvgl_theme_is_mono()) {
LvglThemeSettings theme_settings;
lvgl_theme_get_settings(&theme_settings);
lv_obj_set_style_text_color(label, theme_settings.color_error, LV_STATE_DEFAULT);
}
lv_obj_set_hidden(label, true);
return label;
}
// TODO: Standardize dialogs
void createWidgets(lv_obj_t* parent, void* userData) {
auto* ctx = static_cast<Context*>(userData);
lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_row(parent, 0, LV_STATE_DEFAULT);
auto* toolbar = lvgl_toolbar_create(parent, "Wi-Fi Connect");
// The global toolbar nav callback only knows how to stop old-model apps.
lvgl_toolbar_set_nav_action(toolbar, LV_SYMBOL_CLOSE, onBackPressed, ctx);
auto* wrapper = lv_obj_create(parent);
lv_obj_set_style_border_width(wrapper, 0, LV_STATE_DEFAULT);
lv_obj_set_width(wrapper, LV_PCT(100));
lv_obj_set_flex_grow(wrapper, 1);
lv_obj_set_flex_flow(wrapper, LV_FLEX_FLOW_COLUMN);
auto* card = lvgl_card_create(wrapper);
lv_obj_set_size(card, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(card, LV_FLEX_FLOW_COLUMN);
// SSID
auto* ssid_row = createRow(card, "Network");
ctx->ssid_textarea = lv_textarea_create(ssid_row);
lv_textarea_set_one_line(ctx->ssid_textarea, true);
lv_obj_set_width(ctx->ssid_textarea, LV_PCT(60));
ctx->ssid_error = createErrorLabel(card);
// Password
auto* password_row = createRow(card, "Password");
ctx->password_textarea = lv_textarea_create(password_row);
lv_textarea_set_one_line(ctx->password_textarea, true);
lv_textarea_set_password_mode(ctx->password_textarea, true);
lv_obj_set_width(ctx->password_textarea, LV_PCT(60));
ctx->password_error = createErrorLabel(card);
// Connection error
ctx->connection_error = createErrorLabel(card);
// Bottom buttons
createBottomButtons(ctx, card);
// Init from app parameters
if (!ctx->initialSsid.empty()) {
lv_textarea_set_text(ctx->ssid_textarea, ctx->initialSsid.c_str());
lv_group_focus_obj(ctx->password_textarea);
}
if (!ctx->initialPassword.empty()) {
lv_textarea_set_text(ctx->password_textarea, ctx->initialPassword.c_str());
}
}
int32_t appMain(int argc, char* argv[]) {
uint32_t appInstanceId = app_scheduler_current_app_id();
Context ctx {};
ctx.appInstanceId = appInstanceId;
ctx.initialSsid = (argc > 0) ? argv[0] : std::string();
ctx.initialPassword = (argc > 1) ? argv[1] : std::string();
TaskEventGroup event_group {};
task_event_group_construct(&event_group);
AppEventSubscription sub {};
check(app_event_subscribe(&sub, &event_group) == ERROR_NONE);
Device* wifi_device = nullptr;
if (device_get_first_by_type(&WIFI_TYPE, &wifi_device) == ERROR_NONE) {
if (wifi_event_subscribe(wifi_device, &ctx.wifiEventSub, &event_group) == ERROR_NONE) {
ctx.wifiDevice = wifi_device;
} else {
LOG_W(TAG, "Failed to subscribe to WiFi events");
device_put(wifi_device);
}
} else {
LOG_W(TAG, "No WiFi device found");
}
WindowId window = window_manager_create_ext(appInstanceId, createWidgets, destroyWidgets, &ctx);
bool shouldClose = false;
while (!shouldClose) {
TickType_t wait_timeout = (ctx.wifiDevice == nullptr) ? pdMS_TO_TICKS(500) : portMAX_DELAY;
task_event_group_wait_any(&event_group, nullptr, wait_timeout);
if (ctx.wifiDevice == nullptr) {
Device* retry_device = nullptr;
if (device_get_first_by_type(&WIFI_TYPE, &retry_device) == ERROR_NONE) {
if (wifi_event_subscribe(retry_device, &ctx.wifiEventSub, &event_group) == ERROR_NONE) {
ctx.wifiDevice = retry_device;
} else {
device_put(retry_device);
}
}
}
AppEvent event {};
while (app_event_poll(&sub, &event) == ERROR_NONE) {
switch (event.type) {
case APP_EVENT_CLOSE:
shouldClose = true;
break;
default:
break;
}
if (shouldClose) break;
}
if (ctx.wifiDevice != nullptr) {
WifiEvent wifi_event {};
while (wifi_event_poll(&ctx.wifiEventSub, &wifi_event) == ERROR_NONE) {
onWifiEvent(&ctx, wifi_event);
}
}
}
if (ctx.wifiDevice != nullptr) {
wifi_event_unsubscribe(ctx.wifiDevice, &ctx.wifiEventSub);
device_put(ctx.wifiDevice);
}
window_manager_remove(window);
check(app_event_unsubscribe(&sub) == ERROR_NONE);
task_event_group_destruct(&event_group);
return 0;
}
} // namespace
void start(const std::string& ssid, const std::string& password) {
const char* argv[] = { ssid.c_str(), password.c_str() };
uint32_t instanceId = 0;
AppStartContext context = app_start_context_for_manifest(&manifest);
app_start_context_set_arguments_ext(&context, 2, argv);
app_start_with_context(&context, &instanceId);
}
extern const ::AppManifest manifest = {
.id = "tactility.wificonnect",
.name = "Wi-Fi Connect",
.category = APP_CATEGORY_SYSTEM,
.location = { APP_LOCATION_MEMORY, reinterpret_cast<void*>(appMain) },
.flags = APP_MANIFEST_FLAG_HIDDEN,
.stack = {}
};
} // namespace