### Run Memfault Quickstart Installer Script Source: https://docs.memfault.com/docs/linux/quickstart-installer Execute this command in a shell on the target Linux device. Replace `YOUR_PROJECT_KEY` with your actual Memfault Project Key. The script requires the filesystem to be mounted as read-write. ```bash curl -sSf https://app.memfault.com/static/scripts/linux-quickstart.sh | MEMFAULT_PROJECT_KEY=YOUR_PROJECT_KEY sh ``` -------------------------------- ### Example Session Start/End Callbacks for Battery Metrics Source: https://docs.memfault.com/docs/mcu/metrics-api Demonstrates how to use session start and end callbacks to capture battery metrics like State of Charge drop and discharge duration. Ensure to include `memfault/components.h`. ```c #include "memfault/components.h" static bool s_stopped_discharging_during_interval; static uint32_t s_battery_connection_start_soc_pct; static uint64_t s_start_time_ms; //! This function must be called when the battery stops discharging, eg: //! //! 1. charge mode is entered //! 2. battery is disconnected void battery_stopped_discharging(void) { s_stopped_discharging_during_interval = true; } static void prv_lte_session_start_cb(void) { // Record starting battery state-of-charge and time s_battery_connection_start_soc_pct = 100; s_start_time_ms = memfault_platform_get_time_since_boot_ms(); } static void prv_lte_session_end_cb(void) { const uint64_t current_time = memfault_platform_get_time_since_boot_ms(); const uint32_t session_length_ms = current_time - s_start_time_ms; // Record battery state-of-charge at the end of the connection uint32_t battery_connection_end_soc_pct = 50; // Discard reports when the state of charge increased, or the battery stopped discharging if (s_battery_connection_start_soc_pct >= battery_connection_end_soc_pct && !s_stopped_discharging_during_interval) { MEMFAULT_METRIC_SESSION_SET_UNSIGNED(battery_soc_pct_drop, lte, s_battery_connection_start_soc_pct - battery_connection_end_soc_pct); MEMFAULT_METRIC_SESSION_SET_UNSIGNED(session_length_ms, lte, session_length_ms); } // Reset discharging flag s_stopped_discharging_during_interval = false; } void my_session_start_event_handler(void) { memfault_metrics_session_register_start_cb(MEMFAULT_METRICS_SESSION_KEY(lte), prv_lte_session_start_cb); memfault_metrics_session_register_end_cb(MEMFAULT_METRICS_SESSION_KEY(lte), prv_lte_session_end_cb); MEMFAULT_METRICS_SESSION_START(lte); } void my_session_end_event_handler(void) { MEMFAULT_METRICS_SESSION_END(lte); } ``` -------------------------------- ### Memfaultd configuration file example Source: https://docs.memfault.com/docs/linux/cross-compile-memfaultd Example configuration file for memfaultd. Ensure 'project_key' is replaced with your actual Memfault project key. ```json { "enable_data_collection": true, "software_version": "dev", "software_type": "dev", "project_key": "INSERT_YOUR_PROJECT_KEY_HERE", "persist_dir": "/tmp/memfaultd" } ``` -------------------------------- ### Micrium OS (µC/OS-III) Integration Example Source: https://docs.memfault.com/docs/mcu/rtos-analysis Refer to the memfault-micrium-sample repository for a complete, working example of integrating Memfault with Micrium OS (µC/OS-III). ```c See the [memfault-micrium-sample](https://github.com/memfault/memfault-micrium-sample) repository for a complete working example of this integration. ``` -------------------------------- ### Memfault Device Info Output Example Source: https://docs.memfault.com/docs/mcu/quickstart-esp32 Example output showing Memfault Build ID, Serial Number, Software Type, and Software Version printed to the console after a successful boot. ```text I (694) mflt: Memfault Build ID: 4115098dbf8ea90c802ae21b2e757e033866bd1b I (704) mflt: S/N: C4DEE25A6118 I (704) mflt: SW type: esp32-main I (704) mflt: SW version: 1.0.0-dev ``` -------------------------------- ### Reboot Reason Test Start Output Source: https://docs.memfault.com/docs/mcu/self-test Example output when starting the Reboot Reason Test, instructing the user to run a verification command after reboot. ```text MFLT:[INFO] ============================= MFLT:[INFO] Reboot Reason Test MFLT:[INFO] ============================= MFLT:[INFO] This test will now reboot the device to test reboot reason tracking MFLT:[INFO] After the device reboots, please run with reboot_verify argument MFLT:[INFO] ============================= ``` -------------------------------- ### Example Startup Text with GNU Build ID Source: https://docs.memfault.com/docs/mcu/arm-nxp-mcuxpresso-guide This is an example of the startup text that appears in the serial console after successfully building and flashing the project with GNU Build ID enabled. ```text [I] MFLT: GNU Build ID: 63a58c3567c22fd6786adbc4cc186d258e66efe7 [I] MFLT: S/N: DEMOSERIAL [I] MFLT: SW type: app-fw [I] MFLT: SW version: 1.0.0 [I] MFLT: HW version: dvt1 [I] MFLT: Memfault Initialized! ``` -------------------------------- ### Example Device Logs with Memfault Data Source: https://docs.memfault.com/docs/mcu/arm-infineon-modustoolbox-guide Example console output showing interleaved logs and Memfault data chunks. ```shell # CLI command recording a reboot reason, then rebooting the system shell> test_reboot MFLT:[INFO] GNU Build ID: 3c92e3313fe1c9d00ac8687ce966d5f527a05ed3 MFLT:[INFO] S/N: freertos-example MFLT:[INFO] SW type: qemu-app MFLT:[INFO] SW version: 1.0.0 MFLT:[INFO] HW version: qemu-mps2-an385 MFLT:[INFO] Memfault Initialized! # CLI command capturing a trace event shell> test_trace # CLI command making a call to `memfault_data_export_dump_chunks()` shell> export [00:00:10] INFO: MC:SFQCpwIBAwEHalRFU1RTRVJJQUwKbXRlc3Qtc29mdHdhcmUJajEuMC4wLXRlcw==: ``` -------------------------------- ### Install Memfault CLI Tool Source: https://docs.memfault.com/docs/mcu/export-chunks-over-console Install the Memfault Desktop CLI tool using pip. Ensure you have Python 3.x installed. Use `memfault --help` to verify the installation. ```bash pip3 install memfault-cli memfault --help ``` -------------------------------- ### Build https_client Example Source: https://docs.memfault.com/docs/mcu/quickstart-nrf9160 Build the https_client example for the nRF9160-DK board using the nRF-Connect SDK. The --pristine=always flag ensures a clean build. ```bash west build --pristine=always --board nrf9160dk@1.0.0/nrf9160/ns nrf/samples/net/https_client ``` -------------------------------- ### Log Collection Example (Yocto) Source: https://docs.memfault.com/changelog/2023/03/31 Example configuration for log collection within the `meta-memfault-example` Yocto layer. This demonstrates how to set up logging on embedded Linux devices. ```bb IMAGE_INSTALL:append = " memfault-log-collection" ``` -------------------------------- ### Example: Record Sync Completion Source: https://docs.memfault.com/docs/platform/memfault-core-metrics?platform=MCU This example demonstrates how to record a successful or failed sync event based on a callback's success parameter. ```c void my_data_sync_complete_callback(bool success) { if (success) { memfault_metrics_connectivity_record_sync_success(); } else { memfault_metrics_connectivity_record_sync_failure(); } } ``` -------------------------------- ### Example Linux Kernel Configuration File Source: https://docs.memfault.com/docs/linux/coredumps This is an example path to a Linux kernel configuration file. Verify your project's configuration matches the recommended settings for coredump support. ```text tmp/work/raspberrypi3-poky-linux/linux-yocto/5.15.62+gitAUTOINC+59c8898d45_7cb30c5e95-r0/linux-raspberrypi3-standard-build/.config ``` -------------------------------- ### Example CLI Output with Memfault Data Source: https://docs.memfault.com/docs/mcu/embedded-self-serve This example shows the expected output in a shell when using the `reboot` and `trace` commands, including Memfault build ID information. ```text shell> reboot [00:00:01] INFO: System Booting! [00:00:02] INFO: Memfault Build ID: d8d6a047282f025fffa29fa767100f310bc40f80 shell> trace ``` -------------------------------- ### Example Battery State Management Source: https://docs.memfault.com/docs/platform/memfault-core-metrics?platform=MCU This example demonstrates how to manage and track the battery's discharging state. It includes functions to set the initial state and to handle state changes, triggering callbacks when the discharging status changes. ```c // note: tracking battery state via a static variable is not required. It is // added here to demonstrate that battery_charge_state_changed_callback() is // edge-triggered static bool s_battery_is_discharging = false; // This function is called on system initialization, to set the initial // discharging state void battery_set_initial_discharging_state(void) { s_battery_is_discharging = battery_is_discharging(); } // This function is called by when the battery discharging state changes, i.e.: // CHARGING → DISCHARGING or DISCHARGING → CHARGING void battery_charge_state_changed_callback(void) { const bool discharging = battery_is_discharging(); if (discharging != s_battery_is_discharging) { // update the state of the battery ``` -------------------------------- ### Start a Session with memfaultctl Source: https://docs.memfault.com/docs/linux/reference-memfaultctl-cli Initiates a session in Memfault, optionally including metric readings. Ensure a session type with the provided name is defined in `/etc/memfaultd.conf`. Starting an ongoing session type is a no-op. ```bash memfaultctl start-session my-example-session my_gauge=4.2 ``` -------------------------------- ### Memfault device info script example Source: https://docs.memfault.com/docs/linux/cross-compile-memfaultd Example script for memfault-device-info, which memfaultd uses to detect hardware version and device ID. Make sure to make this script executable. ```bash #!/bin/sh echo MEMFAULT_HARDWARE_VERSION=smart-sink-hw-proto echo MEMFAULT_DEVICE_ID=dev-device-42 ``` -------------------------------- ### Memfault SDK Compact Log Example Source: https://docs.memfault.com/changelog/2021/07/31 Example of how to write a log line using Memfault's Compact Logs feature in the Firmware SDK. This method optimizes log storage by referencing strings with an integer ID. ```c MEMFAULT_TRACE_EVENT_WITH_LOG("QSPI Flash Erase Failure: error code: 0x%x", 0x5); ``` -------------------------------- ### Memfault SDK Custom Data Recording Example Source: https://docs.memfault.com/docs/mcu/custom-data-recording An example implementation of CDR callback functions. This includes state tracking, metadata definition, and the logic for checking data availability, reading data in chunks, and marking data as read. ```c #include "memfault/components.h" // state tracking variables; only read the CDR data one time per boot static bool s_cdr_has_read = false; // keep track of the offset into the CDR data; the packetizer may call // repeatedly depending on chunk size constraints static size_t s_cdr_read_offset = 0; // set of MIME types for this payload static const char *mimetypes[] = {MEMFAULT_CDR_BINARY}; // the actual payload is just a simple string in this example static const char cdr_payload[] = "hello cdr!"; // the CDR metadata structure static const sMemfaultCdrMetadata s_cdr_metadata = { .start_time = { // this could also be a proper timestamp, if the time associated with the // start of the CDR data is known .type = kMemfaultCurrentTimeType_Unknown, }, .mimetypes = mimetypes, .num_mimetypes = MEMFAULT_ARRAY_SIZE(mimetypes), // in this case, the data size is fixed. typically it would be set in the // prv_has_cdr_cb() function, and likely variable size .data_size_bytes = sizeof(cdr_payload), .duration_ms = 0, .collection_reason = "example cdr upload", }; // called to see if there's any data available; uses the *metadata output to set // the header fields in the chunked message sent to Memfault static bool prv_has_cdr_cb(sMemfaultCdrMetadata *metadata) { *metadata = s_cdr_metadata; return !s_cdr_has_read; } // called by the packetizer to read up to .data_size_bytes of CDR data static bool prv_read_data_cb(uint32_t offset, void *data, size_t data_len) { if (offset != s_cdr_read_offset) { LOG_ERR("Unexpected offset: %d vs %d", offset, s_cdr_read_offset); return false; } const size_t copy_len = MEMFAULT_MIN(data_len, sizeof(cdr_payload) - offset); LOG_INF("Reading %d bytes from offset %d", copy_len, offset); memcpy(data, ((uint8_t *)cdr_payload) + offset, copy_len); s_cdr_read_offset += copy_len; return true; } // called when all data has been drained from the read callback static void prv_mark_cdr_read_cb(void) { s_cdr_has_read = true; } // Set up the callback functions. This CDR Source Implementation structure must // have a lifetime through the duration of the program- typically setting it to // 'const' is appropriate static const sMemfaultCdrSourceImpl s_my_custom_data_recording_source = { .has_cdr_cb = prv_has_cdr_cb, .read_data_cb = prv_read_data_cb, .mark_cdr_read_cb = prv_mark_cdr_read_cb, }; void main(void) { // register the CDR Source during system startup memfault_cdr_register_source(&s_my_custom_data_recording_source); ... ``` -------------------------------- ### Get Latest OTA Release and Install Source: https://docs.memfault.com/docs/mcu/demo-cli-cmds-ncs-zephyr The `get_latest_release` command fetches an OTA update payload. If `CONFIG_MEMFAULT_ZEPHYR_FOTA_BACKEND_MCUBOOT` is enabled, it installs the update and reboots. Otherwise, with `CONFIG_MEMFAULT_ZEPHYR_FOTA_BACKEND_DUMMY`, it only downloads the payload. ```bash uart:~$ mflt get_latest_release [00:01:17.304,000] mflt: Downloading OTA payload, size=1048576 bytes [00:01:39.644,000] mflt: OTA download complete! Rebooting... *** Booting Zephyr OS build v3.6.0 *** ``` ```bash uart:~$ mflt get_latest_release [00:01:15.304,000] mflt: Checking for OTA update [00:01:17.304,000] mflt: Downloading OTA payload, size=1048576 bytes [00:01:39.644,000] mflt: OTA download complete! ``` ```bash uart:~$ mflt get_latest_release [00:01:15.304,000] mflt: Checking for OTA update [00:01:17.304,000] mflt: Up to date! ``` -------------------------------- ### Run Image with QEMU Source: https://docs.memfault.com/docs/linux/qemu-example Use the 'q' shortcut to start QEMU and run the previously built image. The system will boot into a root login prompt. ```bash $ q # Run image in QEMU // Linux boots login: root ``` -------------------------------- ### Example OTA Agent Script Source: https://docs.memfault.com/docs/linux/generic-ota A shell script demonstrating how to poll the Memfault OTA API for updates, download the update payload, and install it. This script requires customization for the specific update installer command. ```APIDOC ## Example OTA Agent Script ### Description This script demonstrates a basic OTA agent that runs on a Linux device. It polls the Memfault OTA API for new versions, downloads the update if available, and then invokes a system-specific update installer. It also includes logic for rebooting the device after a successful update or logging errors. ### Script ```bash #!/bin/sh DATA_DIR=$(cat /etc/memfaultd.conf | jq -r '.data_dir') PROJECT_KEY=$(cat /etc/memfaultd.conf | jq -r '.project_key') SOFTWARE_TYPE=$(cat /etc/memfaultd.conf | jq -r '.software_type') SOFTWARE_VERSION=$(cat /etc/memfaultd.conf | jq -r '.software_version') eval "$(memfault-device-info)" url=$(curl -f -s --get \ --data-urlencode "hardware_version=${MEMFAULT_HARDWARE_VERSION}" \ --data-urlencode "software_type=${SOFTWARE_TYPE}" \ --data-urlencode "current_version=${SOFTWARE_VERSION}" \ --data-urlencode "device_serial=${MEMFAULT_DEVICE_ID}" \ --header "Memfault-Project-Key: ${PROJECT_KEY}" \ "https://api.memfault.com/api/v0/releases/latest/url") exit_code=$? if [ "$exit_code" -eq 0 ] && [ -n "$url" ]; then # The following line will need to be updated for the specific update installer # you are using. update-installer $url if [ $? -eq 0 ]; then memfaultctl reboot --reason 3 else logger -p user.err "OTA install failed" fi elif [ "$exit_code" -ne 0 ]; then logger -p user.err "OTA status check request failed" logger -p user.err "curl returned exit code: ${exit_code}" fi ``` ### Usage 1. Save the script to a file, e.g., `/usr/bin/memfault-ota`. 2. Ensure `jq` is installed for parsing configuration. 3. Replace `update-installer $url` with the actual command to install the update payload on your device. 4. Configure a systemd service and timer to run this script periodically (see `memfault-ota.service` and `memfault-ota.timer` examples). ``` -------------------------------- ### ARMv7-A/R Vector Table Setup for Memfault Source: https://docs.memfault.com/docs/mcu/arm-cortex-r-guide Install these functions into the program's vector table to integrate Memfault fault handlers. Ensure the symbols are exported and correctly referenced. ```assembly /*-------------------------------------------------------------------------------*/ @ import reference for interrupt routines .extern _c_int00 .extern phantomInterrupt .weak resetEntry @ Memfault Fault Handlers used in the interrupt vector table below .extern UndefinedInstruction_Handler .extern DataAbort_Handler .extern PrefetchAbort_Handler /*-------------------------------------------------------------------------------*/ @ interrupt vectors resetEntry: ldr pc, =_c_int00 ldr pc, =UndefinedInstruction_Handler /* Memfault handler */ svcEntry: b svcEntry ldr pc, =PrefetchAbort_Handler /* Memfault handler */ ldr pc, =DataAbort_Handler /* Memfault handler */ b phantomInterrupt ldr pc,[pc,#-0x1b0] ldr pc,[pc,#-0x1b0] ``` -------------------------------- ### Send Gauge Metric using Python StatsD Client Source: https://docs.memfault.com/docs/linux/metrics Example of using the python-statsd library to send a gauge metric to the memfaultd StatsD server. Ensure the python-statsd library is installed. ```python from statsd import StatsClient statsd = StatsClient( host="localhost", port=8125, prefix="mypythonapp", ) statsd.gauge("mygauge", 42) ``` -------------------------------- ### Install and Use Memfault CLI for Uploads and Deployments Source: https://docs.memfault.com/docs/ci/uploading-symbols This step installs the Memfault CLI, uploads MCU symbols from the built ELF file, uploads an OTA payload, and deploys a release. It requires the Memfault organization, project, and API token to be configured as secrets. ```bash # install the memfault CLI pip install memfault-cli==1.0.6 # upload the symbol file memfault \ --org-token ${{ secrets.MEMFAULT_ORG_TOKEN }} \ --org ${{ secrets.MEMFAULT_ORG }} \ --project ${{ secrets.MEMFAULT_PROJECT }} \ upload-mcu-symbols build/zephyr/zephyr.elf # create the release and upload the OTA payload. the version is from # the build step memfault \ --org-token ${{ secrets.MEMFAULT_ORG_TOKEN }} \ --org ${{ secrets.MEMFAULT_ORG }} \ --project ${{ secrets.MEMFAULT_PROJECT }} upload-ota-payload \ --hardware-version ${{ env.HARDWARE_VERSION }} \ --software-type ${{ env.SOFTWARE_TYPE }} \ --software-version ${{ steps.build.outputs.version }} \ build/zephyr/app_update.bin memfault \ --org-token ${{ secrets.MEMFAULT_ORG_TOKEN }} \ --org ${{ secrets.MEMFAULT_ORG }} \ --project ${{ secrets.MEMFAULT_PROJECT }} deploy-release \ --release-version ${{ steps.build.outputs.version }} \ --cohort ${{ env.COHORT }} ``` -------------------------------- ### Example OTA Agent Script Source: https://docs.memfault.com/docs/linux/generic-ota A shell script to poll the Memfault OTA API for updates and initiate the installation process. This script requires customization for the 'update-installer' command and relies on configuration from '/etc/memfaultd.conf'. ```bash #!/bin/sh DATA_DIR=$(cat /etc/memfaultd.conf | jq -r '.data_dir') PROJECT_KEY=$(cat /etc/memfaultd.conf | jq -r '.project_key') SOFTWARE_TYPE=$(cat /etc/memfaultd.conf | jq -r '.software_type') SOFTWARE_VERSION=$(cat /etc/memfaultd.conf | jq -r '.software_version') eval "$(memfault-device-info)" url=$(curl -f -s --get \ --data-urlencode "hardware_version=${MEMFAULT_HARDWARE_VERSION}" \ --data-urlencode "software_type=${SOFTWARE_TYPE}" \ --data-urlencode "current_version=${SOFTWARE_VERSION}" \ --data-urlencode "device_serial=${MEMFAULT_DEVICE_ID}" \ --header "Memfault-Project-Key: ${PROJECT_KEY}" \ "https://api.memfault.com/api/v0/releases/latest/url") exit_code=$? if [ "$exit_code" -eq 0 ] && [ -n "$url" ]; then # The following line will need to be updated for the specific update installer # you are using. update-installer $url if [ $? -eq 0 ]; then memfaultctl reboot --reason 3 else logger -p user.err "OTA install failed" fi elif [ "$exit_code" -ne 0 ]; then logger -p user.err "OTA status check request failed" logger -p user.err "curl returned exit code: ${exit_code}" fi ``` -------------------------------- ### Send Gauge Metric using C StatsD Client Source: https://docs.memfault.com/docs/linux/metrics Example of using the C statsd-client library to send a gauge metric to the memfaultd StatsD server. Ensure the statsd-client library is installed and linked. ```c #include #include #include #include #include #define MAX_LINE_LEN 200 #define PKT_LEN 1400 int main(int argc, char *argv[]) { statsd_link *link; link = statsd_init_with_namespace("localhost", 8125, "mycapp"); char pkt[PKT_LEN] = {'\0'}; char tmp[MAX_LINE_LEN] = {'\0'}; statsd_prepare(link, "mygauge", 42, "g", 1.0, tmp, MAX_LINE_LEN, 1); strncat(pkt, tmp, PKT_LEN - 1); statsd_send(link, pkt); statsd_finalize(link); } ``` -------------------------------- ### Initialize Memfault in Application Source: https://docs.memfault.com/docs/mcu/quickstart-esp32 Include the necessary Memfault headers and call `memfault_boot()` and `memfault_device_info_dump()` in your `app_main` function to initialize Memfault and log device information on boot. ```c #include "memfault/esp_port/core.h" #include "memfault/components.h" void app_main(void) { memfault_boot(); memfault_device_info_dump(); //... } ``` -------------------------------- ### Start Demo CLI Console with Invoke Source: https://docs.memfault.com/docs/mcu/demo-cli-cmds-other-platforms Use this command to start the demo CLI console on the target device. Replace 'NAME' with the specific implementation name (e.g., 'nrf'). Refer to the implementation's README for the exact command. ```bash invoke NAME.console ``` -------------------------------- ### Upload and Monitor Device Source: https://docs.memfault.com/docs/mcu/platformio-esp-idf-guide Upload the firmware to the device and start the serial monitor using PlatformIO CLI. ```bash pio run --target upload --target monitor ``` -------------------------------- ### Verify PlatformIO Installation Source: https://docs.memfault.com/docs/mcu/platformio-esp-idf-guide Use this command to ensure PlatformIO is installed and can flash your device. ```bash pio run -t upload ``` -------------------------------- ### Install Memfault Python CLI Tool Source: https://docs.memfault.com/docs/mcu/xilinx-a53-sdk-guide Install the Memfault Desktop CLI tool using pip. This tool is useful for automating data posting and other interactions with Memfault services. Ensure Python 3.x is installed. ```shell $ pip3 install memfault-cli $ memfault --help ``` -------------------------------- ### Call Memfault Platform Boot in Main Source: https://docs.memfault.com/docs/mcu/arm-nxp-mcuxpresso-guide Add the `memfault_platform_boot();` call to your `main()` function to initialize the Memfault SDK during system startup. ```c memfault_platform_boot(); ``` -------------------------------- ### Install Memfault Dependencies Source: https://docs.memfault.com/docs/mcu/platformio-esp-idf-guide Install Memfault's Python SDK and CLI tools using pip. ```bash pip install -r third-party/memfault-firmware-sdk/requirements.txt ``` ```bash pip install memfault-cli ``` ```bash pip install mflt_build_id ``` -------------------------------- ### Initialize Memfault SDK Source: https://docs.memfault.com/docs/mcu/espressif-esp32-guide Initialize the Memfault SDK by calling `memfault_boot()` as early as possible in your application's main task. Ensure any dependencies for `memfault_platform_get_device_info()` are initialized beforehand. ```c #include "memfault/esp_port/core.h" void app_main() { memfault_boot(); // Remainder of your main task } ``` -------------------------------- ### Install Memfault Build ID Package Source: https://docs.memfault.com/docs/mcu/arm-infineon-modustoolbox-guide Install the required 'mflt-build-id' Python package using pip. ```bash pip install mflt-build-id ``` -------------------------------- ### Display memfaultctl Help Information Source: https://docs.memfault.com/docs/linux/reference-memfaultctl-cli Run `memfaultctl --help` to display all available commands, options, and a brief description of the utility's purpose. ```bash # memfaultctl --help Usage: memfaultctl [-c ] [-v] [-V] [] A command line utility to adjust memfaultd configuration and trigger specific events for testing purposes. For further reference, see: https://docs.memfault.com/docs/linux/reference-memfaultctl-cli Options: -c, --config-file use configuration file -v, --version show version information -V, --verbose verbose output --help display usage information Commands: enable-data-collection enable data collection and restart memfaultd disable-data-collection disable data collection and restart memfaultd enable-dev-mode enable developer mode and restart memfaultd disable-dev-mode disable developer mode and restart memfaultd export export (and delete) memfault data reboot register reboot reason and call 'reboot' request-metrics flush collectd metrics to Memfault now show-settings show memfaultd settings sync Upload all pending data to Memfault now trigger-coredump trigger a coredump and immediately reports it to Memfault (defaults to segfault) write-attributes write device attribute(s) to memfaultd add-battery-reading add a reading to memfaultd's battery metrics in format "[status string]:[0.0-100.0]" report-sync-success Report a successful sync for connectivity metrics report-sync-failure Report a failed sync for connectivity metrics start-session Begin a session and start capturing metrics for it end-session End a session and dump its metrics to MAR staging directory add-custom-data-recording Add custom data recording to memfaultd write-metrics write metrics(s) to memfaultd ``` -------------------------------- ### Memfault SDK Boot Messages Source: https://docs.memfault.com/docs/mcu/da1469x-sdk-guide Example log messages displayed on startup after `memfault_platform_boot()` is called, indicating successful initialization and configuration. ```text [I] MFLT: GNU Build ID: 6e6843f5f7410e0a51a0e62ce991fdd0d519eca7 [I] MFLT: S/N: DEMOSERIAL [I] MFLT: SW type: da1469x-demo-app [I] MFLT: SW version: 1.0.0 [I] MFLT: HW version: DA14695 ``` -------------------------------- ### Example Session Usage Source: https://docs.memfault.com/docs/mcu/metrics-api A practical example demonstrating the usage of session metrics for tracking an LTE connection. ```APIDOC ## Example Session Usage This example illustrates tracking an LTE connection using a Memfault Metric Session. ```c #include "memfault/components.h" void my_lte_state_change_handler(enum LteState state) { static uint32_t battery_connection_start_soc_pct; switch (state) { case LTE_STATE_START_CONNECTING: MEMFAULT_METRICS_SESSION_START(lte); battery_connection_start_soc_pct = 100; MEMFAULT_METRIC_SESSION_SET_UNSIGNED(battery_connection_start_soc_pct, lte, battery_connection_start_soc_pct); MEMFAULT_METRIC_SESSION_TIMER_START(lte_connecting_time_ms, lte); break; case LTE_STATE_CONNECTED: MEMFAULT_METRIC_SESSION_TIMER_STOP(lte_connecting_time_ms, lte); MEMFAULT_METRIC_SESSION_TIMER_START(lte_connected_time_ms, lte); break; case LTE_STATE_DISCONNECTED: MEMFAULT_METRIC_SESSION_TIMER_STOP(lte_connected_time_ms, lte); uint32_t battery_connection_end_soc_pct = 50; MEMFAULT_METRIC_SESSION_SET_UNSIGNED(battery_connection_end_soc_pct, lte, battery_connection_end_soc_pct); if (battery_connection_start_soc_pct >= battery_connection_end_soc_pct) { MEMFAULT_METRIC_SESSION_SET_UNSIGNED(battery_soc_pct_drop, lte, battery_connection_start_soc_pct - battery_connection_end_soc_pct); } MEMFAULT_METRIC_SESSION_SET_UNSIGNED(bytes_sent, lte, 1000); MEMFAULT_METRIC_SESSION_SET_UNSIGNED(bytes_received, lte, 2000); MEMFAULT_METRICS_SESSION_END(lte); break; default: break; } } ``` ``` -------------------------------- ### Install Rust and cross tool Source: https://docs.memfault.com/docs/linux/cross-compile-memfaultd Installs the Rust toolchain and the 'cross' utility for cross-compilation. Docker is also a prerequisite. ```bash # Install the rust toolchain on your system curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Install cross cargo install cross ``` -------------------------------- ### Example Coredump Storage Test Success Output Source: https://docs.memfault.com/docs/mcu/self-test This is an example of the expected output when the Coredump Storage self-test passes successfully. ```text MFLT:[INFO] ============================= MFLT:[INFO] Coredump Storage Test MFLT:[INFO] ============================= MFLT:[INFO] Coredump Storage Verification Passed MFLT:[INFO] ============================= ``` -------------------------------- ### Run on Raspberry Pi (Yocto) Source: https://docs.memfault.com/changelog/2023/03/31 Configuration within `meta-memfault-example` to enable Memfault integration on Raspberry Pi 2, 3, and 4. Requires specific Yocto layer setup. ```bb MACHINE = "raspberrypi4" ``` -------------------------------- ### Initialize Memfault Platform Source: https://docs.memfault.com/docs/mcu/arm-infineon-modustoolbox-guide Include the Memfault components and call `memfault_platform_boot()` during your application's initialization. This is typically done before starting the scheduler. ```c #include "memfault/components.h" int main(void) { // ... memfault_platform_boot(); // ... vTaskStartScheduler(); } ``` -------------------------------- ### Initialize Demo Shell Source: https://docs.memfault.com/docs/mcu/demo-cli-cmds-other-platforms Initialize the Memfault platform and the demo shell by providing a callback for sending characters. This should be called after other initialization code. ```c int main(void) { memfault_platform_boot(); // Other init code const sMemfaultShellImpl impl = { .send_char = prv_send_char, }; memfault_demo_shell_boot(&impl); } ``` -------------------------------- ### Install Bort Lite on Windows Source: https://docs.memfault.com/docs/android/bort-lite Use this command to install the Bort Lite APK on Windows. Replace `` with your Memfault project key. ```bash install-bort-lite.bat ``` -------------------------------- ### Install Memfault CLI Tool Source: https://docs.memfault.com/docs/android/android-releases-integration-guide Install the Memfault CLI tool using pip. This tool is used to manage releases from the command line. ```bash pip3 install memfault-cli ``` -------------------------------- ### Initialize Memfault SDK in main Source: https://docs.memfault.com/docs/mcu/arm-infineon-modustoolbox-guide Initialize the Memfault SDK from your main function before starting the FreeRTOS scheduler. ```c //! @file main.c ``` -------------------------------- ### Example Coredump Storage Test Failure Output Source: https://docs.memfault.com/docs/mcu/self-test This is an example of the output when the Coredump Storage self-test fails, indicating a read pattern mismatch. ```text MFLT:[INFO] ============================= MFLT:[INFO] Coredump Storage Test MFLT:[INFO] ============================= MFLT:[ERRO] Coredump Storage Verification Failed MFLT:[ERRO] Read pattern mismatch during memfault_platform_coredump_storage_write() test MFLT:[ERRO] Storage offset: 0x00000000, write size: 12 MFLT:[ERRO] Expected: a0a1a2a3a4a5a6a7a8a9aaab MFLT:[ERRO] Actual : 000000000000000000000000 MFLT:[INFO] ============================= ``` -------------------------------- ### Initialize Memfault Subsystem Source: https://docs.memfault.com/docs/mcu/da1469x-sdk-guide Call `memfault_platform_boot()` during system initialization, preferably after `retarget_init()`, to start the Memfault subsystem and enable logging. ```c #include "memfault/components.h" static void system_init( void *pvParameters ) { // ... #if defined CONFIG_RETARGET retarget_init(); #endif // Note: initialize Memfault after retarget_init() so logs will be displayed memfault_platform_boot(); // ... } ``` -------------------------------- ### Start Memfault CLI Task Source: https://docs.memfault.com/docs/mcu/arm-infineon-modustoolbox-guide Function to create and start the Memfault CLI task. This should be called from your main routine after initializing necessary peripherals. ```c void memfault_cli_task_start(void) { xTaskCreate(memfault_cli_task, "MFLT CLI", MEMFAULT_CLI_TASK_SIZE, NULL, MEMFAULT_CLI_TASK_PRIORITY, NULL); } ``` -------------------------------- ### Create ModusToolbox™ Project Source: https://docs.memfault.com/docs/mcu/arm-infineon-modustoolbox-guide Use the project-creator-cli to generate a sample project for a specific board and application. ```bash project-creator-cli --board-id CY8CKIT-062S2-43012 \ --app-id mtb-example-anycloud-udp-server \ --user-app-name my_example_app ``` -------------------------------- ### Example Connectivity State Callback Source: https://docs.memfault.com/docs/platform/memfault-core-metrics?platform=MCU This example shows how to use the `memfault_metrics_connectivity_connected_state_change` API within a callback function that receives a boolean indicating connection status. ```c void connectivity_state_changed_callback(bool connected) { if (connected) { memfault_metrics_connectivity_connected_state_change( kMemfaultMetricsConnectivityState_Connected); } else { memfault_metrics_connectivity_connected_state_change( kMemfaultMetricsConnectivityState_ConnectionLost); } } ``` -------------------------------- ### Copy Wi-Fi Sample Project Source: https://docs.memfault.com/docs/mcu/nrf-7002-guide Copy the Wi-Fi station sample project to the root of your West checkout for modification. ```bash cp -r nrf/samples/wifi/sta ./wifi-test ```