### Install from Source Source: https://github.com/edjopato/mqttui/blob/main/README.md Build and install the application directly from the cloned repository using Cargo. ```bash cargo install --path . ``` -------------------------------- ### MQTT Publish Command Usage Examples Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/commands.md Provides examples for using the 'mqttui publish' command to send messages, including publishing strings, from files, with retain flag, and verbose output. ```bash # Publish string payload mqttui publish sensors/temp "22.5" # Publish from file cat /etc/hostname | mqttui publish server/name # Publish with retain flag mqttui publish config/mode "auto" --retain # Show MQTT communication mqttui publish my/topic "data" --verbose ``` -------------------------------- ### Install mqttui via Debian Package Source: https://github.com/edjopato/mqttui/blob/main/README.md Install a downloaded .deb file using dpkg. ```bash sudo dpkg -i ``` -------------------------------- ### Install mqttui via Package Managers Source: https://github.com/edjopato/mqttui/blob/main/README.md Commands for installing the tool on various operating systems. ```bash apk add mqttui ``` ```bash pacman -S mqttui ``` ```bash brew install mqttui ``` -------------------------------- ### Subscribe with Custom Broker Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/configuration.md Example of setting the MQTTUI_BROKER environment variable to connect to a specific broker and then subscribing to topics. ```bash export MQTTUI_BROKER=mqtt://home-server.local:1883 mqttui sensors/temperature sensors/humidity ``` -------------------------------- ### Example of formatting QoS level Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/payload-formatting.md Shows how to use the `format::qos` function to convert a QoS enum value to a string and print it. Requires importing QoS and the format module. ```rust use rumqttc::QoS; use mqttui::format; let level = QoS::AtLeastOnce; println!("QoS: {}", format::qos(level)); // QoS: AtLeastOnce ``` -------------------------------- ### Interactive TUI Flow Example Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Illustrates the user interaction flow when running mqttui with a topic argument, detailing argument parsing, MQTT connection, and the main TUI loop. ```text User runs: mqttui sensors/ 1. Parse arguments └─ topics: ["sensors/"] 2. Call mqtt::connect() └─ Return (broker, client, connection) 3. Call interactive::show() ├─ Spawn mqtt_thread (subscribes to topics) ├─ Create App state ├─ Enable raw terminal mode ├─ Enter main_loop │ ├─ Poll for input (500ms) │ ├─ Render frame from app state │ ├─ Query mqtt_thread for history │ └─ Update app state on input ├─ Exit on Ctrl+C or 'q' └─ Restore terminal ``` -------------------------------- ### MQTT Log Command Usage Examples Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/commands.md Demonstrates various ways to use the 'mqttui log' command, including subscribing to all topics, specific topics with JSON output, verbose logging, and logging to a file. ```bash # Subscribe to all topics mqttui log # Subscribe to specific topics with JSON output mqttui log --json sensors/# devices/# # Show full MQTT communication mqttui log --verbose # Log to file with line buffering mqttui log sensors/# | tee output.log ``` -------------------------------- ### Install via RPM Source: https://github.com/edjopato/mqttui/blob/main/README.md Use the rpm command to install the downloaded package on Red Hat, CentOS, and other RPM-based Linux distributions. ```bash sudo rpm -i ``` -------------------------------- ### Broker Parsing and Display Examples Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/types.md Demonstrates parsing a broker string into the Broker enum and formatting a Broker enum back into a URL string. ```rust let broker = "mqtts://broker.example.com:8883".parse::()?; assert_eq!(broker.to_string(), "mqtts://broker.example.com:8883"); let broker = "mqtt://localhost".parse::()?; assert_eq!(broker.to_string(), "mqtt://localhost"); ``` -------------------------------- ### Verify Broker Address and Port Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Example of running mqttui with an incorrect broker address, highlighting the need to verify the URL. ```bash # Wrong host $ mqttui --broker mqtt://wrong.host # Solution: Check broker URL $ mqttui --broker broker.example.com:1883 ``` -------------------------------- ### Configure TLS Verification for MQTTUI Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Use this to set up secure connections to MQTT brokers. The first example shows production settings with certificate verification, while the second (commented out) is for development with self-signed certificates. ```bash #!/bin/bash # Always verify TLS in production (default behavior) # Production: Verify certificates (default) mqttui --broker mqtts://broker.production.com \ --client-cert /etc/mqtt/client.crt \ --client-private-key /etc/mqtt/client.key \ sensors/# # Development/Testing: Allow self-signed (temporary only) # mqttui --broker mqtts://broker.local --insecure sensors/# ``` -------------------------------- ### Connect with Insecure TLS for Testing Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Example of using the `--insecure` flag for testing with self-signed certificates. Not recommended for production. ```bash # For self-signed certs (NOT recommended for production) mqttui --broker mqtts://broker.local --insecure ``` -------------------------------- ### Example Text Log Output Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/commands.md Illustrates the formatted text output for MQTT log messages, showing retained messages and standard messages with timestamps. ```text RETAINED QoS:AtMostOnce sensors/temp Payload( 6): 22.15 12:34:56.789 QoS:AtLeastOnce devices/status/online Payload( 4): true ``` -------------------------------- ### Interactive MQTT Topic Browsing Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/api-overview.md Starts an interactive terminal UI to browse MQTT topics. Connects to the specified broker and subscribes to a topic pattern. ```bash mqttui --broker mqtt://home:1883 "home/#" ``` -------------------------------- ### Test TLS Connection with Client Certificate Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Test a TLS connection to an MQTT broker using OpenSSL, providing client certificate and key for authentication. Essential for mutual TLS (mTLS) setups. ```bash openssl s_client -connect broker.example.com:8883 \ -cert client.crt -key client.key ``` -------------------------------- ### Build Steps for mqttui Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Commands to compile the project for release, generate shell completions, and create man pages using Cargo. ```bash # Compile normally cargo build --release # Generate shell completions cargo build --release --features gen-completions # Generate man pages cargo build --release --features gen-manpages ``` -------------------------------- ### Main Function Entry Point Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/api-overview.md The main function parses CLI arguments, establishes an MQTT connection, and dispatches to the appropriate command handler or launches the interactive TUI. ```rust fn main() -> anyhow::Result<()> { let matches = cli::Cli::parse(); let (broker, client, connection) = mqtt::connect(matches.mqtt_connection, ...)?; match matches.subcommands { Some(Subcommands::Publish { ... }) => publish::eventloop(...), Some(Subcommands::Log { ... }) => log::show(...), Some(Subcommands::ReadOne { ... }) => read_one::show(...), Some(Subcommands::CleanRetained { ... }) => clean_retained::clean_retained(...), None => interactive::show(...), } } ``` -------------------------------- ### Get JSON value by path Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/payload-formatting.md Navigates a JSON structure using a sequence of JsonSelector path components and returns a reference to the selected value. ```rust pub fn get_json( root: &serde_json::Value, selector: &[JsonSelector] ) -> Option<&serde_json::Value> ``` -------------------------------- ### Subscribe to MQTT Topics Source: https://github.com/edjopato/mqttui/blob/main/README.md Use the base command to subscribe to topics. Defaults to localhost if no broker is specified. ```bash # Subscribe to everything (#) mqttui # Subscribe to topic mqttui "topic" # Subscribe to topic with a specific host (default is mqtt://localhost) mqttui --broker "mqtt://test.mosquitto.org" "hello/world" # More arguments and details mqttui --help ``` -------------------------------- ### Show all topics with mqttui log Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Lists all topics on the broker using `mqttui log "#"`. Use with caution on busy brokers. ```bash # Show all topics (be careful on large brokers) mqttui log "#" ``` -------------------------------- ### Distribute Application Configuration via MQTT Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Fetches application configuration from a specified MQTT topic and applies it to the system. ```bash #!/bin/bash # Fetch and apply configuration from MQTT config=$(mqttui read-one config/app-config --pretty) echo "$config" > /etc/app/config.json # Reload application systemctl reload app-service ``` -------------------------------- ### Secure Credential Management with Environment Variables Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Demonstrates secure credential management by using environment variables for MQTT broker connection details, avoiding command-line exposure. ```bash #!/bin/bash # Use environment variables, never command line # Good: Credentials from environment export MQTTUI_USERNAME=admin export MQTTUI_PASSWORD="$(pass show mqtt/broker)" export MQTTUI_BROKER=mqtts://broker.local mqttui log sensors/# # Bad: Credentials in command (visible in ps, history) # mqttui log --username admin --password secret sensors/# ``` -------------------------------- ### Connect with Custom Broker and Credentials Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/interactive-tui.md Launches the interactive TUI, specifying broker address, username, password, and a topic to subscribe to. ```bash mqttui --broker mqtts://broker.local \ --username admin \ --password secret \ home/ ``` -------------------------------- ### Get MessagePack value by path Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/payload-formatting.md Navigates a MessagePack structure using a sequence of JsonSelector path components and returns a reference to the selected value. Handles string and non-string keys in MessagePack maps. ```rust pub fn get_messagepack( root: &rmpv::Value, selector: &[JsonSelector] ) -> Option<&rmpv::Value> ``` -------------------------------- ### Check Certificate File Existence Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Illustrates checking for the existence of client certificate and private key files. ```bash # Certificate file not found $ mqttui --client-cert /etc/mqtt/client.crt --client-private-key /etc/mqtt/key.pem # Solution: Check files exist $ ls -l /etc/mqtt/ ``` -------------------------------- ### Read Single MQTT Message Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/commands.md Reads a single message from a specified topic. Can be used to get current values, wait for specific events, or fetch structured data. Supports ignoring retained messages and pretty-printing output. ```bash temp=$(mqttui read-one room/temperature) echo "Temperature: ${temp}°C" ``` ```bash reading=$(mqttui read-one --ignore-retained sensor/co2) ``` ```bash mqttui read-one --pretty api/response ``` ```bash mqttui read-one devices/+/status ``` -------------------------------- ### connect() Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/mqtt-connect.md Establishes a connection to an MQTT broker and waits for acknowledgement. It supports various connection configurations including authentication and TLS. ```APIDOC ## connect() ### Description Establishes connection to MQTT broker and waits for acknowledgement. ### Method Rust Function ### Parameters #### Path Parameters - **mqtt_connection** (MqttConnection) - Required - Connection configuration (broker URL, auth, TLS settings) - **keep_alive** (Option) - Optional - MQTT keep-alive timeout; None uses rumqttc default ### Returns Tuple of: `Broker`, `Client`, `Connection` ### Throws - `anyhow::Error` if connection fails or broker rejects connection ### Example ```rust use mqttui::cli::{Broker, MqttConnection}; use mqttui::mqtt; let broker: Broker = "mqtt://localhost:1883".parse()?; let mqtt_connection = MqttConnection { broker, username: Some("user".to_string()), password: Some("pass".to_string()), client_id: None, client_cert: None, client_private_key: None, insecure: false, }; let (broker, client, connection) = mqtt::connect(mqtt_connection, None)?; // Now can use client.publish() and client.subscribe() // and iterate over connection for events ``` ``` -------------------------------- ### Publish with Authentication Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/configuration.md Set environment variables for username, password, and broker address before publishing a message. ```bash export MQTTUI_USERNAME=admin export MQTTUI_PASSWORD=secret export MQTTUI_BROKER=mqtts://broker.example.com mqttui publish devices/switch/state "on" ``` -------------------------------- ### Configure MQTT Broker via Environment Variables Source: https://github.com/edjopato/mqttui/blob/main/README.md Set the default broker using environment variables to avoid repeated command-line flags. ```bash export MQTTUI_BROKER=mqtt://pi-home.local # Use the command without specifying the broker every time mqttui "topic" ``` -------------------------------- ### Set MQTT Credentials via Environment Variables Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Configure MQTT username and password using environment variables for authentication. Ensure these are kept secure. ```bash export MQTTUI_USERNAME=admin export MQTTUI_PASSWORD=secret ``` -------------------------------- ### Connect to MQTT Broker Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/mqtt-connect.md Establishes a connection to an MQTT broker with optional authentication and keep-alive settings. Use this to initiate communication with the broker. ```rust use mqttui::cli::{Broker, MqttConnection}; use mqttui::mqtt; let broker: Broker = "mqtt://localhost:1883".parse()?; let mqtt_connection = MqttConnection { broker, username: Some("user".to_string()), password: Some("pass".to_string()), client_id: None, client_cert: None, client_private_key: None, insecure: false, }; let (broker, client, connection) = mqtt::connect(mqtt_connection, None)?; // Now can use client.publish() and client.subscribe() // and iterate over connection for events ``` -------------------------------- ### Log Command Data Flow Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Illustrates the data flow for the 'log' command, from parsing CLI arguments and establishing an MQTT connection to subscribing and printing incoming messages. ```text User runs: mqttui log sensors/temperature 1. Parse CLI arguments ├─ broker: mqtt://localhost ├─ qos: 2 └─ topic: sensors/temperature 2. Call mqtt::connect() ├─ Parse broker URL ├─ Configure transport (TCP) ├─ Create MQTT client ├─ Wait for ConnAck └─ Return (broker, client, connection) 3. Client subscribes to topic with QoS 2 4. Call log::show(connection, ...) ├─ Loop on connection.iter() ├─ For each Publish packet: │ ├─ Extract topic, payload, QoS │ ├─ Call Payload::unlimited() for format detection │ ├─ Format output line │ └─ Print to stdout └─ Exit on connection close ``` -------------------------------- ### Handle Invalid MQTT Credentials Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Demonstrates connecting with invalid username/password and the solution using environment variables. ```bash # Invalid credentials $ mqttui --username admin --password wrong --broker mqtt://broker.local # Solution: Use correct password $ export MQTTUI_PASSWORD=correct mqttui --broker mqtt://broker.local ``` -------------------------------- ### Main Application Loop Logic Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Describes the sequence of operations in the main application entry point, from parsing arguments to executing subcommands or launching the interactive TUI. ```text ┌─ Parse CLI arguments ├─ Create MQTT connection ├─ Check for subcommand │ ├─ If Publish: run publish::eventloop │ ├─ If Log: run log::show │ ├─ If ReadOne: run read_one::show │ ├─ If CleanRetained: run clean_retained::clean_retained │ └─ If None: launch interactive::show └─ Exit with result ``` -------------------------------- ### MQTT Publish Command Usage from Stdin Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/commands.md Shows how to use the 'mqttui publish' command to send data piped from standard input when the payload argument is omitted. ```bash echo "message" | mqttui publish my/topic cowsay "Alert!" | mqttui publish alerts/critical cat large-file.bin | mqttui publish data/upload ``` -------------------------------- ### Test Broker Connectivity with mosquitto tools Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Uses `mosquitto_sub` and `mosquitto_pub` to test publish/subscribe functionality against a broker. ```bash # Test with mosquitto tools mosquitto_sub -h broker.example.com -t "test/topic" & mosquitto_pub -h broker.example.com -t "test/topic" -m "hello" ``` -------------------------------- ### Try Multiple Fallback Brokers Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md This script iterates through a list of MQTT brokers, attempting to connect to each one with a timeout. It breaks the loop upon successful connection. ```bash #!/bin/bash # Try multiple brokers brokers=( "mqtt://primary.local:1883" "mqtt://secondary.local:1883" "mqtt://tertiary.cloud:8883" ) for broker in "${brokers[@]}"; do echo "Trying broker: $broker" if timeout 5 mqttui log --json sensors/# --broker "$broker"; then echo "Connected to $broker" break fi done ``` -------------------------------- ### Publish Command Data Flow Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Details the data flow for the 'publish' command, including reading payload from stdin, establishing an MQTT connection, and publishing the message. ```text User runs: echo "data" | mqttui publish my/topic 1. Parse CLI arguments ├─ topic: my/topic ├─ payload: None (read from stdin) └─ retain: false 2. Read payload from stdin └─ payload = "data" 3. Call mqtt::connect() └─ Return (broker, client, connection) 4. Client publishes ├─ client.publish(topic, QoS::AtLeastOnce, false, payload) └─ Return on success 5. Call publish::eventloop(client, connection, ...) ├─ Loop on connection.iter() ├─ Wait for PubAck or PingResp ├─ On receipt: client.disconnect() └─ Exit ``` -------------------------------- ### Run MQTTUI with RUST_BACKTRACE Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Execute MQTTUI commands with RUST_BACKTRACE enabled to capture detailed backtraces upon encountering errors. This is crucial for diagnosing runtime issues in Rust applications. ```bash RUST_BACKTRACE=1 mqttui log sensors/temp ``` ```bash RUST_BACKTRACE=full mqttui log sensors/temp ``` -------------------------------- ### Verify Certificate File Path Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Demonstrates checking if a certificate file exists at the specified path and using an absolute path if necessary. ```bash # Check path ls -la /etc/mqtt/client-cert.pem # Or use absolute path mqttui --client-cert /absolute/path/to/cert.pem ``` -------------------------------- ### Enable Verbose MQTT Output via Environment Variable Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Enable verbose logging for MQTT communication by setting the MQTTUI_VERBOSE environment variable. Useful for detailed debugging of MQTT interactions. ```bash export MQTTUI_VERBOSE=true ``` -------------------------------- ### Run Unit Tests with Output Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Executes all unit tests and displays their output. Useful for debugging test failures. ```bash cargo test -- --nocapture ``` -------------------------------- ### Run Unit Tests with Backtrace Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Enables the backtrace for unit tests, providing detailed call stack information on panic. ```bash RUST_BACKTRACE=1 cargo test --lib ``` -------------------------------- ### Create TLS Configuration Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/mqtt-connect.md Creates a rustls TLS configuration for secure MQTT connections. Use this when connecting to brokers that require TLS/SSL, providing client certificates and keys if necessary. ```rust use mqttui::mqtt::encryption; use std::path::Path; let tls = encryption::create_tls_configuration( false, Some(Path::new("/etc/mqtt/client.crt")), Some(Path::new("/etc/mqtt/client.key")), )?; ``` -------------------------------- ### Configure Custom MQTT Broker via Environment Variable Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Set a custom MQTT broker address using the MQTTUI_BROKER environment variable. Allows connecting to brokers other than the default. ```bash export MQTTUI_BROKER=mqtt://home-server:1883 ``` -------------------------------- ### Test MQTT Connectivity and Functionality Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Tests basic MQTT publish, read, and cleanup operations against a specified broker. ```bash #!/bin/bash # Test MQTT connectivity and basic functionality set -e BROKER="${1:-mqtt://localhost}" TEST_TOPIC="test/mqttui/$(date +%s)" echo "Testing broker: $BROKER" # Test publish echo "Publishing test message..." echo "test payload" | mqttui publish "$TEST_TOPIC" --broker "$BROKER" # Test read echo "Reading back message..." value=$(mqttui read-one "$TEST_TOPIC" --broker "$BROKER" 2>/dev/null) if [ "$value" = "test payload" ]; then echo "✓ Test passed" else echo "✗ Test failed: got '$value'" exit 1 fi # Test retained cleanup echo "Cleaning retained..." mqttui clean-retained "$TEST_TOPIC" --broker "$BROKER" echo "All tests passed" ``` -------------------------------- ### create_tls_configuration() Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/mqtt-connect.md Creates a rustls TLS configuration for secure MQTT connections, supporting client certificates and disabling verification if needed. ```APIDOC ## create_tls_configuration() ### Description Creates rustls TLS configuration for secure connections. ### Method Rust Function ### Parameters #### Path Parameters - **insecure** (bool) - If true, disables certificate verification - **client_cert** (Option<&Path>) - Path to PEM-encoded client certificate - **client_private_key** (Option<&Path>) - Path to PEM-encoded private key ### Returns `rumqttc::TlsConfiguration::Rustls` wrapping ClientConfig ### Throws - `anyhow::Error` if certificate/key files cannot be read - `anyhow::Error` if TLS configuration fails ### Example ```rust use mqttui::mqtt::encryption; use std::path::Path; let tls = encryption::create_tls_configuration( false, Some(Path::new("/etc/mqtt/client.crt")), Some(Path::new("/etc/mqtt/client.key")), )?; ``` ``` -------------------------------- ### Log MQTT Messages to File Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Logs all incoming MQTT messages in JSON format to a file using tee for simultaneous display and logging. ```bash # Log messages to file mqttui log --json sensors/# | tee sensor-data.jsonl ``` -------------------------------- ### Publish MQTT Messages Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/api-overview.md Connect to an MQTT broker and publish a message to a specified topic. Includes waiting for a publish acknowledgement. ```rust let (_, mut client, connection) = mqtt::connect(mqtt_conn, None)?; client.publish("my/topic", QoS::AtLeastOnce, false, b"Hello")?; // Wait for acknowledgement for notification in connection.iter() { match notification { Ok(Event::Incoming(Packet::PubAck(_))) => break, _ => {} } } ``` -------------------------------- ### Cross-Compile for Release Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Builds the project for a specific target architecture and operating system in release mode. ```bash cargo build --target x86_64-unknown-linux-musl --release ``` -------------------------------- ### Run All Unit Tests Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Command to execute all unit tests within the Rust project. Use `-- --nocapture` to see test output. ```bash cargo test --lib ``` -------------------------------- ### Release Build Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Compiles the project for release, optimizing for runtime performance at the cost of longer compilation times. The executable is located in `target/release/`. ```bash cargo build --release ``` -------------------------------- ### Subscribe to Specific Topics Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/interactive-tui.md Launches the interactive TUI and subscribes to a predefined list of topics. ```bash mqttui sensors/# devices/+/status ``` -------------------------------- ### Connection Iterator Pattern Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/mqtt-connect.md Demonstrates how to iterate over the `Connection` object obtained from `mqtt::connect()` to receive and process MQTT events. ```APIDOC ## Connection Iterator Pattern ### Description After obtaining a `Connection` from `connect()`, iterate to receive events. ### Example ```rust let (broker, client, connection) = mqtt::connect(mqtt_connection, None)?; for notification in connection.iter() { match notification { Ok(rumqttc::Event::Incoming(rumqttc::Packet::Publish(publish))) => { println!("Message on {}: {}", publish.topic, String::from_utf8_lossy(&publish.payload)); } Ok(rumqttc::Event::Outgoing(outgoing)) => { // Track sent packets } Err(e) => eprintln!("Connection error: {}", e), } } ``` ### Event Types | Type | Meaning | |------|---------| | Event::Incoming(Packet::Publish) | New message received | | Event::Incoming(Packet::PubAck) | QoS 1 publish acknowledged | | Event::Incoming(Packet::PubComp) | QoS 2 publish complete | | Event::Incoming(Packet::SubAck) | Subscription acknowledged | | Event::Outgoing(*) | Message sent to broker | ``` -------------------------------- ### Core MQTT UI Modules Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/README.md Exposes core functionalities for connecting to MQTT brokers, handling different payload types, and managing CLI arguments. Includes definitions for Broker, Payload, and Cli structures. ```rust // mqtt:: pub fn connect(...) -> Result<(Broker, Client, Connection)> pub enum Broker { Tcp {...}, Ssl {...}, WebSocket(...), WebSocketSsl(...)} pub struct HistoryEntry { qos, time, payload_size, payload } pub enum Time { Retained, Local(NaiveDateTime) } // payload:: pub enum Payload { Binary(...), Json(...), MessagePack(...), String(...)} impl Payload { pub fn truncated(payload, limit) -> Self pub fn unlimited(payload) -> Self } // cli:: pub struct Cli { subcommands, topic, qos, payload_size_limit, mqtt_connection } pub enum Subcommands { CleanRetained, Log, ReadOne, Publish } // Commands (functions, not exported): fn log::show(connection, json, verbose) fn publish::eventloop(client, connection, verbose) fn read_one::show(client, connection, ignore_retained, pretty) fn clean_retained::clean_retained(client, connection, qos, dry_run) fn interactive::show(client, connection, broker, topics, qos, limit) ``` -------------------------------- ### Event-Driven Processing Architecture Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Illustrates an event-driven architecture where MQTT data is logged, filtered, and then processed by external systems. ```text MQTT Broker ↓ mqttui log --json ↓ [jq filtering/transformation] ↓ [Process (save to DB, trigger action, etc)] ``` -------------------------------- ### MQTT Connection with Keep-Alive Setting Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/mqtt-connect.md Establishes an MQTT connection and configures a custom keep-alive interval to maintain the connection. ```rust use std::time::Duration; let keep_alive = Some(Duration::from_secs(30)); let (_, client, connection) = mqtt::connect(mqtt_conn, keep_alive)?; ``` -------------------------------- ### Subscribe to Specific MQTT Topics Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Subscribe to specific MQTT topic patterns instead of a wildcard like '#'. This reduces CPU load by limiting the number of messages processed. ```bash mqttui log "sensors/+" "devices/status" ``` -------------------------------- ### Subscribe and Receive MQTT Messages Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/api-overview.md Connect to an MQTT broker, subscribe to a topic, and iterate through incoming messages, processing publish events. ```rust let (broker, mut client, connection) = mqtt::connect(mqtt_conn, None)?; // Subscribe to topics client.subscribe("sensors/+/temperature", QoS::AtLeastOnce)?; // Iterate connection to receive events for notification in connection.iter() { match notification { Ok(Event::Incoming(Packet::Publish(publish))) => { let payload = Payload::unlimited(publish.payload.into()); println!("Topic: {}, Payload: {}", publish.topic, payload); } _ => {} } } ``` -------------------------------- ### Adjust Certificate File Permissions Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Provides commands to set appropriate file permissions for certificate and key files. ```bash chmod 644 /path/to/cert.pem chmod 600 /path/to/key.pem ``` -------------------------------- ### Secure Connection with Client Certificate Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/configuration.md Connect to a broker using MQTT over TLS with a client certificate and private key. ```bash mqttui --broker mqtts://broker.example.com \ --client-cert /path/to/client.pem \ --client-private-key /path/to/key.pem \ sensors/# ``` -------------------------------- ### Authenticated MQTT Connection Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/mqtt-connect.md Establishes an MQTT connection with username and password authentication to a specified broker. ```rust let mqtt_conn = MqttConnection { broker: "mqtt://example.com".parse()?, username: Some("admin".to_string()), password: Some("secret".to_string()), client_id: Some("my-client".to_string()), client_cert: None, client_private_key: None, insecure: false, }; let (_, client, connection) = mqtt::connect(mqtt_conn, None)?; ``` -------------------------------- ### Capture Full MQTT Protocol Trace Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Use this command to log all MQTT packets for detailed analysis. The output can be piped to 'tee' to save to a file and then filtered for specific packet types. ```bash # Log all MQTT packets for analysis mqttui log --verbose sensors/# 2>&1 | tee protocol-trace.log # Later, analyze: grep "outgoing\|incoming" protocol-trace.log | head -50 ``` -------------------------------- ### Build MQTTUI with Debug Symbols Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Compile the MQTTUI project with debug symbols enabled for easier debugging. The `--release` flag is used for optimized builds. ```bash cargo build # Debug build with symbols ``` ```bash cargo build --release # Optimized build ``` -------------------------------- ### List Available Targets Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Displays a list of all available compilation targets for the Rust toolchain. ```bash rustc --print target-list ``` -------------------------------- ### Launch Interactive TUI Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/interactive-tui.md Launches the interactive terminal UI and blocks until the user quits. Requires MQTT client, connection, broker info, initial topics, QoS, and payload size limit. ```rust pub fn show( client: Client, connection: Connection, broker: &Broker, subscribe_topic: Vec, qos: QoS, payload_size_limit: usize, ) -> anyhow::Result<()> ``` -------------------------------- ### Main Application State Structure Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/interactive-tui.md Defines the core structure of the application state, managing different UI panes and the focus. ```rust pub struct App { details: details::Details, focus: ElementInFocus, footer: footer::Footer, mqtt_thread: mqtt_thread::MqttThread, topic_overview: topic_overview::TopicOverview, } ``` -------------------------------- ### Subscribe to MQTT Topic Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/mqtt-connect.md Subscribes to a specified MQTT topic with a given Quality of Service level. Supports topic wildcards. ```rust pub fn subscribe(&mut self, topic: impl Into, qos: QoS) -> Result<(), ClientError> ``` -------------------------------- ### Launch Interactive TUI Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/interactive-tui.md Launches the interactive TUI for all topics. This is the default command. ```bash mqttui ``` -------------------------------- ### Decrypt Encrypted Private Key Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Shows how to decrypt an encrypted private key using OpenSSL before using it with mqttui. ```bash # Decrypt encrypted private key openssl pkey -in encrypted.key -out decrypted.key mqttui --client-cert cert.pem --client-private-key client-decrypted.key --broker mqtts://broker.local ``` -------------------------------- ### Log MQTT Topics to Stdout Source: https://github.com/edjopato/mqttui/blob/main/README.md Monitor one or more topics and stream incoming messages to the terminal. ```plaintext $ mqttui log "espHome-co2/sensor/#" "espHome-test/sensor/temperature/state" RETAINED espHome-co2/sensor/rssi/state QoS:AtMostOnce Payload( 6): -80.09 RETAINED espHome-co2/sensor/co2/state QoS:AtMostOnce Payload( 5): 450.8 RETAINED espHome-co2/sensor/temperature/state QoS:AtMostOnce Payload( 6): 22.129 RETAINED espHome-co2/sensor/humidity/state QoS:AtMostOnce Payload( 5): 25.18 RETAINED espHome-test/sensor/temperature/state QoS:AtMostOnce Payload( 6): 10.339 12:10:06.650 espHome-test/sensor/temperature/state QoS:AtMostOnce Payload( 6): 10.454 12:10:39.606 espHome-co2/sensor/co2/state QoS:AtMostOnce Payload( 5): 432.5 12:10:53.860 espHome-co2/sensor/temperature/state QoS:AtMostOnce Payload( 6): 21.974 12:12:06.644 espHome-test/sensor/temperature/state QoS:AtMostOnce Payload( 6): 10.536 12:12:39.556 espHome-co2/sensor/co2/state QoS:AtMostOnce Payload( 5): 404.3 12:12:53.859 espHome-co2/sensor/temperature/state QoS:AtMostOnce Payload( 6): 21.921 12:13:20.146 espHome-co2/sensor/humidity/state QoS:AtMostOnce Payload( 5): 25.11 12:13:27.906 espHome-co2/sensor/rssi/state QoS:AtMostOnce Payload( 6): -79.81 12:14:06.643 espHome-test/sensor/temperature/state QoS:AtMostOnce Payload( 6): 10.568 ``` ```bash # Subscribe to topic mqttui log "topic" # Multiple topics mqttui log "topic1" "topic2" # More arguments and details mqttui log --help ``` -------------------------------- ### Test TLS Connection with OpenSSL Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Perform a basic TLS connection test to an MQTT broker using OpenSSL. This helps verify broker accessibility and TLS configuration. ```bash openssl s_client -connect broker.example.com:8883 ``` -------------------------------- ### TLS MQTT Connection with Client Certificate Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/mqtt-connect.md Establishes a secure MQTT connection using TLS, providing client certificate and private key for authentication. ```rust use std::path::PathBuf; let mqtt_conn = MqttConnection { broker: "mqtts://secure.example.com".parse()?, username: None, password: None, client_id: None, client_cert: Some(PathBuf::from("/etc/mqtt/client.crt")), client_private_key: Some(PathBuf::from("/etc/mqtt/client.key")), insecure: false, }; let (_, client, connection) = mqtt::connect(mqtt_conn, None)?; ``` -------------------------------- ### Check Code Formatting Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Verifies that the code adheres to the project's formatting standards using `cargo fmt`. ```bash cargo fmt --check ``` -------------------------------- ### MQTT Request-Response Client Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Implements a client that sends a request to a specific topic and waits for a response on a generated response topic with a timeout. ```bash #!/bin/bash # Client sends request and waits for response request_id="req-$(date +%s%N)" request_topic="api/requests/$request_id" response_topic="api/responses/$request_id" # Send request echo '{"action":"getData"}' | \ mqttui publish "$request_topic" --broker mqtt://server # Wait for response (with timeout) timeout 5 mqttui read-one "$response_topic" --pretty --ignore-retained ``` -------------------------------- ### Log MQTT Topics Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/api-overview.md Logs messages from specified MQTT topics in JSON format. Useful for monitoring sensor data. ```bash mqttui log sensors/temperature sensors/humidity --json ``` -------------------------------- ### Project Metadata in Cargo.toml Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Defines the core metadata for the mqttui project, including its name, description, version, license, repository, authors, keywords, categories, and Rust edition. ```toml [package] name = "mqttui" description = "Subscribe to a MQTT Topic or publish something quickly from the terminal" version = "0.23.0" license = "GPL-3.0-or-later" repository = "https://github.com/EdJoPaTo/mqttui" authors = ["EdJoPaTo "] keywords = ["mqtt", "iot", "tui", "cli", "terminal"] categories = ["command-line-utilities", "network-programming"] edition = "2024" rust-version = "1.86" ``` -------------------------------- ### Development Build Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Compiles the project for development, resulting in faster build times but slower runtime performance. The executable is located in `target/debug/`. ```bash cargo build ``` -------------------------------- ### Real-Time Dashboard Architecture Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Describes an architecture for a real-time dashboard that uses MQTT data directly for in-process display and user interaction. ```text MQTT Data Stream ↓ mqttui log (in-process) ↓ [TUI display, updated in real-time] ↓ [User interaction] ``` -------------------------------- ### Data Pipeline Architecture Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md A high-level view of a data pipeline that ingests MQTT data, processes it, and stores it. ```text [MQTT Sources] → mqttui → [File/Stream] → [Processing] → [Storage] ``` -------------------------------- ### Reusable MQTT Utility Functions Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md A bash script library providing reusable functions for publishing, reading, and logging MQTT messages, designed for module composition. ```bash #!/bin/bash # lib/mqtt.sh - Common MQTT functions mqtt_publish() { local topic="$1" local payload="$2" local broker="${MQTT_BROKER:-mqtt://localhost}" echo "$payload" | mqttui publish "$topic" --broker "$broker" } mqtt_read() { local topic="$1" local broker="${MQTT_BROKER:-mqtt://localhost}" mqttui read-one "$topic" --broker "$broker" 2>/dev/null } mqtt_log_json() { local topic="${1:-#}" local broker="${MQTT_BROKER:-mqtt://localhost}" mqttui log --json "$topic" --broker "$broker" } # Usage in other scripts source lib/mqtt.sh value=$(mqtt_read "sensors/temperature") echo "Temperature: $value" ``` -------------------------------- ### Capturing MQTT Read One Output Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/commands.md Demonstrates how to capture the payload and topic from the 'mqttui read-one' command into shell variables, separating stdout (payload) from stderr (topic). ```bash # Capture payload to variable temp=$(mqttui read-one sensors/temperature) # Capture payload and process, separating from topic name payload=$(mqttui read-one data/feed 2>/dev/null) topic=$(mqttui read-one data/feed 2>&1 >/dev/null) ``` -------------------------------- ### Monitor Broker Status Topics Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Subscribe to system-level topics on an MQTT broker to monitor its status, such as connected clients and received messages. The specific topics may vary by broker implementation. ```bash # Subscribe to broker info topic (broker-specific) mqttui log "$SYS/broker/clients/connected" "$SYS/broker/publish/messages/received" ``` ```bash # Monitor disconnections mqttui log "$SYS/broker/clients/disconnected" ``` -------------------------------- ### Aggregate Sensor Data via FIFO Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Logs sensor temperature readings to a FIFO pipe for real-time aggregation and display. ```bash #!/bin/bash # Aggregate data from multiple sensors # In background, log all sensor readings mkfifo /tmp/mqtt-fifo tail -f /tmp/mqtt-fifo & mqtt_tail_pid=$! # Publish sensor data to aggregator topic mqttui log --json sensors/+/temperature | \ jq -r '.payload' | \ while read value; do echo "[$(date +%T)] Temperature: $value" >> /tmp/mqtt-fifo done wait $mqtt_tail_pid ``` -------------------------------- ### Alert on High Temperature via MQTT Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Monitors a specific MQTT topic for temperature readings and sends an email alert if the threshold is exceeded. ```bash #!/bin/bash # Alert if temperature exceeds threshold mqttui read-one room/temperature | { read -r temp if (( $(echo "$temp > 30" | bc -l) )); then echo "HIGH TEMPERATURE ALERT: $temp°C" | mail -s "Alert" admin@example.com fi } ``` -------------------------------- ### Backup Retained MQTT Messages Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Creates a timestamped directory and backs up retained messages from specified topics. ```bash #!/bin/bash # Backup retained messages from topics backup_dir="mqtt-backup-$(date +%Y%m%d_%H%M%S)" mkdir "$backup_dir" ``` -------------------------------- ### Implement Audit Logging for MQTT Operations Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md This script logs all MQTT operations to a specified audit file for compliance purposes. It records the user, time, and command executed. ```bash #!/bin/bash # Log all MQTT operations for compliance audit_log="/var/log/mqtt-audit.log" { echo "User: $(whoami)" echo "Time: $(date -Iseconds)" echo "Command: $@" echo "---" } >> "$audit_log" $@ ``` -------------------------------- ### Debian Package Metadata Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md TOML configuration for packaging the application as a Debian (.deb) package, specifying assets and dependencies. ```toml [package.metadata.deb] depends = "" section = "net" assets = [ ["target/release/mqttui", "/usr/bin/", "755"], ["target/completions/mqttui.bash", "/usr/share/bash-completion/completions/", "644"], ] ``` -------------------------------- ### Log MQTT Data with Timestamps Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Logs incoming JSON MQTT messages to a timestamped file, appending a current timestamp to each line. ```bash #!/bin/bash # Log MQTT data with timestamp for analysis logfile="mqtt-$(date +%Y%m%d_%H%M%S).log" echo "Logging to $logfile..." mqttui log --json sensors/# | while read line; do timestamp=$(date -Iseconds) echo "[$timestamp] $line" >> "$logfile" done ``` -------------------------------- ### Interactive Mode Usage Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/configuration.md Run MQTT UI in interactive mode to subscribe to topics. Supports wildcard subscriptions. Environment variable MQTTUI_TOPIC can be used to set default topics. ```bash mqttui [TOPICS...] ``` -------------------------------- ### Publish a Message Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/README.md Send a message to a specified MQTT topic. Supports retaining messages. ```bash echo "data" | mqttui publish my/topic mqttui publish config/mode "auto" --retain ``` -------------------------------- ### Enable Verbose Output in mqttui Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Activates detailed MQTT protocol logging for debugging outgoing and incoming packets. ```bash mqttui log --verbose sensors/temp ``` -------------------------------- ### Alert on MQTT Connection Errors Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md This script logs MQTT connection errors to a file and sends an email notification to an administrator if the exit code is non-zero. ```bash #!/bin/bash # Alert on connection errors logfile="/tmp/mqttui.log" mqttui log sensors/# --broker mqtt://broker.local 2>"$logfile" exit_code=$? if [ $exit_code -ne 0 ]; then error_msg=$(cat "$logfile") echo "MQTT error: $error_msg" | \ mail -s "MQTT Connection Failed" admin@example.com fi ``` -------------------------------- ### Generate Debian and RPM Packages Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/build-and-architecture.md Commands to generate Debian (.deb) and RPM packages using Cargo. ```bash cargo deb cargo generate-rpm ``` -------------------------------- ### Basic TCP MQTT Connection Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/mqtt-connect.md Establishes a basic MQTT connection over TCP to a local broker. No authentication or TLS is used. ```rust let broker: Broker = "mqtt://localhost".parse()?; let mqtt_conn = MqttConnection { broker, username: None, password: None, client_id: None, client_cert: None, client_private_key: None, insecure: false, }; let (_, client, connection) = mqtt::connect(mqtt_conn, None)?; ``` -------------------------------- ### Efficient Topic Filtering Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Demonstrates efficient topic filtering by subscribing to specific branches instead of all topics. ```bash # Inefficient - subscribes to everything mqttui log "#" # Efficient - subscribes to specific branches mqttui log "home/sensors/+/reading" "home/devices/+/status" ``` -------------------------------- ### Monitor MQTT QoS Levels with grep Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/advanced-patterns.md Counts the number of MQTT messages with a specific QoS level using grep. ```bash # Monitor specific QoS levels mqttui log sensors/# | \ grep "QoS:AtLeastOnce" | wc -l ``` -------------------------------- ### Fallback to Read-One on Log Command Failure Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Attempt to log MQTT messages for a short duration (5 seconds) and fall back to using `read-one` if the log command times out or fails. This ensures message retrieval even with intermittent issues. ```bash #!/bin/bash # Try log first, fall back to read-one timeout 5 mqttui log sensors/temp 2>/dev/null | head -1 if [ $? -ne 0 ]; then # Timeout or error, use read-one instead mqttui read-one sensors/temp fi ``` -------------------------------- ### Check Broker Connectivity with netcat Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/errors-and-debugging.md Verifies if a TCP connection can be established to the MQTT broker's address and port. ```bash # Test TCP connection nc -zv broker.example.com 1883 ``` -------------------------------- ### Log as JSON for Processing Source: https://github.com/edjopato/mqttui/blob/main/_autodocs/configuration.md Log messages in JSON format and pipe the output to 'jq' for filtering based on payload values. ```bash mqttui log --json sensors/# | jq 'select(.payload > 50)' ```