[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79EX5MHYC0YCGY9GFPABZPT":3,"skill-same:01M79EX5MHYC0YCGY9GFPABZPT":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M79EX5MHYC0YCGY9GFPABZPT","mqtt-and-iot-edge-protocols",null,"Architectural and implementation standards for MQTT, MQTT-SN, CoAP, and IoT edge protocols. Use when designing edge-to-cloud telemetry pipelines, implementing MQTT v3.1.1\u002Fv5.0 clients, handling QoS levels, KeepAlive, Last Will and Testament (LWT), network reconnections, TLS security, and payload serialization (Protobuf, CBOR, JSON).","hamzabellouch\u002Fagent-skills","hamzabellouch","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F237856042?v=4","01M79BRYW7XAMK3YDWQEMTWGWS","Hamza Bellouch","01M79BRYWXQV3JK2TGVTX8GN2A",8,"MIT","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FProgramming\u002FSystems_and_Hardware\u002FEmbedded_and_IoT\u002Fmqtt-and-iot-edge-protocols\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: mqtt-and-iot-edge-protocols\ndescription: Architectural and implementation standards for MQTT, MQTT-SN, CoAP, and IoT edge protocols. Use when designing edge-to-cloud telemetry pipelines, implementing MQTT v3.1.1\u002Fv5.0 clients, handling QoS levels, KeepAlive, Last Will and Testament (LWT), network reconnections, TLS security, and payload serialization (Protobuf, CBOR, JSON).\n---\n\n# MQTT & IoT Edge Protocols Production Standards\n\nThis skill provides production standards for IoT edge-to-cloud communication using MQTT (v3.1.1 \u002F v5.0), MQTT-SN, and CoAP. It focuses on low-latency messaging, zero-allocation memory buffers, network resilience, payload optimization, and edge security.\n\n---\n\n## 1. Protocol Architecture & Decision Matrix\n\n### 1.1 Protocol Selection Guide\n\n| Criterion | MQTT v5.0 | MQTT v3.1.1 | MQTT-SN | CoAP |\n|---|---|---|---|---|\n| **Transport Layer** | TCP \u002F TLS | TCP \u002F TLS | UDP \u002F DTLS | UDP \u002F DTLS |\n| **Header Overhead** | 2 - 5 bytes | 2 bytes | 2 - 7 bytes | 4 bytes fixed |\n| **Connection Type** | Stateful Connection | Stateful Connection | Connectionless \u002F Sleep | Connectionless (RESTful) |\n| **Ideal Network** | Cellular, Wi-Fi, Ethernet | Cellular, Wi-Fi, Ethernet | LoRa, NB-IoT, Zigbee | LPWAN, 802.15.4, Thread |\n| **Advanced Features** | User properties, Reason codes, Topic aliases | Standard pub\u002Fsub | Pre-defined topics, Sleep mode | Resource discovery, Blockwise transfer |\n\n### 1.2 QoS (Quality of Service) Strategy\n- **QoS 0 (At most once)**: High-frequency telemetry (e.g., sensor streaming at 10Hz). Dropped packets are tolerable. Minimum memory and bandwidth.\n- **QoS 1 (At least once)**: State changes, alarms, configuration sync, critical events. Requires acknowledgment (PUBACK) and message retry buffer. **Default choice for industrial IoT**.\n- **QoS 2 (Exactly once)**: Financial transactions or billing meters. Involves 4-step handshake (PUBLISH -> PUBREC -> PUBREL -> PUBCOMP). Avoid on battery-constrained devices due to high latency and RAM consumption.\n\n---\n\n## 2. Real-Time Memory & Buffer Management\n\n### 2.1 Ring Buffer for Offline Network Resiliency\nWhen an edge gateway loses cellular\u002FWi-Fi connection:\n- Incoming telemetry must be queued in a **bounded circular ring buffer** residing in static RAM or non-volatile flash (SPIFFS\u002FLittleFS).\n- If network blackout exceeds buffer capacity, apply explicit drop policies:\n  - `DROP_OLDEST`: Discard oldest telemetry to preserve recent state.\n  - `COALESCE`: Overwrite pending messages matching identical topic paths.\n\n```\n       [ Incoming Telemetry ]\n                 |\n                 v\n      +---------------------+\n      | Bounded Ring Buffer | === (Full?) ===> [ Apply Drop Oldest Policy ]\n      +---------------------+\n                 |\n        (Network Restored)\n                 |\n                 v\n   [ Sequential MQTT Publish (QoS 1) ]\n```\n\n### 2.2 Payload Serialization Efficiency\nAvoid verbose text formats like uncompressed JSON in low-bandwidth or battery-powered edge nodes:\n- **JSON**: High CPU overhead for string parsing, high bandwidth (~150+ bytes per payload).\n- **CBOR (Concise Binary Object Representation)**: Schema-less binary JSON replacement (~40% smaller payload size).\n- **Protocol Buffers (Protobuf) \u002F FlatBuffers**: Compact binary format (~70% smaller payload size), zero-copy parsing, requires fixed schema `.proto`.\n\n---\n\n## 3. Network Resilience & Security Hardening\n\n### 3.1 Reconnection with Exponential Backoff + Jitter\nNever reconnect blindly in a tight loop upon TCP socket loss. Use truncated exponential backoff with full jitter to avoid thundering herd problems on MQTT brokers:\n\n$$\\text{Sleep Time} = \\text{random}(0, \\min(\\text{MAX\\_BACKOFF}, \\text{BASE\\_BACKOFF} \\times 2^{\\text{attempt}}))$$\n\n```cpp\nuint32_t calculate_backoff(uint32_t attempt) {\n    uint32_t max_backoff = 300000; \u002F\u002F 30 seconds\n    uint32_t base_backoff = 1000;   \u002F\u002F 1 second\n    uint32_t temp = base_backoff * (1 \u003C\u003C std::min(attempt, (uint32_t)10));\n    uint32_t current_backoff = std::min(max_backoff, temp);\n    return esp_random() % current_backoff; \u002F\u002F Full jitter\n}\n```\n\n### 3.2 Last Will & Testament (LWT)\nAlways register an LWT message on connection setup for offline node detection:\n- **Topic**: `telemetry\u002Fv1\u002Fdevices\u002F{device_id}\u002Fstatus`\n- **Payload**: `{\"state\": \"offline\", \"reason\": \"unexpected_disconnect\"}`\n- **Retain Flag**: `true`\n- **QoS**: `1`\n\n### 3.3 Security Baseline (mTLS & TLS 1.3)\n- **Port 8883**: Use TLS with x509 Mutual Authentication (mTLS) where device provides unique client certificate.\n- **SNI (Server Name Indication)**: Mandated for cloud brokers (AWS IoT Core, Azure IoT Hub, HiveMQ Cloud).\n- **Time Synchronization**: Validate X.509 certificate expiry by syncing system RTC via NTP prior to establishing TLS handshake.\n\n---\n\n## 4. Anti-Patterns & Pitfalls\n\n| Anti-Pattern | Impact | Solution |\n|---|---|---|\n| Unbounded queue in RAM on network loss | Out-Of-Memory panic crash | Enforce static max queue size + drop oldest policy |\n| Blocking `publish()` on main thread | Application freezes on packet retransmission | Use async non-blocking socket loops or dedicated telemetry task |\n| Hardcoded TLS Client Certificates | Inability to rotate compromised keys | Store certificates in secure hardware element (ATECC608A) or encrypted NVS |\n| Using wildcard topics `#` or `+` in device publishes | Broker rejections, security breaches | Direct specific, strictly scoped topic strings (`devices\u002F{id}\u002Ftelemetry`) |\n| Setting KeepAlive too low (\u003C 10s) | Excessive battery drain and cellular data overhead | Set KeepAlive to 60-120s; use TCP Keep-Alive socket options |\n\n---\n\n## 5. Production Code Example\n\nBelow is a production-grade C++ MQTT Client wrapper for embedded targets (FreeRTOS \u002F ESP-IDF \u002F POSIX) demonstrating static memory management, MQTT v5 LWT, payload formatting with CBOR, and exponential backoff reconnection logic.\n\n```cpp\n#include \u003Ccstdio>\n#include \u003Ccstring>\n#include \u003Calgorithm>\n#include \"freertos\u002FFreeRTOS.h\"\n#include \"freertos\u002Ftask.h\"\n#include \"freertos\u002Fqueue.h\"\n#include \"esp_event.h\"\n#include \"esp_log.h\"\n#include \"mqtt_client.h\"\n#include \"esp_random.h\"\n\nstatic const char *TAG = \"MQTT_PROTOCOL\";\n\n\u002F\u002F Configuration Constants\n#define BROKER_URI           \"mqtts:\u002F\u002Ftelemetry.example.com:8883\"\n#define DEVICE_ID            \"ESP32_EDGE_001\"\n#define TELEMETRY_TOPIC      \"v1\u002Fdevices\u002F\" DEVICE_ID \"\u002Ftelemetry\"\n#define LWT_TOPIC            \"v1\u002Fdevices\u002F\" DEVICE_ID \"\u002Fstatus\"\n#define MAX_RING_BUFFER_SIZE 32\n#define MAX_PAYLOAD_SIZE     256\n\n\u002F\u002F Telemetry Message Structure\nstruct TelemetryMessage {\n    uint32_t timestamp;\n    float temperature;\n    float humidity;\n    uint32_t seq_num;\n};\n\n\u002F\u002F Ring Buffer Structure (Static Memory Allocation)\nclass StaticTelemetryRingBuffer {\nprivate:\n    TelemetryMessage buffer[MAX_RING_BUFFER_SIZE];\n    size_t head = 0;\n    size_t tail = 0;\n    size_t count = 0;\n    portMUX_TYPE lock = portMUX_INITIALIZER_UNLOCKED;\n\npublic:\n    bool push(const TelemetryMessage &msg) {\n        portENTER_CRITICAL(&lock);\n        if (count >= MAX_RING_BUFFER_SIZE) {\n            \u002F\u002F Overwrite oldest item (DROP_OLDEST policy)\n            tail = (tail + 1) % MAX_RING_BUFFER_SIZE;\n            count--;\n            ESP_LOGW(TAG, \"Ring buffer full! Dropped oldest record.\");\n        }\n        buffer[head] = msg;\n        head = (head + 1) % MAX_RING_BUFFER_SIZE;\n        count++;\n        portEXIT_CRITICAL(&lock);\n        return true;\n    }\n\n    bool pop(TelemetryMessage &out_msg) {\n        portENTER_CRITICAL(&lock);\n        if (count == 0) {\n            portEXIT_CRITICAL(&lock);\n            return false;\n        }\n        out_msg = buffer[tail];\n        tail = (tail + 1) % MAX_RING_BUFFER_SIZE;\n        count--;\n        portEXIT_CRITICAL(&lock);\n        return true;\n    }\n\n    size_t size() {\n        portENTER_CRITICAL(&lock);\n        size_t s = count;\n        portEXIT_CRITICAL(&lock);\n        return s;\n    }\n};\n\nstatic StaticTelemetryRingBuffer g_telemetry_buffer;\nstatic esp_mqtt_client_handle_t g_mqtt_client = nullptr;\nstatic bool g_mqtt_connected = false;\nstatic uint32_t g_reconnect_attempts = 0;\n\n\u002F\u002F --- MQTT Event Handler ---\nstatic void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {\n    esp_mqtt_event_handle_t event = (esp_mqtt_event_handle_t)event_data;\n    \n    switch ((esp_mqtt_event_id_t)event_id) {\n        case MQTT_EVENT_CONNECTED:\n            ESP_LOGI(TAG, \"MQTT Connected successfully to broker.\");\n            g_mqtt_connected = true;\n            g_reconnect_attempts = 0;\n            break;\n            \n        case MQTT_EVENT_DISCONNECTED:\n            ESP_LOGW(TAG, \"MQTT Disconnected. Scheduling reconnection...\");\n            g_mqtt_connected = false;\n            g_reconnect_attempts++;\n            break;\n            \n        case MQTT_EVENT_PUBLISHED:\n            ESP_LOGD(TAG, \"Message published successfully, msg_id=%d\", event->msg_id);\n            break;\n            \n        case MQTT_EVENT_ERROR:\n            ESP_LOGE(TAG, \"MQTT Internal Error Occurred\");\n            break;\n            \n        default:\n            break;\n    }\n}\n\n\u002F\u002F --- Serializer Utility (Compact CBOR\u002FBinary representation) ---\nstatic size_t serialize_payload(const TelemetryMessage &msg, uint8_t *out_buffer, size_t max_len) {\n    \u002F\u002F Compact binary format: [uint32 ts][float temp][float hum][uint32 seq] = 16 bytes\n    if (max_len \u003C sizeof(TelemetryMessage)) return 0;\n    memcpy(out_buffer, &msg, sizeof(TelemetryMessage));\n    return sizeof(TelemetryMessage);\n}\n\n\u002F\u002F --- Telemetry Publisher Task ---\nvoid MqttTelemetryTask(void *pvParameters) {\n    uint8_t payload_buffer[MAX_PAYLOAD_SIZE];\n    TelemetryMessage msg;\n\n    for (;;) {\n        if (g_mqtt_connected && g_telemetry_buffer.size() > 0) {\n            if (g_telemetry_buffer.pop(msg)) {\n                size_t payload_len = serialize_payload(msg, payload_buffer, sizeof(payload_buffer));\n                \n                int msg_id = esp_mqtt_client_publish(\n                    g_mqtt_client, \n                    TELEMETRY_TOPIC, \n                    (const char*)payload_buffer, \n                    payload_len, \n                    1, \u002F\u002F QoS 1\n                    0  \u002F\u002F Retain = false\n                );\n                \n                if (msg_id \u003C 0) {\n                    ESP_LOGE(TAG, \"Publish failed! Re-queuing telemetry message...\");\n                    g_telemetry_buffer.push(msg); \u002F\u002F Push back on failure\n                    vTaskDelay(pdMS_TO_TICKS(1000));\n                }\n            }\n        } else {\n            \u002F\u002F Sleep when disconnected or idle\n            vTaskDelay(pdMS_TO_TICKS(200));\n        }\n    }\n}\n\n\u002F\u002F --- Client Initialization ---\nvoid init_mqtt_protocol_stack() {\n    const char *lwt_payload = \"{\\\"state\\\":\\\"offline\\\",\\\"reason\\\":\\\"power_loss\\\"}\";\n\n    esp_mqtt_client_config_t mqtt_cfg = {};\n    mqtt_cfg.broker.address.uri = BROKER_URI;\n    mqtt_cfg.credentials.client_id = DEVICE_ID;\n    \n    \u002F\u002F Last Will & Testament Setup\n    mqtt_cfg.session.last_will.topic = LWT_TOPIC;\n    mqtt_cfg.session.last_will.msg = lwt_payload;\n    mqtt_cfg.session.last_will.msg_len = strlen(lwt_payload);\n    mqtt_cfg.session.last_will.qos = 1;\n    mqtt_cfg.session.last_will.retain = 1;\n\n    \u002F\u002F Network & KeepAlive Configuration\n    mqtt_cfg.session.keepalive = 60; \u002F\u002F 60 seconds keepalive\n    mqtt_cfg.network.reconnect_timeout_ms = 5000;\n\n    g_mqtt_client = esp_mqtt_client_init(&mqtt_cfg);\n    esp_mqtt_client_register_event(g_mqtt_client, MQTT_EVENT_ANY, mqtt_event_handler, nullptr);\n    esp_mqtt_client_start(g_mqtt_client);\n\n    \u002F\u002F Spawn Publisher Task\n    xTaskCreate(MqttTelemetryTask, \"MqttPublisher\", 4096, nullptr, 5, nullptr);\n}\n```\n","# MQTT & IoT Edge Protocols Production Standards\n\nThis skill provides production standards for IoT edge-to-cloud communication using MQTT (v3.1.1 \u002F v5.0), MQTT-SN, and CoAP. It focuses on low-latency messaging, zero-allocation memory buffers, network resilience, payload optimization, and edge security.\n\n---\n\n## 1. Protocol Architecture & Decision Matrix\n\n### 1.1 Protocol Selection Guide\n\n| Criterion | MQTT v5.0 | MQTT v3.1.1 | MQTT-SN | CoAP |\n|---|---|---|---|---|\n| **Transport Layer** | TCP \u002F TLS | TCP \u002F TLS | UDP \u002F DTLS | UDP \u002F DTLS |\n| **Header Overhead** | 2 - 5 bytes | 2 bytes | 2 - 7 bytes | 4 bytes fixed |\n| **Connection Type** | Stateful Connection | Stateful Connection | Connectionless \u002F Sleep | Connectionless (RESTful) |\n| **Ideal Network** | Cellular, Wi-Fi, Ethernet | Cellular, Wi-Fi, Ethernet | LoRa, NB-IoT, Zigbee | LPWAN, 802.15.4, Thread |\n| **Advanced Features** | User properties, Reason codes, Topic aliases | Standard pub\u002Fsub | Pre-defined topics, Sleep mode | Resource discovery, Blockwise transfer |\n\n### 1.2 QoS (Quality of Service) Strategy\n- **QoS 0 (At most once)**: High-frequency telemetry (e.g., sensor streaming at 10Hz). Dropped packets are tolerable. Minimum memory and bandwidth.\n- **QoS 1 (At least once)**: State changes, alarms, configuration sync, critical events. Requires acknowledgment (PUBACK) and message retry buffer. **Default choice for industrial IoT**.\n- **QoS 2 (Exactly once)**: Financial transactions or billing meters. Involves 4-step handshake (PUBLISH -> PUBREC -> PUBREL -> PUBCOMP). Avoid on battery-constrained devices due to high latency and RAM consumption.\n\n---\n\n## 2. Real-Time Memory & Buffer Management\n\n### 2.1 Ring Buffer for Offline Network Resiliency\nWhen an edge gateway loses cellular\u002FWi-Fi connection:\n- Incoming telemetry must be queued in a **bounded circular ring buffer** residing in static RAM or non-volatile flash (SPIFFS\u002FLittleFS).\n- If network blackout exceeds buffer capacity, apply explicit drop policies:\n  - `DROP_OLDEST`: Discard oldest telemetry to preserve recent state.\n  - `COALESCE`: Overwrite pending messages matching identical topic paths.\n\n```\n       [ Incoming Telemetry ]\n                 |\n                 v\n      +---------------------+\n      | Bounded Ring Buffer | === (Full?) ===> [ Apply Drop Oldest Policy ]\n      +---------------------+\n                 |\n        (Network Restored)\n                 |\n                 v\n   [ Sequential MQTT Publish (QoS 1) ]\n```\n\n### 2.2 Payload Serialization Efficiency\nAvoid verbose text formats like uncompressed JSON in low-bandwidth or battery-powered edge nodes:\n- **JSON**: High CPU overhead for string parsing, high bandwidth (~150+ bytes per payload).\n- **CBOR (Concise Binary Object Representation)**: Schema-less binary JSON replacement (~40% smaller payload size).\n- **Protocol Buffers (Protobuf) \u002F FlatBuffers**: Compact binary format (~70% smaller payload size), zero-copy parsing, requires fixed schema `.proto`.\n\n---\n\n## 3. Network Resilience & Security Hardening\n\n### 3.1 Reconnection with Exponential Backoff + Jitter\nNever reconnect blindly in a tight loop upon TCP socket loss. Use truncated exponential backoff with full jitter to avoid thundering herd problems on MQTT brokers:\n\n$$\\text{Sleep Time} = \\text{random}(0, \\min(\\text{MAX\\_BACKOFF}, \\text{BASE\\_BACKOFF} \\times 2^{\\text{attempt}}))$$\n\n```cpp\nuint32_t calculate_backoff(uint32_t attempt) {\n    uint32_t max_backoff = 300000; \u002F\u002F 30 seconds\n    uint32_t base_backoff = 1000;   \u002F\u002F 1 second\n    uint32_t temp = base_backoff * (1 \u003C\u003C std::min(attempt, (uint32_t)10));\n    uint32_t current_backoff = std::min(max_backoff, temp);\n    return esp_random() % current_backoff; \u002F\u002F Full jitter\n}\n```\n\n### 3.2 Last Will & Testament (LWT)\nAlways register an LWT message on connection setup for offline node detection:\n- **Topic**: `telemetry\u002Fv1\u002Fdevices\u002F{device_id}\u002Fstatus`\n- **Payload**: `{\"state\": \"offline\", \"reason\": \"unexpected_disconnect\"}`\n- **Retain Flag**: `true`\n- **QoS**: `1`\n\n### 3.3 Security Baseline (mTLS & TLS 1.3)\n- **Port 8883**: Use TLS with x509 Mutual Authentication (mTLS) where device provides unique client certificate.\n- **SNI (Server Name Indication)**: Mandated for cloud brokers (AWS IoT Core, Azure IoT Hub, HiveMQ Cloud).\n- **Time Synchronization**: Validate X.509 certificate expiry by syncing system RTC via NTP prior to establishing TLS handshake.\n\n---\n\n## 4. Anti-Patterns & Pitfalls\n\n| Anti-Pattern | Impact | Solution |\n|---|---|---|\n| Unbounded queue in RAM on network loss | Out-Of-Memory panic crash | Enforce static max queue size + drop oldest policy |\n| Blocking `publish()` on main thread | Application freezes on packet retransmission | Use async non-blocking socket loops or dedicated telemetry task |\n| Hardcoded TLS Client Certificates | Inability to rotate compromised keys | Store certificates in secure hardware element (ATECC608A) or encrypted NVS |\n| Using wildcard topics `#` or `+` in device publishes | Broker rejections, security breaches | Direct specific, strictly scoped topic strings (`devices\u002F{id}\u002Ftelemetry`) |\n| Setting KeepAlive too low (\u003C 10s) | Excessive battery drain and cellular data overhead | Set KeepAlive to 60-120s; use TCP Keep-Alive socket options |\n\n---\n\n## 5. Production Code Example\n\nBelow is a production-grade C++ MQTT Client wrapper for embedded targets (FreeRTOS \u002F ESP-IDF \u002F POSIX) demonstrating static memory management, MQTT v5 LWT, payload formatting with CBOR, and exponential backoff reconnection logic.\n\n```cpp\n#include \u003Ccstdio>\n#include \u003Ccstring>\n#include \u003Calgorithm>\n#include \"freertos\u002FFreeRTOS.h\"\n#include \"freertos\u002Ftask.h\"\n#include \"freertos\u002Fqueue.h\"\n#include \"esp_event.h\"\n#include \"esp_log.h\"\n#include \"mqtt_client.h\"\n#include \"esp_random.h\"\n\nstatic const char *TAG = \"MQTT_PROTOCOL\";\n\n\u002F\u002F Configuration Constants\n#define BROKER_URI           \"mqtts:\u002F\u002Ftelemetry.example.com:8883\"\n#define DEVICE_ID            \"ESP32_EDGE_001\"\n#define TELEMETRY_TOPIC      \"v1\u002Fdevices\u002F\" DEVICE_ID \"\u002Ftelemetry\"\n#define LWT_TOPIC            \"v1\u002Fdevices\u002F\" DEVICE_ID \"\u002Fstatus\"\n#define MAX_RING_BUFFER_SIZE 32\n#define MAX_PAYLOAD_SIZE     256\n\n\u002F\u002F Telemetry Message Structure\nstruct TelemetryMessage {\n    uint32_t timestamp;\n    float temperature;\n    float humidity;\n    uint32_t seq_num;\n};\n\n\u002F\u002F Ring Buffer Structure (Static Memory Allocation)\nclass StaticTelemetryRingBuffer {\nprivate:\n    TelemetryMessage buffer[MAX_RING_BUFFER_SIZE];\n    size_t head = 0;\n    size_t tail = 0;\n    size_t count = 0;\n    portMUX_TYPE lock = portMUX_INITIALIZER_UNLOCKED;\n\npublic:\n    bool push(const TelemetryMessage &msg) {\n        portENTER_CRITICAL(&lock);\n        if (count >= MAX_RING_BUFFER_SIZE) {\n            \u002F\u002F Overwrite oldest item (DROP_OLDEST policy)\n            tail = (tail + 1) % MAX_RING_BUFFER_SIZE;\n            count--;\n            ESP_LOGW(TAG, \"Ring buffer full! Dropped oldest record.\");\n        }\n        buffer[head] = msg;\n        head = (head + 1) % MAX_RING_BUFFER_SIZE;\n        count++;\n        portEXIT_CRITICAL(&lock);\n        return true;\n    }\n\n    bool pop(TelemetryMessage &out_msg) {\n        portENTER_CRITICAL(&lock);\n        if (count == 0) {\n            portEXIT_CRITICAL(&lock);\n            return false;\n        }\n        out_msg = buffer[tail];\n        tail = (tail + 1) % MAX_RING_BUFFER_SIZE;\n        count--;\n        portEXIT_CRITICAL(&lock);\n        return true;\n    }\n\n    size_t size() {\n        portENTER_CRITICAL(&lock);\n        size_t s = count;\n        portEXIT_CRITICAL(&lock);\n        return s;\n    }\n};\n\nstatic StaticTelemetryRingBuffer g_telemetry_buffer;\nstatic esp_mqtt_client_handle_t g_mqtt_client = nullptr;\nstatic bool g_mqtt_connected = false;\nstatic uint32_t g_reconnect_attempts = 0;\n\n\u002F\u002F --- MQTT Event Handler ---\nstatic void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {\n    esp_mqtt_event_handle_t event = (esp_mqtt_event_handle_t)event_data;\n    \n    switch ((esp_mqtt_event_id_t)event_id) {\n        case MQTT_EVENT_CONNECTED:\n            ESP_LOGI(TAG, \"MQTT Connected successfully to broker.\");\n            g_mqtt_connected = true;\n            g_reconnect_attempts = 0;\n            break;\n            \n        case MQTT_EVENT_DISCONNECTED:\n            ESP_LOGW(TAG, \"MQTT Disconnected. Scheduling reconnection...\");\n            g_mqtt_connected = false;\n            g_reconnect_attempts++;\n            break;\n            \n        case MQTT_EVENT_PUBLISHED:\n            ESP_LOGD(TAG, \"Message published successfully, msg_id=%d\", event->msg_id);\n            break;\n            \n        case MQTT_EVENT_ERROR:\n            ESP_LOGE(TAG, \"MQTT Internal Error Occurred\");\n            break;\n            \n        default:\n            break;\n    }\n}\n\n\u002F\u002F --- Serializer Utility (Compact CBOR\u002FBinary representation) ---\nstatic size_t serialize_payload(const TelemetryMessage &msg, uint8_t *out_buffer, size_t max_len) {\n    \u002F\u002F Compact binary format: [uint32 ts][float temp][float hum][uint32 seq] = 16 bytes\n    if (max_len \u003C sizeof(TelemetryMessage)) return 0;\n    memcpy(out_buffer, &msg, sizeof(TelemetryMessage));\n    return sizeof(TelemetryMessage);\n}\n\n\u002F\u002F --- Telemetry Publisher Task ---\nvoid MqttTelemetryTask(void *pvParameters) {\n    uint8_t payload_buffer[MAX_PAYLOAD_SIZE];\n    TelemetryMessage msg;\n\n    for (;;) {\n        if (g_mqtt_connected && g_telemetry_buffer.size() > 0) {\n            if (g_telemetry_buffer.pop(msg)) {\n                size_t payload_len = serialize_payload(msg, payload_buffer, sizeof(payload_buffer));\n                \n                int msg_id = esp_mqtt_client_publish(\n                    g_mqtt_client, \n                    TELEMETRY_TOPIC, \n                    (const char*)payload_buffer, \n                    payload_len, \n                    1, \u002F\u002F QoS 1\n                    0  \u002F\u002F Retain = false\n                );\n                \n                if (msg_id \u003C 0) {\n                    ESP_LOGE(TAG, \"Publish failed! Re-queuing telemetry message...\");\n                    g_telemetry_buffer.push(msg); \u002F\u002F Push back on failure\n                    vTaskDelay(pdMS_TO_TICKS(1000));\n                }\n            }\n        } else {\n            \u002F\u002F Sleep when disconnected or idle\n            vTaskDelay(pdMS_TO_TICKS(200));\n        }\n    }\n}\n\n\u002F\u002F --- Client Initialization ---\nvoid init_mqtt_protocol_stack() {\n    const char *lwt_payload = \"{\\\"state\\\":\\\"offline\\\",\\\"reason\\\":\\\"power_loss\\\"}\";\n\n    esp_mqtt_client_config_t mqtt_cfg = {};\n    mqtt_cfg.broker.address.uri = BROKER_URI;\n    mqtt_cfg.credentials.client_id = DEVICE_ID;\n    \n    \u002F\u002F Last Will & Testament Setup\n    mqtt_cfg.session.last_will.topic = LWT_TOPIC;\n    mqtt_cfg.session.last_will.msg = lwt_payload;\n    mqtt_cfg.session.last_will.msg_len = strlen(lwt_payload);\n    mqtt_cfg.session.last_will.qos = 1;\n    mqtt_cfg.session.last_will.retain = 1;\n\n    \u002F\u002F Network & KeepAlive Configuration\n    mqtt_cfg.session.keepalive = 60; \u002F\u002F 60 seconds keepalive\n    mqtt_cfg.network.reconnect_timeout_ms = 5000;\n\n    g_mqtt_client = esp_mqtt_client_init(&mqtt_cfg);\n    esp_mqtt_client_register_event(g_mqtt_client, MQTT_EVENT_ANY, mqtt_event_handler, nullptr);\n    esp_mqtt_client_start(g_mqtt_client);\n\n    \u002F\u002F Spawn Publisher Task\n    xTaskCreate(MqttTelemetryTask, \"MqttPublisher\", 4096, nullptr, 5, nullptr);\n}\n```\n",{"name":5,"description":7},"main","e905af21e5f1e1c3ca605e9656c3a7930360a84e","Programming\u002FSystems_and_Hardware\u002FEmbedded_and_IoT\u002Fmqtt-and-iot-edge-protocols",1,"https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills","https:\u002F\u002Fhamzabellouch.github.io\u002F","https:\u002F\u002Fgithub.com\u002Fhamzabellouch","hamzabellouch.github.io","CEO & Founder of @tknoglobal | Researcher in Technology & Applied Sciences.","2026-10-17 03:20:19",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add hamzabellouch\u002Fagent-skills --skill mqtt-and-iot-edge-protocols",{"tool":40,"command":41},"bunx","bunx skills add hamzabellouch\u002Fagent-skills --skill mqtt-and-iot-edge-protocols",{"tool":43,"command":44},"pnpm","pnpm dlx skills add hamzabellouch\u002Fagent-skills --skill mqtt-and-iot-edge-protocols","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FProgramming\u002FSystems_and_Hardware\u002FEmbedded_and_IoT\u002Fmqtt-and-iot-edge-protocols\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M79FHH2H815A9TAP6WNKH4Q8","security-audit","Comprehensive security guidance, source code audit, vulnerability assessment, and penetration test review for codebases, APIs, microservices, CLI tools, libraries, and LLM-backed applications. Triggers on requests to audit a codebase, conduct security reviews, find vulnerabilities or flaws, pen-test source code, or when the user asks in Arabic (فحص أمني، تدقيق الكود أمنياً، مراجعة الثغرات، فحص أمان المشروع). Supports Guidance mode (focused review) and Full Audit mode (deterministic 6-phase harness).","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FSecurity_Audit_and_Code_Review\u002Fsecurity-audit\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M79FHBGXVBY6VQ1X7ETAZMF1","malware-analysis-reversing","Production malware analysis workflows, reverse engineering methodologies, isolated sandbox triage, static\u002Fdynamic binary analysis, memory forensics, and YARA detection rule authoring.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FOffensive_Security_and_Pentesting\u002Fmalware-analysis-reversing\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M79FH6EACDR801TZCE4R8SAC","application-security-pentesting","Production Application Security (AppSec) standards, OWASP Top 10 vulnerability remediation, SAST\u002FDAST pipeline integration, secure code review, threat modeling, and defensive security posture.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FOffensive_Security_and_Pentesting\u002Fapplication-security-pentesting\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M79FH0VKVT44FK923K520ZQA","oauth2-oidc-security-flows","Implement enterprise OAuth 2.1 and OpenID Connect (OIDC) authorization code flow with Proof Key for Code Exchange (PKCE), state and nonce verification, refresh token rotation, token revocation, and centralized IdP federation (Keycloak, Auth0, Okta). Trigger when building secure authentication, single sign-on (SSO), or third-party delegated authorization.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FIdentity_and_Access_Management_IAM\u002Foauth2-oidc-security-flows\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M79FGVVB3R4T88XXD8FRSV5B","jwt-session-management-hardening","Harden JWT-based authentication and session lifecycles using asymmetric signing (RS256\u002FEdDSA), JWKS rotation, strict claims validation, Redis-backed sliding window sessions, revocation lists, and secure HttpOnly cookie storage. Trigger when implementing token validation, session revocation, or hardening API authentication.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FIdentity_and_Access_Management_IAM\u002Fjwt-session-management-hardening\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M79FGNCPZ85CVEY0B3NE4H3B","soc2-compliance-automation","Best practices for implementing SOC 2 Type II compliance controls, continuous evidence collection, infrastructure policy-as-code, and automated security monitoring. Use when automating Trust Services Criteria (Security, Availability, Confidentiality, Processing Integrity, Privacy), audit logging, IAM least privilege, or CI\u002FCD security gates.","https:\u002F\u002Fgithub.com\u002Fhamzabellouch\u002Fagent-skills\u002Fblob\u002Fmain\u002FSecurity\u002FGovernance_Compliance_and_Legal_Tech\u002Fsoc2-compliance-automation\u002FSKILL.md",[],[]]