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
example.cpp File Reference

Pico W lwIP httpd (TLS) + mDNS example ported to STK. More...

#include <assert.h>
#include <stk.h>
#include <sync/stk_sync.h>
#include <time/stk_time.h>
#include "example.h"
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "hardware/structs/rosc.h"
#include "lwip/ip4_addr.h"
#include "lwip/apps/mdns.h"
#include "lwip/apps/mdns_priv.h"
#include "lwip/init.h"
#include "lwip/apps/httpd.h"
#include "lwip/altcp_tls.h"
#include "example_certs.h"
#include "psa/crypto.h"
#include "mbedtls/platform.h"
#include "arch/sys_arch.h"
#include "pico/cyw43_arch_stk.h"
#include "threading_alt.h"
Include dependency graph for httpd_tls/example.cpp:

Go to the source code of this file.

Classes

class  WifiHttpdTask

Macros

#define STR_HELPER(x)
#define STR(x)

Enumerations

enum  { TASK_STACK_SIZE = 4096 }

Functions

void httpd_init (void)
static bool InitNetwork ()
static void ShutdownNetwork ()
static void InitServer ()
static bool ConnectWiFi ()
void RunExample ()
int __mbedtls_platform_get_entropy (psa_driver_get_entropy_flags_t flags, size_t *estimate_bits, unsigned char *output, size_t output_size)

Variables

const char WIFI_SSID [] = ENV_WIFI_SSID
const char WIFI_PASSWORD [] = ENV_WIFI_PASSWORD
static const char * SSI_TAGS []

Detailed Description

Pico W lwIP httpd (TLS) + mDNS example ported to STK.

Definition in file httpd_tls/example.cpp.

Macro Definition Documentation

◆ STR

#define STR ( x)
Value:
#define STR_HELPER(x)

Definition at line 99 of file httpd_tls/example.cpp.

◆ STR_HELPER

#define STR_HELPER ( x)
Value:
#x

Definition at line 98 of file httpd_tls/example.cpp.

Enumeration Type Documentation

◆ anonymous enum

anonymous enum
Enumerator
TASK_STACK_SIZE 

Definition at line 96 of file httpd_tls/example.cpp.

96{ TASK_STACK_SIZE = 4096 };
#define TASK_STACK_SIZE

Function Documentation

◆ __mbedtls_platform_get_entropy()

int __mbedtls_platform_get_entropy ( psa_driver_get_entropy_flags_t flags,
size_t * estimate_bits,
unsigned char * output,
size_t output_size )
Examples
httpd_tls/example.cpp.

Definition at line 544 of file httpd_tls/example.cpp.

546{
547 /* We don't implement any special flags */
548 if (flags != 0)
549 {
550 return PSA_ERROR_NOT_SUPPORTED;
551 }
552
553 if (output == NULL || estimate_bits == NULL)
554 {
555 return PSA_ERROR_INVALID_ARGUMENT;
556 }
557
558 /* Sample physical noise bits from ROSC */
559 for (size_t i = 0; i < output_size; i++)
560 {
561 uint8_t random_byte = 0;
562 for (int b = 0; b < 8; b++)
563 {
564 random_byte = (random_byte << 1) | (rosc_hw->randombit & 1);
565 }
566 output[i] = random_byte;
567 }
568
569 /* Set the estimated entropy bits gathered (8 bits per byte) */
570 *estimate_bits = 8 * output_size;
571
572 return 0; // Success
573}

◆ ConnectWiFi()

bool ConnectWiFi ( )
static
Examples
httpd/example.cpp, and httpd_tls/example.cpp.

Definition at line 420 of file httpd_tls/example.cpp.

421{
422 printf("Connecting to WiFi...\n");
423 if (cyw43_arch_wifi_connect_timeout_ms(WIFI_SSID, WIFI_PASSWORD, CYW43_AUTH_WPA2_AES_PSK, 30000))
424 {
425 printf("failed to connect.\n");
426 return false;
427 }
428 else
429 {
430 printf("Connected.\n");
431 }
432 printf("\nReady, running httpd at %s\n", ip4addr_ntoa(netif_ip4_addr(netif_list)));
433
434 // Record the connect time for the "uptime" SSI tag.
435 s_ConnectedTime = get_absolute_time();
436
437 return true;
438}
const char WIFI_PASSWORD[]
const char WIFI_SSID[]

References WIFI_PASSWORD, and WIFI_SSID.

Referenced by WifiHttpdTask::Run().

Here is the caller graph for this function:

◆ httpd_init()

void httpd_init ( void )

◆ InitNetwork()

bool InitNetwork ( )
static
Examples
httpd/example.cpp, and httpd_tls/example.cpp.

Definition at line 333 of file httpd_tls/example.cpp.

334{
335 // Must run from inside the task, not from RunExample() before kernel.Start() -
336 // see the file header for why (cyw43_arch_init()'s async_context_stk needs a
337 // running STK task to call stk::GetTid() from).
338 if (cyw43_arch_init())
339 {
340 printf("failed to initialise\n");
341 return false;
342 }
343
344 // Initialize PSA Crypto engine (Required for Mbed TLS 4)
345 psa_status_t status = psa_crypto_init();
346 if (status != PSA_SUCCESS)
347 {
348 printf("failed to initialise PSA crypto: %d\n", (int)status);
349 cyw43_arch_deinit();
350 return false;
351 }
352
353 cyw43_arch_enable_sta_mode();
354
355 return true;
356}

Referenced by WifiHttpdTask::Run().

Here is the caller graph for this function:

◆ InitServer()

void InitServer ( )
static
Examples
httpd/example.cpp, and httpd_tls/example.cpp.

Definition at line 370 of file httpd_tls/example.cpp.

371{
372 char hostname[sizeof(CYW43_HOST_NAME) + 4];
373 memcpy(&hostname[0], CYW43_HOST_NAME, sizeof(CYW43_HOST_NAME) - 1);
374 get_mac_ascii(CYW43_HAL_MAC_WLAN0, 8, 4, &hostname[sizeof(CYW43_HOST_NAME) - 1]);
375 hostname[sizeof(hostname) - 1] = '\0';
376 netif_set_hostname(&cyw43_state.netif[CYW43_ITF_STA], hostname);
377
378#if LWIP_MDNS_RESPONDER
379 // Set up the mDNS responder.
380 cyw43_arch_lwip_begin();
381 mdns_resp_init();
382 printf("mdns host name %s.local\n", hostname);
383#if LWIP_VERSION_MAJOR >= 2 && LWIP_VERSION_MINOR >= 2
384 mdns_resp_add_netif(&cyw43_state.netif[CYW43_ITF_STA], hostname);
385 mdns_resp_add_service(&cyw43_state.netif[CYW43_ITF_STA], "pico_httpd", "_http", DNSSD_PROTO_TCP, 80, srv_txt, NULL);
386#else
387 mdns_resp_add_netif(&cyw43_state.netif[CYW43_ITF_STA], hostname, 60);
388 mdns_resp_add_service(&cyw43_state.netif[CYW43_ITF_STA], "pico_httpd", "_http", DNSSD_PROTO_TCP, 80, 60, srv_txt, NULL);
389#endif
390 cyw43_arch_lwip_end();
391#endif
392 // Set up the HTTP server. CGI/SSI handlers are global state shared by
393 // both the plain-HTTP and HTTPS listeners below, so only need setting once.
394 cyw43_arch_lwip_begin();
395 httpd_init();
396 http_set_cgi_handlers(CGI_HANDLERS, LWIP_ARRAYSIZE(CGI_HANDLERS));
397 http_set_ssi_handler(ssi_example_ssi_handler, SSI_TAGS, LWIP_ARRAYSIZE(SSI_TAGS));
398
399 // Set up HTTPS on top of the same httpd instance. Uses a self-signed
400 // cert (see certs_der.h / generate_cert.sh) - browsers will show a
401 // "not private" warning on first visit since it's not CA-signed; that's
402 // expected for a self-generated cert and can be bypassed/accepted or
403 // the cert can be installed as trusted on the client.
404 s_TlsConfig = altcp_tls_create_config_server_privkey_cert(
405 s_TlsKey, sizeof(s_TlsKey),
406 NULL, 0, /* private key is not password-protected */
407 s_TlsCert, sizeof(s_TlsCert));
408 if (s_TlsConfig == NULL)
409 {
410 printf("Failed to create TLS config - HTTPS disabled, HTTP still available\n");
411 }
412 else
413 {
414 httpd_inits(s_TlsConfig);
415 printf("HTTPS server listening on port %d\n", HTTPD_SERVER_PORT_HTTPS);
416 }
417 cyw43_arch_lwip_end();
418}
const unsigned char s_TlsCert[]
const unsigned char s_TlsKey[]
static const char * SSI_TAGS[]
void httpd_init(void)

References httpd_init(), s_TlsCert, s_TlsKey, and SSI_TAGS.

Referenced by WifiHttpdTask::Run().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ RunExample()

void RunExample ( void )

Definition at line 493 of file httpd_tls/example.cpp.

494{
495 using namespace stk;
496
497 // Bring up stdio for logging.
498 stdio_init_all();
499
500 // Enable dynamic task registration and inter-task sync, plus tickless idle
501 // where the platform supports it.
502 static constexpr uint8_t KernelMode = KERNEL_DYNAMIC | KERNEL_SYNC | (STK_TICKLESS_IDLE ? KERNEL_TICKLESS : 0);
503
504 // Task budget: WifiHttpdTask + TimerHost + async_context_stk's worker tasks +
505 // lwIP's own sys_thread_new()-spawned tcpip thread (sized by
506 // LWIP_STK_THREAD_POOL_SIZE). Note: LWIP_STK_NETCONN_SEM_MAX_THREADS is NOT a
507 // task count - it sizes sys_arch's TId-keyed side-table for
508 // LWIP_NETCONN_SEM_PER_THREAD and has no bearing on kernel.AddTask() capacity.
509 static constexpr size_t tasks_count = 1U + stk::time::TimerHost::TASK_COUNT + ASYNC_CONTEXT_STK_TASKS + LWIP_STK_THREAD_POOL_SIZE;
510
511 // Allocate the scheduling kernel with priority-based scheduling (sched::SwitchStrategyFP32).
513 static stk::time::TimerHost timer_host;
514 static WifiHttpdTask task;
515
516 kernel.Initialize();
517
518 timer_host.Initialize(&kernel, stk::ACCESS_USER);
519
520 // Register the task with the kernel.
521 kernel.AddTask(&task);
522
523 // init mbedTLS threading
524 stk_mbedtls_threading_init();
525
526 // Wire the kernel into lwIP's sys_arch port - must happen before lwip_init().
527 sys_arch_set_kernel(&kernel);
528
529 // Wire the kernel and timer host into the cyw43 port - must happen before cyw43_arch_init().
530 cyw43_arch_stk_preinit(&kernel, &timer_host);
531
532 // Kick off network init once the task starts running; safe to request before kernel.Start().
533 RequestInitNetwork();
534
535 // Start the scheduler - this runs the registered task and blocks here permanently.
536 kernel.Start();
537
538 // Unreachable: kernel.Start() never returns.
539 STK_ASSERT(false);
540}
#define STK_ASSERT(e)
Runtime assertion. Halts execution if the expression e evaluates to false.
Definition stk_defs.h:532
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
@ 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
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
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

References stk::ACCESS_USER, stk::Kernel< TMode, TSize, TStrategy, TPlatform >::AddTask(), stk::Kernel< TMode, TSize, TStrategy, TPlatform >::Initialize(), stk::time::TimerHost::Initialize(), stk::KERNEL_DYNAMIC, stk::KERNEL_SYNC, stk::KERNEL_TICKLESS, stk::Kernel< TMode, TSize, TStrategy, TPlatform >::Start(), STK_ASSERT, and stk::time::TimerHost::TASK_COUNT.

Here is the call graph for this function:

◆ ShutdownNetwork()

void ShutdownNetwork ( )
static
Examples
httpd/example.cpp, and httpd_tls/example.cpp.

Definition at line 358 of file httpd_tls/example.cpp.

359{
360#if LWIP_MDNS_RESPONDER
361 mdns_resp_remove_netif(&cyw43_state.netif[CYW43_ITF_STA]);
362 udp_remove(get_mdns_pcb());
363 // KNOWN ISSUE: this doesn't decrement netif_client_id in netif.c, so a later
364 // mdns_resp_add_netif() will assert in netif_alloc_client_data_id() on reinit.
365#endif
366 cyw43_arch_disable_sta_mode();
367 cyw43_arch_deinit();
368}

Referenced by WifiHttpdTask::Run().

Here is the caller graph for this function:

Variable Documentation

◆ SSI_TAGS

const char* SSI_TAGS[]
static
Initial value:
=
{
"status",
"welcome",
"uptime",
"ledstate",
"ledinv",
"table",
}

Definition at line 107 of file httpd_tls/example.cpp.

108{
109 "status",
110 "welcome",
111 "uptime",
112 "ledstate",
113 "ledinv",
114 "table",
115};

◆ WIFI_PASSWORD

const char WIFI_PASSWORD[] = ENV_WIFI_PASSWORD

Definition at line 104 of file httpd_tls/example.cpp.

◆ WIFI_SSID

const char WIFI_SSID[] = ENV_WIFI_SSID

Definition at line 103 of file httpd_tls/example.cpp.