SuperTinyKernel™ RTOS 1.08.x
Lightweight, high-performance, deterministic, bare-metal C++ RTOS for resource-constrained embedded systems. MIT Open Source License.
Loading...
Searching...
No Matches
httpd/example.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) 2022 Raspberry Pi (Trading) Ltd.
3 * Copyright (c) 2022-2026 Neutron Code Limited <stk@neutroncode.com> (STK threading adaptation)
4 *
5 * SPDX-License-Identifier: BSD-3-Clause
6 *
7 * ---------------------------------------------------------------------------
8 * Pico W lwIP httpd + mDNS example, ported to STK
9 * ---------------------------------------------------------------------------
10 *
11 * A direct port of Raspberry Pi's original single-superloop example onto STK
12 * threading. It follows the same split used in example-blinky.cpp: one-time
13 * hardware bring-up runs directly in RunExample(), and everything ongoing
14 * (Wi-Fi connect, server setup, and the polling loop) runs inside a task's
15 * Run().
16 *
17 * Exception to that split: cyw43_arch_init() is called from inside the
18 * task's Run(), not from RunExample() alongside the rest of one-time
19 * bring-up. cyw43_arch_init() builds (or reuses) an async_context_stk,
20 * whose locking/ownership checks - async_context_stk_lock_check(),
21 * async_context_stk_execute_sync() - call stk::GetTid() to identify the
22 * calling task. stk::GetTid() only means something once it's called from a
23 * real, running STK task, i.e. after kernel.Start(). RunExample() runs
24 * before that, so cyw43_arch_init() can't live there. sys_arch_set_kernel()
25 * and cyw43_arch_stk_preinit() have no such restriction - they only stash
26 * pointers - so those still run from RunExample() as usual.
27 *
28 * Threading model: this targets cyw43_arch_stk's task-based background
29 * model, the STK analogue of upstream's FREERTOS backend, rather than
30 * POLL or THREADSAFE_BACKGROUND. cyw43_arch_stk.cpp hard-errors under
31 * NO_SYS=1, so this port only ever runs under NO_SYS=0: cyw43_arch_init()
32 * spins up async_context_stk's own worker task to drive the driver, and -
33 * since CYW43_LWIP is set - also spawns lwIP's tcpip thread via
34 * tcpip_init()/sys_thread_new(), sharing its core lock with the async
35 * context through sys_arch's LWIP_STK_CUSTOM_CORE_LOCKING hook (see
36 * lwip_stk.cpp/.h). This task itself never polls the driver; it just needs
37 * to stay alive after setup.
38 *
39 * Efficiency: WifiHttpdTask blocks on s_ControlFlags.Wait() rather than
40 * spinning, so it only runs when there's actually something to do (an LED
41 * request, a connect/init/shutdown request). The same holds one level down:
42 * async_context_stk's worker task and lwIP's tcpip thread are themselves
43 * STK tasks that block on their own queues/semaphores when idle, rather than
44 * polling the cyw43 driver or the network stack in a loop. With every task
45 * in the system blocked on an event rather than busy-waiting, the STK
46 * scheduler has nothing runnable and puts the CPU to sleep (WFI, or a
47 * tickless idle that also skips the periodic tick - see KERNEL_TICKLESS /
48 * STK_TICKLESS_IDLE below) until an interrupt - Wi-Fi/lwIP activity, a POST
49 * request, a timer - wakes something up. None of that requires any explicit
50 * power-management code in this file: it falls out of every task in the
51 * chain (this one, the driver's worker, lwIP's tcpip thread) using
52 * event-driven waits instead of polling.
53 * ---------------------------------------------------------------------------
54 */
55
61
62#include <assert.h>
63
64#include <stk.h>
65#include <sync/stk_sync.h>
66#include <time/stk_time.h>
67
68#include "example.h"
69
70#include "pico/cyw43_arch.h"
71#include "pico/stdlib.h"
72
73#include "lwip/ip4_addr.h"
74#include "lwip/apps/mdns.h"
75#include "lwip/apps/mdns_priv.h"
76#include "lwip/init.h"
77#include "lwip/apps/httpd.h"
78
79// STK
80#include "arch/sys_arch.h"
81#include "pico/cyw43_arch_stk.h"
82
83// The driver work plus httpd/mDNS buffers make this a heavier task than a
84// typical blinky-style one, so the stack is sized generously.
85enum { TASK_STACK_SIZE = 4096 };
86
87#define STR_HELPER(x) #x
88#define STR(x) STR_HELPER(x)
89
90void httpd_init(void);
91
92const char WIFI_SSID[] = ENV_WIFI_SSID;
93const char WIFI_PASSWORD[] = ENV_WIFI_PASSWORD;
94
95// Tag names are capped by LWIP_HTTPD_MAX_TAG_NAME_LEN - keep entries within it.
96static const char *SSI_TAGS[] =
97{
98 "status",
99 "welcome",
100 "uptime",
101 "ledstate",
102 "ledinv",
103 "table",
104};
105
106#if LWIP_HTTPD_SUPPORT_POST
107#define LED_STATE_BUFSIZE 4
108
109static const uint32_t FLAG_LED_UPDATE = (1U << 0); // A POST handler requested a GPIO write.
110static const uint32_t FLAG_CONNECT_WIFI = (1U << 1); // Wi-Fi should (re)connect.
111static const uint32_t FLAG_INIT_NET = (1U << 2); // The network stack should (re)initialize.
112static const uint32_t FLAG_SHUTDOWN_NET = (1U << 3); // The network stack should shut down.
113
114static void *s_CurrentConnection;
115static absolute_time_t s_ConnectedTime;
116static bool s_LedOn = false;
117stk::sync::EventFlags s_ControlFlags;
118
119static void RequestLedUpdate() { s_ControlFlags.Set(FLAG_LED_UPDATE); } // ISR-safe - callable from lwIP callback context.
120static void RequestConnectWiFi() { s_ControlFlags.Set(FLAG_CONNECT_WIFI); }
121static void RequestInitNetwork() { s_ControlFlags.Set(FLAG_INIT_NET); }
122static void RequestShutdownNetwork() { s_ControlFlags.Set(FLAG_SHUTDOWN_NET); }
123
124#if LWIP_MDNS_RESPONDER
125static void srv_txt(struct mdns_service *service, void *txt_userdata)
126{
127 err_t res;
128 LWIP_UNUSED_ARG(txt_userdata);
129
130 res = mdns_resp_add_service_txtitem(service, "path=/", 6);
131 LWIP_ERROR("mdns add service txt failed\n", (res == ERR_OK), return);
132}
133#endif
134
135// Writes a substring of the MAC address's ASCII hex representation
136// (e.g. "112233445566") into dest_in, starting at character index chr_off
137// and taking chr_len characters - e.g. chr_off=8, chr_len=4 returns "5566".
138// Returns the number of characters written.
139static size_t get_mac_ascii(int idx, size_t chr_off, size_t chr_len, char *dest_in)
140{
141 static const char hexchr[] = "0123456789ABCDEF";
142 uint8_t mac[6];
143 char *dest = dest_in;
144 assert(chr_off + chr_len <= (2 * sizeof(mac)));
145 cyw43_hal_get_mac(idx, mac);
146 for (; chr_len && (chr_off >> 1) < sizeof(mac); ++chr_off, --chr_len)
147 {
148 *dest++ = hexchr[mac[chr_off >> 1] >> (4 * (1 - (chr_off & 1))) & 0xf];
149 }
150 return dest - dest_in;
151}
152
153static const char *cgi_handler_test(int iIndex, int iNumParams, char *pcParam[], char *pcValue[])
154{
155 STK_UNUSED(iIndex);
156 STK_UNUSED(pcValue);
157
158 if (iNumParams > 0)
159 {
160 if (strcmp(pcParam[0], "test") == 0)
161 {
162 return "/test.shtml";
163 }
164 }
165 return "/index.shtml";
166}
167
168static const char *cgi_handler_restart(int iIndex, int iNumParams, char *pcParam[], char *pcValue[])
169{
170 //RequestShutdownNetwork(); // Disabled: network shutdown doesn't work reliably with lwIP.
171 return "/index.shtml";
172}
173
174static const tCGI CGI_HANDLERS[] =
175{
176 { "/", cgi_handler_test },
177 { "/index.shtml", cgi_handler_test },
178 { "/restart", cgi_handler_restart },
179};
180
181// pcInsert is capped at LWIP_HTTPD_MAX_TAG_INSERT_LEN; use LWIP_HTTPD_SSI_MULTIPART
182// (see the "table" tag below) to stream larger amounts of data across multiple calls.
183u16_t ssi_example_ssi_handler(int iIndex, char *pcInsert, int iInsertLen
185 , uint16_t current_tag_part, uint16_t *next_tag_part
186#endif
187 )
188{
189 size_t printed;
190 switch (iIndex)
191 {
192 case 0: // "status"
193 {
194 printed = snprintf(pcInsert, iInsertLen, "Pass");
195 break;
196 }
197 case 1: // "welcome"
198 {
199 printed = snprintf(pcInsert, iInsertLen, "Hello from Pico");
200 break;
201 }
202 case 2: // "uptime"
203 {
204 uint64_t uptime_s = absolute_time_diff_us(s_ConnectedTime, get_absolute_time()) / 1e6;
205 printed = snprintf(pcInsert, iInsertLen, "%d", (int)uptime_s);
206 break;
207 }
208 case 3: // "ledstate"
209 {
210 printed = snprintf(pcInsert, iInsertLen, "%s", s_LedOn ? "ON" : "OFF");
211 break;
212 }
213 case 4: // "ledinv"
214 {
215 printed = snprintf(pcInsert, iInsertLen, "%s", s_LedOn ? "OFF" : "ON");
216 break;
217 }
218#if LWIP_HTTPD_SSI_MULTIPART
219 case 5: /* "table" */
220 {
221 printed = snprintf(pcInsert, iInsertLen, "<tr><td>This is table row number %d</td></tr>", current_tag_part + 1);
222 // Advance next_tag_part to request another call for the next row; leaving it
223 // unchanged (once we hit 9) tells lwIP this tag is fully sent.
224 if (current_tag_part < 9)
225 {
226 *next_tag_part = current_tag_part + 1;
227 }
228 break;
229 }
230#endif
231 default: // unknown tag
232 {
233 printed = 0;
234 break;
235 }
236 }
237 return (u16_t)printed;
238}
239
240err_t httpd_post_begin(void *connection, const char *uri, const char *http_request,
241 u16_t http_request_len, int content_len, char *response_uri,
242 u16_t response_uri_len, u8_t *post_auto_wnd)
243{
244 STK_UNUSED(http_request);
245 STK_UNUSED(http_request_len);
246 STK_UNUSED(content_len);
247
248 if (memcmp(uri, "/led.cgi", 8) == 0 && s_CurrentConnection != connection)
249 {
250 s_CurrentConnection = connection;
251 snprintf(response_uri, response_uri_len, "/ledfail.shtml");
252 *post_auto_wnd = 1;
253 return ERR_OK;
254 }
255 return ERR_VAL;
256}
257
258// Finds param_name in the POST body pbuf chain and copies its value into
259// value_buf (NUL-terminated). Returns value_buf on success, NULL if the
260// parameter is missing or its value doesn't fit in value_buf_len.
261char *httpd_param_value(struct pbuf *p, const char *param_name, char *value_buf, size_t value_buf_len)
262{
263 size_t param_len = strlen(param_name);
264 u16_t param_pos = pbuf_memfind(p, param_name, param_len, 0);
265 if (param_pos != 0xFFFF)
266 {
267 u16_t param_value_pos = param_pos + param_len;
268 u16_t param_value_len = 0;
269 u16_t tmp = pbuf_memfind(p, "&", 1, param_value_pos);
270 if (tmp != 0xFFFF)
271 {
272 param_value_len = tmp - param_value_pos;
273 }
274 else
275 {
276 param_value_len = p->tot_len - param_value_pos;
277 }
278 if (param_value_len > 0 && param_value_len < value_buf_len)
279 {
280 char *result = (char *)pbuf_get_contiguous(p, value_buf, value_buf_len, param_value_len, param_value_pos);
281 if (result)
282 {
283 result[param_value_len] = 0;
284 return result;
285 }
286 }
287 }
288 return NULL;
289}
290
291err_t httpd_post_receive_data(void *connection, struct pbuf *p)
292{
293 err_t ret = ERR_VAL;
294 LWIP_ASSERT("NULL pbuf", p != NULL);
295 if (s_CurrentConnection == connection)
296 {
297 char buf[LED_STATE_BUFSIZE];
298 char *val = httpd_param_value(p, "led_state=", buf, sizeof(buf));
299 if (val)
300 {
301 s_LedOn = (strcmp(val, "ON") == 0) ? true : false;
302 RequestLedUpdate();
303 ret = ERR_OK;
304 }
305 }
306 pbuf_free(p);
307 return ret;
308}
309
310void httpd_post_finished(void *connection, char *response_uri, u16_t response_uri_len)
311{
312 snprintf(response_uri, response_uri_len, "/ledfail.shtml");
313 if (s_CurrentConnection == connection)
314 {
315 snprintf(response_uri, response_uri_len, "/ledpass.shtml");
316 }
317 s_CurrentConnection = NULL;
318}
319#endif
320
321static bool InitNetwork()
322{
323 // Must run from inside the task, not from RunExample() before kernel.Start() -
324 // see the file header for why (cyw43_arch_init()'s async_context_stk needs a
325 // running STK task to call stk::GetTid() from).
326 if (cyw43_arch_init())
327 {
328 printf("failed to initialise\n");
329 return false;
330 }
331 cyw43_arch_enable_sta_mode();
332
333 return true;
334}
335
336static void ShutdownNetwork()
337{
338#if LWIP_MDNS_RESPONDER
339 mdns_resp_remove_netif(&cyw43_state.netif[CYW43_ITF_STA]);
340 udp_remove(get_mdns_pcb());
341 // KNOWN ISSUE: this doesn't decrement netif_client_id in netif.c, so a later
342 // mdns_resp_add_netif() will assert in netif_alloc_client_data_id() on reinit.
343#endif
344 cyw43_arch_disable_sta_mode();
345 cyw43_arch_deinit();
346}
347
348static void InitServer()
349{
350 char hostname[sizeof(CYW43_HOST_NAME) + 4];
351 memcpy(&hostname[0], CYW43_HOST_NAME, sizeof(CYW43_HOST_NAME) - 1);
352 get_mac_ascii(CYW43_HAL_MAC_WLAN0, 8, 4, &hostname[sizeof(CYW43_HOST_NAME) - 1]);
353 hostname[sizeof(hostname) - 1] = '\0';
354 netif_set_hostname(&cyw43_state.netif[CYW43_ITF_STA], hostname);
355
356#if LWIP_MDNS_RESPONDER
357 // Set up the mDNS responder.
358 cyw43_arch_lwip_begin();
359 mdns_resp_init();
360 printf("mdns host name %s.local\n", hostname);
361#if LWIP_VERSION_MAJOR >= 2 && LWIP_VERSION_MINOR >= 2
362 mdns_resp_add_netif(&cyw43_state.netif[CYW43_ITF_STA], hostname);
363 mdns_resp_add_service(&cyw43_state.netif[CYW43_ITF_STA], "pico_httpd", "_http", DNSSD_PROTO_TCP, 80, srv_txt, NULL);
364#else
365 mdns_resp_add_netif(&cyw43_state.netif[CYW43_ITF_STA], hostname, 60);
366 mdns_resp_add_service(&cyw43_state.netif[CYW43_ITF_STA], "pico_httpd", "_http", DNSSD_PROTO_TCP, 80, 60, srv_txt, NULL);
367#endif
368 cyw43_arch_lwip_end();
369#endif
370 // Set up the HTTP server.
371 cyw43_arch_lwip_begin();
372 httpd_init();
373 http_set_cgi_handlers(CGI_HANDLERS, LWIP_ARRAYSIZE(CGI_HANDLERS));
374 http_set_ssi_handler(ssi_example_ssi_handler, SSI_TAGS, LWIP_ARRAYSIZE(SSI_TAGS));
375 cyw43_arch_lwip_end();
376}
377
378static bool ConnectWiFi()
379{
380 printf("Connecting to WiFi...\n");
381 if (cyw43_arch_wifi_connect_timeout_ms(WIFI_SSID, WIFI_PASSWORD, CYW43_AUTH_WPA2_AES_PSK, 30000))
382 {
383 printf("failed to connect.\n");
384 return false;
385 }
386 else
387 {
388 printf("Connected.\n");
389 }
390 printf("\nReady, running httpd at %s\n", ip4addr_ntoa(netif_ip4_addr(netif_list)));
391
392 // Record the connect time for the "uptime" SSI tag.
393 s_ConnectedTime = get_absolute_time();
394
395 return true;
396}
397
398// Owns Wi-Fi connect and httpd/mDNS server setup, driven by control-flag events
399// rather than the original's while(true) superloop. It doesn't drive the cyw43
400// driver itself - async_context_stk's own worker task (spun up inside
401// cyw43_arch_init()) does that - so this task's loop just needs to stay alive
402// and react to flags after setup.
403class WifiHttpdTask : public stk::Task<TASK_STACK_SIZE, stk::ACCESS_PRIVILEGED>
404{
405private:
406 void Run() override
407 {
408 bool running = true;
409 while (running)
410 {
411 const uint32_t raised = s_ControlFlags.Wait(FLAG_CONNECT_WIFI | FLAG_LED_UPDATE | FLAG_INIT_NET | FLAG_SHUTDOWN_NET, stk::sync::EventFlags::OPT_WAIT_ANY, stk::WAIT_INFINITE);
413 {
414 continue;
415 }
416
417 if (raised & FLAG_LED_UPDATE)
418 {
419 cyw43_arch_lwip_begin();
420 cyw43_gpio_set(&cyw43_state, 0, s_LedOn);
421 cyw43_arch_lwip_end();
422 }
423 if (raised & FLAG_CONNECT_WIFI)
424 {
425 if (!ConnectWiFi())
426 {
427 RequestConnectWiFi();
428 }
429 }
430 if (raised & FLAG_INIT_NET)
431 {
432 if (InitNetwork())
433 {
434 InitServer();
435 RequestConnectWiFi();
436 }
437 else
438 {
439 RequestInitNetwork();
440 }
441 }
442 if (raised & FLAG_SHUTDOWN_NET)
443 {
445 RequestInitNetwork();
446 }
447 }
448 }
449};
450
452{
453 using namespace stk;
454
455 // Bring up stdio for logging.
456 stdio_init_all();
457
458 // Enable dynamic task registration and inter-task sync, plus tickless idle
459 // where the platform supports it.
460 static constexpr uint8_t KernelMode = KERNEL_DYNAMIC | KERNEL_SYNC | (STK_TICKLESS_IDLE ? KERNEL_TICKLESS : 0);
461
462 // Task budget: WifiHttpdTask + TimerHost + async_context_stk's worker tasks +
463 // lwIP's own sys_thread_new()-spawned tcpip thread (sized by
464 // LWIP_STK_THREAD_POOL_SIZE). Note: LWIP_STK_NETCONN_SEM_MAX_THREADS is NOT a
465 // task count - it sizes sys_arch's TId-keyed side-table for
466 // LWIP_NETCONN_SEM_PER_THREAD and has no bearing on kernel.AddTask() capacity.
467 static constexpr size_t tasks_count = 1U + stk::time::TimerHost::TASK_COUNT + ASYNC_CONTEXT_STK_TASKS + LWIP_STK_THREAD_POOL_SIZE;
468
469 // Allocate the scheduling kernel with priority-based scheduling (sched::SwitchStrategyFP32).
471 static stk::time::TimerHost timer_host;
472 static WifiHttpdTask task;
473
474 kernel.Initialize();
475
476 timer_host.Initialize(&kernel, stk::ACCESS_USER);
477
478 // Register the task with the kernel.
479 kernel.AddTask(&task);
480
481 // Wire the kernel into lwIP's sys_arch port - must happen before lwip_init().
482 sys_arch_set_kernel(&kernel);
483
484 // Wire the kernel and timer host into the cyw43 port - must happen before cyw43_arch_init().
485 cyw43_arch_stk_preinit(&kernel, &timer_host);
486
487 // Kick off network init once the task starts running; safe to request before kernel.Start().
488 RequestInitNetwork();
489
490 // Start the scheduler - this runs the registered task and blocks here permanently.
491 kernel.Start();
492
493 // Unreachable: kernel.Start() never returns.
494 STK_ASSERT(false);
495}
#define LWIP_HTTPD_SSI_MULTIPART
Definition lwipopts.h:23
Top-level STK include. Provides the Kernel class template and all built-in task-switching strategies.
#define STK_UNUSED(X)
Explicitly marks a variable as unused to suppress compiler warnings.
Definition stk_defs.h:715
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:532
Collection of synchronization primitives (stk::sync namespace).
Collection of time-related primitives (stk::time namespace).
Namespace of STK package.
@ ACCESS_USER
Unprivileged access mode (access to some hardware is restricted, see CPU manual for details)....
Definition stk_common.h:37
static constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:274
@ KERNEL_TICKLESS
Tickless mode. To use this mode STK_TICKLESS_IDLE must be defined to 1 in stk_config....
Definition stk_common.h:51
@ KERNEL_SYNC
Synchronization support (see Event).
Definition stk_common.h:50
@ KERNEL_DYNAMIC
Tasks can be added or removed and therefore exit when done.
Definition stk_common.h:48
EventFlagsT< uint32_t > EventFlags
Default event flags group with a 32-bit flags word (31 usable flags, bit 31 reserved).
Concrete implementation of IKernel.
Definition stk.h:102
void Start() override
Start the scheduler. This call does not return until all tasks have exited (KERNEL_DYNAMIC mode) or i...
Definition stk.h:1999
EAddResult AddTask(ITask *user_task) override
Register task for a soft real-time (SRT) scheduling.
Definition stk.h:1465
void Initialize(uint32_t resolution_us=PERIODICITY_DEFAULT) override
Initialize kernel.
Definition stk.h:1425
Partial implementation of the user task.
Definition stk_helper.h:98
T Set(T flags)
Set one or more flags.
static constexpr uint32_t OPT_WAIT_ANY
T Wait(T flags, uint32_t options=OPT_WAIT_ANY, Timeout timeout_ticks=WAIT_INFINITE)
Wait for one or more flags to be set.
static bool IsError(uint32_t result)
Software timer multiplexer that manages multiple Timer instances on top of a small fixed set of kerne...
EAddResult Initialize(IKernel *kernel, EAccessMode mode, const Config &cfg=Config())
Initialize timer host instance.
@ TASK_COUNT
total number of tasks serving this instance
void Run() override
Entry point of the user task.
static const char * SSI_TAGS[]
static bool ConnectWiFi()
static void InitServer()
static void ShutdownNetwork()
const char WIFI_PASSWORD[]
void httpd_init(void)
static bool InitNetwork()
const char WIFI_SSID[]
static bool ConnectWiFi()
static void InitServer()
static void ShutdownNetwork()
static bool InitNetwork()
#define TASK_STACK_SIZE