TinyWifiDongle 0.1.0
Header-only USB WiFi dongle for Arduino
Loading...
Searching...
No Matches
SetupPortal.h
Go to the documentation of this file.
1#pragma once
2#include <Arduino.h>
3#include <DNSServer.h>
4#include <WebServer.h>
5#include <WiFi.h>
6
7#include "../core/Logger.h"
8
9namespace twd {
10
21 public:
23 explicit SetupPortal(const char* network, const char* password = nullptr)
24 : network_(network), apPassword_(password ? password : "") {}
25
27 void run(String& ssid, String& password) {
28 submitted_ = false;
29 scan();
30 start();
31 uint32_t lastReport = 0;
32 int stations = -1;
33 while (!submitted_) {
34 dns_.processNextRequest();
35 server_.handleClient();
36 if (TWD_LOGGER.enabled() && millis() - lastReport > 2000) { // report when the number of connected devices changes
37 lastReport = millis();
38 int n = WiFi.softAPgetStationNum();
39 if (n != stations) {
40 stations = n;
41 TWD_LOGGER.info("setup: %d device(s) connected to the setup network", n);
42 }
43 }
44 delay(2);
45 }
46 delay(1500); // let the answer reach the browser
47 stop();
48 ssid = ssid_;
49 password = enteredPassword_;
50 }
51
52 private:
53 String network_, apPassword_; // access point: name and password
54 WebServer server_{80};
55 DNSServer dns_;
56 String options_; // <option> list of the networks found by the scan
57 String ssid_, enteredPassword_; // what the user submitted
58 bool submitted_ = false;
59
60 static String escape(const String& s) {
61 String out;
62 for (size_t i = 0; i < s.length(); i++) {
63 char c = s[i];
64 if (c == '<') out += "&lt;";
65 else if (c == '>') out += "&gt;";
66 else if (c == '&') out += "&amp;";
67 else if (c == '"') out += "&quot;";
68 else out += c;
69 }
70 return out;
71 }
72
73 // Scanning needs the station, so it happens before the access point opens.
74 void scan() {
75 options_ = "";
76 WiFi.mode(WIFI_STA);
77 int n = WiFi.scanNetworks();
78 if (n < 0) {
79 TWD_LOGGER.error("setup: scan failed (%d), the network name must be typed in", n);
80 return;
81 }
82 TWD_LOGGER.info("setup: scan found %d network(s)", n);
83 for (int i = 0; i < n; i++) {
84 String name = WiFi.SSID(i);
85 TWD_LOGGER.info("setup: '%s' channel %d, %d dBm", name.c_str(), (int)WiFi.channel(i), (int)WiFi.RSSI(i));
86 if (name.length()) options_ += "<option value=\"" + escape(name) + "\">";
87 }
88 }
89
90 void start() {
91 WiFi.mode(WIFI_AP);
92#if !defined(ESP32)
93 // The Pico picks 192.168.4.1 or 192.168.42.1 depending on the state of the radio; fix it.
94 WiFi.softAPConfig(IPAddress(192, 168, 4, 1), IPAddress(192, 168, 4, 1), IPAddress(255, 255, 255, 0));
95#endif
96 bool ap = apPassword_.length() ? WiFi.softAP(network_.c_str(), apPassword_.c_str()) : WiFi.softAP(network_.c_str());
97 if (!ap) {
98 TWD_LOGGER.error("setup: could not open the setup network '%s'%s", network_.c_str(),
99 apPassword_.length() && apPassword_.length() < 8 ? " (password shorter than 8 characters)" : "");
100 }
101 if (!dns_.start(53, "*", WiFi.softAPIP())) {
102 TWD_LOGGER.error("setup: could not start the DNS server, the page does not open by itself");
103 }
104 TWD_LOGGER.info("setup: setup network '%s' open, address %s", network_.c_str(), WiFi.softAPIP().toString().c_str());
105 server_.on("/", [this]() {
106 TWD_LOGGER.debug("setup: GET /");
107 sendForm();
108 });
109 server_.on("/save", HTTP_POST, [this]() {
110 TWD_LOGGER.debug("setup: POST /save");
111 receive();
112 });
113 server_.onNotFound([this]() { // connectivity checks of phones and laptops end up here
115 TWD_LOGGER.debug("setup: %s %s%s -> redirect", server_.method() == HTTP_GET ? "GET" : "other",
116 server_.hostHeader().c_str(), server_.uri().c_str());
117 }
118 server_.sendHeader("Location", String("http://") + WiFi.softAPIP().toString() + "/");
119 server_.send(302, "text/plain", "");
120 });
121 server_.begin();
122 }
123
124 void stop() {
125 server_.stop();
126 dns_.stop();
127 WiFi.softAPdisconnect(true);
128 // Not WIFI_OFF: on the Raspberry Pi Pico that leaves the core in WIFI_AP, in which its begin() starts an
129 // access point instead of joining a network.
130 WiFi.mode(WIFI_STA);
131 }
132
133 void sendForm() {
134 server_.send(200, "text/html",
135 String("<!doctype html><meta name=viewport content='width=device-width,initial-scale=1'>"
136 "<title>WiFi setup</title><h2>Choose your WiFi network</h2>"
137 "<form method=post action=/save>Network<br>"
138 "<input name=ssid list=networks required maxlength=32><datalist id=networks>") +
139 options_ +
140 "</datalist><br><br>Password<br><input name=password type=password maxlength=64>"
141 "<br><br><button>Save</button></form>");
142 }
143
144 void receive() {
145 ssid_ = server_.arg("ssid");
146 if (ssid_.length() == 0) {
147 TWD_LOGGER.error("setup: form submitted without a network name");
148 server_.send(400, "text/plain", "The network name is missing.");
149 return;
150 }
151 enteredPassword_ = server_.arg("password");
152 server_.send(200, "text/html",
153 "<!doctype html><meta name=viewport content='width=device-width,initial-scale=1'>"
154 "<h2>Saved</h2>The board now joins the network. You can close this page.");
155 submitted_ = true;
156 }
157};
158
159} // namespace twd
Printf-style logging through the global TWD_LOGGER object.
static twd::LoggerClass TWD_LOGGER
The logger used by all components; configure it in the sketch with TWD_LOGGER.begin(Serial).
Definition Logger.h:107
void error(const char *fmt,...)
Definition Logger.h:75
bool enabled(LogLevel level=LogLevel::Info) const
True if lines of level are written somewhere.
Definition Logger.h:48
void debug(const char *fmt,...)
Definition Logger.h:57
void info(const char *fmt,...)
Definition Logger.h:63
void run(String &ssid, String &password)
Serves the form until a network is submitted and returns it. Blocks.
Definition SetupPortal.h:27
SetupPortal(const char *network, const char *password=nullptr)
The access point is called network; password (at least 8 characters) protects it, nullptr leaves it o...
Definition SetupPortal.h:23