Kasa smart plug Riemann monitoring
README.md

plugd #

plugd is a lightweight, 12-factor daemon written in Go that monitors TP-Link Kasa smart plugs (including multi-outlet strips like the KP303), publishes outlet status periodically to Riemann, and subscribes to Riemann for real-time control events to toggle outlets on and off.

Designed to run continuously on low-power servers, Raspberry Pis, or container environments.


Features #

  • Multi-Outlet & Single-Plug Support: Automatically handles both single smart plugs and multi-outlet power strips (like the KP303 with 3 independent outlets).
  • Multi-Network UDP Autodiscovery: When no plugs are specified, plugd automatically scans all attached network interfaces and computes directed subnet broadcast addresses (e.g., 192.168.86.255, 192.168.87.255) and 255.255.255.255:20002 to discover plugs across multiple local or guest subnets.
  • Dual Protocol Support (KLAP & Legacy XOR):
    • KLAP (Kasa Local API Protocol): Connects over HTTP port 80 using AES-128-CBC encryption, PKCS#7 padding, and SHA-256 HMAC request signatures required by modern TP-Link firmware.
    • Legacy Autokey XOR: Automatic fallback to TCP port 9999 for older Kasa hardware and firmware.
  • Bi-directional Riemann Integration:
    • Status Telemetry: Periodically polls outlet states and publishes structured metrics over TCP/UDP protobuf to Riemann (port 5555).
    • Event-Driven Control: Subscribes to Riemann's HTTP Server-Sent Events (SSE) stream (port 5556) to execute real-time state changes (on / off) without polling Riemann.
  • Immediate Feedback & State Reconciliation: When a control command succeeds on the device, plugd immediately publishes the confirmed state back to Riemann, keeping the index synchronized.
  • 12-Factor App Configuration: Configure via environment variables or command-line flags.

Architecture #

+-------------------------------------------------------------+
| External Trigger (riemann-client, curl, cron, alert stream) |
+-------------------------------------------------------------+
                            |
                            |  1. Send control event (tagged "plug-command")
                            v
              +----------------------------+
              |     Riemann Service        |
              |     (127.0.0.1:5555)       |
              |                            |
              |  - Updates index           |
              |  - Broadcasts via PubSub   |
              +----------------------------+
                            |
                            |  2. Real-time push over SSE (/index?query=...)
                            v
                      +------------+
                      |   plugd    |
                      +------------+
                       |          ^
     3. KLAP /app/request |          | 4. Hardware status confirmed
      (set_relay_state)v          |
                  +--------------------+
                  | Kasa Smart Plug    |
                  |  (192.0.2.1:80)    |
                  +--------------------+
                       |
                       v 5. Confirmed state published
              +----------------------------+
              |     Riemann Service        |
              | (service: .../state,       |
              |  metric: 1.0, state: "ok") |
              +----------------------------+

Installation #

Using standard Go tooling:

go install go.iscode.ca/plugd/cmd/plugd@latest

Configuration #

Command-line Flag Environment Variable Default Value Description
-plugs PLUGD_PLUGS "" (autodiscover if empty) Comma-separated list of plug IP/hostnames
-autodiscover PLUGD_AUTODISCOVER true (if -plugs empty) Enable UDP broadcast discovery on all subnets
-discover-targets PLUGD_DISCOVER_TARGETS "" (interfaces broadcast) Target IPs, broadcast addrs, or CIDRs to probe
-discover-interval PLUGD_DISCOVER_INTERVAL 5m Interval for periodic rediscovery of new plugs
-kasa-username PLUGD_KASA_USERNAME "" TP-Link / Kasa account email
-kasa-password PLUGD_KASA_PASSWORD "" TP-Link / Kasa account password
-riemann-endpoint PLUGD_RIEMANN_ENDPOINT 127.0.0.1:5555 Riemann TCP/UDP protobuf server (host:port)
-riemann-transport PLUGD_RIEMANN_TRANSPORT tcp Riemann transport protocol (tcp or udp)
-riemann-ttl PLUGD_RIEMANN_TTL 60s Riemann event TTL
-riemann-web PLUGD_RIEMANN_WEB_ENDPOINT http://127.0.0.1:5556 Riemann Web Server HTTP/SSE endpoint
-command-query PLUGD_COMMAND_QUERY tagged "plug-command" Riemann query to filter control events
-poll-interval PLUGD_POLL_INTERVAL 15s Telemetry polling interval
-service-prefix PLUGD_SERVICE_PREFIX kasa/ Service name prefix for Riemann events
-tag PLUGD_TAG kp303 Base model tag for Riemann events
-verbose PLUGD_VERBOSE false Enable verbose debug logging

Event Model #

1. Status Telemetry (Emitted by plugd) #

Published to Riemann at each -poll-interval and immediately after any state change:

  • Host: Device alias (e.g. strip1) or device IP.
  • Service: <prefix><device>/<outlet-index>/state (e.g. kasa/strip1/0/state).
  • Metric: 1.0 (ON) or 0.0 (OFF).
  • State: "ok".
  • Tags: ["kasa", "plug", "power", "<tag>"].
  • Attributes:
    • outlet: Outlet index (0, 1, 2).
    • alias: Individual outlet alias (e.g. "Desk Lamp").
    • ip: IP address of the plug.

2. Control Commands (Monitored by plugd) #

Any process can switch an outlet by emitting an event to Riemann matching -command-query:

  • Service Pattern: <prefix><device>/<outlet-index>/set (e.g. kasa/strip1/0/set).
  • State / Metric:
    • Turn ON: state="on", state="1", state="true", or metric=1.0.
    • Turn OFF: state="off", state="0", state="false", or metric=0.0.
  • Tags: ["plug-command"] (or matching -command-query).

Usage Examples #

Switching Outlets with riemann-client #

Turn outlet 0 ON:

riemann-client send \
  --host "kp303" \
  --service "kasa/strip1/0/set" \
  --state "on" \
  --metric-d 1.0 \
  --tag "plug-command" \
  127.0.0.1 5555

Turn outlet 0 OFF:

riemann-client send \
  --host "kp303" \
  --service "kasa/strip1/0/set" \
  --state "off" \
  --metric-d 0.0 \
  --tag "plug-command" \
  127.0.0.1 5555

Switching Outlets with curl (HTTP) #

curl -X POST http://127.0.0.1:5556/events -d '{
  "host": "strip1",
  "service": "kasa/strip1/0/set",
  "state": "on",
  "metric": 1,
  "tags": ["plug-command"]
}'

Building and Testing #

# Run unit tests
make test

# Build binary into bin/plugd
make build

License #

ISC License