homebridge-philips-air-purifier-complete 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -0
- package/CONTRIBUTORS.md +25 -0
- package/LICENSE +24 -0
- package/README.md +230 -0
- package/aioairctrl/__init__.py +1 -0
- package/aioairctrl/__main__.py +4 -0
- package/aioairctrl/cli.py +143 -0
- package/aioairctrl/coap/__init__.py +0 -0
- package/aioairctrl/coap/aiocoap_monkeypatch.py +34 -0
- package/aioairctrl/coap/client.py +135 -0
- package/aioairctrl/coap/encryption.py +65 -0
- package/config.schema.json +53 -0
- package/icon.png +0 -0
- package/index.js +657 -0
- package/package.json +43 -0
- package/philips_air_api.py +469 -0
- package/philipsairhbicon.png +0 -0
- package/postinstall.sh +65 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here.
|
|
4
|
+
|
|
5
|
+
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## [1.0.0] — 2026-05-17
|
|
10
|
+
|
|
11
|
+
Initial release of `homebridge-philips-air-purifier-complete`.
|
|
12
|
+
|
|
13
|
+
### Highlights
|
|
14
|
+
|
|
15
|
+
- **Bundled aioairctrl** — The [betaboon/aioairctrl](https://github.com/betaboon/aioairctrl) CoAP library is included in the plugin package. Users no longer need to separately `pip install aioairctrl`.
|
|
16
|
+
- **Automated Python environment setup** — An npm `postinstall` hook creates a virtual environment and installs `aiocoap` and `pycryptodomex` automatically on `npm install` or Homebridge UI install.
|
|
17
|
+
- **Simplified configuration** — Only `name` and `host` are required. `pythonPath` and `apiScriptPath` are retained as optional advanced overrides.
|
|
18
|
+
|
|
19
|
+
### Features (from prior forks)
|
|
20
|
+
|
|
21
|
+
- Power on/off, Auto/Manual/Sleep/Medium/Turbo fan modes
|
|
22
|
+
- Sleep Mode as a dedicated HomeKit switch (sets Sleep mode, dims display)
|
|
23
|
+
- Real-time PM2.5 air quality sensor with AQI rating
|
|
24
|
+
- Display light control (Off / Dim / Bright)
|
|
25
|
+
- Child lock
|
|
26
|
+
- HEPA filter and pre-filter life percentage with change alerts
|
|
27
|
+
- CoAP Observe push updates — no polling
|
|
28
|
+
- Daemon auto-restart with exponential backoff (5s → 10s → 30s → 60s)
|
|
29
|
+
- Homebridge 2.0+ and Node.js 18+ compatible
|
|
30
|
+
|
|
31
|
+
### Bug Fixes (in bundled aioairctrl)
|
|
32
|
+
|
|
33
|
+
- **`encryption.py`** — Added minimum-length validation in `decrypt()` to prevent silent corruption on short payloads
|
|
34
|
+
- **`encryption.py`** — `DigestMismatchException` now includes key and digest values in its message for easier debugging
|
|
35
|
+
- **`client.py`** — Fixed return type annotation: `set_control_value` and `set_control_values` annotated as `-> bool` (were incorrectly `-> None`)
|
|
36
|
+
- **`client.py`** — `_sync()` now raises `ValueError` on empty client key response instead of silently proceeding
|
|
37
|
+
- **`cli.py`** — Fixed `e.split("=")` → `e.split("=", 1)` in the `set` command to correctly handle values containing `=` characters
|
|
38
|
+
|
|
39
|
+
### Bug Fixes (in philips_air_api.py)
|
|
40
|
+
|
|
41
|
+
- Fixed `status, _ = await self._client.get_status()` — `get_status()` returns a single `dict`, not a tuple. The incorrect unpacking would raise `ValueError` in CLI mode. Fixed to `status = await self._client.get_status()`.
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Prior History
|
|
46
|
+
|
|
47
|
+
Changes made in [MadDogWarner/homebridge-philips-air-purifier](https://github.com/MadDogWarner/homebridge-philips-air-purifier) before this combined release are not repeated here. That repo's history serves as the prior changelog.
|
package/CONTRIBUTORS.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Contributors
|
|
2
|
+
|
|
3
|
+
## Project Maintainer
|
|
4
|
+
|
|
5
|
+
**[MadDogWarner](https://github.com/MadDogWarner)**
|
|
6
|
+
Combined fork author. Bundled aioairctrl into the plugin, automated Python environment setup via npm postinstall, applied code quality and security fixes, authored streamlined Homebridge deployment, project versioning and maintenance.
|
|
7
|
+
|
|
8
|
+
## AI Assistance
|
|
9
|
+
|
|
10
|
+
**[Claude Sonnet 4.6](https://claude.ai)** (Anthropic)
|
|
11
|
+
Code review of aioairctrl (bug fixes, type annotation corrections, input validation), refactoring of homebridge plugin for the bundled architecture, postinstall automation, documentation authoring.
|
|
12
|
+
|
|
13
|
+
## Original Authors
|
|
14
|
+
|
|
15
|
+
**[louiscrc](https://github.com/louiscrc)**
|
|
16
|
+
Original homebridge-philips-air-purifier author. Designed the CoAP Observe daemon architecture and Python/Node.js IPC protocol that this plugin is built upon.
|
|
17
|
+
See the original project: [louiscrc/homebridge-philips-air-purifier](https://github.com/louiscrc/homebridge-philips-air-purifier)
|
|
18
|
+
|
|
19
|
+
**[MadDogWarner](https://github.com/MadDogWarner)** (fork of louiscrc)
|
|
20
|
+
Homebridge 2.0+ and Node.js 24 compatibility, daemon auto-restart with exponential backoff, security hardening, sleep mode support.
|
|
21
|
+
See the fork: [MadDogWarner/homebridge-philips-air-purifier](https://github.com/MadDogWarner/homebridge-philips-air-purifier)
|
|
22
|
+
|
|
23
|
+
**[betaboon](https://github.com/betaboon)**
|
|
24
|
+
Original aioairctrl author. Reverse-engineered the Philips CoAP encryption protocol and built the Python library used for device communication.
|
|
25
|
+
See the original project: [betaboon/aioairctrl](https://github.com/betaboon/aioairctrl)
|
package/LICENSE
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MadDogWarner
|
|
4
|
+
|
|
5
|
+
Portions copyright (c) louiscrc — homebridge-philips-air-purifier
|
|
6
|
+
Portions copyright (c) betaboon — aioairctrl
|
|
7
|
+
|
|
8
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
9
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
10
|
+
in the Software without restriction, including without limitation the rights
|
|
11
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
12
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
13
|
+
furnished to do so, subject to the following conditions:
|
|
14
|
+
|
|
15
|
+
The above copyright notice and this permission notice shall be included in all
|
|
16
|
+
copies or substantial portions of the Software.
|
|
17
|
+
|
|
18
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
19
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
20
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
21
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
22
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
23
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
24
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
# homebridge-philips-air-purifier-complete
|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
<img src="https://raw.githubusercontent.com/MadDogWarner/homebridge-philips-air-purifier-complete/main/icon.png" width="200" alt="Philips Air Purifier">
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<a href="https://www.npmjs.com/package/homebridge-philips-air-purifier-complete"><img src="https://img.shields.io/npm/v/homebridge-philips-air-purifier-complete" alt="npm"></a>
|
|
9
|
+
<a href="https://homebridge.io"><img src="https://img.shields.io/badge/homebridge-%3E%3D2.0.0-blue" alt="Homebridge"></a>
|
|
10
|
+
<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
|
|
11
|
+
</p>
|
|
12
|
+
|
|
13
|
+
Control your Philips Air Purifier from Apple HomeKit via Homebridge — **with no separate Python package install required**.
|
|
14
|
+
|
|
15
|
+
This plugin bundles the [aioairctrl](https://github.com/betaboon/aioairctrl) CoAP library directly. Installing the plugin is all you need; the Python environment is set up automatically.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Features
|
|
20
|
+
|
|
21
|
+
- **Power On/Off** — Turn your air purifier on or off
|
|
22
|
+
- **4 Fan Modes** — Auto, Sleep, Medium, Turbo (via rotation speed slider)
|
|
23
|
+
- **Sleep Mode Switch** — Dedicated HomeKit switch that sets Sleep mode and dims the display
|
|
24
|
+
- **Air Quality Sensor** — Real-time PM2.5 readings with derived AQI rating
|
|
25
|
+
- **Display Light Control** — Toggle and 3-level brightness (Off / Dim / Bright)
|
|
26
|
+
- **Child Lock** — Lock or unlock physical controls on the device
|
|
27
|
+
- **HEPA Filter Status** — Filter life percentage and change alert
|
|
28
|
+
- **Pre-Filter Status** — Cleanup cycle percentage and change alert
|
|
29
|
+
- **Real-time Updates** — CoAP Observe push updates from the device (~every 30s or on change)
|
|
30
|
+
- **Auto-reconnect** — Daemon restarts automatically with exponential backoff if the device drops off
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## Prerequisites
|
|
35
|
+
|
|
36
|
+
| Requirement | Version |
|
|
37
|
+
|-------------|---------|
|
|
38
|
+
| [Homebridge](https://homebridge.io) | >= 2.0.0 |
|
|
39
|
+
| Node.js | >= 18.0.0 |
|
|
40
|
+
| Python 3 | >= 3.8 |
|
|
41
|
+
| Your Philips Air Purifier's **IP address** | — |
|
|
42
|
+
|
|
43
|
+
Python 3 must be installed on the system running Homebridge. On most platforms:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
# macOS
|
|
47
|
+
brew install python3
|
|
48
|
+
|
|
49
|
+
# Raspberry Pi / Ubuntu / Debian
|
|
50
|
+
sudo apt install python3 python3-venv
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## Installation
|
|
56
|
+
|
|
57
|
+
### Via Homebridge UI (recommended)
|
|
58
|
+
|
|
59
|
+
1. Open the Homebridge UI
|
|
60
|
+
2. Go to **Plugins**
|
|
61
|
+
3. Search for `homebridge-philips-air-purifier-complete`
|
|
62
|
+
4. Click **Install**
|
|
63
|
+
|
|
64
|
+
The plugin automatically sets up a Python virtual environment and installs its CoAP dependencies during install. No extra steps needed.
|
|
65
|
+
|
|
66
|
+
### Via npm
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
npm install -g homebridge-philips-air-purifier-complete
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
If the automatic setup fails (e.g., Python 3 wasn't installed yet), re-run it manually:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
bash $(npm root -g)/homebridge-philips-air-purifier-complete/postinstall.sh
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## Configuration
|
|
81
|
+
|
|
82
|
+
Add to your Homebridge `config.json` under `"accessories"`:
|
|
83
|
+
|
|
84
|
+
```json
|
|
85
|
+
{
|
|
86
|
+
"accessories": [
|
|
87
|
+
{
|
|
88
|
+
"accessory": "PhilipsAirPurifier",
|
|
89
|
+
"name": "Living Room Air Purifier",
|
|
90
|
+
"host": "192.168.1.100"
|
|
91
|
+
}
|
|
92
|
+
]
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Or configure via the Homebridge UI — just fill in the **Name** and **IP Address** fields.
|
|
97
|
+
|
|
98
|
+
### Configuration Options
|
|
99
|
+
|
|
100
|
+
| Option | Required | Default | Description |
|
|
101
|
+
|--------|----------|---------|-------------|
|
|
102
|
+
| `name` | Yes | — | Name shown in HomeKit |
|
|
103
|
+
| `host` | Yes | — | IPv4 address of your air purifier |
|
|
104
|
+
| `pythonPath` | No | Auto-detected | Path to Python 3 with `aiocoap` and `pycryptodomex` installed. Leave blank to use the plugin's bundled virtual environment. |
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## Connectivity Check (optional)
|
|
109
|
+
|
|
110
|
+
Before configuring Homebridge, you can verify the plugin can reach your device:
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
# Activate the plugin's virtual environment
|
|
114
|
+
source $(npm root -g)/homebridge-philips-air-purifier-complete/.venv/bin/activate
|
|
115
|
+
|
|
116
|
+
# Run a sensor query
|
|
117
|
+
python3 $(npm root -g)/homebridge-philips-air-purifier-complete/philips_air_api.py 192.168.1.100 sensors
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
You should see a JSON payload with PM2.5, filter life, temperature, and so on. CoAP can be flaky on the first connection — re-run if you get a timeout.
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## HomeKit Tiles
|
|
125
|
+
|
|
126
|
+
Once configured, your air purifier appears in the Apple Home app with:
|
|
127
|
+
|
|
128
|
+
| Tile | What It Controls |
|
|
129
|
+
|------|-----------------|
|
|
130
|
+
| Air Purifier | Power, Auto/Manual mode, fan speed (Sleep / Medium / Turbo) |
|
|
131
|
+
| Sleep Mode | Switch that activates Sleep mode and dims the display |
|
|
132
|
+
| Air Quality | PM2.5 density and derived AQI rating |
|
|
133
|
+
| Display Light | On/off toggle and 3-level brightness |
|
|
134
|
+
| Child Lock | Lock/unlock physical controls on the device |
|
|
135
|
+
| HEPA Filter | Remaining filter life percentage, change alert below 10% |
|
|
136
|
+
| Pre-Filter | Cleanup cycle status, change alert below 10% |
|
|
137
|
+
|
|
138
|
+
---
|
|
139
|
+
|
|
140
|
+
## Architecture
|
|
141
|
+
|
|
142
|
+
```
|
|
143
|
+
Homebridge (Node.js)
|
|
144
|
+
│
|
|
145
|
+
│ stdin/stdout JSON
|
|
146
|
+
│
|
|
147
|
+
▼
|
|
148
|
+
philips_air_api.py ─── aioairctrl/ (bundled) ──► aiocoap ──► Philips device (CoAP)
|
|
149
|
+
│
|
|
150
|
+
│ CoAP Observe (push)
|
|
151
|
+
│ ≈ every 30s or on change
|
|
152
|
+
▼
|
|
153
|
+
State cache ──► HomeKit characteristics
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
- The Python daemon maintains a **CoAP Observe** subscription to the device
|
|
157
|
+
- The device pushes state updates; no polling
|
|
158
|
+
- Commands (power, mode, light) are sent directly and complete in ~100–300ms
|
|
159
|
+
- The Node.js plugin communicates with the daemon over stdin/stdout JSON
|
|
160
|
+
- If the daemon exits for any reason, Homebridge restarts it with exponential backoff (5s → 10s → 30s → 60s)
|
|
161
|
+
|
|
162
|
+
---
|
|
163
|
+
|
|
164
|
+
## CLI Tool
|
|
165
|
+
|
|
166
|
+
The bundled Python script can be used standalone for diagnostics:
|
|
167
|
+
|
|
168
|
+
```bash
|
|
169
|
+
python3 philips_air_api.py 192.168.1.100 sensors
|
|
170
|
+
python3 philips_air_api.py 192.168.1.100 status
|
|
171
|
+
python3 philips_air_api.py 192.168.1.100 power on
|
|
172
|
+
python3 philips_air_api.py 192.168.1.100 power off
|
|
173
|
+
python3 philips_air_api.py 192.168.1.100 mode auto
|
|
174
|
+
python3 philips_air_api.py 192.168.1.100 mode sleep
|
|
175
|
+
python3 philips_air_api.py 192.168.1.100 mode medium
|
|
176
|
+
python3 philips_air_api.py 192.168.1.100 mode turbo
|
|
177
|
+
python3 philips_air_api.py 192.168.1.100 light 0 # off
|
|
178
|
+
python3 philips_air_api.py 192.168.1.100 light 115 # dim
|
|
179
|
+
python3 philips_air_api.py 192.168.1.100 light 123 # bright
|
|
180
|
+
python3 philips_air_api.py 192.168.1.100 childlock on
|
|
181
|
+
python3 philips_air_api.py 192.168.1.100 childlock off
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
---
|
|
185
|
+
|
|
186
|
+
## Troubleshooting
|
|
187
|
+
|
|
188
|
+
**Plugin loads but device is "No Response" in HomeKit**
|
|
189
|
+
- Verify the IP address is correct and the device is on the same network
|
|
190
|
+
- Run the connectivity check above
|
|
191
|
+
- Check Homebridge logs for daemon error messages
|
|
192
|
+
|
|
193
|
+
**Python setup failed during install**
|
|
194
|
+
- Ensure Python 3 and `python3-venv` are installed, then re-run `bash postinstall.sh`
|
|
195
|
+
|
|
196
|
+
**Persistent CoAP timeouts**
|
|
197
|
+
- CoAP (UDP) can be blocked by some network configurations; ensure UDP is allowed between Homebridge and the device
|
|
198
|
+
- Assign a static IP to the device in your router's DHCP settings
|
|
199
|
+
|
|
200
|
+
---
|
|
201
|
+
|
|
202
|
+
## Versioning
|
|
203
|
+
|
|
204
|
+
This project follows [Semantic Versioning](https://semver.org/). See [CHANGELOG.md](CHANGELOG.md) for the full history.
|
|
205
|
+
|
|
206
|
+
---
|
|
207
|
+
|
|
208
|
+
## License
|
|
209
|
+
|
|
210
|
+
MIT — see [LICENSE](LICENSE).
|
|
211
|
+
|
|
212
|
+
---
|
|
213
|
+
|
|
214
|
+
## Credits and Attribution
|
|
215
|
+
|
|
216
|
+
This project is a combined and enhanced fork of two open-source projects:
|
|
217
|
+
|
|
218
|
+
| Project | Author | Licence |
|
|
219
|
+
|---------|--------|---------|
|
|
220
|
+
| [louiscrc/homebridge-philips-air-purifier](https://github.com/louiscrc/homebridge-philips-air-purifier) | [louiscrc](https://github.com/louiscrc) | MIT |
|
|
221
|
+
| [betaboon/aioairctrl](https://github.com/betaboon/aioairctrl) | [betaboon](https://github.com/betaboon) | MIT |
|
|
222
|
+
|
|
223
|
+
See [CONTRIBUTORS.md](CONTRIBUTORS.md) for the full contributor list.
|
|
224
|
+
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
## Support
|
|
228
|
+
|
|
229
|
+
- **Issues:** [GitHub Issues](https://github.com/MadDogWarner/homebridge-philips-air-purifier-complete/issues)
|
|
230
|
+
- **Homebridge community:** [homebridge.io](https://homebridge.io)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from aioairctrl.coap.client import Client as CoAPClient
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import asyncio
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
|
|
6
|
+
from aioairctrl import CoAPClient
|
|
7
|
+
|
|
8
|
+
logging.basicConfig(level=logging.WARN)
|
|
9
|
+
logger = logging.getLogger(__package__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def parse_args() -> argparse.Namespace:
|
|
13
|
+
parser = argparse.ArgumentParser()
|
|
14
|
+
subparsers = parser.add_subparsers(
|
|
15
|
+
dest="command",
|
|
16
|
+
required=True,
|
|
17
|
+
help="sub-command help",
|
|
18
|
+
)
|
|
19
|
+
parser.add_argument(
|
|
20
|
+
"-H",
|
|
21
|
+
"--host",
|
|
22
|
+
metavar="HOST",
|
|
23
|
+
dest="host",
|
|
24
|
+
type=str,
|
|
25
|
+
required=True,
|
|
26
|
+
help="Address of CoAP-device",
|
|
27
|
+
)
|
|
28
|
+
parser.add_argument(
|
|
29
|
+
"-P",
|
|
30
|
+
"--port",
|
|
31
|
+
metavar="PORT",
|
|
32
|
+
dest="port",
|
|
33
|
+
type=int,
|
|
34
|
+
required=False,
|
|
35
|
+
default=5683,
|
|
36
|
+
help="Port of CoAP-device (default: %(default)s)",
|
|
37
|
+
)
|
|
38
|
+
parser.add_argument(
|
|
39
|
+
"-D",
|
|
40
|
+
"--debug",
|
|
41
|
+
dest="debug",
|
|
42
|
+
action="store_true",
|
|
43
|
+
help="Enable debug output",
|
|
44
|
+
)
|
|
45
|
+
parser_status = subparsers.add_parser(
|
|
46
|
+
"status",
|
|
47
|
+
help="get status of device",
|
|
48
|
+
)
|
|
49
|
+
parser_status.add_argument(
|
|
50
|
+
"-J",
|
|
51
|
+
"--json",
|
|
52
|
+
dest="json",
|
|
53
|
+
action="store_true",
|
|
54
|
+
help="Output status as JSON",
|
|
55
|
+
)
|
|
56
|
+
parser_status_observe = subparsers.add_parser(
|
|
57
|
+
"status-observe",
|
|
58
|
+
help="Observe status of device",
|
|
59
|
+
)
|
|
60
|
+
parser_status_observe.add_argument(
|
|
61
|
+
"-J",
|
|
62
|
+
"--json",
|
|
63
|
+
dest="json",
|
|
64
|
+
action="store_true",
|
|
65
|
+
help="Output status as JSON",
|
|
66
|
+
)
|
|
67
|
+
parser_set = subparsers.add_parser(
|
|
68
|
+
"set",
|
|
69
|
+
help="Set value of device",
|
|
70
|
+
)
|
|
71
|
+
parser_set.add_argument(
|
|
72
|
+
"values",
|
|
73
|
+
metavar="K=V",
|
|
74
|
+
type=str,
|
|
75
|
+
nargs="+",
|
|
76
|
+
help="Key-Value pairs to set",
|
|
77
|
+
)
|
|
78
|
+
parser_set.add_argument(
|
|
79
|
+
"-I",
|
|
80
|
+
"--int",
|
|
81
|
+
dest="value_as_int",
|
|
82
|
+
action="store_true",
|
|
83
|
+
help="Encode value as integer",
|
|
84
|
+
)
|
|
85
|
+
return parser.parse_args()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
async def async_main() -> None:
|
|
89
|
+
args = parse_args()
|
|
90
|
+
if args.debug:
|
|
91
|
+
logger.setLevel(logging.DEBUG)
|
|
92
|
+
logging.getLogger("coap").setLevel(logging.DEBUG)
|
|
93
|
+
logging.getLogger("philips_airpurifier").setLevel(logging.DEBUG)
|
|
94
|
+
client = None
|
|
95
|
+
try:
|
|
96
|
+
client = await CoAPClient.create(host=args.host, port=args.port)
|
|
97
|
+
if args.command == "status":
|
|
98
|
+
status = await client.get_status()
|
|
99
|
+
if args.json:
|
|
100
|
+
print(json.dumps(status))
|
|
101
|
+
else:
|
|
102
|
+
print(status)
|
|
103
|
+
elif args.command == "status-observe":
|
|
104
|
+
async for status in client.observe_status():
|
|
105
|
+
if args.json:
|
|
106
|
+
print(json.dumps(status))
|
|
107
|
+
else:
|
|
108
|
+
print(status)
|
|
109
|
+
elif args.command == "set":
|
|
110
|
+
data = {}
|
|
111
|
+
for e in args.values:
|
|
112
|
+
# split on first '=' only so values containing '=' are preserved
|
|
113
|
+
k, v = e.split("=", 1)
|
|
114
|
+
if v == "true":
|
|
115
|
+
v = True
|
|
116
|
+
elif v == "false":
|
|
117
|
+
v = False
|
|
118
|
+
if args.value_as_int:
|
|
119
|
+
try:
|
|
120
|
+
v = int(v)
|
|
121
|
+
except ValueError:
|
|
122
|
+
print("Cannot encode value '%s' as int" % v)
|
|
123
|
+
data = None
|
|
124
|
+
break
|
|
125
|
+
data[k] = v
|
|
126
|
+
if data:
|
|
127
|
+
await client.set_control_values(data=data)
|
|
128
|
+
except (KeyboardInterrupt, asyncio.CancelledError):
|
|
129
|
+
pass
|
|
130
|
+
finally:
|
|
131
|
+
if client:
|
|
132
|
+
await client.shutdown()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def main():
|
|
136
|
+
try:
|
|
137
|
+
asyncio.run(async_main())
|
|
138
|
+
except KeyboardInterrupt:
|
|
139
|
+
pass
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
if __name__ == "__main__":
|
|
143
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import functools
|
|
3
|
+
|
|
4
|
+
from aiocoap.messagemanager import MessageManager
|
|
5
|
+
from aiocoap.numbers.constants import EXCHANGE_LIFETIME
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _deduplicate_message(self, message):
|
|
9
|
+
key = (message.remote, message.mid)
|
|
10
|
+
self.log.debug("MP: New unique message received")
|
|
11
|
+
self.loop.call_later(EXCHANGE_LIFETIME, functools.partial(self._recent_messages.pop, key))
|
|
12
|
+
self._recent_messages[key] = None
|
|
13
|
+
return False
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
MessageManager._deduplicate_message = _deduplicate_message
|
|
17
|
+
|
|
18
|
+
from aiocoap.protocol import ClientObservation
|
|
19
|
+
from aiocoap.error import ObservationCancelled, NotObservable, LibraryShutdown
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def __del__(self):
|
|
23
|
+
if self._future.done():
|
|
24
|
+
try:
|
|
25
|
+
self._future.result()
|
|
26
|
+
except (ObservationCancelled, NotObservable):
|
|
27
|
+
pass
|
|
28
|
+
except LibraryShutdown:
|
|
29
|
+
pass
|
|
30
|
+
except asyncio.CancelledError:
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
ClientObservation._Iterator.__del__ = __del__
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
from aioairctrl.coap import aiocoap_monkeypatch # noqa: F401
|
|
6
|
+
from aiocoap import (
|
|
7
|
+
Context,
|
|
8
|
+
GET,
|
|
9
|
+
Message,
|
|
10
|
+
NON,
|
|
11
|
+
POST,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
from aioairctrl.coap.encryption import EncryptionContext
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Client:
|
|
20
|
+
STATUS_PATH = "/sys/dev/status"
|
|
21
|
+
CONTROL_PATH = "/sys/dev/control"
|
|
22
|
+
SYNC_PATH = "/sys/dev/sync"
|
|
23
|
+
|
|
24
|
+
def __init__(self, host, port=5683):
|
|
25
|
+
self.host = host
|
|
26
|
+
self.port = port
|
|
27
|
+
self._client_context = None
|
|
28
|
+
self._encryption_context = None
|
|
29
|
+
|
|
30
|
+
async def _init(self):
|
|
31
|
+
self._client_context = await Context.create_client_context()
|
|
32
|
+
self._encryption_context = EncryptionContext()
|
|
33
|
+
await self._sync()
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
async def create(cls, *args, **kwargs):
|
|
37
|
+
obj = cls(*args, **kwargs)
|
|
38
|
+
await obj._init()
|
|
39
|
+
return obj
|
|
40
|
+
|
|
41
|
+
async def shutdown(self) -> None:
|
|
42
|
+
if self._client_context:
|
|
43
|
+
await self._client_context.shutdown()
|
|
44
|
+
|
|
45
|
+
async def _sync(self):
|
|
46
|
+
logger.debug("syncing")
|
|
47
|
+
sync_request = os.urandom(4).hex().upper()
|
|
48
|
+
request = Message(
|
|
49
|
+
code=POST,
|
|
50
|
+
mtype=NON,
|
|
51
|
+
uri=f"coap://{self.host}:{self.port}{self.SYNC_PATH}",
|
|
52
|
+
payload=sync_request.encode(),
|
|
53
|
+
)
|
|
54
|
+
response = await self._client_context.request(request).response
|
|
55
|
+
client_key = response.payload.decode()
|
|
56
|
+
if not client_key:
|
|
57
|
+
raise ValueError("Sync response contained empty client key")
|
|
58
|
+
logger.debug("synced: %s", client_key)
|
|
59
|
+
self._encryption_context.set_client_key(client_key)
|
|
60
|
+
|
|
61
|
+
async def get_status(self):
|
|
62
|
+
logger.debug("retrieving status")
|
|
63
|
+
request = Message(
|
|
64
|
+
code=GET,
|
|
65
|
+
mtype=NON,
|
|
66
|
+
uri=f"coap://{self.host}:{self.port}{self.STATUS_PATH}",
|
|
67
|
+
)
|
|
68
|
+
request.opt.observe = 0
|
|
69
|
+
response = await self._client_context.request(request).response
|
|
70
|
+
payload_encrypted = response.payload.decode()
|
|
71
|
+
payload = self._encryption_context.decrypt(payload_encrypted)
|
|
72
|
+
logger.debug("status: %s", payload)
|
|
73
|
+
state_reported = json.loads(payload)
|
|
74
|
+
return state_reported["state"]["reported"]
|
|
75
|
+
|
|
76
|
+
async def observe_status(self):
|
|
77
|
+
def decrypt_status(response):
|
|
78
|
+
payload_encrypted = response.payload.decode()
|
|
79
|
+
payload = self._encryption_context.decrypt(payload_encrypted)
|
|
80
|
+
logger.debug("observation status: %s", payload)
|
|
81
|
+
status = json.loads(payload)
|
|
82
|
+
return status["state"]["reported"]
|
|
83
|
+
|
|
84
|
+
logger.debug("observing status")
|
|
85
|
+
request = Message(
|
|
86
|
+
code=GET,
|
|
87
|
+
mtype=NON,
|
|
88
|
+
uri=f"coap://{self.host}:{self.port}{self.STATUS_PATH}",
|
|
89
|
+
)
|
|
90
|
+
request.opt.observe = 0
|
|
91
|
+
requester = self._client_context.request(request)
|
|
92
|
+
response = await requester.response
|
|
93
|
+
yield decrypt_status(response)
|
|
94
|
+
async for response in requester.observation:
|
|
95
|
+
yield decrypt_status(response)
|
|
96
|
+
|
|
97
|
+
async def set_control_value(self, key, value, retry_count=5, resync=True) -> bool:
|
|
98
|
+
return await self.set_control_values(
|
|
99
|
+
data={key: value}, retry_count=retry_count, resync=resync
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
async def set_control_values(self, data: dict, retry_count=5, resync=True) -> bool:
|
|
103
|
+
state_desired = {
|
|
104
|
+
"state": {
|
|
105
|
+
"desired": {
|
|
106
|
+
"CommandType": "app",
|
|
107
|
+
"DeviceId": "",
|
|
108
|
+
"EnduserId": "",
|
|
109
|
+
**data,
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
payload = json.dumps(state_desired)
|
|
114
|
+
logger.debug("REQUEST: %s", payload)
|
|
115
|
+
payload_encrypted = self._encryption_context.encrypt(payload)
|
|
116
|
+
request = Message(
|
|
117
|
+
code=POST,
|
|
118
|
+
mtype=NON,
|
|
119
|
+
uri=f"coap://{self.host}:{self.port}{self.CONTROL_PATH}",
|
|
120
|
+
payload=payload_encrypted.encode(),
|
|
121
|
+
)
|
|
122
|
+
response = await self._client_context.request(request).response
|
|
123
|
+
logger.debug("RESPONSE: %s", response.payload)
|
|
124
|
+
result = json.loads(response.payload)
|
|
125
|
+
if result.get("status") == "success":
|
|
126
|
+
return True
|
|
127
|
+
else:
|
|
128
|
+
if resync:
|
|
129
|
+
logger.debug("set_control_value failed. resyncing...")
|
|
130
|
+
await self._sync()
|
|
131
|
+
if retry_count > 0:
|
|
132
|
+
logger.debug("set_control_value failed. retrying...")
|
|
133
|
+
return await self.set_control_values(data, retry_count - 1, resync)
|
|
134
|
+
logger.error("set_control_value failed: %s", data)
|
|
135
|
+
return False
|