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:
Key Features
- Direct Device Control: A new
switchbot_commandaction 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
/metricsendpoint. - Powerful Automation Rules: Define complex automations with a unified
if/thenstructure. - 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 aSIGHUPsignal.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"
Advanced Example: Comparing Against the Previous State
switchbot-actions can create automations based not just on the current state, but by comparing it against the immediately preceding state. This is enabled by the previous context, allowing for more dynamic and powerful scenarios.
A great practical use case for this is detecting a button press on devices like the SwitchBot Contact Sensor or Bot. These devices expose a button_count attribute that increments each time the button is pressed. By checking if the current count is different from the previous one, you can reliably trigger an action on the press event itself.
Example: Turn on a light when the Contact Sensor's button is pressed
automations:
- name: "Turn on light when sensor button is pressed"
if:
source: "switchbot"
conditions:
modelName: "WoContact"
# Trigger if the current button_count is not equal to the previous one.
button_count: "!= {previous.button_count}"
then:
type: "shell_command"
command: "echo 'Button on {address} was pressed. Turning on light.' >&2"
This pattern allows you to react to discrete events (a state change), rather than just static states (a door is open/closed), making your automations more intelligent.
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.
Using Device Aliases in if Blocks
You can now use device aliases, defined in the top-level devices section, directly within the if block of your automations. This improves readability and maintainability by allowing you to refer to devices by a friendly name instead of their MAC address.
Example:
devices:
livingroom-meter:
address: "11:22:33:44:55:66"
automations:
- name: "Monitor Living Room Meter"
if:
source: "switchbot"
# Reference a device alias defined in the `devices` section.
# The `address` from `ivingroom-meter` will be automatically injected into `conditions.address`.
device: "livingroom-meter"
conditions:
# If `address` is also specified here, the `device` alias's address
# will take precedence and overwrite it.
temperature: "> 25.0"
humidity: "< 60.0"
then:
type: "shell_command"
command: "echo 'Living room is hot and humid! ({temperature}C, {humidity}%)' >&2"
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).--debugor-d: EnablesDEBUGlevel 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 anytruesetting in the configuration file. - And many more for MQTT, Prometheus, etc. Run
switchbot-actions --helpfor a full list.
Configuration Precedence: Settings are applied in the following order of priority (later items override earlier ones):
- Application defaults.
config.yamlsettings.- 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
SIGHUPsignal 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file switchbot_actions-1.4.0.tar.gz.
File metadata
- Download URL: switchbot_actions-1.4.0.tar.gz
- Upload date:
- Size: 52.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
eeceb18a85571ffe4a18361e465f783ca15436ec4ae1d57ce014f27658f054d2
|
|
| MD5 |
d1eb34fb84b17a9245fb167278441d7b
|
|
| BLAKE2b-256 |
003060b9954bd498df948f8605cce04a02cbd3c3c0f4e7a03a9407c788454a18
|
Provenance
The following attestation bundles were made for switchbot_actions-1.4.0.tar.gz:
Publisher:
publish-to-pypi.yml on hnw/switchbot-actions
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
switchbot_actions-1.4.0.tar.gz -
Subject digest:
eeceb18a85571ffe4a18361e465f783ca15436ec4ae1d57ce014f27658f054d2 - Sigstore transparency entry: 365326156
- Sigstore integration time:
-
Permalink:
hnw/switchbot-actions@a7b6ccc3e4ce1f51c7da1f46f94bc6ce16c9fc88 -
Branch / Tag:
refs/tags/v1.4.0 - Owner: https://github.com/hnw
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-to-pypi.yml@a7b6ccc3e4ce1f51c7da1f46f94bc6ce16c9fc88 -
Trigger Event:
release
-
Statement type:
File details
Details for the file switchbot_actions-1.4.0-py3-none-any.whl.
File metadata
- Download URL: switchbot_actions-1.4.0-py3-none-any.whl
- Upload date:
- Size: 30.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
478a906cc5a86bb3e012009e6f01351199ce73bc48b048384487a7fc0bbc4d8c
|
|
| MD5 |
87e31473099f769e1d290930719ea292
|
|
| BLAKE2b-256 |
f7174152f7534108e0e52202c9becb6ad255bd3d634f342090be85301868b074
|
Provenance
The following attestation bundles were made for switchbot_actions-1.4.0-py3-none-any.whl:
Publisher:
publish-to-pypi.yml on hnw/switchbot-actions
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
switchbot_actions-1.4.0-py3-none-any.whl -
Subject digest:
478a906cc5a86bb3e012009e6f01351199ce73bc48b048384487a7fc0bbc4d8c - Sigstore transparency entry: 365326162
- Sigstore integration time:
-
Permalink:
hnw/switchbot-actions@a7b6ccc3e4ce1f51c7da1f46f94bc6ce16c9fc88 -
Branch / Tag:
refs/tags/v1.4.0 - Owner: https://github.com/hnw
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-to-pypi.yml@a7b6ccc3e4ce1f51c7da1f46f94bc6ce16c9fc88 -
Trigger Event:
release
-
Statement type: