### Start ESP-NOW Module Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/07-esp-now-module.md Initializes the ESP-NOW protocol stack, encryption keys, and message queues. It also starts the dedicated ESP-NOW processing task. ```APIDOC ## db_start_espnow_module ### Description Initializes ESP-NOW protocol stack, encryption keys, and message queues. Starts the ESP-NOW processing task. ### Method void ### Parameters None ### Returns void ### Initialization Steps 1. Initialize FreeRTOS queues for send/receive 2. Initialize ESP-NOW protocol 3. Configure encryption (AES-GCM 256-bit) 4. Register receive/send callbacks 5. Create processing task (calls `process_espnow_data()`) ### Configuration Sources - Wireless mode: `DB_PARAM_RADIO_MODE` (ESP-NOW Air or Ground) - Channel: `DB_PARAM_CHANNEL` (1-13) ``` -------------------------------- ### Example: Add UDP Client Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/05-network-control-module.md Provides an example of how to populate and add a UDP client structure to the known clients list. It sets the client's IP, port, and MAC address. ```c struct db_udp_client_t client = {0}; client.udp_client.sin_family = AF_INET; client.udp_client.sin_port = htons(14550); client.udp_client.sin_addr.s_addr = inet_addr("192.168.2.100"); memcpy(client.mac, gcs_mac_address, 6); add_to_known_udp_clients(udp_conn_list, client, false); ``` -------------------------------- ### Start REST Server Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md Initializes the HTTP server with configured handlers for the web interface and REST API. It registers URI handlers for static files and API endpoints, configures the base path for static content, and starts the server on port 80. ```APIDOC ## start_rest_server ### Description Initializes HTTP server with configured handlers for web interface and REST API. ### Method POST ### Endpoint N/A (Function call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (ESP_OK) - **ESP_OK** (esp_err_t) - Indicates successful initialization. #### Response Example ESP_OK ``` -------------------------------- ### GET Static File Response Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md This is an example of a successful response when requesting a static file. The Content-Length indicates the size of the file being sent. ```http HTTP/1.1 200 OK Content-Type: text/html Content-Length: 2048 [HTML content streamed in chunks] ``` -------------------------------- ### Start ESP-NOW Module Function Signature Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/07-esp-now-module.md This is the function signature for initializing the ESP-NOW module. It sets up the protocol stack, encryption, and message queues, then starts the processing task. ```c void db_start_espnow_module(void); ``` -------------------------------- ### Start REST Server Function Signature Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md This function initializes the HTTP server with handlers for the web interface and REST API. It requires a base path for static content. ```c esp_err_t start_rest_server(const char *base_path); ``` -------------------------------- ### Start Network Control Module Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/05-network-control-module.md Starts the main control task for managing WiFi clients, UDP I/O, and telemetry routing. This function creates a FreeRTOS task and initializes UDP communication. ```c void db_start_control_module(void); ``` -------------------------------- ### BLE Initialization Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/08-ble-interface.md Initializes the BLE stack, configures GATT services and characteristics, and starts advertising. This function must be called once during firmware startup if BLE mode is enabled. ```APIDOC ## db_ble_init ### Description Initializes the BLE stack, configures GATT services/characteristics, and starts advertising. Must be called once during firmware startup if BLE mode is enabled. ### Signature ```c void db_ble_init(void); ``` ### Parameters None ### Returns void ### Initialization Sequence 1. Initialize NimBLE stack (Bluetooth Core Specification v5.x) 2. Configure GAP (advertiser name, appearance) 3. Create GATT server with serial service 4. Add characteristics (write, notify) 5. Register write/read/notify callbacks 6. Start advertising (undirected, connectable) ### Advertising Parameters - Advertisement Type: Connectable Undirected - Address Type: Random or Public - Advertisement Interval: Configurable (default 100ms) ### GATT Database Single primary service (0xDB32) with two characteristics ### Prerequisite `db_ble_queue_init()` must be called first ``` -------------------------------- ### MAVLink Transparent Bridge Usage Example Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/04-serial-interface.md Demonstrates initializing a serial socket, reading data, parsing it based on the configured protocol (MAVLink, MSPLTM, or transparent), and writing a response back to the serial port. Ensure the serial socket is opened successfully before proceeding to the data loop. ```c // Initialize int uart_fd = open_serial_socket(); if (uart_fd < 0) { ESP_LOGE(TAG, "Failed to open serial"); return; } // Main data loop uint8_t serial_buffer[UART_BUF_SIZE]; unsigned int buff_pos = 0; int bytes_read = uart_read_bytes(UART_NUM, serial_buffer, UART_BUF_SIZE, 100); if (bytes_read > 0) { buff_pos = bytes_read; // Parse based on configured protocol if (DB_PARAM_SERIAL_PROTO == DB_SERIAL_PROTOCOL_MAVLINK) { db_read_serial_parse_mavlink(tcp_clients, udp_conns, serial_buffer, &buff_pos); } else if (DB_PARAM_SERIAL_PROTO == DB_SERIAL_PROTOCOL_MSPLTM) { db_parse_msp_ltm(tcp_clients, udp_conns, serial_buffer, &buff_pos, &msp_ltm_port); } else { db_read_serial_parse_transparent(tcp_clients, udp_conns, serial_buffer, &buff_pos); } } // Send response back to flight controller uint8_t response[256]; int response_len = prepare_response(response); write_to_serial(response, response_len); ``` -------------------------------- ### db_start_control_module Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/05-network-control-module.md Starts the main control task for network operations. This includes managing WiFi clients, handling UDP I/O, and routing telemetry data between UART and wireless interfaces. ```APIDOC ## db_start_control_module ### Description Starts the main control task that manages WiFi client connections, UDP socket I/O, and telemetry routing between UART and wireless interfaces. ### Signature ```c void db_start_control_module(void); ``` ### Parameters None ### Returns void ### Behavior - Creates FreeRTOS task for control loop - Opens UDP socket on port 14550 (MAVLink telemetry) - Initializes UDP client list - Enters main loop reading from UART and UDP sockets - Routes data based on protocol and current wireless mode ``` -------------------------------- ### CMake Boilerplate and Frontend Build Setup Source: https://github.com/dronebridge/esp32/blob/master/CMakeLists.txt Essential CMake boilerplate and custom targets for building the frontend using npm. This setup ensures the frontend build artifacts are correctly placed within the project structure. ```cmake cmake_minimum_required(VERSION 3.10) add_custom_target( frontend # add final and temporary build directory for the frontend. That way npm does not need to know the CMAKE_BINARY_DIR which can variable COMMAND cmake -E make_directory "${CMAKE_BINARY_DIR}/frontend" COMMAND cmake -E make_directory "${CMAKE_SOURCE_DIR}/frontend/build" # Run frontend npm build process COMMAND npm install && npm run build WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/frontend") # Copy the content of npm to the build directory add_custom_command( TARGET frontend POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/frontend/build" "${CMAKE_BINARY_DIR}/frontend") # delete npm temp build folder add_custom_command ( TARGET frontend POST_BUILD COMMAND cmake -E remove_directory "${CMAKE_SOURCE_DIR}/frontend/build" ) set(PROJECT_VER "2.2.1 (stable)") include($ENV{IDF_PATH}/tools/cmake/project.cmake) project(db_esp32) ``` -------------------------------- ### Initialize BLE Stack Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/08-ble-interface.md Initializes the BLE stack, configures GATT services and characteristics, and starts advertising. Must be called once during firmware startup if BLE mode is enabled. Prerequisite: db_ble_queue_init() must be called first. ```c void db_ble_init(void); ``` -------------------------------- ### WiFi RSSI Timer Start Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/10-utility-modules.md Starts a periodic timer to measure WiFi RSSI. The measurement updates the `db_esp_signal_quality.air_rssi` value. ```APIDOC ## db_timer_start_wifi_rssi_timer ### Description Starts a periodic timer that measures WiFi RSSI. The measured value is used to update `db_esp_signal_quality.air_rssi`. ### Signature ```c void db_timer_start_wifi_rssi_timer(void); ``` ### Period 1000ms ``` -------------------------------- ### Start Status LED Timer Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/10-utility-modules.md Starts a periodic timer for processing LED state updates, specifically for ESP32-C6 with an onboard status LED. This function calls db_status_led_process() every 1000ms. ```c void db_timer_start_status_led(void); ``` -------------------------------- ### GET Static File Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md Serves static files from the system, such as the main HTML page. ```APIDOC ## GET /index.html ### Description Serves the main index HTML file. ### Method GET ### Endpoint /index.html ### Response #### Success Response (200) - **Content-Type** (string) - The MIME type of the file being served. - **Content-Length** (integer) - The size of the file in bytes. - **Body** (stream) - The content of the HTML file. #### Response Example ``` HTTP/1.1 200 OK Content-Type: text/html Content-Length: 2048 [HTML content streamed in chunks] ``` ``` -------------------------------- ### Status LED Timer Start (ESP32-C6) Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/10-utility-modules.md Starts a periodic timer to process the status LED state, specifically for the ESP32-C6 with an onboard status LED. This function drives the LED blinking patterns. ```APIDOC ## db_timer_start_status_led ### Description Starts a periodic timer that calls `db_status_led_process()` to update the status LED's blinking pattern. This is primarily used on the ESP32-C6 with an onboard status LED. ### Signature ```c void db_timer_start_status_led(void); ``` ### Period 1000ms ### Action Calls `db_status_led_process()` to update the LED blinking pattern. ``` -------------------------------- ### Send Telemetry via ESP-NOW Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/07-esp-now-module.md Example of preparing and queuing a MAVLink message for transmission over ESP-NOW. The data is encrypted and sent by a separate task. ```c // Prepare a MAVLink message uint8_t mavlink_msg[256]; uint16_t msg_len = db_mav_create_heartbeat(mavlink_msg, &fmav_status); // Queue for ESP-NOW transmission db_espnow_queue_event_t tx_event = { .data_len = msg_len, .data = malloc(msg_len), .packet_type = DB_ESP_NOW_PACKET_TYPE_DATA }; memcpy(tx_event.data, mavlink_msg, msg_len); if (xQueueSend(db_espnow_send_queue, &tx_event, pdMS_TO_TICKS(100)) != pdPASS) { free(tx_event.data); // Queue full } // process_espnow_data() task will: // 1. Encrypt payload with AES-256-GCM // 2. Generate random IV // 3. Increment sequence number // 4. Send via ESP-NOW to configured peer/broadcast ``` -------------------------------- ### Start WiFi RSSI Timer Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/10-utility-modules.md Starts a periodic timer for WiFi RSSI measurement. This function updates the air_rssi value and samples the current RSSI from the WiFi interface every 1000ms. ```c void db_timer_start_wifi_rssi_timer(void); ``` -------------------------------- ### Byte-by-Byte MSP/LTM Parser Usage Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/10-utility-modules.md Example demonstrating how to use the `parse_msp_ltm_byte` function to process incoming UART bytes and detect complete MSP or LTM frames. ```c uint8_t byte; msp_ltm_port_t parser = {0}; while (uart_read_bytes(UART_NUM, &byte, 1, 10) > 0) { if (parse_msp_ltm_byte(&parser, byte)) { // Frame complete - process parser.inBuf or parser.ltm_frame_buffer if (parser.parse_state == MSP_PACKET_RECEIVED) { // Handle MSP message } else if (parser.parse_state == LTM_PACKET_RECEIVED) { // Handle LTM frame } parser.parse_state = IDLE; } } ``` -------------------------------- ### Start MAVLink Heartbeat Timer Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/10-utility-modules.md Starts a periodic timer to transmit heartbeat messages to the GCS. This ensures the GCS is aware the ESP32 is alive and enables system ID learning. ```c void db_timer_start_mavlink_heartbeat(void); ``` -------------------------------- ### Common GET Handler Function Signature Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md This handler serves static web content like HTML, CSS, and JavaScript. It constructs the file path, determines the MIME type, and streams the file content. ```c static esp_err_t rest_common_get_handler(httpd_req_t *req); ``` -------------------------------- ### Common GET Handler Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md Serves static web content including HTML, CSS, JavaScript, images, and icons. It parses the requested URI, constructs the file path, determines the MIME type, sets the Content-Type header, and streams the file content in chunks. Handles root path requests by serving index.html. ```APIDOC ## Common GET Handler ### Description Serves static web content (HTML, CSS, JavaScript, images, icons). ### Method GET ### Endpoint / * ### Parameters #### Path Parameters - **req** (httpd_req_t*) - Required - HTTP request context #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (ESP_OK) - **ESP_OK** (esp_err_t) - On success #### Response Example ESP_OK ### Error Handling - **404 Not Found**: File doesn't exist - **500 Internal Server Error**: File read failed ``` -------------------------------- ### GET Static File Request Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md Use this request to fetch static files, such as the main HTML page, from the web server. ```http GET /index.html HTTP/1.1 Host: dronebridge.local ``` -------------------------------- ### Initialize and Route MAVLink Telemetry Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/05-network-control-module.md Initializes UDP and TCP sockets, starts the control module, and routes MAVLink data from UART to connected clients. Ensure sockets are properly opened and the control loop is running. ```c // Initialization udp_conn_list = udp_client_list_create(); int udp_sock = db_open_serial_udp_socket(); int tcp_sock = open_tcp_server(APP_PORT_PROXY); db_start_control_module(); // Start main loop // In control loop - route MAVLink from UART to all clients uint8_t uart_buffer[512]; int bytes_read = read_from_uart(uart_buffer, 512); if (bytes_read > 0) { // Parse MAVLink, then broadcast to all clients db_send_to_all_clients(connected_tcp_clients, udp_conn_list, uart_buffer, bytes_read); } ``` -------------------------------- ### MAVLink Radio Status Timer Start Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/10-utility-modules.md Starts a periodic timer to send signal quality metrics to the GCS via the RADIO_STATUS MAVLink message. This provides real-time link quality feedback. ```APIDOC ## db_timer_start_mavlink_radio_status ### Description Starts a periodic timer that transmits signal quality metrics to the GCS using the RADIO_STATUS MAVLink message. This provides real-time link quality feedback in applications like QGroundControl. ### Signature ```c void db_timer_start_mavlink_radio_status(void); ``` ### Period 1000ms ### Payload - RSSI (air to ESP32) - Noise floor - Packet loss count - TX/RX status ``` -------------------------------- ### WiFi Operating Modes (E_DB_WIFI_MODE) Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/02-types-and-structures.md Enumeration for selecting the wireless operating mode. Controls WiFi initialization and the wireless driver started. Set via the db_param_radio_mode parameter and takes effect after reboot. ```c enum E_DB_WIFI_MODE { DB_WIFI_MODE_AP = 1, // WiFi access point mode (802.11b) DB_WIFI_MODE_STA = 2, // WiFi client mode (802.11b + LR enabled) DB_WIFI_MODE_AP_LR = 3, // ESP32 WiFi LR Mode (802.11b) DB_WIFI_MODE_ESPNOW_AIR = 4, // ESP-NOW Mode (broadcaster/drone) DB_WIFI_MODE_ESPNOW_GND = 5, // ESP-NOW Mode (ground station) DB_BLUETOOTH_MODE = 6, // Bluetooth BLE mode DB_WIFI_MODE_END = 7, // Enum sentinel }; ``` -------------------------------- ### Initialize and Use UDP Client List Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/05-network-control-module.md Demonstrates the creation of a UDP client list and handles potential allocation failures. This snippet shows how to initialize the list and check for errors. ```c udp_conn_list = udp_client_list_create(); if (udp_conn_list == NULL) { ESP_LOGE(TAG, "Failed to create UDP client list"); return; } ``` -------------------------------- ### Initialize Firmware Parameters Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/03-parameters-configuration.md Initializes all firmware parameters, including metadata, MAVLink bindings, and string parameter storage. Must be called once at startup. ```c void db_param_init_parameters(void); ``` -------------------------------- ### MAVLink Heartbeat Timer Start Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/10-utility-modules.md Starts a periodic timer to transmit MAVLink heartbeat messages. This ensures the Ground Control Station (GCS) is aware the system is alive. ```APIDOC ## db_timer_start_mavlink_heartbeat ### Description Starts a periodic timer to transmit MAVLink heartbeat messages to the GCS. This function is crucial for maintaining system awareness and enabling GCS to learn the system ID. ### Signature ```c void db_timer_start_mavlink_heartbeat(void); ``` ### Period 1000ms ### Action Calls `db_mav_create_heartbeat()` and broadcasts the message to all clients. ``` -------------------------------- ### Parameter Initialization Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/03-parameters-configuration.md Initializes all firmware parameters, setting up metadata, MAVLink bindings, and storage allocation. This function must be called once during startup. ```APIDOC ## Function: db_param_init_parameters ### Description Initializes all 25 firmware parameters. Must be called once during startup before parameters are accessed or stored. Sets up parameter metadata, MAVLink bindings, and allocates storage for string parameters. ### Signature ```c void db_param_init_parameters(void); ``` ### Parameters None ### Returns void ### Side Effects - Allocates heap memory for string parameter values - Populates `db_params[]` array of pointers - Initializes NVS handle for parameter storage ``` -------------------------------- ### Start MAVLink Radio Status Timer Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/10-utility-modules.md Starts a periodic timer to transmit signal quality metrics to the GCS via RADIO_STATUS message. This provides real-time link quality feedback. ```c void db_timer_start_mavlink_radio_status(void); ``` -------------------------------- ### Initial ESP32 Settings Load Source: https://github.com/dronebridge/esp32/blob/master/frontend/index.html Loads system information and settings when the page loads. It retries until successful. ```javascript // get settings once upon page load while (get_system_info() < 0) { } while (get_settings() < 0) { } ``` -------------------------------- ### Initialize and Use ESP32 BLE Interface Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/08-ble-interface.md This snippet shows how to initialize the BLE interface on firmware startup, process incoming BLE data in the main loop, send data via BLE, and retrieve the BLE signal strength. Ensure CONFIG_BT_ENABLED is defined for BLE functionality. ```c // On firmware startup #ifdef CONFIG_BT_ENABLED db_ble_queue_init(); db_ble_init(); // Starts advertising #endif // In main loop - process BLE RX from mobile db_ble_queue_event_t rx_event; if (xQueueReceive(db_uart_read_queue_ble, &rx_event, pdMS_TO_TICKS(10))) { // Data from mobile GCS write_to_serial(rx_event.data, rx_event.data_len); free(rx_event.data); } // In serial parser - send TX to mobile void send_to_ble(uint8_t *data, uint16_t len) { db_ble_queue_event_t tx_event = { .data_len = len, .data = malloc(len) }; memcpy(tx_event.data, data, len); xQueueSend(db_uart_write_queue_ble, &tx_event, pdMS_TO_TICKS(100)); } // Get signal quality for display int8_t ble_rssi; db_ble_request_rssi(&ble_rssi); ESP_LOGI(TAG, "BLE Signal: %d dBm", ble_rssi); ``` -------------------------------- ### Parameter System Integration (C) Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md These C functions demonstrate how the HTTP server interacts with the parameter management system to read and write settings. ```c // Read current settings for GET /api/settings db_param_write_all_params_json(&response_json); // Apply settings from POST /api/settings db_param_read_all_params_json(&request_json); // Persist changes db_param_write_all_params_nvs(&nvs_handle); ``` -------------------------------- ### Initialize Status LED Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/10-utility-modules.md Configures GPIO and PWM for LED control. This function sets up the LED GPIO pin and PWM timer if supported. ```c void db_status_led_init(void); ``` -------------------------------- ### Define Project Source Files Source: https://github.com/dronebridge/esp32/blob/master/main/CMakeLists.txt Lists the main source files for the ESP32 project. These files are compiled into the final firmware. ```cmake set(SRCS main.c tcp_server.c msp_ltm_serial.c http_server.c db_esp32_control.c db_crc.c db_esp_now.c db_serial.c db_mavlink_msgs.c db_parameters.c db_led_indicator.c db_timers.c ) ``` -------------------------------- ### Initialize BLE Queues Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/08-ble-interface.md Creates FreeRTOS queues for UART to BLE data transfer. Must be called before db_ble_init(). ```c void db_ble_queue_init(void); ``` -------------------------------- ### Create SPIFFS Partition Image for Web Deployment Source: https://github.com/dronebridge/esp32/blob/master/main/CMakeLists.txt If CONFIG_WEB_DEPLOY_SF is enabled, this command creates a SPIFFS (SPI Flash File System) image from the web frontend sources. This image is then included in the project's flash. ```cmake if(CONFIG_WEB_DEPLOY_SF) set(WEB_SRC_DIR "${CMAKE_BINARY_DIR}/frontend") spiffs_create_partition_image(www ${WEB_SRC_DIR} FLASH_IN_PROJECT DEPENDS frontend) endif() ``` -------------------------------- ### Get MAVLink System ID Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/06-mavlink-telemetry.md Retrieves the system ID for this device. This ID is normally set from the first MAVLink heartbeat received from the flight controller. ```APIDOC ## Get MAVLink System ID ### Description Returns the system ID for this device. The system ID is normally set from the first MAVLink heartbeat received from the flight controller via UART. ### Method `uint8_t db_get_mav_sys_id()` ### Parameters None ### Returns - **system_id** (uint8_t) - The system ID for this device (1-255). Defaults to 1 if no heartbeat is received. ### Usage All outgoing MAVLink messages use this system ID to maintain message associations in GCS. ``` -------------------------------- ### Get MAVLink Component ID Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/06-mavlink-telemetry.md Retrieves the component ID for this device in MAVLink messages. This ID uniquely identifies the ESP32 device within a system. ```APIDOC ## Get MAVLink Component ID ### Description Returns the component ID for this device in MAVLink messages. The component ID uniquely identifies the ESP32 device within a system (different from system ID which identifies the entire aircraft). ### Method `uint8_t db_get_mav_comp_id()` ### Parameters None ### Returns - **component_id** (uint8_t) - The component ID for this device. Typically MAV_COMP_ID_TELEMETRY_RADIO (68). ### Usage Set in MAVLink header `compid` field when constructing outgoing messages. ``` -------------------------------- ### Queue Initialization Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/08-ble-interface.md Creates FreeRTOS queues for UART to BLE data transfer. This function must be called before `db_ble_init()`. ```APIDOC ## db_ble_queue_init ### Description Creates FreeRTOS queues for UART ↔ BLE data transfer. Must be called before `db_ble_init()`. ### Signature ```c void db_ble_queue_init(void); ``` ### Parameters None ### Returns void ### Queues Created - `db_uart_write_queue_ble`: UART → BLE (5 events) - `db_uart_read_queue_ble`: BLE → UART (5 events) ### Element Size sizeof(db_ble_queue_event_t) ### Error Handling Logs failures; continues (non-critical) ``` -------------------------------- ### Parameter Persistence - Read All Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/03-parameters-configuration.md Reads all parameters from NVS into memory, typically used at startup to restore saved configuration. Requires an open NVS handle. ```APIDOC ## Function: db_param_read_all_params_nvs ### Description Reads all parameters from NVS into memory. Used at startup to restore saved configuration. ### Signature ```c void db_param_read_all_params_nvs(const nvs_handle_t *nvs_handle); ``` ### Parameters #### Path Parameters - **nvs_handle** (const nvs_handle_t*) - Required - Open NVS handle for "settings" namespace ### Returns void ### Side Effects Updates all 25 `db_parameter_t` values from stored NVS data. Missing keys are initialized to defaults. ``` -------------------------------- ### udp_client_list_create Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/05-network-control-module.md Allocates and initializes a UDP client connection list structure. This is used at startup to prepare for tracking connected GCS devices. ```APIDOC ## udp_client_list_create ### Description Allocates and initializes a UDP client connection list structure. Used at startup to prepare for tracking connected GCS devices. ### Signature ```c udp_conn_list_t *udp_client_list_create(void); ``` ### Parameters None ### Returns Pointer to newly allocated `udp_conn_list_t` structure, or NULL on allocation failure ### Initialization State - `.size = 0` (no clients initially) - `.db_udp_clients[]` zeroed - `.udp_socket = -1` (not yet bound) ### Memory Allocates sizeof(udp_conn_list_t) bytes on heap ``` -------------------------------- ### Get Parameter Value Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/06-mavlink-telemetry.md Retrieves a MAVLink parameter's value by its ID or index. This function is useful for Ground Control Station (GCS) requests or internal system checks. ```APIDOC ## Get Parameter Value ### Description Retrieves a parameter value by ID or index for GCS requests or internal use. ### Function Signature ```c MAV_PARAM_TYPE db_mav_get_parameter_value(float_int_union *float_int, const char *param_id, const int16_t param_index); ``` ### Parameters #### Input Parameters - **param_id** (const char*) - Optional - Parameter name to search for. If NULL, `param_index` is used. - **param_index** (int16_t) - Optional - Parameter index (0-16). Ignored if `param_id` is provided. #### Output Parameters - **float_int** (float_int_union*) - Output - Pointer to a union that will be populated with the parameter's value. ### Returns - **MAV_PARAM_TYPE** - An enum value indicating the type of the parameter retrieved: - `MAV_PARAM_TYPE_INT32`: Signed 32-bit integer - `MAV_PARAM_TYPE_UINT8`: Unsigned 8-bit integer - `MAV_PARAM_TYPE_UINT16`: Unsigned 16-bit integer - `MAV_PARAM_TYPE_REAL32`: Floating-point value (stored in the `f` member of the union) ### Lookup Method - If `param_id` is not NULL, the function searches for the parameter by its name. - If `param_id` is NULL, the function uses `param_index` to directly access the parameter. ### Example ```c float_int_union param_val; MAV_PARAM_TYPE type = db_mav_get_parameter_value(¶m_val, "SERIAL_BAUD", -1); if (type == MAV_PARAM_TYPE_INT32) { int32_t baud = param_val.i32; // Use baud rate } ``` ``` -------------------------------- ### Handle GCS Parameter Read Request Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/06-mavlink-telemetry.md Example of handling a MAVLink PARAM_REQUEST_READ message from a GCS to retrieve the SERIAL_BAUD parameter. The function `handle_mavlink_message` processes the request and sends a PARAM_VALUE response. ```c // GCS sends PARAM_REQUEST_READ for "SERIAL_BAUD" fmav_message_t gcs_msg; fmav_param_request_read_t req = { .target_system = 1, .target_component = 68, .param_index = 4, .param_type = MAV_PARAM_TYPE_INT32 }; memcpy(req.param_id, "SERIAL_BAUD", 11); // Process the request handle_mavlink_message(&gcs_msg, tcp_clients, udp_conns, &fmav_status, DB_MAVLINK_DATA_ORIGIN_RADIO); // Response: PARAM_VALUE message with current baud rate sent to all clients ``` -------------------------------- ### Parameter Persistence - Write All Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/03-parameters-configuration.md Writes all 25 parameters to Non-Volatile Storage (NVS) for persistent storage across reboots. Requires an open NVS handle. ```APIDOC ## Function: db_param_write_all_params_nvs ### Description Writes all 25 parameters to Non-Volatile Storage (NVS) for persistent storage across reboots. ### Signature ```c void db_param_write_all_params_nvs(const nvs_handle_t *nvs_handle); ``` ### Parameters #### Path Parameters - **nvs_handle** (const nvs_handle_t*) - Required - Open NVS handle for "settings" namespace ### Returns void ### Side Effects Writes up to 25 key-value pairs to NVS with keys from `db_parameter_t.db_name` ``` -------------------------------- ### LED Status Indicator Initialization Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/10-utility-modules.md Initializes the GPIO and PWM for the LED status indicator. This function must be called before any other LED control functions. ```APIDOC ## db_status_led_init ### Description Initializes the GPIO and PWM for LED control, supporting both on/off and brightness modulation. ### Signature ```c void db_status_led_init(void); ``` ### Side Effects Sets up the LED GPIO pin and PWM timer (if supported). ``` -------------------------------- ### Get MAVLink Parameter Value Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/06-mavlink-telemetry.md Retrieves a MAVLink parameter value by its ID or index. Use this function when a GCS requests a parameter or for internal system use. Ensure the `float_int_union` is correctly sized for the expected parameter type. ```c float_int_union param_val; MAV_PARAM_TYPE type = db_mav_get_parameter_value(¶m_val, "SERIAL_BAUD", -1); if (type == MAV_PARAM_TYPE_INT32) { int32_t baud = param_val.i32; } ``` -------------------------------- ### Initialize and Register mDNS HTTP Service Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md Initializes the mDNS service, sets the device hostname, and registers an HTTP service on port 80. This makes the device discoverable on the network. ```c mdns_init(); mdns_hostname_set("dronebridge"); mdns_service_add(NULL, "_http", "_tcp", 80, NULL, 0); mdns_service_instance_name_set("_http", "_tcp", "DroneBridge for ESP32"); ``` -------------------------------- ### Get MAVLink Component ID Function Signature Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/06-mavlink-telemetry.md Retrieves the MAVLink component ID for the ESP32 device. This ID is used to identify the specific component (e.g., telemetry radio) within a MAVLink system. Typically set to MAV_COMP_ID_TELEMETRY_RADIO (68). ```c uint8_t db_get_mav_comp_id(void); ``` -------------------------------- ### Write All Parameters to NVS Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/03-parameters-configuration.md Persistently stores all 25 firmware parameters to Non-Volatile Storage (NVS). Requires an open NVS handle for the 'settings' namespace. ```c void db_param_write_all_params_nvs(const nvs_handle_t *nvs_handle); ``` -------------------------------- ### Get MAVLink System ID Function Signature Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/06-mavlink-telemetry.md Retrieves the MAVLink system ID for the ESP32 device. This ID is typically learned from the flight controller's heartbeat message and is used to associate outgoing messages with the correct system in a Ground Control Station (GCS). Defaults to 1 if no heartbeat is received. ```c uint8_t db_get_mav_sys_id(void); ``` -------------------------------- ### Settings POST Request JSON Format Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md Illustrates the expected JSON format for POST requests to the settings handler. This JSON object should contain key-value pairs for parameters to be updated. ```json { "baud": 115200, "wifi_chan": 6, "esp32_mode": 4, "ssid": "MyNetwork" } ``` -------------------------------- ### ESP-NOW Clients List Structure Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/02-types-and-structures.md Represents a list of connected ESP-NOW peers for internal telemetry. It includes the number of peers and ground noise floor, along with an array of broadcast peer information. This structure is packed for efficient serialization. ```c typedef struct { uint8_t size; int8_t gnd_noise_floor; db_esp_now_bpeer_info_t db_esp_now_bpeer_info[DB_ESPNOW_MAX_BROADCAST_PEERS]; } __attribute__((__packed__)) db_esp_now_clients_list_t; ``` -------------------------------- ### Open TCP Server Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/05-network-control-module.md Creates a listening TCP server socket on the specified port. Ensure the port is valid and available. The function registers the socket for asynchronous event handling. ```c int open_tcp_server(int port); ``` ```c int tcp_sock = open_tcp_server(APP_PORT_PROXY); if (tcp_sock < 0) { ESP_LOGE(TAG, "Failed to open TCP server"); } ``` -------------------------------- ### Initialize Serial Port Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/04-serial-interface.md Initializes UART1 with configured settings. Must be called before any serial operations. Configures GPIO pins, baud rate, and flow control. ```c int open_serial_socket(void); ``` -------------------------------- ### Create UDP Client List Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/05-network-control-module.md Allocates and initializes a structure to manage UDP client connections. This is used to track connected Ground Control Station (GCS) devices. ```c udp_conn_list_t *udp_client_list_create(void); ``` -------------------------------- ### API Endpoints Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md Handles API requests for settings and system control. Supports retrieving current settings, applying configuration changes, rebooting the device, and resetting to default configurations. ```APIDOC ## API Endpoints ### Description Handles API requests for settings and system control. ### Method POST, GET ### Endpoint /api/settings /api/restart /api/reset ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **POST /api/settings**: Configuration changes (format not specified) - **POST /api/restart**: No body required - **POST /api/reset**: No body required ### Request Example ```json { "example": "POST /api/settings request body" } ``` ### Response #### Success Response (200 OK) - **GET /api/settings**: Current settings in JSON format. - **POST /api/restart**: Success indication (details not specified). - **POST /api/reset**: Success indication (details not specified). #### Response Example ```json { "example": "GET /api/settings response body" } ``` ``` -------------------------------- ### Server Context Structure Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md Defines the structure for server context, holding the base path for static files and a temporary buffer for I/O operations. This context is passed to request handlers. ```c typedef struct rest_server_context { char base_path[ESP_VFS_PATH_MAX + 1]; // Root directory for static files char scratch[SCRATCH_BUFSIZE]; // Temporary buffer for I/O } rest_server_context_t; ``` -------------------------------- ### POST Settings Handler Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md Processes configuration changes submitted via the web interface. It accepts a JSON object containing parameter key-value pairs, validates them, updates the in-memory configuration, and persists the changes to NVS. ```APIDOC ## POST /settings ### Description Processes configuration changes from the web interface. Accepts a JSON object with parameter key-value pairs. ### Method POST ### Endpoint /settings ### Parameters #### Request Body - **baud** (integer) - Optional - Baud rate for serial communication. - **wifi_chan** (integer) - Optional - Wi-Fi channel to use. - **esp32_mode** (integer) - Optional - Operating mode of the ESP32. - **ssid** (string) - Optional - SSID for Wi-Fi connection. ### Request Example { "baud": 115200, "wifi_chan": 6, "esp32_mode": 4, "ssid": "MyNetwork" } ### Response #### Success Response (200) - **status** (string) - Indicates success or failure. - **message** (string) - Details about the operation. #### Response Example { "status": "success", "message": "Settings updated successfully." } ``` -------------------------------- ### Read All Parameters from NVS Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/03-parameters-configuration.md Restores all firmware parameters from NVS into memory. Used during startup to load saved configurations. Missing keys are initialized to defaults. ```c void db_param_read_all_params_nvs(const nvs_handle_t *nvs_handle); ``` -------------------------------- ### Conditionally Add Bluetooth Source File Source: https://github.com/dronebridge/esp32/blob/master/main/CMakeLists.txt Appends 'db_ble.c' to the source files list if the CONFIG_BT_ENABLED option is set. This enables Bluetooth functionality when configured. ```cmake if(CONFIG_BT_ENABLED) list(APPEND SRCS db_ble.c) endif() ``` -------------------------------- ### Reset All Parameters to Factory Defaults Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/03-parameters-configuration.md Resets all 25 project parameters to their factory default values. Note that this function does not automatically write to NVS; a separate call to `db_param_write_all_params_nvs()` is required. ```c void db_param_reset_all(void); ``` -------------------------------- ### open_serial_socket Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/04-serial-interface.md Initializes UART1 with configured GPIO pins, baud rate, and flow control settings. This function must be called before any serial read/write operations. ```APIDOC ## open_serial_socket ### Description Initializes UART1 with configured GPIO pins, baud rate, and flow control settings. Must be called before any serial read/write operations. ### Signature ```c int open_serial_socket(void); ``` ### Parameters None ### Returns - 0 on success - Non-zero error code on failure (ESP_ERR_*) ### Configuration Used - `DB_PARAM_GPIO_TX`, `DB_PARAM_GPIO_RX`, `DB_PARAM_GPIO_RTS`, `DB_PARAM_GPIO_CTS` - `DB_PARAM_SERIAL_BAUD` - `DB_PARAM_SERIAL_RTS_THRESH` (flow control threshold) ### Side Effects - Configures GPIO pins as UART I/O - Installs UART driver with queue - Enables receive interrupt handler ``` -------------------------------- ### POST Settings Change Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md Allows modification of system settings via a JSON payload. ```APIDOC ## POST /api/settings ### Description Updates system settings such as baud rate and WiFi channel. The request body must be a JSON object containing the settings to be changed. ### Method POST ### Endpoint /api/settings ### Parameters #### Request Body - **baud** (integer) - Required - The baud rate for serial communication. Must be within the range [1200, 5000000]. - **wifi_chan** (integer) - Required - The WiFi channel to use. Must be within the range [1, 13]. ### Request Example ```json { "baud": 115200, "wifi_chan": 6 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation ('success'). - **message** (string) - A confirmation message ('Settings saved'). #### Response Example ```json { "status": "success", "message": "Settings saved" } ``` ``` -------------------------------- ### ESP-NOW Queue Configuration Constants Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/07-esp-now-module.md Defines constants for configuring the ESP-NOW event queue size and the maximum delay for queue operations. ```c #define ESPNOW_QUEUE_SIZE 6 // Queue depth for events #define ESPNOW_MAXDELAY 512 // Max milliseconds to wait for queue ``` -------------------------------- ### Open TCP Server Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/05-network-control-module.md Creates a listening TCP server socket on the specified port for inbound GCS connections. ```APIDOC ## open_tcp_server ### Description Creates a listening TCP server socket on the specified port for inbound GCS connections. ### Signature ```c int open_tcp_server(int port); ``` ### Parameters #### Path Parameters - **port** (int) - Required - TCP port to listen on (e.g., APP_PORT_PROXY = 5760) ### Returns - Socket descriptor (>= 0) on success - Negative error code on failure ### Configuration - Listening backlog: typically 5 connections - SO_REUSEADDR enabled to allow quick restart after shutdown - Non-blocking mode via fcntl() ### Side Effects Registers socket for async event handling ### Typical Ports - 5760: APP_PORT_PROXY (MAVLink TCP proxy) - 1603: APP_PORT_COMM (DroneBridge control protocol) ### Request Example ```c int tcp_sock = open_tcp_server(APP_PORT_PROXY); if (tcp_sock < 0) { ESP_LOGE(TAG, "Failed to open TCP server"); } ``` ``` -------------------------------- ### Handle File Not Found Error Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md Sends a 404 Not Found HTTP response when a requested file cannot be read. This is typically used when a file descriptor is invalid. ```c if (fd == -1) { httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "Failed to read existing file"); return ESP_FAIL; } ``` -------------------------------- ### Buffer Size Configuration Constants Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/02-types-and-structures.md Constants specifying the buffer sizes for UART, UDP, and TCP communication. ```plaintext UART_BUF_SIZE = 1024 // Serial read buffer UDP_BUF_SIZE = 2048 // UDP receive buffer TCP_BUFF_SIZ = 4096 // TCP receive buffer ``` -------------------------------- ### POST Settings Handler Signature Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/09-http-web-interface.md Defines the signature for the settings POST handler, which processes configuration changes from the web interface. ```c static esp_err_t settings_post_handler(httpd_req_t *req); ``` -------------------------------- ### Signed 32-bit Integer Parameter Structure (db_parameter_i32_t) Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/02-types-and-structures.md Defines a structure for signed 32-bit integer parameters, specifying the current value, default value, and valid range. Supports negative values and is used for baud rates and timeouts. ```c typedef struct db_parameter_i32_s { int32_t value; // Current value int32_t default_value; // Default value int32_t min; // Minimum valid value int32_t max; // Maximum valid value } db_param_i32_t; ``` -------------------------------- ### Network Configuration Constants Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/05-network-control-module.md These constants configure network parameters such as multicast IP addresses, TTL, maximum UDP clients, and UDP buffer size. ```c #define MULTICAST_IPV4_ADDR "232.10.11.12" // Internal telemetry multicast group #define MULTICAST_TTL 1 // Local network only #define MAX_UDP_CLIENTS 8 // Max simultaneous UDP endpoints #define UDP_BUF_SIZE 2048 // UDP receive buffer per packet ``` -------------------------------- ### DroneBridge ESP32 Parameter Access Macros Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/03-parameters-configuration.md These macros provide direct access to configuration parameters for Wi-Fi, radio settings, serial communication, and control options. They are defined in `db_parameters.h` and are intended for use within the DroneBridge ESP32 project. ```c #define DB_PARAM_WIFI_SSID (char *) db_param_ssid.value.db_param_str.value #define DB_PARAM_PASS (char *) db_param_pass.value.db_param_str.value #define DB_PARAM_AP_IP (char *) db_param_wifi_ap_ip.value.db_param_str.value #define DB_PARAM_STA_IP db_param_wifi_sta_ip.value.db_param_str.value #define DB_PARAM_STA_GW db_param_wifi_sta_gw.value.db_param_str.value #define DB_PARAM_STA_IP_NETMASK db_param_wifi_sta_netmask.value.db_param_str.value // Wireless #define DB_PARAM_RADIO_MODE db_param_radio_mode.value.db_param_u8.value #define DB_PARAM_CHANNEL db_param_channel.value.db_param_u8.value #define DB_PARAM_WIFI_EN_GN db_param_wifi_en_gn.value.db_param_u8.value #define DB_PARAM_EN_EXT_ANT db_param_radio_ant_ext.value.db_param_u8.value // Serial #define DB_PARAM_SERIAL_BAUD db_param_baud.value.db_param_i32.value #define DB_PARAM_SERIAL_PROTO db_param_proto.value.db_param_u8.value #define DB_PARAM_SERIAL_PACK_SIZE db_param_serial_pack_size.value.db_param_u16.value #define DB_PARAM_GPIO_TX db_param_gpio_tx.value.db_param_u8.value #define DB_PARAM_GPIO_RX db_param_gpio_rx.value.db_param_u8.value #define DB_PARAM_GPIO_RTS db_param_gpio_rts.value.db_param_u8.value #define DB_PARAM_GPIO_CTS db_param_gpio_cts.value.db_param_u8.value #define DB_PARAM_SERIAL_RTS_THRESH db_param_gpio_rts_thresh.value.db_param_u8.value // Control #define DB_PARAM_DIS_RADIO_ON_ARM db_param_dis_radio_armed.value.db_param_u8.value ``` -------------------------------- ### ESP-NOW Send Callback Structure Source: https://github.com/dronebridge/esp32/blob/master/_autodocs/07-esp-now-module.md Defines the structure for data passed to the ESP-NOW send callback event. It includes the peer's MAC address and the transmission status. ```c typedef struct { uint8_t mac_addr[ESP_NOW_ETH_ALEN]; esp_now_send_status_t status; } db_espnow_event_send_cb_t; ```