mqtt
Lightweight pub/sub protocol for efficient IoT communication and telemetry
What this skill does
# mqtt
## Purpose
This skill allows the AI to interact with MQTT, a lightweight pub/sub protocol, for efficient IoT communication. Use it to publish telemetry data or subscribe to device updates, enabling real-time interactions in constrained environments.
## When to Use
Use this skill for scenarios requiring low-bandwidth, real-time messaging, such as sending sensor data from IoT devices, remote device control, or telemetry monitoring. Avoid it for high-throughput needs like file transfers, where HTTP is more suitable.
## Key Capabilities
- Publish messages to topics with configurable Quality of Service (QoS) levels (0, 1, or 2).
- Subscribe to topics and handle incoming messages asynchronously.
- Support for retained messages, last will and testament, and wildcard subscriptions (e.g., "#" for all subtopics).
- Secure connections via TLS and authentication methods like username/password.
## Usage Patterns
To use MQTT, first connect to a broker using a client library. Establish a connection with credentials, then publish or subscribe. For example, in a loop: connect, subscribe, process messages, and disconnect. Use environment variables for sensitive data, like `$MQTT_BROKER_URL` for the broker address. Always handle reconnections for unstable networks.
## Common Commands/API
Use the Paho MQTT library for Python interactions. Import it as follows:
```python
import paho.mqtt.client as mqtt
```
To connect to a broker:
- Command: `client.connect(broker_address, port=1883)`
- Example with auth: `client.username_pw_set(username='$MQTT_USERNAME', password='$MQTT_PASSWORD')`
To publish a message:
- API: `client.publish(topic, payload, qos=1)`
- Example: `client.publish('sensors/temp', '22.5', qos=1)`
To subscribe:
- API: `client.subscribe(topic, qos=1)`
- Example: `client.subscribe('commands/device1', qos=1)`
Config format: Use a JSON file for settings, e.g., `{"broker": "$MQTT_BROKER_URL", "topic": "sensors/temp"}`. CLI tools like `mosquitto_pub` can be invoked via subprocess: `subprocess.run(['mosquitto_pub', '-h', '$MQTT_BROKER_URL', '-t', 'sensors/temp', '-m', '22.5'])`.
## Integration Notes
Integrate MQTT by wrapping it in your AI agent's code. Set environment variables for keys, e.g., export `$MQTT_API_KEY` for token-based auth. For multi-service setups, use a broker like HiveMQ or Mosquitto; connect via `client.connect('$MQTT_BROKER_URL')`. Ensure TLS for secure endpoints (e.g., `client.tls_set()`). If combining with other skills, like a database, publish data on success: e.g., after inserting into a DB, run `client.publish('db/updates', json.dumps(data))`.
## Error Handling
Handle common errors explicitly. For connection issues, catch `ConnectionRefusedError` and retry with exponential backoff: e.g., `time.sleep(5)`. For publish failures, check return codes (e.g., if `client.publish()` returns >0, log and retry). Subscription errors might involve invalid topics; validate with `if '/' not in topic: raise ValueError('Invalid topic')`. Use callbacks for message errors, like in `on_message` handler: `if error: print('Error: ', error)`. Always clean up with `client.disconnect()` in a finally block.
## Concrete Usage Examples
**Example 1: Publish sensor data**
To publish a temperature reading to an MQTT topic, first set env vars: `export MQTT_BROKER_URL='broker.example.com'`. Then, in code:
```python
client = mqtt.Client()
client.connect(os.environ['MQTT_BROKER_URL'])
client.publish('sensors/temperature', '25.0', qos=1)
client.disconnect()
```
This sends a message to the broker for IoT dashboard updates.
**Example 2: Subscribe to device commands**
To subscribe and react to commands, use:
```python
def on_message(client, userdata, message):
print(f"Received: {message.payload.decode()}")
client = mqtt.Client()
client.on_message = on_message
client.connect(os.environ['MQTT_BROKER_URL'])
client.subscribe('commands/device1', qos=1)
client.loop_forever()
```
This keeps the client listening for commands to control an IoT device.
## Graph Relationships
- Related to cluster: iot
- Related to tags: iot, mqtt
- Connections: Can integrate with other iot skills, such as for data processing or device management.
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.