Skip to main content

A YAML-based automation engine for SwitchBot BLE devices with a Prometheus exporter.

Project description

SwitchBot Actions: A YAML-based Automation Engine

A powerful, configurable automation engine for SwitchBot BLE devices, with an optional Prometheus exporter.

switchbot-actions is a lightweight, standalone automation engine for your SwitchBot BLE devices. It turns a single config.yaml file into a powerful local controller, allowing you to react to device states, create time-based triggers, and integrate with MQTT and Prometheus. Its efficiency makes it a great fit for resource-constrained hardware, running comfortably on a Raspberry Pi 3 and even on a Raspberry Pi Zero. It's ideal for those who prefer a simple, configuration-driven approach to home automation without needing a large, all-in-one platform.

At its core, switchbot-actions monitors various input sources and, based on your rules, triggers different actions. The overall architecture can be visualized as follows:

graph TD
    subgraph "Inputs (Triggers)"
        A["SwitchBot<br>Sensors"]
        B["MQTT<br>Subscriptions"]
    end

    subgraph "Application"
        S["switchbot-actions"]
    end

    subgraph "Outputs (Actions)"
        W["SwitchBot<br>Commands"]
        X["MQTT<br>Publishing"]
        Y["Webhooks"]
        Z["Shell<br>Commands"]
        V["Prometheus<br>Metrics"]
    end

    A --> S
    B --> S

    S --> W
    S --> X
    S --> Y
    S --> Z
    S --> V

Key Features

  • Direct Device Control: A new switchbot_command action allows you to directly control any SwitchBot device, enabling powerful, interconnected automations without external scripts.
  • Real-time Monitoring: Gathers data from all nearby SwitchBot devices.
  • Full MQTT Integration: Use MQTT messages as triggers for automations, and publish messages as an action.
  • Prometheus Exporter: Exposes metrics at a configurable /metrics endpoint.
  • Powerful Automation Rules: Define complex automations with a unified if/then structure.
  • Flexible Conditions: Build rules based on device model, address, sensor values, and even signal strength (rssi).
  • Highly Configurable: Control every aspect of the application from a single configuration file.

Getting Started

1. Prerequisites

  • Python 3.11+
  • A Linux-based system with a Bluetooth adapter that supports BLE (e.g., a Raspberry Pi).

2. Installation (Recommended)

We strongly recommend installing with pipx to keep your system clean and avoid dependency conflicts.

# Install pipx
pip install pipx
pipx ensurepath

# Install the application
pipx install switchbot-actions

(You may need to restart your terminal after the pipx ensurepath step for the changes to take effect.)

Running as a Systemd Service

For continuous, 24/7 monitoring, running this application as a background service is the ideal setup.

Step 1: Create a Dedicated Virtual Environment

# Create a directory and a virtual environment for the application
sudo mkdir -p /opt/switchbot-actions
sudo python3 -m venv /opt/switchbot-actions

Step 2: Install the Application into the venv

# Use the pip from the new environment to install the package
sudo /opt/switchbot-actions/bin/pip install switchbot-actions

Step 3: Place the Configuration File

# Create a dedicated directory for the config file
sudo mkdir -p /etc/switchbot-actions

# Download the example config to the new location
sudo curl -o /etc/switchbot-actions/config.yaml https://raw.githubusercontent.com/hnw/switchbot-actions/main/config.yaml.example

# Edit the configuration for your needs
sudo nano /etc/switchbot-actions/config.yaml

Step 4: Create the systemd Service File

Create a new file at /etc/systemd/system/switchbot-actions.service and paste the following content. Using DynamicUser=yes is a modern, secure way to run services without pre-existing users.

[Unit]
Description=SwitchBot Actions Daemon
After=network.target bluetooth.service

[Service]
# Run the service as its own minimal-privilege, dynamically-created user
DynamicUser=yes

# Use the absolute path to the executable and config file
ExecStart=/opt/switchbot-actions/bin/switchbot-actions -c /etc/switchbot-actions/config.yaml

Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

Step 5: Enable and Start the Service

# Reload systemd to recognize the new service
sudo systemctl daemon-reload

# Enable the service to start automatically on boot
sudo systemctl enable switchbot-actions.service

# Start the service immediately
sudo systemctl start switchbot-actions.service

# Check the status to ensure it's running correctly
sudo systemctl status switchbot-actions.service

[!NOTE] Reloading Configuration without Downtime After modifying /etc/switchbot-actions/config.yaml, you can apply the changes without restarting the service by sending a SIGHUP signal.

sudo kill -HUP $(systemctl show --value --property MainPID switchbot-actions.service)

Usage

We recommend a two-step process to get started smoothly.

Step 1: Verify Hardware and Device Discovery

First, run the application in debug mode to confirm that your Bluetooth adapter is working and can discover your SwitchBot devices.

switchbot-actions --debug

If you see log lines containing "Received advertisement from...", your hardware setup is correct.

[!IMPORTANT] A Note on Permissions on Linux If you encounter errors related to "permission denied," you may need to run the command with sudo.

Step 2: Configure and Run

Once discovery is confirmed, create your config.yaml file. You can download the example file as a starting point.

curl -o config.yaml https://raw.githubusercontent.com/hnw/switchbot-actions/main/config.yaml.example

Edit config.yaml to define your automations, then run the application with your configuration.

switchbot-actions -c config.yaml

Configuration

The application is controlled by config.yaml.

Quick Start Example

To get started quickly, copy and paste the following into your config.yaml. This automation will log a message whenever a SwitchBot Meter's temperature rises above 28.0℃.

automations:
  - name: "High Temperature Alert"
    if:
      source: "switchbot"
      conditions:
        modelName: "WoSensorTH"
        temperature: "> 28.0"
    then:
      type: "shell_command"
      # We redirect to stderr (>&2) so the application logs the output
      # as an ERROR, making it visible by default without needing to
      # enable DEBUG level logging.
      command: "echo 'High temperature detected: {temperature}℃' >&2"

Advanced Example: Inter-Device Automation

This example showcases the power of the new switchbot_command action. When a SwitchBot Contact Sensor on a door is opened, it triggers a SwitchBot Bot to press a button.

automations:
  - name: "Press Light Switch when Office Door Opens"
    if:
      source: "switchbot"
      conditions:
        modelName: "WoContact"
        address: "XX:XX:XX:XX:XX:AA" # <-- Address of your Contact Sensor
        contact_open: True
    then:
      # This action directly controls another SwitchBot device.
      type: "switchbot_command"
      address: "YY:YY:YY:YY:YY:BB" # <-- Address of your SwitchBot Bot
      command: "press"

Detailed Reference & More Examples

For a complete reference of all configuration options--including advanced automations, time-based triggers, MQTT settings, the Prometheus exporter, and logging--please see the Project Specification.

Command-Line Options

Command-line options provide a convenient way to override settings in your config.yaml for testing or temporary changes.

  • --config <path> or -c <path>: Path to the configuration file (default: config.yaml).
  • --debug or -d: Enables DEBUG level logging.
  • --scan-cycle <seconds>: Overrides the scan cycle time.
  • --scan-duration <seconds>: Overrides the scan duration time.
  • Boolean Flags: For any boolean flag like --prometheus-exporter-enabled, a corresponding --no- version is available to explicitly disable the feature, overriding any true setting in the configuration file.
  • And many more for MQTT, Prometheus, etc. Run switchbot-actions --help for a full list.

Configuration Precedence: Settings are applied in the following order of priority (later items override earlier ones):

  1. Application defaults.
  2. config.yaml settings.
  3. Command-line flags.

Robustness Features

switchbot-actions is designed with reliability in mind, ensuring stable operation even in the face of certain issues.

  • Fail-Fast Startup: The application performs critical resource checks at startup. If a required resource (e.g., the configured Prometheus port) is unavailable, the application will fail immediately with a clear error message. This prevents silent failures and ensures that operational issues are identified and addressed promptly.
  • Configuration Reload with Rollback: The application supports dynamic configuration reloading by sending a SIGHUP signal to its process. If a new configuration contains errors or leads to a failed reload, the application will automatically attempt to roll back to the last known good configuration. This prevents service interruptions due to misconfigurations and enhances overall system stability.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

switchbot_actions-1.2.0.tar.gz (46.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

switchbot_actions-1.2.0-py3-none-any.whl (28.2 kB view details)

Uploaded Python 3

File details

Details for the file switchbot_actions-1.2.0.tar.gz.

File metadata

  • Download URL: switchbot_actions-1.2.0.tar.gz
  • Upload date:
  • Size: 46.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for switchbot_actions-1.2.0.tar.gz
Algorithm Hash digest
SHA256 3425dcfc9380d49758d2588ee2f021f283b9059bcedf0ecbf44b846b933ce9a1
MD5 5259561bfad703d26b8ca0df1d344d34
BLAKE2b-256 64b61737d8b693003e122ce80495279cddcfeb938a8608da320313643039ba2f

See more details on using hashes here.

Provenance

The following attestation bundles were made for switchbot_actions-1.2.0.tar.gz:

Publisher: publish-to-pypi.yml on hnw/switchbot-actions

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file switchbot_actions-1.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for switchbot_actions-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e5907f678094cc63600883a683ba40f094ccd03dd5f2d853940e804736ecd98b
MD5 68d908ac0f3ab7c194f8b95e0a040b00
BLAKE2b-256 2f7e72c63d56037e15ede8f1665a6f9ac2f5ba44e4f7cb5a2fada35eb6b1f3fa

See more details on using hashes here.

Provenance

The following attestation bundles were made for switchbot_actions-1.2.0-py3-none-any.whl:

Publisher: publish-to-pypi.yml on hnw/switchbot-actions

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page