# 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:
```mermaid
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.
```bash
# 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
```bash
# 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
```bash
# 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
```bash
# 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.
```ini
[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
```bash
# 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.
>
> ```bash
> 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.
```bash
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.
```bash
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.
```bash
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℃.
```yaml
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.
```yaml
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**](https://github.com/hnw/switchbot-actions/blob/main/docs/specification.md).
### 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.
Raw data
{
"_id": null,
"home_page": null,
"name": "switchbot-actions",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.11",
"maintainer_email": null,
"keywords": "switchbot, automation, prometheus, ble, home-automation",
"author": null,
"author_email": "Yoshio HANAWA <y@hnw.jp>",
"download_url": "https://files.pythonhosted.org/packages/64/b6/1737d8b693003e122ce80495279cddcfeb938a8608da320313643039ba2f/switchbot_actions-1.2.0.tar.gz",
"platform": null,
"description": "# SwitchBot Actions: A YAML-based Automation Engine\n\nA powerful, configurable automation engine for SwitchBot BLE devices, with an optional Prometheus exporter.\n\n`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.\n\nAt its core, `switchbot-actions` monitors various input sources and, based on your rules, triggers different actions. The overall architecture can be visualized as follows:\n\n```mermaid\ngraph TD\n subgraph \"Inputs (Triggers)\"\n A[\"SwitchBot<br>Sensors\"]\n B[\"MQTT<br>Subscriptions\"]\n end\n\n subgraph \"Application\"\n S[\"switchbot-actions\"]\n end\n\n subgraph \"Outputs (Actions)\"\n W[\"SwitchBot<br>Commands\"]\n X[\"MQTT<br>Publishing\"]\n Y[\"Webhooks\"]\n Z[\"Shell<br>Commands\"]\n V[\"Prometheus<br>Metrics\"]\n end\n\n A --> S\n B --> S\n\n S --> W\n S --> X\n S --> Y\n S --> Z\n S --> V\n```\n\n## Key Features\n\n - **Direct Device Control**: A new `switchbot_command` action allows you to directly control any SwitchBot device, enabling powerful, interconnected automations without external scripts.\n - **Real-time Monitoring**: Gathers data from all nearby SwitchBot devices.\n - **Full MQTT Integration**: Use MQTT messages as triggers for automations, and publish messages as an action.\n - **Prometheus Exporter**: Exposes metrics at a configurable `/metrics` endpoint.\n - **Powerful Automation Rules**: Define complex automations with a unified `if/then` structure.\n - **Flexible Conditions**: Build rules based on device model, address, sensor values, and even signal strength (`rssi`).\n - **Highly Configurable**: Control every aspect of the application from a single configuration file.\n\n## Getting Started\n\n### 1. Prerequisites\n\n - Python 3.11+\n - A Linux-based system with a Bluetooth adapter that supports BLE (e.g., a Raspberry Pi).\n\n### 2. Installation (Recommended)\n\nWe strongly recommend installing with `pipx` to keep your system clean and avoid dependency conflicts.\n\n```bash\n# Install pipx\npip install pipx\npipx ensurepath\n\n# Install the application\npipx install switchbot-actions\n```\n\n*(You may need to restart your terminal after the `pipx ensurepath` step for the changes to take effect.)*\n\n## Running as a Systemd Service\n\nFor continuous, 24/7 monitoring, running this application as a background service is the ideal setup.\n\n#### Step 1: Create a Dedicated Virtual Environment\n\n```bash\n# Create a directory and a virtual environment for the application\nsudo mkdir -p /opt/switchbot-actions\nsudo python3 -m venv /opt/switchbot-actions\n```\n\n#### Step 2: Install the Application into the venv\n\n```bash\n# Use the pip from the new environment to install the package\nsudo /opt/switchbot-actions/bin/pip install switchbot-actions\n```\n\n#### Step 3: Place the Configuration File\n\n```bash\n# Create a dedicated directory for the config file\nsudo mkdir -p /etc/switchbot-actions\n\n# Download the example config to the new location\nsudo curl -o /etc/switchbot-actions/config.yaml https://raw.githubusercontent.com/hnw/switchbot-actions/main/config.yaml.example\n\n# Edit the configuration for your needs\nsudo nano /etc/switchbot-actions/config.yaml\n```\n\n#### Step 4: Create the systemd Service File\n\nCreate 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.\n\n```ini\n[Unit]\nDescription=SwitchBot Actions Daemon\nAfter=network.target bluetooth.service\n\n[Service]\n# Run the service as its own minimal-privilege, dynamically-created user\nDynamicUser=yes\n\n# Use the absolute path to the executable and config file\nExecStart=/opt/switchbot-actions/bin/switchbot-actions -c /etc/switchbot-actions/config.yaml\n\nRestart=on-failure\nRestartSec=5\n\n[Install]\nWantedBy=multi-user.target\n```\n\n#### Step 5: Enable and Start the Service\n\n```bash\n# Reload systemd to recognize the new service\nsudo systemctl daemon-reload\n\n# Enable the service to start automatically on boot\nsudo systemctl enable switchbot-actions.service\n\n# Start the service immediately\nsudo systemctl start switchbot-actions.service\n\n# Check the status to ensure it's running correctly\nsudo systemctl status switchbot-actions.service\n```\n\n> [\\!NOTE]\n> **Reloading Configuration without Downtime**\n> After modifying `/etc/switchbot-actions/config.yaml`, you can apply the changes without restarting the service by sending a `SIGHUP` signal.\n>\n> ```bash\n> sudo kill -HUP $(systemctl show --value --property MainPID switchbot-actions.service)\n> ```\n\n## Usage\n\nWe recommend a two-step process to get started smoothly.\n\n### Step 1: Verify Hardware and Device Discovery\n\nFirst, run the application in debug mode to confirm that your Bluetooth adapter is working and can discover your SwitchBot devices.\n\n```bash\nswitchbot-actions --debug\n```\n\nIf you see log lines containing \"Received advertisement from...\", your hardware setup is correct.\n\n> [\\!IMPORTANT]\n> **A Note on Permissions on Linux**\n> If you encounter errors related to \"permission denied,\" you may need to run the command with `sudo`.\n\n### Step 2: Configure and Run\n\nOnce discovery is confirmed, create your `config.yaml` file. You can download the example file as a starting point.\n\n```bash\ncurl -o config.yaml https://raw.githubusercontent.com/hnw/switchbot-actions/main/config.yaml.example\n```\n\nEdit `config.yaml` to define your automations, then run the application with your configuration.\n\n```bash\nswitchbot-actions -c config.yaml\n```\n\n## Configuration\n\nThe application is controlled by `config.yaml`.\n\n### Quick Start Example\n\nTo 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\u2103.\n\n```yaml\nautomations:\n - name: \"High Temperature Alert\"\n if:\n source: \"switchbot\"\n conditions:\n modelName: \"WoSensorTH\"\n temperature: \"> 28.0\"\n then:\n type: \"shell_command\"\n # We redirect to stderr (>&2) so the application logs the output\n # as an ERROR, making it visible by default without needing to\n # enable DEBUG level logging.\n command: \"echo 'High temperature detected: {temperature}\u2103' >&2\"\n```\n\n### Advanced Example: Inter-Device Automation\n\nThis 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.\n\n```yaml\nautomations:\n - name: \"Press Light Switch when Office Door Opens\"\n if:\n source: \"switchbot\"\n conditions:\n modelName: \"WoContact\"\n address: \"XX:XX:XX:XX:XX:AA\" # <-- Address of your Contact Sensor\n contact_open: True\n then:\n # This action directly controls another SwitchBot device.\n type: \"switchbot_command\"\n address: \"YY:YY:YY:YY:YY:BB\" # <-- Address of your SwitchBot Bot\n command: \"press\"\n```\n\n### Detailed Reference & More Examples\n\nFor 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**](https://github.com/hnw/switchbot-actions/blob/main/docs/specification.md).\n\n### Command-Line Options\n\nCommand-line options provide a convenient way to override settings in your `config.yaml` for testing or temporary changes.\n\n - `--config <path>` or `-c <path>`: Path to the configuration file (default: `config.yaml`).\n - `--debug` or `-d`: Enables `DEBUG` level logging.\n - `--scan-cycle <seconds>`: Overrides the scan cycle time.\n - `--scan-duration <seconds>`: Overrides the scan duration time.\n - **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.\n - And many more for MQTT, Prometheus, etc. Run `switchbot-actions --help` for a full list.\n\n**Configuration Precedence**: Settings are applied in the following order of priority (later items override earlier ones):\n1. Application defaults.\n2. `config.yaml` settings.\n3. Command-line flags.\n\n## Robustness Features\n\n`switchbot-actions` is designed with reliability in mind, ensuring stable operation even in the face of certain issues.\n\n - **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.\n - **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.\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A YAML-based automation engine for SwitchBot BLE devices with a Prometheus exporter.",
"version": "1.2.0",
"project_urls": {
"Bug Tracker": "https://github.com/hnw/switchbot-actions/issues",
"Homepage": "https://github.com/hnw/switchbot-actions",
"Repository": "https://github.com/hnw/switchbot-actions"
},
"split_keywords": [
"switchbot",
" automation",
" prometheus",
" ble",
" home-automation"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "2f7e72c63d56037e15ede8f1665a6f9ac2f5ba44e4f7cb5a2fada35eb6b1f3fa",
"md5": "68d908ac0f3ab7c194f8b95e0a040b00",
"sha256": "e5907f678094cc63600883a683ba40f094ccd03dd5f2d853940e804736ecd98b"
},
"downloads": -1,
"filename": "switchbot_actions-1.2.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "68d908ac0f3ab7c194f8b95e0a040b00",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.11",
"size": 28189,
"upload_time": "2025-08-05T00:47:42",
"upload_time_iso_8601": "2025-08-05T00:47:42.914722Z",
"url": "https://files.pythonhosted.org/packages/2f/7e/72c63d56037e15ede8f1665a6f9ac2f5ba44e4f7cb5a2fada35eb6b1f3fa/switchbot_actions-1.2.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "64b61737d8b693003e122ce80495279cddcfeb938a8608da320313643039ba2f",
"md5": "5259561bfad703d26b8ca0df1d344d34",
"sha256": "3425dcfc9380d49758d2588ee2f021f283b9059bcedf0ecbf44b846b933ce9a1"
},
"downloads": -1,
"filename": "switchbot_actions-1.2.0.tar.gz",
"has_sig": false,
"md5_digest": "5259561bfad703d26b8ca0df1d344d34",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.11",
"size": 46606,
"upload_time": "2025-08-05T00:47:44",
"upload_time_iso_8601": "2025-08-05T00:47:44.565083Z",
"url": "https://files.pythonhosted.org/packages/64/b6/1737d8b693003e122ce80495279cddcfeb938a8608da320313643039ba2f/switchbot_actions-1.2.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-05 00:47:44",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "hnw",
"github_project": "switchbot-actions",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "switchbot-actions"
}