TinyMaterialDesign
Loading...
Searching...
No Matches
WifiLoginPage.h
Go to the documentation of this file.
1#pragma once
2#include <stdio.h>
3
4#include <algorithm>
5#include <functional>
6#include <string>
7#include <vector>
8
9#include "TinyMaterialDesign/Core/Page.h"
10#include "TinyMaterialDesign/Core/Screen.h"
11#include "TinyMaterialDesign/Draw/Icons.h"
12#include "TinyMaterialDesign/Widgets/Button.h"
13#include "TinyMaterialDesign/Widgets/IconButton.h"
14#include "TinyMaterialDesign/Widgets/Keyboard.h"
15#include "TinyMaterialDesign/Widgets/Label.h"
16#include "TinyMaterialDesign/Widgets/ListItem.h"
17#include "TinyMaterialDesign/Widgets/Menu.h"
18#include "TinyMaterialDesign/Widgets/SettingRows.h"
19#include "TinyMaterialDesign/Widgets/TextField.h"
20#include "TinyMaterialDesign/Wifi/WifiControl.h"
21
22namespace tinymd {
23
24/**
25 * @brief One network in a list: name, a lock for a secured network and the
26 * signal bars; tapping the row calls onSelect. The connected network is
27 * highlighted.
28 */
29template <typename RGB_T = TINYMD_DEFAULT_RGB_T>
30class WifiNetworkRow : public Widget<RGB_T> {
31 public:
32 static constexpr int32_t kHeight = 32;
33 std::function<void()> onSelect;
34
35 void setNetwork(const char* ssid, int bars, bool secure, bool current) {
36 ssid_ = ssid;
37 bars_ = bars;
38 secure_ = secure;
39 current_ = current;
40 }
41
42 void draw(tinygpu::ISurface<RGB_T>& target) override {
43 const MaterialTheme<RGB_T>& t = this->theme();
44 const Bounds& b = this->bounds;
45 const RGB_T bg = current_ ? t.colors.secondaryContainer : t.colors.surface;
46 target.fillRect(toPx(b.x + 1), toPx(b.y), toPx(b.w - 2), toPx(b.h), bg);
47 tinygpu::IFont<RGB_T>& body = *t.typography.body;
48 const RGB_T fg = current_ ? t.colors.onSecondaryContainer : t.colors.onSurface;
49 std::string name = ssid_;
50 const int32_t maxW = b.w - 64;
51 while (name.size() > 3 && static_cast<int32_t>(body.measureTextWidth(name.c_str())) > maxW) name.pop_back();
52 body.drawText(target, static_cast<int16_t>(b.x + 10),
53 static_cast<int16_t>(b.centerY() - static_cast<int32_t>(body.getHeight(1)) / 2), name.c_str(), fg,
54 bg, false);
55 if (secure_) drawLock(target, Bounds(b.right() - 48, b.centerY() - 6, 9, 12), t.colors.onSurfaceVariant);
56 drawSignalBars(target, Bounds(b.right() - 30, b.centerY() - 7, 18, 14), bars_, t.colors.primary, t.colors.outline);
57 }
58
59 bool onGesture(const tinygpu::GestureEvent& event) override {
60 if (!isTapGesture(event.type)) return false;
61 if (onSelect) onSelect();
62 return true;
63 }
64
65 private:
66 std::string ssid_;
67 int bars_ = 0;
68 bool secure_ = false;
69 bool current_ = false;
70};
71
72/**
73 * @brief WiFi selection and login as a Page: the state of the connection,
74 * the SSID with a button that opens the networks of a scan as pop-up list,
75 * the password (masked, "Show password"), Connect (Disconnect while
76 * connected) and Cancel (leaves the page without connecting).
77 *
78 * - When a field is tapped, the page scrolls it to the top, so that it stays
79 * visible above the keyboard.
80 * - Connect scrolls back to the top: the state of the connection is visible.
81 * - Selecting a network in the pop-up connects at once to an open network
82 * and opens the keyboard for the password of a secured one.
83 * - Once a connection works, the page calls onDone (after showing
84 * "Connected" briefly).
85 *
86 * The WiFi itself is a WifiControl: Esp32Wifi (Wifi/WifiEsp32.h) on the
87 * ESP32, SimulatedWifi on the desktop. Show the page on its own, or add it
88 * to a PageNavigator; call tick() regularly while it is shown (the
89 * PageNavigator does that) - it polls the scan and the connection and
90 * returns true when the page must be redrawn.
91 *
92 * Keyboard<RGB565> keyboard(Bounds(0, 150, 240, 170));
93 * WifiLoginPage<RGB565> login(keyboard, app.screen());
94 * Esp32Wifi wifi;
95 *
96 * void setup() {
97 * app.begin();
98 * wifi.begin();
99 * login.setWifi(&wifi);
100 * login.bounds = Bounds(0, 40, 240, 280);
101 * app.screen().addWidget(login);
102 * login.build();
103 * login.onShow();
104 * app.screen().addFixedWidget(keyboard);
105 * login.onDone = []() { ... }; // connected or cancelled
106 * }
107 * void loop() {
108 * if (login.tick(millis())) app.screen().invalidate();
109 * app.update();
110 * }
111 */
112template <typename RGB_T = TINYMD_DEFAULT_RGB_T>
113class WifiLoginPage : public Page<RGB_T> {
114 public:
115 static constexpr int kMaxNetworks = 12;
116
117 WifiLoginPage(Keyboard<RGB_T>& keyboard, Screen<RGB_T>& screen, const char* title = "WiFi")
118 : Page<RGB_T>(title, drawWifi<RGB_T>), keyboard_(keyboard), screen_(screen), showPassword_("Show password") {}
119
120 /// The user is done: connected or cancelled.
121 std::function<void()> onDone;
122
123 void setWifi(WifiControl* wifi) { wifi_ = wifi; }
124
125 /// Text of the button that leaves the page without connecting (default
126 /// "Cancel"); nullptr hides it.
127 void setCancelText(const char* text) {
128 cancelText_ = text != nullptr ? text : "";
129 if (built_) {
130 cancel_.setLabel(cancelText_.c_str());
131 layout();
132 }
133 }
134
135 /// Fills in the fields and connects (as the Connect button).
136 void connect(const char* ssid, const char* password) {
137 ssid_.setText(ssid);
138 password_.setText(password);
139 connectFromFields();
140 }
141
142 /// Starts a new scan.
143 void startScan() {
144 if (wifi_ == nullptr || scanning_) return;
145 scanning_ = wifi_->startScan();
146 refreshStatus();
147 if (popupOpen_) fillPopup();
148 }
149
150 /// Opens the pop-up list of the networks (as the button next to the SSID).
152 if (networks_.empty() && !scanning_) startScan();
153 keyboard_.hide();
154 ssid_.blur();
155 password_.blur();
156 fillPopup();
157 popupOpen_ = true;
158 screen_.presentDialog(popup_);
159 }
160
161 /// The networks of the last scan.
162 const std::vector<WifiNetwork>& networks() const { return networks_; }
163
164 void build() override {
165 title_ = Label<RGB_T>(Bounds(), this->title(), TypographyRole::kTitle);
166 title_.setOnBackground(true);
167 this->addChild(title_);
168 status_ = Label<RGB_T>(Bounds(), "", TypographyRole::kLabel);
169 status_.setOnBackground(true);
170 this->addChild(status_);
171
172 ssid_ = TextField<RGB_T>(Bounds(), "Network (SSID)", "tap the list or type");
173 ssid_.setMaxLength(32);
174 ssid_.setOnBackground(true);
175 manage(ssid_);
176 this->addChild(ssid_);
177 list_ = IconButton<RGB_T>(Bounds(), drawChevronDown<RGB_T>); // opens the list of networks
178 list_.onClick = [this]() { showNetworks(); };
179 this->addChild(list_);
180 password_ = TextField<RGB_T>(Bounds(), "Password", "");
181 password_.setMaxLength(63);
182 password_.setPasswordMode(true);
183 password_.setOnBackground(true);
184 password_.onSubmit = [this]() { connectFromFields(); };
185 manage(password_);
186 this->addChild(password_);
187 showPassword_.onChange = [this](bool v) { password_.setPasswordMode(!v); };
188 this->addChild(showPassword_);
189
190 connect_ = Button<RGB_T>(Bounds(), "Connect");
191 connect_.onClick = [this]() {
192 if (connected()) {
193 disconnect();
194 } else {
195 connectFromFields();
196 }
197 };
198 this->addChild(connect_);
199 cancel_ = Button<RGB_T>(Bounds(), cancelText_.c_str(), ButtonVariant::kOutlined);
200 cancel_.onClick = [this]() {
201 keyboard_.hide();
202 if (onDone) onDone();
203 };
204 this->addChild(cancel_);
205 this->addChild(spacer_); // room to scroll each field to the top
206
207 // the pop-up list of the networks
208 for (int i = 0; i < kMaxNetworks; ++i) rows_[i].onSelect = [this, i]() { select(i); };
209 scanAgain_ = ListItem<RGB_T>(Bounds(), "Scan again");
210 scanAgain_.onClick = [this]() { startScan(); };
211 popup_.onOutsideTap = [this]() { closePopup(); };
212 built_ = true;
213 layout();
214 }
215
216 void onShow() override {
217 if (wifi_ != nullptr && ssid_.text().empty()) ssid_.setText(wifi_->ssid().c_str());
218 // only a new connection closes the page (not one that existed already)
219 lastState_ = wifi_ != nullptr ? wifi_->state() : WifiControl::State::kDisconnected;
220 doneAtMs_ = 0;
221 this->setScrollOffset(0);
222 if (networks_.empty()) startScan();
223 refreshStatus();
224 }
225
226 void onHide() override {
227 keyboard_.hide();
228 if (popupOpen_) closePopup();
229 doneAtMs_ = 0;
230 }
231
232 /// Polls the scan and the connection: true if the page changed.
233 bool tick(uint32_t nowMs) override {
234 if (wifi_ == nullptr || nowMs - lastTickMs_ < 250) return false;
235 lastTickMs_ = nowMs;
236 bool changed = false;
237 if (scanning_ && wifi_->scanDone(networks_)) {
238 scanning_ = false;
239 if (networks_.size() > kMaxNetworks) networks_.resize(kMaxNetworks);
240 if (popupOpen_) fillPopup();
241 changed = true;
242 }
243 const WifiControl::State state = wifi_->state();
244 if (state != lastState_) {
245 // a new connection: show "Connected" briefly, then close
246 if (state == WifiControl::State::kConnected) doneAtMs_ = nowMs + 1500;
247 lastState_ = state;
248 changed = true;
249 }
250 if (doneAtMs_ != 0 && static_cast<int32_t>(nowMs - doneAtMs_) >= 0) {
251 doneAtMs_ = 0;
252 if (onDone) onDone();
253 }
254 if (changed) refreshStatus();
255 return changed;
256 }
257
258 private:
259 Keyboard<RGB_T>& keyboard_;
260 Screen<RGB_T>& screen_;
261 WifiControl* wifi_ = nullptr;
262 bool built_ = false;
263 bool scanning_ = false;
264 bool popupOpen_ = false;
266 uint32_t lastTickMs_ = 0;
267 uint32_t doneAtMs_ = 0;
268 std::vector<WifiNetwork> networks_;
269 std::string cancelText_ = "Cancel";
270
271 Label<RGB_T> title_, status_, spacer_;
272 TextField<RGB_T> ssid_, password_;
273 IconButton<RGB_T> list_;
274 SwitchRow<RGB_T> showPassword_;
275 Button<RGB_T> connect_, cancel_;
276 Menu<RGB_T> popup_;
277 WifiNetworkRow<RGB_T> rows_[kMaxNetworks];
278 ListItem<RGB_T> scanAgain_;
279
280 /// The keyboard serves the field, and the page scrolls the field to the
281 /// top so that it stays visible above the keyboard.
282 void manage(TextField<RGB_T>& field) {
283 keyboard_.manage(field);
284 std::function<void()> showKeyboard = field.onFocus;
285 field.onFocus = [this, showKeyboard, &field]() {
286 if (showKeyboard) showKeyboard();
287 this->scrollToChild(field);
288 screen_.invalidate();
289 };
290 }
291
292 /// (Re)fills the pop-up with the networks and "Scan again".
293 void fillPopup() {
294 const Bounds& b = this->bounds;
295 const int count = static_cast<int>(networks_.size());
296 const int32_t rowH = WifiNetworkRow<RGB_T>::kHeight;
297 const int32_t maxH = b.h - 40;
298 const int32_t h = std::min<int32_t>((count + 1) * rowH, maxH - maxH % rowH);
299 popup_ = Menu<RGB_T>(Bounds(b.x + 12, b.y + 20, b.w - 24, h));
300 popup_.onOutsideTap = [this]() { closePopup(); };
301 const std::string current =
302 wifi_ != nullptr && wifi_->state() == WifiControl::State::kConnected ? wifi_->ssid() : "";
303 for (int i = 0; i < count; ++i) {
304 const WifiNetwork& n = networks_[i];
305 rows_[i].setNetwork(n.ssid.c_str(), wifiBars(n.rssi), n.secure, n.ssid == current);
306 rows_[i].bounds = popup_.itemRect(i, rowH);
307 popup_.addItem(rows_[i]);
308 }
309 scanAgain_.setTitle(scanning_ ? "Scanning ..." : count == 0 ? "No networks - scan again" : "Scan again");
310 scanAgain_.bounds = popup_.itemRect(count, rowH);
311 popup_.addItem(scanAgain_);
312 popup_.setTheme(this->theme());
313 screen_.invalidate();
314 }
315
316 void closePopup() {
317 popupOpen_ = false;
318 screen_.dismissDialog();
319 }
320
321 void select(int index) {
322 if (index >= static_cast<int>(networks_.size())) return;
323 closePopup();
324 ssid_.setText(networks_[index].ssid.c_str());
325 password_.setText("");
326 if (networks_[index].secure) {
327 password_.focus(); // keyboard; scrolls the field to the top
328 } else {
329 connectFromFields();
330 }
331 }
332
333 bool connected() { return wifi_ != nullptr && wifi_->state() == WifiControl::State::kConnected; }
334
335 void disconnect() {
336 keyboard_.hide();
337 wifi_->disconnect();
338 lastState_ = wifi_->state(); // not a new connection: the page stays
339 doneAtMs_ = 0;
340 refreshStatus();
341 }
342
343 void connectFromFields() {
344 if (wifi_ == nullptr || ssid_.text().empty()) return;
345 keyboard_.hide();
346 ssid_.blur();
347 password_.blur();
348 this->setScrollOffset(0); // the state of the connection is visible
349 wifi_->connect(ssid_.text().c_str(), password_.text().c_str());
351 refreshStatus();
352 }
353
354 void refreshStatus() {
355 if (!built_) return;
356 if (wifi_ == nullptr) {
357 status_.setText("No WiFi available");
358 return;
359 }
360 const ColorScheme<RGB_T>& c = this->theme().colors;
361 char buf[96];
362 switch (wifi_->state()) {
364 snprintf(buf, sizeof(buf), "Connected to %s (%s)", wifi_->ssid().c_str(), wifi_->ip().c_str());
365 status_.setColor(c.primary);
366 break;
368 snprintf(buf, sizeof(buf), "Connecting to %s ...", wifi_->ssid().c_str());
369 status_.setColor(c.onSurfaceVariant);
370 break;
372 snprintf(buf, sizeof(buf), "Could not connect to %s: check the password", wifi_->ssid().c_str());
373 status_.setColor(c.error);
374 break;
375 default:
376 snprintf(buf, sizeof(buf), scanning_ ? "Not connected - scanning for networks ..."
377 : "Not connected: select a network");
378 status_.setColor(c.onSurfaceVariant);
379 break;
380 }
381 status_.setText(buf);
382 connect_.setLabel(connected() ? "Disconnect" : "Connect");
383 screen_.invalidate();
384 }
385
386 void layout() {
387 const Bounds& b = this->bounds;
388 constexpr int32_t margin = 8;
389 const int32_t x = b.x + margin;
390 const int32_t w = b.w - margin - Container<RGB_T>::kScrollbarTouchWidth;
391 int32_t y = b.y + 6;
392 title_.bounds = Bounds(x, y, w, 18);
393 y += 20;
394 status_.bounds = Bounds(x, y, w, 12);
395 y += 20;
396 ssid_.bounds = Bounds(x, y, w - 44, 44);
397 list_.bounds = Bounds(x + w - 40, y + 12, 40, 32);
398 y += 50;
399 password_.bounds = Bounds(x, y, w, 44);
400 y += 46;
401 showPassword_.bounds = Bounds(x, y, w, SwitchRow<RGB_T>::kHeight);
402 y += SwitchRow<RGB_T>::kHeight + 6;
403 // Connect / Disconnect and Cancel side by side
404 cancel_.visible = !cancelText_.empty();
405 if (cancel_.visible) {
406 const int32_t half = (w - 8) / 2;
407 connect_.bounds = Bounds(x, y, half, 32);
408 cancel_.bounds = Bounds(x + half + 8, y, half, 32);
409 } else {
410 connect_.bounds = Bounds(x, y, w, 32);
411 cancel_.bounds = Bounds(x, b.y, 0, 0);
412 }
413 y += 40;
414 // enough room below to scroll the password field to the top
415 spacer_.bounds = Bounds(x, y, w, b.h);
416 }
417};
418
419} // namespace tinymd
Material Design button: Filled / Tonal / Outlined / Text / Elevated.
Definition: Button.h:25
A widget that holds child widgets, draws/dispatches gestures to them, and scrolls its content vertica...
Definition: Container.h:56
Circular tap target hosting one vector glyph from Draw/Icons.h (or any function matching IconPainter)...
Definition: IconButton.h:34
On-screen QWERTY keyboard that drives one text input at a time.
Definition: Keyboard.h:44
Single line of themed, non-interactive text.
Definition: Label.h:34
Tappable row: optional leading icon + title, with a selected state.
Definition: ListItem.h:22
Popover list of items (typically ListItem), anchored near whatever opened it - e.g....
Definition: Menu.h:40
One page (tab) of an app: a scrollable Container with a title and an icon for the navigation,...
Definition: Page.h:28
Owns a set of widgets, draws them, and routes gesture events to whichever one should handle each even...
Definition: Screen.h:71
Caption on the left, Switch on the right; tapping the row toggles it.
Definition: SettingRows.h:138
Single-line text input box.
Definition: TextField.h:41
Base class every TinyMaterialDesign widget derives from.
Definition: Widget.h:58
The WiFi of a device as WifiLoginPage uses it: scan, connect and the stored credentials....
Definition: WifiControl.h:50
virtual State state()=0
virtual std::string ip()
The IP address while connected.
Definition: WifiControl.h:68
State
Definition: WifiControl.h:52
virtual void connect(const char *ssid, const char *password)=0
Connects in the background; the credentials are stored when it works.
virtual std::string ssid()=0
The network that is connected or that is being connected to.
virtual bool startScan()=0
Starts a scan in the background.
virtual void disconnect()=0
WiFi selection and login as a Page: the state of the connection, the SSID with a button that opens th...
Definition: WifiLoginPage.h:113
bool tick(uint32_t nowMs) override
Polls the scan and the connection: true if the page changed.
Definition: WifiLoginPage.h:233
const std::vector< WifiNetwork > & networks() const
The networks of the last scan.
Definition: WifiLoginPage.h:162
void onHide() override
The page is hidden (another page is shown).
Definition: WifiLoginPage.h:226
void showNetworks()
Opens the pop-up list of the networks (as the button next to the SSID).
Definition: WifiLoginPage.h:151
void startScan()
Starts a new scan.
Definition: WifiLoginPage.h:143
void onShow() override
The page becomes visible.
Definition: WifiLoginPage.h:216
WifiLoginPage(Keyboard< RGB_T > &keyboard, Screen< RGB_T > &screen, const char *title="WiFi")
Definition: WifiLoginPage.h:117
std::function< void()> onDone
The user is done: connected or cancelled.
Definition: WifiLoginPage.h:121
void build() override
Creates the widgets (called once by PageNavigator::begin()).
Definition: WifiLoginPage.h:164
void connect(const char *ssid, const char *password)
Fills in the fields and connects (as the Connect button).
Definition: WifiLoginPage.h:136
static constexpr int kMaxNetworks
Definition: WifiLoginPage.h:115
void setCancelText(const char *text)
Definition: WifiLoginPage.h:127
void setWifi(WifiControl *wifi)
Definition: WifiLoginPage.h:123
One network in a list: name, a lock for a secured network and the signal bars; tapping the row calls ...
Definition: WifiLoginPage.h:30
bool onGesture(const tinygpu::GestureEvent &event) override
Handles one gesture event. Returns true if this widget consumed it.
Definition: WifiLoginPage.h:59
static constexpr int32_t kHeight
Definition: WifiLoginPage.h:32
std::function< void()> onSelect
Definition: WifiLoginPage.h:33
void draw(tinygpu::ISurface< RGB_T > &target) override
Definition: WifiLoginPage.h:42
void setNetwork(const char *ssid, int bars, bool secure, bool current)
Definition: WifiLoginPage.h:35
Definition: AnchorLayout.h:4
TypographyRole
Definition: Label.h:11
int wifiBars(int rssi)
Signal strength as 0-4 bars (see drawSignalBars()).
Definition: WifiControl.h:20
Axis-aligned pixel rectangle used for widget bounds and hit-testing.
Definition: Bounds.h:21
int32_t w
Definition: Bounds.h:24
Bounds(int32_t x, int32_t y, int32_t w, int32_t h)
Definition: Bounds.h:28
int32_t h
Definition: Bounds.h:25
int32_t y
Definition: Bounds.h:23
int32_t x
Definition: Bounds.h:22
Bounds()=default
Material Design 3 color roles.
Definition: MaterialColors.h:24
Bundles a color scheme, shape tokens, typography, and spacing into one theme, passed to widgets so th...
Definition: MaterialTheme.h:50
A WiFi network found by a scan.
Definition: WifiControl.h:11
std::string ssid
Definition: WifiControl.h:12
int rssi
Signal strength in dBm (e.g. -45 strong, -85 weak).
Definition: WifiControl.h:14
bool secure
Needs a password.
Definition: WifiControl.h:16