### Build and Run Mongoose Dashboard with Watch
Source: https://mongoose.ws/docs/guides/web-dashboard-guide
Navigates to the minimal device dashboard example and runs 'make watch' to build, run, and monitor for changes. Starts a server on port 8000.
```bash
cd tutorials/device-dashboard/minimal
make watch
```
--------------------------------
### Mongoose HTTP Handler Setup Examples
Source: https://mongoose.ws/docs/guides/web-ui-builder
Illustrates how to set up different types of REST API endpoint handlers in Mongoose.
```c
mongoose_set_http_handlers("data", my_get_XXX, my_set_XXX);
mongoose_set_http_handlers("array", my_get_XXX, my_set_XXX);
mongoose_set_http_handlers("action", my_check_XXX, my_start_XXX);
mongoose_set_http_handlers("file", my_read_XXX, my_write_XXX);
mongoose_set_http_handlers("ota", my_open_XXX, my_close_XXX, my_write_XXX);
```
--------------------------------
### Build and Flash Example Project (W5500)
Source: https://mongoose.ws/docs/guides/rp-tcpip-stack
Use this command to build and flash the Mongoose example for W5500 on a Raspberry Pi Pico.
```bash
cd ~/src/mongoose/tutorials/rp/w5500-evb-pico2
make build flash
```
--------------------------------
### Install Development Tools on macOS
Source: https://mongoose.ws/docs/guides/web-dashboard-guide
Installs Homebrew, then installs gcc, make, git, and node using Homebrew.
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew install gcc make git node
```
--------------------------------
### Build and Flash Example Project (Pico 2 W)
Source: https://mongoose.ws/docs/guides/rp-tcpip-stack
Use this command to build and flash the Mongoose example for Pico 2 W.
```bash
cd ~/src/mongoose/tutorials/rp/pico2-w
make build flash
```
--------------------------------
### Start Modbus-TCP Listener
Source: https://mongoose.ws/docs/api/util
Example of how to start a Modbus-TCP listener on a specific URL using the `mg_modbus_listen` function and a custom event handler.
```c
mg_modbus_listen(&g_mgr, "tcp://0.0.0.0:502", modbus_ev_handler, NULL);
```
--------------------------------
### MQTT Connection Event Handler Example
Source: https://mongoose.ws/docs/api/mqtt
Example event handler function demonstrating how to process MG_EV_CONNECT and MG_EV_MQTT_OPEN events for MQTT connections.
```c
void fn(struct mg_connection *c, int ev, void *ev_data, void *fnd) {
if (ev == MG_EV_CONNECT) {
// TCP connection succeeded,
// If target URL is TLS, set it up
} else if (ev == MG_EV_MQTT_OPEN) {
// MQTT connection process finished
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
if(mm->ack) // MQTT connection succeeded
}
}
```
--------------------------------
### mg_ota_begin()
Source: https://mongoose.ws/docs/api/ota
Starts a firmware update session. This function should be called before writing any firmware data.
```APIDOC
## mg_ota_begin()
Start a firmware update session.
### Function Signature
```c
bool mg_ota_begin(size_t new_firmware_size);
```
### Parameters
* `new_firmware_size` (size_t) - Expected size of the new firmware image.
### Return Value
* `true` on success, `false` on failure.
### Usage Example
```c
if (mg_ota_begin(firmware_size)) {
// Ready to write firmware
} else {
// OTA begin failed
}
```
```
--------------------------------
### Server TLS Initialization Example
Source: https://mongoose.ws/docs/api/tls
Example of initializing TLS for a server connection within an event handler. It sets the certificate and private key options.
```c
// server event handler:
if (ev == MG_EV_ACCEPT) {
struct mg_tls_opts opts = {.cert = mg_str(s_tls_cert),
.key = mg_str(s_tls_key)};
mg_tls_init(c, &opts);
```
--------------------------------
### Mongoose Logging Example
Source: https://mongoose.ws/docs/api/logging
Example of how to use the MG_INFO macro to log a formatted string message.
```c
MG_INFO(("Hello %s!", "world")); // Output "Hello, world"
```
--------------------------------
### Install Build Tools on Linux (Ubuntu)
Source: https://mongoose.ws/docs/getting-started/build-environment
Installs essential build tools including GCC and ARM GCC for Ubuntu Linux.
```bash
sudo apt -y update
sudo apt -y install build-essential make gcc-arm-none-eabi git
```
--------------------------------
### Client TLS Initialization Example
Source: https://mongoose.ws/docs/api/tls
Example of initializing TLS for a client connection within an event handler. It sets the Certificate Authority option.
```c
// client event handler:
if (ev == MG_EV_CONNECT) {
struct mg_tls_opts opts = {.ca = mg_str(s_tls_ca)};
mg_tls_init(c, &opts);
```
--------------------------------
### Install Development Tools on Linux/WSL
Source: https://mongoose.ws/docs/guides/web-dashboard-guide
Installs essential development tools like git, make, gcc, and nodejs using apt package manager.
```bash
sudo apt -y update
sudo apt -y install build-essential make git nodejs
```
--------------------------------
### Example: Custom REST API Handler
Source: https://mongoose.ws/docs/guides/web-ui-builder
Shows how to create a custom API handler that responds to HTTP requests. This example logs POST data, URI, and query parameters, then replies with 'ok'.
```c
#include "mongoose/mongoose_glue.h"
// curl -qs IP/my/api
// curl -qs IP/my/api/1/2/3?foo=bar -d '{"a":42}'
static void my_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_HTTP_MSG) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
MG_INFO(("POST data: [%.*s], URI: [%.*s], QUERY: [%.*s]", //
hm->body.len, hm->body.buf, //
hm->uri.len, hm->uri.buf, //
hm->query.len, hm->query.buf));
mg_http_reply(c, 200, "", "ok\n");
}
}
int main(void) {
mongoose_init();
mongoose_add_custom_handler("/my/api#", my_ev_handler);
for (;;) {
mongoose_poll();
}
return 0;
}
```
--------------------------------
### Install Build Tools on macOS
Source: https://mongoose.ws/docs/getting-started/build-environment
Installs Git, GCC, Make, and ARM GCC using Homebrew on macOS.
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew install gcc make git gcc-arm-embedded
```
--------------------------------
### Initialize MQTT Listener
Source: https://mongoose.ws/docs/api/mqtt
Example of initializing an MQTT listener on all interfaces and port 1883, with error checking.
```c
struct mg_connection *c = mg_mqtt_listen(&mgr, "mqtt://0.0.0.0:1883", fn, arg);
if (c == NULL) return -1; // Could not create connection
```
--------------------------------
### Example: Wrapping MQTT Login Message with mg_ws_wrap
Source: https://mongoose.ws/docs/api/websocket
This example demonstrates how to use `mg_ws_wrap` to wrap an MQTT login message into WebSocket format. It first stores the current output buffer length, writes the MQTT login message, and then wraps the written data.
```c
size_t len = c->send.len; // Store output buffer len
mg_mqtt_login(c, s_url, &opts); // Write MQTT login message
mg_ws_wrap(c, c->send.len - len, WEBSOCKET_OP_BINARY); // Wrap it into WS
```
--------------------------------
### HTTP OTA Update Handler Example
Source: https://mongoose.ws/docs/api/http
Example of how to use `mg_http_start_ota` within an event handler. This snippet demonstrates handling `MG_EV_HTTP_HDRS` to initiate the OTA process when an OTA request is received.
```c
static void ota_done(struct mg_connection *c, const char *errmsg) {
mg_http_reply(c, errmsg == NULL ? 200 : 500, "", "%s\n",
errmsg == NULL ? "ok" : errmsg);
c->is_draining = 1;
}
static void fn(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_HTTP_HDRS) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_match(hm->uri, mg_str("/ota"), NULL)) {
mg_http_start_ota(c, hm, ota_done);
}
}
}
```
--------------------------------
### Compile and Run HTTP Server
Source: https://mongoose.ws/docs/getting-started/first-web-server
These commands show how to compile the C source code using GCC and then run the resulting executable to start the HTTP server.
```bash
cc main.c mongoose.c -I. -o http_server
./http_server
```
--------------------------------
### Minimal Mongoose Server
Source: https://mongoose.ws/docs/getting-started/programming-model
A complete example of a minimal Mongoose server. It initializes the event manager, sets up an HTTP listener, and runs the event loop.
```c
#include "mongoose.h"
static void http_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_HTTP_MSG) {
mg_http_reply(c, 200, "", "hello\n");
}
}
int main(void) {
struct mg_mgr mgr;
mg_mgr_init(&mgr);
mg_http_listen(&mgr, "http://0.0.0.0:8000", http_ev_handler, NULL);
for (;;) {
mg_mgr_poll(&mgr, 1000);
}
return 0;
}
```
--------------------------------
### Send RPC OK Response Usage Example
Source: https://mongoose.ws/docs/api/json-rpc
Example of using mg_rpc_ok() within an RPC handler to send a successful response with the calculated sum.
```c
static void rpc_sum(struct mg_rpc_req *r) {
double a = 0.0, b = 0.0;
mg_json_get_num(r->frame, "$.params[0]", &a);
mg_json_get_num(r->frame, "$.params[1]", &b);
mg_rpc_ok(r, "%g", a + b);
}
```
--------------------------------
### Usage Example for mg_rpc_err()
Source: https://mongoose.ws/docs/api/json-rpc
Example demonstrating how to use mg_rpc_err to send an error response, formatting a string with dynamic content.
```c
static void rpc_dosome(struct mg_rpc_req *r) {
...
mg_rpc_err(r, -32109, "\"%.*s not found\"", len, &r->frame.buf[offset]);
}
```
--------------------------------
### Hardware-Specific GPIO Read Example
Source: https://mongoose.ws/docs/guides/web-dashboard-guide
Example C snippet for reading a GPIO pin state (GPIOB, GPIO_PIN_0) and assigning it to 's_led1', specific to MG_ARCH_CUBE.
```c
#if MG_ARCH == MG_ARCH_CUBE
s_led1 = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_0); // Read LED state into field
#endif
```
--------------------------------
### Usage Example for mg_iobuf_del()
Source: https://mongoose.ws/docs/api/core/content.html
Demonstrates how to initialize an iobuf, add data to it, and then delete a portion of that data using `mg_iobuf_del()`.
```c
struct mg_iobuf io;
mg_iobuf_init(&io, 0, 16); // Empty buffer, 16-bytes aligned
mg_iobuf_add(&io, 0, "hello", 5); // io->len is 5, io->size is 16
mg_iobuf_del(&io, 1, 3); // io->len is 2, io->size is still 16
```
--------------------------------
### Add RPC Method Usage Example
Source: https://mongoose.ws/docs/api/json-rpc
Demonstrates how to add RPC methods like 'sum' and 'mul' to a linked list using mg_rpc_add().
```c
struct mg_rpc *s_rpc_head = NULL;
static void rpc_sum(struct mg_rpc_req *r) {
double a = 0.0, b = 0.0;
mg_json_get_num(r->frame, "$.params[0]", &a);
mg_json_get_num(r->frame, "$.params[1]", &b);
mg_rpc_ok(r, "%g", a + b);
}
static void rpc_mul(struct mg_rpc_req *r) {//...}
mg_rpc_add(&s_rpc_head, mg_str("sum"), rpc_sum, NULL);
mg_rpc_add(&s_rpc_head, mg_str("mul"), rpc_mul, NULL);
```
--------------------------------
### Client WebSocket Connection
Source: https://mongoose.ws/docs/api/websocket
Shows how to initiate a client-side WebSocket connection using `mg_ws_connect()`. This function allocates resources and starts the connection process.
```c
struct mg_connection *mg_ws_connect(struct mg_mgr *mgr, const char *url,
mg_event_handler_t fn, void *fn_data,
const char *fmt, ...);
```
```c
struct mg_connection *c = mg_ws_connect(&mgr, "ws://test_ws_server.com:1000",
handler, NULL, "%s", "Sec-WebSocket-Protocol: echo\r\n");
if(c == NULL) fatal("Cannot create connection");
```
--------------------------------
### Parse IP Address String
Source: https://mongoose.ws/docs/api/string
Example of using `mg_aton` to parse an IP address string into a binary representation.
```c
struct mg_addr addr;
if (mg_aton(mg_str("127.0.0.1"), &addr)) {
// addr is now binary representation of 127.0.0.1 IP address
}
```
--------------------------------
### Mongoose Protocol Handler Setup Functions
Source: https://mongoose.ws/docs/guides/web-ui-builder
Provides reference for setting up handlers for MQTT, Modbus, SNTP, Authentication, and Modbus requests in Mongoose.
```c
struct mongoose_mqtt_handlers {
struct mg_connection *(*connect_fn)(mg_event_handler_t);
void (*tls_init_fn)(struct mg_connection *);
void (*on_connect_fn)(struct mg_connection *, int);
void (*on_message_fn)(struct mg_connection *, struct mg_str, struct mg_str);
void (*on_cmd_fn)(struct mg_connection *, struct mg_mqtt_message *);
};
void mongoose_set_mqtt_handlers(struct mongoose_mqtt_handlers *);
struct mongoose_modbus_handlers {
bool (*read_reg_fn)(uint16_t address, uint16_t *value);
bool (*write_reg_fn)(uint16_t address, uint16_t value);
};
void mongoose_set_modbus_handlers(struct mongoose_modbus_handlers *);
void mongoose_set_sntp_handler(void (*fn)(uint64_t epoch_ms));
void mongoose_set_auth_handler(int (*fn)(const char *user, const char *pass));
void mongoose_set_modbus_handler(void (*fn)(struct mg_modbus_req *req));
```
--------------------------------
### Example: Real-time Data Update
Source: https://mongoose.ws/docs/guides/web-ui-builder
Demonstrates how to send real-time data from a device to the UI. It initializes Mongoose, sets up a getter function for real-time data, and registers a WebSocket reporter.
```c
#include "mongoose_glue.h"
static void my_getter(struct real_time_data *data) {
data->value1 = read_adc();
}
int main(void) {
mongoose_init();
mongoose_set_http_handlers("real_time_data", my_getter, NULL);
mongoose_add_ws_reporter(200, "real_time_data");
for (;;) {
mongoose_poll();
}
}
```
--------------------------------
### JSON API Response Example
Source: https://mongoose.ws/docs/getting-started/first-web-server
This is the expected JSON output from the /api/hello endpoint when accessed via a web browser or client.
```json
{"status":1}
```
--------------------------------
### Append String to Output Buffer
Source: https://mongoose.ws/docs/api/string
Example of using `mg_xprintf` with `mg_pfn_iobuf` to append a string to an output buffer.
```c
mg_xprintf(mg_pfn_iobuf, &c->send, "hi!"); // Append to the output buffer
```
--------------------------------
### Register mg_rpc_list() Method
Source: https://mongoose.ws/docs/api/json-rpc
Example showing how to register the built-in mg_rpc_list function as an RPC method named 'rpc.list'.
```c
mg_rpc_add(&s_rpc_head, mg_str("rpc.list"), mg_rpc_list, &s_rpc_head);
```
--------------------------------
### Custom MIME Type Configuration
Source: https://mongoose.ws/docs/api/http
Example of configuring custom MIME types, including a wildcard for default types and specific overrides.
```c
sopts.mime_types = "*=preferred/default,txt=override/text"
```
--------------------------------
### mg_connect()
Source: https://mongoose.ws/docs/api/core
Initiates an outbound connection to a specified URL. It appends the connection to the event manager and starts the connection process asynchronously.
```APIDOC
## mg_connect()
### Description
Creates an outbound connection and appends it to the event manager's connection list. This function initiates the process of connecting to a remote peer. A notification event (`MG_EV_CONNECT`) is sent when the connection is established.
### Parameters
* `mgr` (struct mg_mgr *) - An event manager to use.
* `url` (const char *) - A URL specifying the remote IP address and port to connect to (e.g., `http://a.com`). If the URL is a known TLS URL, the `is_tls` flag will be set. If name resolution is required, it will start asynchronously.
* `fn` (mg_event_handler_t) - An event handler function to be called for events related to this connection.
* `fn_data` (void *) - An arbitrary pointer that will be stored in the connection structure as `c->fn_data`, accessible by the event handler.
### Return Value
Returns a pointer to the created connection, or `NULL` on error. Possible errors include insufficient memory, a NULL URL, or network issues if using the built-in TCP/IP stack.
### Notes
* This function allocates resources and starts the connection process; it does not guarantee an immediate connection.
* mDNS resolution for '.local' domain addresses requires an mDNS listener to be started separately using `mg_mdns_listen()`.
### Usage Example
```c
struct mg_connection *c = mg_connect(&mgr, "http://example.org", fn, NULL);
```
```
--------------------------------
### Start OTA Firmware Update
Source: https://mongoose.ws/docs/api/ota
Initiates an OTA firmware update session. Call this before writing any firmware data. It requires the expected size of the new firmware image.
```c
bool mg_ota_begin(size_t new_firmware_size);
```
```c
if (mg_ota_begin(firmware_size)) {
// Ready to write firmware
} else {
// OTA begin failed
}
```
--------------------------------
### Pushing Firmware Image via HTTP
Source: https://mongoose.ws/docs/guides/firmware-ota-updates
Command-line example to push a signed firmware image to the device using curl. Ensure the firmware file is correctly signed before uploading.
```bash
curl http://DEVICE_IP/api/ota/update --data-binary @firmware.signed.bin
```
--------------------------------
### mg_snprintf Usage Examples
Source: https://mongoose.ws/docs/api/string
Demonstrates various uses of mg_snprintf, including standard formatting and custom handlers for base64, JSON escaping, hex encoding, and IP addresses.
```c
mg_snprintf(buf, sizeof(buf), "%lld", (int64_t) 123); // 123 (64-bit integer)
mg_snprintf(buf, sizeof(buf), "%.2s", "abcdef"); // ab (part of a string)
mg_snprintf(buf, sizeof(buf), "%.*s", 2, "abcdef"); // ab (part of a string)
mg_snprintf(buf, sizeof(buf), "%05x", 123); // 00123 (padded integer)
mg_snprintf(buf, sizeof(buf), "%%-%3s", "a"); // %- a (padded string)
mg_snprintf(buf, sizeof(buf), "hi, %m", mg_print_base64, 1, "a"); // hi, "YWJj" (base64-encode)
mg_snprintf(buf, sizeof(buf), "[%m]", mg_print_esc, 0, "two\nlines"); // ["two\nlines"] (JSON-escaped string)
mg_snprintf(buf, sizeof(buf), "{%m:%g}", mg_print_esc, 0, "val", 1.2); // {"val": 1.2} (JSON object)
mg_snprintf(buf, sizeof(buf), "hi, %M", mg_print_hex, 3, "abc"); // hi, 616263 (hex-encode)
mg_snprintf(buf, sizeof(buf), "IP: %M", mg_print_ip, &c->rem); // IP: 1.2.3.4 (struct mg_addr)
mg_snprintf(buf, sizeof(buf), "Peer: %M", mg_print_ip_port, &c->rem); // Peer: 1.2.3.4:21345 (struct mg_addr with port)
mg_snprintf(buf, sizeof(buf), "%M", mg_print_ip4, "abcd"); // 97.98.99.100 (IPv4 address)
mg_snprintf(buf, sizeof(buf), "%M", mg_print_ip6, "abcdefghijklmnop"); // [4142:4344:4546:4748:494a:4b4c:4d4e:4f50]
mg_snprintf(buf, sizeof(buf), "%M", mg_print_mac, "abcdef"); // 61:62:63:64:65:66 (MAC address)
```
--------------------------------
### Create MQTT Client Connection
Source: https://mongoose.ws/docs/api/mqtt
Initiates an MQTT client connection to a broker. This function allocates resources and starts the TCP connection process, followed by the MQTT connection.
```c
struct mg_connection *mg_mqtt_connect(struct mg_mgr *mgr, const char *url,
const struct mg_mqtt_opts *opts,
mg_event_handler_t fn, void *fn_data);
```
--------------------------------
### Serving Directory with Custom Root and Aliases
Source: https://mongoose.ws/docs/api/http
Example Mongoose event handler demonstrating how to use mg_http_serve_dir with custom root directory and URI-to-path mappings.
```c
// Mongoose events handler
void fn(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_HTTP_MSG) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
struct mg_http_serve_opts opts;
memset(&opts, 0, sizeof(opts));
opts.root_dir = "/var/www,/conf=/etc"; // Serve /var/www. URIs starting with /conf are served from /etc
mg_http_serve_dir(c, hm, &opts);
}
}
```
--------------------------------
### mg_wifi_ap_start
Source: https://mongoose.ws/docs/api/wifi
Starts the device as a Wi-Fi Access Point (AP) mode. The configuration for the AP, such as SSID and password, is provided via a `mg_wifi_data` structure.
```APIDOC
## mg_wifi_ap_start()
### Description
Start being an Access Point (AP mode), as defined by the argument.
### Method
`bool mg_wifi_ap_start(struct mg_wifi_data *wifi);
`
### Parameters
* **wifi** (`struct mg_wifi_data *`) - Required - Pointer to a structure containing AP configuration details, including SSID, password, IP address, and security settings.
```
--------------------------------
### JSON-RPC Get All Fields Request
Source: https://mongoose.ws/docs/api/dash
Example of a JSON-RPC 'get' request to fetch all data fields from the device. The response includes the requested fields and their current values.
```json
{"id": 1, "method": "get"}
```
```json
{"id": 1, "result": {"led1": true, "led2": false, "volume": 17}}
```
--------------------------------
### JSON-RPC Get Specific Field Request
Source: https://mongoose.ws/docs/api/dash
Example of a JSON-RPC 'get' request to fetch a specific data field ('volume') from the device. The response contains only the requested field.
```json
{"id": 1, "method": "get", "params": "volume"}
```
```json
{"id": 1, "result": {"volume": 17}}
```
--------------------------------
### Mongoose Pico W Wi-Fi Configuration Macro
Source: https://mongoose.ws/docs/guides/rp-tcpip-stack
Defines a macro to integrate the Pico W Wi-Fi configuration function into the Mongoose setup.
```c
extern void wifi_setconfig(void *data);
#define MG_SET_WIFI_CONFIG(data) wifi_setconfig(data)
```
--------------------------------
### Start Access Point Mode
Source: https://mongoose.ws/docs/api/wifi
Initiates the device to act as a WiFi Access Point (AP mode). Configuration details for the AP should be provided in the 'struct mg_wifi_data' argument.
```c
bool mg_wifi_ap_start(struct mg_wifi_data *wifi);
```
--------------------------------
### mg_mqtt_connect()
Source: https://mongoose.ws/docs/api/mqtt
Creates a client MQTT connection to a broker. It allocates resources and initiates the TCP connection process. After a successful TCP connection, an MG_EV_CONNECT event is sent, followed by the MQTT connection process. Upon a successful MQTT connection response, an MG_EV_MQTT_OPEN event is sent.
```APIDOC
## mg_mqtt_connect()
### Description
Creates a client MQTT connection to a broker. It allocates resources and initiates the TCP connection process. After a successful TCP connection, an MG_EV_CONNECT event is sent, followed by the MQTT connection process. Upon a successful MQTT connection response, an MG_EV_MQTT_OPEN event is sent.
### Method
`struct mg_connection *mg_mqtt_connect(struct mg_mgr *mgr, const char *url, const struct mg_mqtt_opts *opts, mg_event_handler_t fn, void *fn_data);`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
* `mgr` - Event manager to use.
* `url` - Specifies the broker URL, e.g. `mqtt://cloud.hivemq.com`. If this URL is 'mqtts', the `is_tls` flag will be set. See mg_connect().
* `opts` - Pointer to MQTT options like client ID, clean session, last will, etc. Can be NULL.
* `fn` - The event handler function.
* `fn_data` - An arbitrary pointer, which will be stored in the connection structure as `c->fn_data`, so the event handler can use it when called.
### Return Value
Created connection, or `NULL` on error. Possible errors are: not enough memory, a NULL URL, or, in the case of our built-in TCP/IP stack, the network not being ready.
### Note
This function does not connect to a broker; it allocates the required resources and starts the TCP connection process. Once that connection is established, an `MG_EV_CONNECT` event is sent to the connection event handler, then the MQTT connection process is started (by means of mg_mqtt_login()); and once the MQTT connection request gets a response from the broker, an `MG_EV_MQTT_OPEN` event is sent to the connection event handler; connection results are inside a struct mg_mqtt_message.
### Usage Example
```c
void fn(struct mg_connection *c, int ev, void *ev_data, void *fnd) {
if (ev == MG_EV_CONNECT) {
// TCP connection succeeded,
// If target URL is TLS, set it up
} else if (ev == MG_EV_MQTT_OPEN) {
// MQTT connection process finished
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
if(mm->ack) // MQTT connection succeeded
}
}
```
```c
mg_mqtt_connect(&mgr, "mqtt://test.org:1883", NULL, fn, NULL);
```
or
```c
struct mg_mqtt_opts opts = {.qos = 1,
.retain = true,
.topic = mg_str("mytopic"),
.message = mg_str("goodbye")};
mg_mqtt_connect(&mgr, "mqtt://test.org:1883", &opts, fn, NULL);
```
```
--------------------------------
### Connect to MQTT Broker (Default Options)
Source: https://mongoose.ws/docs/api/mqtt
Connects to an MQTT broker using default options.
```c
mg_mqtt_connect(&mgr, "mqtt://test.org:1883", NULL, fn, NULL);
```
--------------------------------
### mg_mqtt_listen()
Source: https://mongoose.ws/docs/api/mqtt
Creates an MQTT listener, allowing the system to act as an MQTT broker. It listens on a specified local IP address and port for incoming MQTT connections.
```APIDOC
## mg_mqtt_listen()
### Description
Creates an MQTT listener (act like a broker). It listens on a specified local IP address and port for incoming MQTT connections.
### Method
`struct mg_connection *mg_mqtt_listen(struct mg_mgr *mgr, const char *url, mg_event_handler_t fn, void *fn_data);
`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
* `mgr` - Event manager to use.
* `url` - Specifies the local IP address and port to listen on, e.g. `mqtt://0.0.0.0:1883`. If this URL is 'mqtts', the `is_tls` flag will be set.
* `fn` - The event handler function.
* `fn_data` - An arbitrary pointer, which will be stored in the connection structure as `c->fn_data`, so the event handler can use it when called.
### Return Value
Pointer to the created connection or `NULL` on error.
### Usage Example
```c
struct mg_connection *c = mg_mqtt_listen(&mgr, "mqtt://0.0.0.0:1883", fn, arg);
if (c == NULL) return -1; // Could not create connection
```
```
--------------------------------
### Modbus Event Handler Example
Source: https://mongoose.ws/docs/api/util
An example event handler function for Modbus requests. It processes `MG_EV_MODBUS_REQ` events, checking the function code and setting coil values or error codes.
```c
static void modbus_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_MODBUS_REQ) {
struct mg_modbus_req *mr = (struct mg_modbus_req *) ev_data;
if (mr->func == MG_MODBUS_FUNC_READ_COILS) {
for (uint16_t i = 0; i < mr->len; i++) {
mr->u.bits[i] = 1;
}
} else {
mr->error = MG_MODBUS_ERR_DEVICE_FAILURE;
}
}
}
```
--------------------------------
### mg_md5_init()
Source: https://mongoose.ws/docs/api/util
Initializes a context for MD5 hashing.
```APIDOC
## mg_md5_init()
### Description
Initialize context for MD5 hashing.
### Parameters
- **c** (*mg_md5_ctx ") - Pointer to `mg_md5_ctx` structure to initialize
### Return value
None
### Usage example
```c
mg_md5_ctx ctx;
mg_md5_init(&ctx);
```
```
--------------------------------
### mg_mgr_init()
Source: https://mongoose.ws/docs/api/core/content.html
Initializes an event manager structure, setting up default DNS servers and timeouts.
```APIDOC
## mg_mgr_init()
### Description
Initializes event manager structure: sets a list of active connections to NULL, sets default DNS servers for IPv4 and IPv6, and sets default DNS lookup timeout.
### Method
`void mg_mgr_init(struct mg_mgr *mgr)`
### Parameters
* `mgr` - a pointer to `mg_mgr` structure that needs to be initialized
### Return value
none
### Usage example
```c
struct mg_mgr mgr;
mg_mgr_init(&mgr);
```
```
--------------------------------
### Get Uptime in Milliseconds
Source: https://mongoose.ws/docs/api/time
Retrieves the current system uptime in milliseconds. No parameters are required.
```c
uint64_t mg_millis(void);
```
```c
uint64_t uptime = mg_millis();
```
--------------------------------
### Connect to MQTT Broker (Custom Options)
Source: https://mongoose.ws/docs/api/mqtt
Connects to an MQTT broker with custom options, including QoS, retain flag, topic, and message.
```c
struct mg_mqtt_opts opts = {.qos = 1,
.retain = true,
.topic = mg_str("mytopic"),
.message = mg_str("goodbye")};
mg_mqtt_connect(&mgr, "mqtt://test.org:1883", &opts, fn, NULL);
```
--------------------------------
### mg_modbus_listen
Source: https://mongoose.ws/docs/api/util
Starts a Modbus-TCP listener. When a Modbus-TCP request arrives, Mongoose calls the provided event handler function.
```APIDOC
## mg_modbus_listen
### Description
Starts a Modbus-TCP listener. When a Modbus-TCP request arrives, Mongoose calls the provided event handler function.
### Parameters
* `mgr` - Event manager
* `url` - Listening URL
* `fn` - Event handler function. Should catch `MG_EV_MODBUS_REQ` and process `struct mg_modbus_req *` passed as `ev_data`
* `fn_data` - Arbitrary user data
### Return Value
listening connection or NULL
### Usage Example
```c
static void modbus_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_MODBUS_REQ) {
struct mg_modbus_req *mr = (struct mg_modbus_req *) ev_data;
if (mr->func == MG_MODBUS_FUNC_READ_COILS) {
for (uint16_t i = 0; i < mr->len; i++) {
mr->u.bits[i] = 1;
}
} else {
mr->error = MG_MODBUS_ERR_DEVICE_FAILURE;
}
}
}
/// ...
mg_modbus_listen(&g_mgr, "tcp://0.0.0.0:502", modbus_ev_handler, NULL);
```
```
--------------------------------
### mg_path_is_sane()
Source: https://mongoose.ws/docs/api/string
Checks if a Mongoose path string `path` is "sane" by verifying it does not start with double dots.
```APIDOC
## mg_path_is_sane() API
### Description
Check `path` for starting with double dots in it.
### Parameters
#### Path Parameters
* `path` (struct mg_str) - Mongoose string to check
### Return Value
true if OK, false otherwise
### Usage Example
```c
char data[] = "../../a.txt";
bool res = mg_path_is_sane(mg_str(data)); // returns false
```
```
--------------------------------
### Example mongoose_config.h for STM32
Source: https://mongoose.ws/docs/getting-started/build-options
This configuration is for an STM32 firmware project using the Cube framework. It sets the build environment, IO buffer size, TLS support, TCP/IP stack, and specific STM32H5 drivers.
```c
#define MG_ARCH MG_ARCH_CUBE // Build environment is Cube
#define MG_IO_SIZE 1024 // IO buffer growth granularity is 1Kb
#define MG_TLS MG_TLS_BUILTIN // Use built-in TLS 1.3 stack
#define MG_ENABLE_TCPIP 1 // Use built-in TCP/IP stack
#define MG_ENABLE_DRIVER_STM32H5 1 // With STM32H5 ethernet driver
#define MG_OTA MG_OTA_STM32H5 // Use built-in OTA for STM32H5
```
--------------------------------
### Get HTTP Request Length
Source: https://mongoose.ws/docs/api/http
Calculates the length of the HTTP request headers within a buffer. It does not include the body.
```c
int mg_http_get_request_len(const unsigned char *buf, size_t buf_len);
```
```c
const char *buf = "GET /test \n\nGET /foo\n\n";
int req_len = mg_http_get_request_len(buf, strlen(buf)); // req_len == 12
```
--------------------------------
### Initialize Dashboard UI with JavaScript
Source: https://mongoose.ws/docs/api/dash
Include the dashboard.js library and initialize the Dashboard with debug mode and initial data. This script should be added to your web UI.
```html
```
--------------------------------
### Bundle UI with inline.js
Source: https://mongoose.ws/docs/api/dash
Bundles a UI into a single HTML file using the inline.js tool. This is a prerequisite for embedding the UI into firmware.
```shell
curl -sO https://raw.githubusercontent.com/cesanta/mongoose/master/resources/inline.js
node inline.js dashboard.html > inline.html
```
--------------------------------
### REST API 'data' Type Configuration
Source: https://mongoose.ws/docs/guides/web-ui-builder
Example configuration for a 'data' type REST API endpoint named 'settings'.
```json
"settings": {
"type": "data",
"attributes": {
"level": { "type": "int", "value": 42},
"name": { "type": "string", "value": "unit1", "size": 20}
}
}
```
--------------------------------
### Configuration File Structure
Source: https://mongoose.ws/docs/guides/web-ui-builder
The main configuration file defines various sections for API, UI, and protocol support.
```json
{
"version": "1.0.1", // format version
"api": { ... }, // RESTful API definitions
"ui": { ... }, // Web UI controls
"http": { ... }, // HTTP protocol support
"mqtt": { ... }, // MQTT protocol support
"dns": { ... }, // DNS/MDNS protocol support
"sntp": { ... }, // SNTP (network time sync) protocol protocol support
"modbus": { ... }, // Modbus-TCP protocol support
"build": { ... } // Target hardware, IDE, OS
}
```
--------------------------------
### Sending a Formatted JSON Response
Source: https://mongoose.ws/docs/api/http
Example of constructing a JSON string using mg_mprintf and sending it as an HTTP response with mg_http_reply.
```c
char *json = mg_mprintf("{%m:%d}", MG_ESC("name"), 123);
mg_http_reply(c, 200, "Content-Type: application/json\r\n", "%s\n", json);
mg_free(json);
```
--------------------------------
### mg_tls_init()
Source: https://mongoose.ws/docs/api/tls
Initializes TLS on a given connection using the provided TLS options.
```APIDOC
## mg_tls_init()
### Description
Initialise TLS on a given connection.
### Parameters
- **c** (struct mg_connection *) - Connection, for which TLS should be initialized.
- **opts** (const struct mg_tls_opts *) - TLS initialization parameters.
### Return Value
None
### Usage Example
```c
// client event handler:
if (ev == MG_EV_CONNECT) {
struct mg_tls_opts opts = {.ca = mg_str(s_tls_ca)};
mg_tls_init(c, &opts);
}
// server event handler:
if (ev == MG_EV_ACCEPT) {
struct mg_tls_opts opts = {.cert = mg_str(s_tls_cert),
.key = mg_str(s_tls_key)};
mg_tls_init(c, &opts);
}
```
**Note**: The mbedTLS implementation uses `mg_random` as RNG. The `mg_random` function can be overridden by setting `MG_ENABLE_CUSTOM_RANDOM=1` and defining your own `mg_random()` implementation.
```
--------------------------------
### AI-Driven Dashboard Modification Prompt
Source: https://mongoose.ws/docs/guides/web-dashboard-guide
Example prompt for AI to apply changes from AGENTS.md and modify the dashboard theme to dark.
```bash
Read and apply https://github.com/cesanta/mongoose/blob/master/AGENTS.md
Change dashboard.html, make HTML theme dark
```
--------------------------------
### Custom Modbus API Handler
Source: https://mongoose.ws/docs/guides/web-ui-builder
Example of a custom Modbus handler in C for reading coils. Requires mongoose_init() and mongoose_set_modbus_handler().
```c
// See modbus definitions at https://github.com/cesanta/mongoose/blob/modbus/src/modbus.h
static void my_modbus_handler(struct mg_modbus_req *req) {
if (req->func == MG_MODBUS_FUNC_READ_COILS) {
for (uint16_t i = 0; i < req->len; i++) {
req->u.bits[i] = READ_COIL(i);
}
} else {
req->error = MG_MODBUS_ERR_DEVICE_FAILURE;
}
}
// ....
mongoose_init();
mongoose_set_modbus_handler(my_modbus_handler); // <-- Add this
```
--------------------------------
### mg_ota_end()
Source: https://mongoose.ws/docs/api/ota
Finalizes the firmware update session, verifying the written firmware and preparing it for boot.
```APIDOC
## mg_ota_end()
Finalize the firmware update session. This function verifies the written firmware and prepares it for boot.
### Function Signature
```c
bool mg_ota_end(void);
```
### Return Value
* `true` on success, `false` on failure.
### Usage Example
```c
if (mg_ota_end()) {
// Firmware update complete, reboot to apply
} else {
// OTA end failed
}
```
```
--------------------------------
### Delete RPC Method Usage Example
Source: https://mongoose.ws/docs/api/json-rpc
Shows how to remove a specific RPC handler ('rpc_mul') or all RPC handlers from the list.
```c
struct mg_rpc *s_rpc_head = NULL;
// add methods
// ...
// Time to cleanup
mg_rpc_del(&s_rpc_head, rpc_mul); // Deallocate specific handler
mg_rpc_del(&s_rpc_head, NULL); // Deallocate all RPC handlers
```
--------------------------------
### REST API 'array' Type Configuration
Source: https://mongoose.ws/docs/guides/web-ui-builder
Example configuration for a 'sensors' REST API endpoint of type 'array' (used for sensors).
```json
"wifi": {
"type": "sensors",
"attributes": {
"type": { "type": "int", "value": 10},
"name": { "type": "string", "value": "temp1", "size": 20}
}
}
```
--------------------------------
### Generate Keys and Sign Firmware
Source: https://mongoose.ws/docs/guides/firmware-ota-updates
Use the sign.js script to generate ECDSA-P256 keys and sign firmware binaries. The private key is kept secure on the build machine.
```bash
node sign.js keygen # generate private.pem, print public key #define
node sign.js sign firmware.bin # append 64-byte signature
```
--------------------------------
### Clone Mongoose Git Repository
Source: https://mongoose.ws/docs/guides/stm32-cubeide-mongoose
Clones the Mongoose library repository from GitHub. This is a prerequisite for importing Mongoose examples into your STM32CubeIDE workspace.
```bash
git clone https://github.com/cesanta/mongoose
```
--------------------------------
### mg_iobuf_init()
Source: https://mongoose.ws/docs/api/core/content.html
Initializes a generic IO buffer structure, allocating a specified amount of memory for data storage.
```APIDOC
### mg_iobuf_init()
### Description
Initialize IO buffer, allocate `size` bytes.
### Parameters
* `io` - Pointer to `mg_iobuf` structure to initialize
* `size` - Amount of bytes to allocate
* `align` - Align `size` to the `align` mem boundary. `0` means no alignment
### Return Value
1 on success, 0 on allocation failure
### Usage Example
```c
struct mg_iobuf io;
if (mg_iobuf_init(&io, 0, 64)) {
// io successfully initialized
}
```
```
--------------------------------
### mg_http_start_ota()
Source: https://mongoose.ws/docs/api/http
Starts streaming an HTTP request or response body into the OTA writer. This is intended to be called from `MG_EV_HTTP_HDRS` after headers are available and the firmware image size is known from `Content-Length`. It handles the OTA begin, write, and end process, with a callback for completion status.
```APIDOC
## mg_http_start_ota()
### Description
Starts streaming an HTTP request or response body into the OTA writer. This helper is intended to be called from `MG_EV_HTTP_HDRS`, after the headers are available and the firmware image size is known from `Content-Length`. The function calls `mg_ota_begin(hm->body.len)`, streams incoming body data with `mg_ota_write()`, then calls `mg_ota_end()` when all expected bytes have been received. The completion callback receives `NULL` on success, or an error message on failure.
### Parameters
#### Parameters
- **c** (`struct mg_connection *`) - a connection
- **hm** (`struct mg_http_message *`) - a parsed HTTP message
- **fn** (`void (*)(struct mg_connection *, const char *)`) - completion callback; receives `NULL` on success, or an error message on failure
### Return value
none
### Usage example
```c
static void ota_done(struct mg_connection *c, const char *errmsg) {
mg_http_reply(c, errmsg == NULL ? 200 : 500, "", "%s\n",
errmsg == NULL ? "ok" : errmsg);
c->is_draining = 1;
}
static void fn(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_HTTP_HDRS) {
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_match(hm->uri, mg_str("/ota"), NULL)) {
mg_http_start_ota(c, hm, ota_done);
}
}
}
```
```
--------------------------------
### Sending a 302 Redirect Response
Source: https://mongoose.ws/docs/api/http
Example of using mg_http_reply to send a 302 Found status code with a 'Location' header for redirection.
```c
mg_http_reply(c, 302, "Location: /\r\n", "");
```
--------------------------------
### mg_http_start_ota Function Signature
Source: https://mongoose.ws/docs/api/http
The signature for starting an HTTP OTA stream. It takes a connection, parsed HTTP message, and a completion callback.
```c
void mg_http_start_ota(struct mg_connection *c, struct mg_http_message *hm,
void (*fn)(struct mg_connection *, const char *));
```
--------------------------------
### Minimal HTTP Server in C
Source: https://mongoose.ws/docs/guides/html-css-js-flash-embedded-web-server
A basic Mongoose HTTP server that replies with 'Hello world' to any request. Suitable for simple demonstrations.
```c
#include "mongoose.h"
static void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_HTTP_MSG) {
mg_http_reply(c, 200, "", "%s", "Hello world");
}
}
int main() {
struct mg_mgr mgr;
mg_mgr_init(&mgr);
mg_http_listen(&mgr, "http://0.0.0.0:8000", ev_handler, NULL);
for (;;) {
mg_mgr_poll(&mgr, 100);
}
return 0;
}
```
--------------------------------
### Initiate WiFi Scan
Source: https://mongoose.ws/docs/api/wifi
Call this function to start scanning for available WiFi networks. This function must be called while in AP mode.
```c
bool mg_wifi_scan(void);
```
--------------------------------
### Sending an HTTP Error Response
Source: https://mongoose.ws/docs/api/http
Example of using mg_http_reply to send a 403 Forbidden status code with a simple error message body.
```c
mg_http_reply(c, 403, "", "%s", "Not Authorized\n");
```
--------------------------------
### Custom Data API Handlers for LED Control
Source: https://mongoose.ws/docs/guides/web-ui-builder
Example of implementing custom C handlers to control an LED via the data API. This involves reading hardware state and applying it to hardware. Requires mongoose_init() and mongoose_set_http_handlers().
```c
void my_get_leds(struct leds *leds) {
leds->led1 = gpio_read(LED1); // Read hardware state
}
void my_set_leds(struct leds *leds) {
gpio_write(LED1, leds->led1); // Apply state to hardware
}
// ....
mongoose_init();
mongoose_set_http_handlers("leds", my_get_leds, my_set_leds); // <-- Add this
```
--------------------------------
### Sending a Simple JSON Response
Source: https://mongoose.ws/docs/api/http
Example of using mg_http_reply to send a 200 OK status with JSON content and a dynamic integer value.
```c
mg_http_reply(c, 200, "Content-Type: application/json\r\n", "{\"result\": %d}", 123);
```
--------------------------------
### Minimal HTTP/HTTPS Server with Mongoose
Source: https://mongoose.ws/docs/concepts/event-driven-architecture
This example demonstrates a basic Mongoose application that sets up both HTTP and HTTPS servers. It registers a single event handler to respond to incoming HTTP messages with a 'Hello world' reply. Each call to mg_mgr_poll processes network events and dispatches them to the appropriate handlers.
```c
#include "mongoose.h"
static void http_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_HTTP_MSG) {
mg_http_reply(c, 200, "", "Hello world\n");
}
}
int main(void) {
struct mg_mgr mgr;
mg_mgr_init(&mgr);
mg_http_listen(&mgr, "http://0.0.0.0:8000", http_ev_handler, NULL);
mg_http_listen(&mgr, "https://0.0.0.0:8443", http_ev_handler, NULL);
for (;;) {
mg_mgr_poll(&mgr, 100);
}
return 0;
}
```