homebridge-cuktech-ha 0.0.0-stage → 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 +15 -0
- package/LICENSE +9 -0
- package/README.md +155 -2
- package/config.schema.json +86 -0
- package/docs/BEHAVIOR.md +51 -0
- package/docs/images/ha-companion-dashboard.png +0 -0
- package/index.js +216 -0
- package/lib/client.js +194 -0
- package/lib/model.js +105 -0
- package/package.json +37 -4
- package/scripts/smoke.js +40 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.0.0
|
|
4
|
+
|
|
5
|
+
- First stable GitHub release of the Home Assistant REST adapter; existing package `homebridge-cuktech-ha` and platform `CuktechHA` remain unchanged for cache/configuration compatibility.
|
|
6
|
+
- Refresh English documentation, installation guidance, genuine companion-dashboard screenshot, safety reference, and repository metadata after the repository rename.
|
|
7
|
+
- Runtime behavior is unchanged from 0.1.1. Stable denotes the release channel, not vendor endorsement, physical-control certification, or direct Xiaomi/BLE support.
|
|
8
|
+
- npm publication requires maintainer authentication; GitHub release assets provide manual installation independently.
|
|
9
|
+
|
|
10
|
+
## 0.1.1 — experimental
|
|
11
|
+
|
|
12
|
+
- IR-1: close the write queue at shutdown; immediately reject unsent/new writes, stop confirmation, and abort HTTP transport. Already-sent POSTs remain ambiguous and unconfirmed, never automatically replayed.
|
|
13
|
+
- IR-2: reconcile obsolete prefix-derived cached accessories within this singular plugin/platform only. Same-prefix cache restores current fail-closed handlers; other plugin/platform accessories are untouched.
|
|
14
|
+
- Add seven offline regressions (34 tests total), including real Homebridge/HAP cache serialization and transport AbortSignal coverage.
|
|
15
|
+
- No electrical, BLE actuation, physical pairing/display or production-install verification. HA timestamps remain readback, not property-specific electrical acknowledgement.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 homebridge-cuktech-ha contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,156 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# CUKTECH 10 Ultra for Homebridge
|
|
4
|
+
|
|
5
|
+
**Four ports. Familiar HomeKit controls. Your existing Home Assistant connection.**
|
|
6
|
+
|
|
7
|
+
Bring the CUKTECH 10 Ultra into Homebridge through Home Assistant's local BLE integration.
|
|
8
|
+
|
|
9
|
+
[](https://github.com/thanhduy1706/homebridge-cuktech-10-ultra/actions/workflows/test.yml)
|
|
10
|
+
[](https://github.com/thanhduy1706/homebridge-cuktech-10-ultra/releases)
|
|
11
|
+
[](https://homebridge.io/)
|
|
12
|
+
[](LICENSE)
|
|
13
|
+
|
|
14
|
+
[](#installation)
|
|
15
|
+
[](https://github.com/thanhduy1706/cuktech-10u-hass#installation)
|
|
16
|
+
|
|
17
|
+
[Features](#features) · [Requirements](#requirements) · [Installation](#installation) · [Configuration](#configuration) · [Troubleshooting](#troubleshooting)
|
|
18
|
+
|
|
19
|
+
</div>
|
|
20
|
+
|
|
21
|
+
> **Connection model:** charger → Home Assistant BLE integration → authenticated REST → Homebridge → HomeKit client. Home Assistant is required. This plugin does not sign in to Xiaomi, fetch device tokens, or open its own Bluetooth connection.
|
|
22
|
+
|
|
23
|
+
## Features
|
|
24
|
+
|
|
25
|
+
| Capability | What you get |
|
|
26
|
+
| --- | --- |
|
|
27
|
+
| **Individual port control** | C1, C2, C3 and USB-A exposed as four HomeKit outlets. On/off reflects output control, not whether a device is charging. |
|
|
28
|
+
| **Charging modes** | AI Smart, Digital Ecosystem, Ultra-fast Single Charging and Balanced Output as mutually exclusive switches. Turn the desired mode on to select it. |
|
|
29
|
+
| **USB-A low-current mode** | A separate switch on the controls accessory. |
|
|
30
|
+
| **Live telemetry** | Read-only, Eve-compatible custom power, voltage and current characteristics per port; total output power on the low-current controller service. |
|
|
31
|
+
| **Estimated energy** | Existing HA kWh entities exposed when available; no local accumulation or invented history. |
|
|
32
|
+
| **Availability-aware behavior** | Missing/stale readings become No Response, not made-up zeroes. Writes are serialized and checked against fresh HA readback, without automatic replay. |
|
|
33
|
+
|
|
34
|
+
Apple Home normally shows outlet and switch controls, **not custom W/A/V/kWh readings**. Eve, Controller or another compatible HomeKit client may display these characteristics; handset display and pairing have not been independently verified for this package. No Eve history or Apple Home Energy-tab support is claimed.
|
|
35
|
+
|
|
36
|
+
## Companion dashboard preview
|
|
37
|
+
|
|
38
|
+

|
|
39
|
+
|
|
40
|
+
*Actual browser capture of the maintainer's optional **Home Assistant CUKTECH Studio dashboard**, December 5, 2026. This is **not a Homebridge or Apple Home screen**. The pictured frontend is separate and is not shipped in this plugin. The capture shows observed idle telemetry (0 W), not simulated charging. Private navigation/account details were cropped away; readings were not edited.*
|
|
41
|
+
|
|
42
|
+
## Requirements
|
|
43
|
+
|
|
44
|
+
- **CUKTECH 10 Ultra / AD1204** and a working HA `cuktech_10u` integration with the matching entity contract. Start with the [companion integration](https://github.com/thanhduy1706/cuktech-10u-hass). Other charger models are not claimed compatible.
|
|
45
|
+
- Home Assistant owns the BLE connection and device authentication. Homebridge only needs network access to HA.
|
|
46
|
+
- **Node.js ≥22.12.0** and **Homebridge ≥1.8.0, <3**, as declared in the package. Offline validation uses Node 24, Homebridge **2.5.1**, and real HAP **2.3.1** classes; the full declared range has not been tested.
|
|
47
|
+
- A Home Assistant long-lived access token, stored in a restricted file or securely injected environment variable.
|
|
48
|
+
- A dedicated Homebridge **child bridge** is recommended, with a new identity and unused port allocated by Homebridge UI.
|
|
49
|
+
|
|
50
|
+
## Installation
|
|
51
|
+
|
|
52
|
+
### 1. Download the release package
|
|
53
|
+
|
|
54
|
+
Download **`homebridge-cuktech-ha-1.0.0.tgz`** from the [v1.0.0 release](https://github.com/thanhduy1706/homebridge-cuktech-10-ultra/releases/tag/v1.0.0).
|
|
55
|
+
|
|
56
|
+
The repository is named `homebridge-cuktech-10-ultra`; the existing **package identifier remains `homebridge-cuktech-ha`** and the platform remains **`CuktechHA`**. Keeping these identifiers preserves accessory/cache compatibility. Do not rename configuration blocks to match the repository.
|
|
57
|
+
|
|
58
|
+
### 2. Install in the correct Homebridge environment
|
|
59
|
+
|
|
60
|
+
Use the terminal belonging to your Homebridge installation (for containers, the Homebridge container terminal), not an unrelated host Node installation:
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
npm install --global --ignore-scripts /path/to/homebridge-cuktech-ha-1.0.0.tgz
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Use the permissions/package location appropriate to your installation; see the [official Homebridge documentation](https://github.com/homebridge/homebridge/wiki). The release archive is a normal npm package; its installability is checked in an isolated prefix without starting Homebridge.
|
|
67
|
+
|
|
68
|
+
**Registry status:** this package is not currently published to npm. The button above opens these manual instructions, not a nonexistent registry listing or one-click install. GitHub downloads work without npm account authentication.
|
|
69
|
+
|
|
70
|
+
### 3. Configure and pair deliberately
|
|
71
|
+
|
|
72
|
+
Add the platform below through Homebridge UI, enable its dedicated child bridge and schedule any required Homebridge restart. Initial plugin discovery may need a main-process restart; it is not guaranteed to be restart-free. Verify read-only telemetry first, then pair the new child bridge using Homebridge's own UI. Do not copy another bridge's pairing identity, `_bridge` block or port.
|
|
73
|
+
|
|
74
|
+
Existing users: back up first, install the release package and keep the same package/platform name, entity prefix and child-bridge identity. See the [changelog](CHANGELOG.md). To roll back, reinstall the prior package and restore the matching backup if needed; never delete shared accessory caches as a shortcut.
|
|
75
|
+
|
|
76
|
+
## Configuration
|
|
77
|
+
|
|
78
|
+
Example **platform fragment** with placeholder paths and entity prefix, not a complete `config.json`:
|
|
79
|
+
|
|
80
|
+
```json
|
|
81
|
+
{
|
|
82
|
+
"platform": "CuktechHA",
|
|
83
|
+
"name": "CUKTECH HA",
|
|
84
|
+
"url": "http://127.0.0.1:8123",
|
|
85
|
+
"prefix": "cuktech_10_ultra_example_",
|
|
86
|
+
"tokenFile": "/homebridge/secrets/cuktech-ha-token",
|
|
87
|
+
"pollSeconds": 5,
|
|
88
|
+
"staleSeconds": 90,
|
|
89
|
+
"inUseWatts": 0.1,
|
|
90
|
+
"readbackSeconds": 40,
|
|
91
|
+
"exposeEnergy": true
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Replace the prefix with the exact existing HA entity prefix, including its trailing underscore. Loopback refers to the **Homebridge process/container**, not necessarily your HA host. Use HTTPS for a remote HA endpoint.
|
|
96
|
+
|
|
97
|
+
| Option | Default | Purpose |
|
|
98
|
+
| --- | --- | --- |
|
|
99
|
+
| `url` | `http://127.0.0.1:8123` | Reachable HA base URL. Plain HTTP outside loopback is refused unless explicitly overridden. |
|
|
100
|
+
| `prefix` | `cuktech_10_ultra_example_` | HA entity prefix. Changing it changes HomeKit identities and may lose tile customizations/automations. |
|
|
101
|
+
| `tokenFile` | — | Regular bearer-token file, readable only by the Homebridge user (`chmod 600` or `400`). Takes precedence over `tokenEnv`. |
|
|
102
|
+
| `tokenEnv` | `CUKTECH_HA_TOKEN` | Environment-variable name, **not the token itself**. |
|
|
103
|
+
| `pollSeconds` | `5` | REST polling interval, 2–60 seconds. |
|
|
104
|
+
| `staleSeconds` | `90` | Freshness threshold, 10–300 seconds. |
|
|
105
|
+
| `timeoutSeconds` | `10` | HTTP timeout, 1–30 seconds. |
|
|
106
|
+
| `inUseWatts` | `0.1` | Above this fresh per-port wattage, OutletInUse becomes true. This does not identify an attached device. |
|
|
107
|
+
| `readbackSeconds` | `40` | Write-confirmation timeout, 17–60 seconds. |
|
|
108
|
+
| `exposeEnergy` | `true` | Add discovered existing HA kWh values. Removing cached energy characteristics requires a deliberate cache migration. |
|
|
109
|
+
| `energyEntities` | auto-discovery | Optional existing kWh entity mapping for `total`, `c1`, `c2`, `c3`, `usb_a`. |
|
|
110
|
+
| `allowInsecureHttp` | `false` | Explicit plaintext exception outside loopback; not recommended. |
|
|
111
|
+
|
|
112
|
+
The [configuration schema](config.schema.json) and [example fragment](examples/platform.json) are included in the repository. Keep bearer values out of `config.json`, Git, logs, URLs and issue reports. Files are read on each request to allow token rotation; redirects are refused.
|
|
113
|
+
|
|
114
|
+
## Readings and safe control
|
|
115
|
+
|
|
116
|
+
- Charger power/current/voltage are **reported estimates**, not calibrated billing measurements. HA energy is an integration of those estimates, with persistence and sampling-gap limitations. The plugin only proxies it.
|
|
117
|
+
- Controls wait for newer matching HA readback. The output guard waits at least **16 seconds after the service response**, which may exceed a HomeKit client's timeout. This is not independent electrical proof or a property-specific BLE acknowledgement.
|
|
118
|
+
- Pending or failed/unconfirmed controls return No Response. Do not repeatedly toggle the charger to clear an error. A restart resets plugin guards, not hardware state.
|
|
119
|
+
- Startup does not issue automatic hardware writes. Shutdown rejects unsent/new writes and aborts transport; an already-sent command remains ambiguous and is never automatically replayed.
|
|
120
|
+
- No PD/PPS selectors, cable identity, temperature, negotiated protocol, battery information, firmware operations or factory reset are invented.
|
|
121
|
+
|
|
122
|
+
See [behavior and safety details](docs/BEHAVIOR.md) for acknowledgement limits, entity semantics, cache reconciliation and measurement caveats.
|
|
123
|
+
|
|
124
|
+
## Troubleshooting
|
|
125
|
+
|
|
126
|
+
| Symptom | Check |
|
|
127
|
+
| --- | --- |
|
|
128
|
+
| Plugin missing after install | Confirm the archive was installed in Homebridge's own Node environment; schedule a discovery restart. |
|
|
129
|
+
| All accessories show No Response | Check HA reachability from that environment, token-file ownership/mode, entity prefix, BLE connectivity and fresh device timestamps. |
|
|
130
|
+
| HTTP endpoint rejected | Use HTTPS outside loopback. Do not put credentials in the URL or bypass TLS verification. |
|
|
131
|
+
| Controls time out | Wait for fresh matching HA readback. Output confirmation can exceed client timeouts; do not repeatedly resend commands. |
|
|
132
|
+
| Energy is missing | Confirm existing HA entities report kWh and use `energyEntities` if necessary. No local history is generated. |
|
|
133
|
+
| Watts are absent in Apple Home | Expected for custom characteristics. Try a compatible client; rendering is not guaranteed. |
|
|
134
|
+
| Old accessories after a prefix change | Prefix changes intentionally replace only this singular platform's owned accessories. Restore your original prefix/backup if the change was unintended. |
|
|
135
|
+
|
|
136
|
+
[Open an issue](https://github.com/thanhduy1706/homebridge-cuktech-10-ultra/issues/new) with plugin, Node, Homebridge and HA versions, steps, and redacted logs. Never attach credentials, pairing codes, device identifiers or full configuration exports.
|
|
137
|
+
|
|
138
|
+
## Development and verification
|
|
139
|
+
|
|
140
|
+
```sh
|
|
141
|
+
npm ci --ignore-scripts --no-audit --no-fund
|
|
142
|
+
npm test
|
|
143
|
+
npm pack --ignore-scripts
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
The **34-test offline suite** uses simulated HA requests and real Homebridge/HAP classes, including serialization, shutdown, failed-write non-replay and freshness validation. It does not advertise mDNS, bind HAP ports, pair a handset, access BLE or change hardware outputs. Source and extracted release-package tests are checked separately. Consult [Actions](https://github.com/thanhduy1706/homebridge-cuktech-10-ultra/actions) for the exact revision.
|
|
147
|
+
|
|
148
|
+
Optional `npm run smoke` is authenticated GET-only. Set `CUKTECH_HA_URL`, `CUKTECH_HA_PREFIX` and a restricted `CUKTECH_HA_TOKEN_FILE` or securely injected `CUKTECH_HA_TOKEN`. Its output may include entity identifiers: keep it private.
|
|
149
|
+
|
|
150
|
+
## License and notice
|
|
151
|
+
|
|
152
|
+
Independent, unofficial community software; not affiliated with, endorsed, sponsored or supported by CUKTECH, Xiaomi, Apple or Homebridge. Stable release status does **not** mean vendor approval, Homebridge verification or physical-control certification.
|
|
153
|
+
|
|
154
|
+
Plugin code is [MIT licensed](LICENSE). This REST adapter does **not bundle** the separate BLE integration. Its original entity contract was inspected against [archiveduser/cuktech-10u-hass](https://github.com/archiveduser/cuktech-10u-hass), revision `dc1e07219bef03bd8c128dfc0b6de903b190c5d9`; upstream licensing remains unspecified and is not replaced by this plugin's MIT license. Product names and pictured marks describe compatibility and remain their owners' property.
|
|
155
|
+
|
|
156
|
+
Provided **AS IS**, without warranty. Use at your own risk; to the extent permitted by law, contributors disclaim liability for damage, data loss, device malfunction or charging interruptions. Do not rely on this software as a safety mechanism or bypass hardware protections. Rights and liabilities that cannot legally be excluded are unaffected.
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
{
|
|
2
|
+
"pluginAlias": "CuktechHA",
|
|
3
|
+
"pluginType": "platform",
|
|
4
|
+
"singular": true,
|
|
5
|
+
"headerDisplay": "Uses the existing Home Assistant BLE integration. Do not put bearer tokens in this configuration. Deploy in a dedicated child bridge, not the camera bridge.",
|
|
6
|
+
"schema": {
|
|
7
|
+
"type": "object",
|
|
8
|
+
"required": ["url"],
|
|
9
|
+
"properties": {
|
|
10
|
+
"name": { "type": "string", "default": "CUKTECH HA" },
|
|
11
|
+
"url": {
|
|
12
|
+
"title": "Home Assistant URL",
|
|
13
|
+
"type": "string",
|
|
14
|
+
"default": "http://127.0.0.1:8123"
|
|
15
|
+
},
|
|
16
|
+
"prefix": {
|
|
17
|
+
"title": "HA entity prefix",
|
|
18
|
+
"description": "Changing prefix replaces this singular platform's old cached accessories; HomeKit identity and automations may change.",
|
|
19
|
+
"type": "string",
|
|
20
|
+
"default": "cuktech_10_ultra_example_",
|
|
21
|
+
"pattern": "^[a-z0-9_]+_$"
|
|
22
|
+
},
|
|
23
|
+
"tokenFile": {
|
|
24
|
+
"title": "Restricted bearer file (container path, chmod 600)",
|
|
25
|
+
"type": "string"
|
|
26
|
+
},
|
|
27
|
+
"tokenEnv": {
|
|
28
|
+
"title": "Bearer environment variable name",
|
|
29
|
+
"type": "string",
|
|
30
|
+
"default": "CUKTECH_HA_TOKEN"
|
|
31
|
+
},
|
|
32
|
+
"pollSeconds": {
|
|
33
|
+
"type": "number",
|
|
34
|
+
"minimum": 2,
|
|
35
|
+
"maximum": 60,
|
|
36
|
+
"default": 5
|
|
37
|
+
},
|
|
38
|
+
"staleSeconds": {
|
|
39
|
+
"type": "number",
|
|
40
|
+
"minimum": 10,
|
|
41
|
+
"maximum": 300,
|
|
42
|
+
"default": 90
|
|
43
|
+
},
|
|
44
|
+
"inUseWatts": {
|
|
45
|
+
"type": "number",
|
|
46
|
+
"minimum": 0,
|
|
47
|
+
"maximum": 10,
|
|
48
|
+
"default": 0.1
|
|
49
|
+
},
|
|
50
|
+
"timeoutSeconds": {
|
|
51
|
+
"type": "number",
|
|
52
|
+
"minimum": 1,
|
|
53
|
+
"maximum": 30,
|
|
54
|
+
"default": 10
|
|
55
|
+
},
|
|
56
|
+
"readbackSeconds": {
|
|
57
|
+
"type": "number",
|
|
58
|
+
"minimum": 17,
|
|
59
|
+
"maximum": 60,
|
|
60
|
+
"default": 40
|
|
61
|
+
},
|
|
62
|
+
"exposeEnergy": {
|
|
63
|
+
"title": "Expose existing HA estimated kWh when discovered",
|
|
64
|
+
"type": "boolean",
|
|
65
|
+
"default": true
|
|
66
|
+
},
|
|
67
|
+
"energyEntities": {
|
|
68
|
+
"title": "Optional explicit existing HA kWh entity mapping",
|
|
69
|
+
"type": "object",
|
|
70
|
+
"properties": {
|
|
71
|
+
"total": { "type": "string" },
|
|
72
|
+
"c1": { "type": "string" },
|
|
73
|
+
"c2": { "type": "string" },
|
|
74
|
+
"c3": { "type": "string" },
|
|
75
|
+
"usb_a": { "type": "string" }
|
|
76
|
+
},
|
|
77
|
+
"additionalProperties": false
|
|
78
|
+
},
|
|
79
|
+
"allowInsecureHttp": {
|
|
80
|
+
"title": "Allow plaintext HA outside loopback (not recommended)",
|
|
81
|
+
"type": "boolean",
|
|
82
|
+
"default": false
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
package/docs/BEHAVIOR.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# Behavior and safety reference
|
|
2
|
+
|
|
3
|
+
Implementation details for the HA-backed Homebridge adapter. The timing discussion records the upstream behavior inspected during adapter development; a newer HA integration may use stricter acknowledgement handling. Homebridge still requires fresh matching HA readback, not electrical proof.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
* Four actual `Outlet` services: C1, C2, C3, USB-A. `On` reads the HA output control, **not** charging activity.
|
|
8
|
+
* `OutletInUse` is true only when fresh HA per-port measured/estimated power exceeds `inUseWatts` (default 0.1 W). Fresh zero stays zero; missing/stale/invalid values produce No Response rather than fabricated zero or false. It does not identify an attached device.
|
|
9
|
+
* USB-A low-current switch; four mutually exclusive charging-scene switches: `AI Smart`, `Digital Ecosystem`, `Ultra-fast Single Charging`, `Balanced Output`. Turning an inactive scene off is a no-op; turning the active one off is rejected. Turn the desired scene on instead. External HA changes are authoritative.
|
|
10
|
+
* Read-only Eve-compatible custom power (W), current (A), voltage (V) characteristics on each outlet. Total output power is attached to the low-current controller service. Existing HA cumulative energy (kWh) is added dynamically, including total. USB-A energy discovers `usb_a_energy` then `a_energy`; optional explicit `energyEntities` maps existing entities. Energy is NEVER accumulated locally. `exposeEnergy:false` disables newly added energy characteristics; already cached characteristics require a cache migration to remove.
|
|
11
|
+
* Availability from HA reachability, `connected`, device `last_update`, and bounded REST receipt age. HTTP timeout, 2–60 second polling, bounded exponential retry, serialized writes, shutdown timer cancellation. No automatic replay of failed POSTs.
|
|
12
|
+
* No protocol bit guesses. Properties 7/17/18/21 remain **unexposed** until independently verified semantics and authoritative entities exist. No invented PD/PPS switches, cable identity, temperature, negotiated protocol, or battery information.
|
|
13
|
+
|
|
14
|
+
## Measurement and Apple Home limitations
|
|
15
|
+
|
|
16
|
+
The integration decodes charger `*_est_w`, `*_est_v`, `*_est_a` estimates. These are genuine reported estimates, **not calibrated billing measurements**. Existing HA RestoreSensor energy is an integration of those estimates and may have persistence/gap limitations; this plugin only proxies it. Total/port values depend on the HA BLE decoder and merged sample freshness. Device-level timestamps do not establish individual-property freshness.
|
|
17
|
+
|
|
18
|
+
Apple's native Home app normally displays outlet/control switches, not these custom W/A/V/kWh values. Eve/Controller or another compatible HomeKit client may display custom characteristics; client display is not guaranteed. There is no Eve history, reset-energy control, tariff, or invented historical data. No handset pairing/display test has been performed.
|
|
19
|
+
|
|
20
|
+
## Write safety and acknowledgement limits
|
|
21
|
+
|
|
22
|
+
All writes run in one queue, call an explicit HA service, and wait for a newer device timestamp and matching readback. Pending and failed/unconfirmed controls return No Response, never optimistic success; a later successful explicit write can clear the guard. No blind retry. Unconfirmed guards last for the process lifetime (restart only resets the plugin guard, not the hardware). Do not repeatedly toggle a charger to clear an error.
|
|
23
|
+
|
|
24
|
+
The inspected HA integration optimistically changes `port_ctl` for up to a 15-second expected-mask window. Output confirmation therefore waits at least **16 seconds after the HA service response** (request latency does not count) and requires fresh matching HA readback. This can exceed HomeKit client write timeouts; a client may report a write error before a later authoritative update arrives. Scene/low-current writes do not need that delay. Confirmation is **HA readback, not independent electrical proof**: HA merges properties and can retain an optimistic port mask beyond that window if no new property notification arrives. A generic timestamp cannot prove a property-specific BLE acknowledgement. Do not describe this as verified physical actuation. No actual output/scene writes were performed for this package's validation. There is no factory reset, unpair, firmware operation, or automatic hardware write at startup.
|
|
25
|
+
|
|
26
|
+
Shutdown permanently closes the client: unsent queued/new writes fail without dispatch, confirmation stops, and in-flight HTTP requests are aborted. An already-dispatched POST remains ambiguous; abort is not reversal or electrical cancellation, and no replay occurs. Potentially dispatched controls retain their unconfirmed guard.
|
|
27
|
+
|
|
28
|
+
This is a singular platform (one configured charger per child bridge). On restart, same-prefix cached accessories regain current fail-closed handlers. Changing `prefix` removes only obsolete accessories restored to this plugin/platform and registers the five current accessories; it changes HomeKit identity and may lose tile customizations/automations. Other plugins/platforms are not reconciled.
|
|
29
|
+
|
|
30
|
+
## Credentials and configuration
|
|
31
|
+
|
|
32
|
+
Use a normal HA long-lived access token created by the owner. Keep it in a file **readable only by the Homebridge process** (regular file, chmod 600 or 400), or inject an environment variable. Never paste it into logs, a URL, source, Git, npm, or `config.json`. `tokenFile` takes precedence; otherwise `tokenEnv` defaults to `CUKTECH_HA_TOKEN`. Files are read for each request, allowing rotation. The plugin logs only generic errors; redirects are refused. HTTPS is required for non-loopback unless explicitly overridden.
|
|
33
|
+
|
|
34
|
+
Example platform fragment (no bearer value and no pairing material):
|
|
35
|
+
|
|
36
|
+
```json
|
|
37
|
+
{
|
|
38
|
+
"platform": "CuktechHA",
|
|
39
|
+
"name": "CUKTECH HA",
|
|
40
|
+
"url": "http://127.0.0.1:8123",
|
|
41
|
+
"prefix": "cuktech_10_ultra_example_",
|
|
42
|
+
"tokenFile": "/homebridge/secrets/cuktech-ha-token",
|
|
43
|
+
"pollSeconds": 5,
|
|
44
|
+
"staleSeconds": 90,
|
|
45
|
+
"inUseWatts": 0.1,
|
|
46
|
+
"readbackSeconds": 40,
|
|
47
|
+
"exposeEnergy": true
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Use the UI's dedicated **child bridge** option for this platform and let it allocate a new private identity/unused port. Do not copy another bridge's `_bridge` block. Check local listeners and do not reuse another bridge’s port. Accessory UUIDs derive from HA prefix + service key. HAP's required SerialNumber is labeled `HA-<prefix>`: it is a transport entity identifier, **not a claimed physical serial**. Model/manufacturer are actual CUKTECH 10 Ultra; no firmware version is invented.
|
|
Binary file
|
package/index.js
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
const { Model, SCENES } = require("./lib/model");
|
|
3
|
+
const { Client } = require("./lib/client");
|
|
4
|
+
const PLUGIN = "homebridge-cuktech-ha",
|
|
5
|
+
PLATFORM = "CuktechHA";
|
|
6
|
+
function characteristics(hap) {
|
|
7
|
+
const { Characteristic: C } = hap;
|
|
8
|
+
const result = {};
|
|
9
|
+
for (const [key, name, uuid, unit, max] of [
|
|
10
|
+
[
|
|
11
|
+
"energy",
|
|
12
|
+
"HA Estimated Energy",
|
|
13
|
+
"E863F10C-079E-48FF-8F27-9C2605A29F52",
|
|
14
|
+
"kWh",
|
|
15
|
+
1000000,
|
|
16
|
+
],
|
|
17
|
+
[
|
|
18
|
+
"power",
|
|
19
|
+
"Output Power",
|
|
20
|
+
"E863F10D-079E-48FF-8F27-9C2605A29F52",
|
|
21
|
+
"W",
|
|
22
|
+
1000,
|
|
23
|
+
],
|
|
24
|
+
[
|
|
25
|
+
"current",
|
|
26
|
+
"Output Current",
|
|
27
|
+
"E863F126-079E-48FF-8F27-9C2605A29F52",
|
|
28
|
+
"A",
|
|
29
|
+
100,
|
|
30
|
+
],
|
|
31
|
+
[
|
|
32
|
+
"voltage",
|
|
33
|
+
"Output Voltage",
|
|
34
|
+
"E863F10A-079E-48FF-8F27-9C2605A29F52",
|
|
35
|
+
"V",
|
|
36
|
+
1000,
|
|
37
|
+
],
|
|
38
|
+
]) {
|
|
39
|
+
class Meter extends C {
|
|
40
|
+
constructor() {
|
|
41
|
+
super(name, uuid);
|
|
42
|
+
this.setProps({
|
|
43
|
+
format: hap.Formats.FLOAT,
|
|
44
|
+
unit,
|
|
45
|
+
minValue: 0,
|
|
46
|
+
maxValue: max,
|
|
47
|
+
minStep: key === "energy" ? 0.000001 : 0.001,
|
|
48
|
+
perms: [hap.Perms.PAIRED_READ, hap.Perms.NOTIFY],
|
|
49
|
+
});
|
|
50
|
+
this.value = this.getDefaultValue();
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
Meter.UUID = uuid;
|
|
54
|
+
result[key] = Meter;
|
|
55
|
+
}
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
module.exports = (api) => {
|
|
59
|
+
class CuktechPlatform {
|
|
60
|
+
constructor(log, config, api) {
|
|
61
|
+
this.log = log;
|
|
62
|
+
this.config = config;
|
|
63
|
+
this.api = api;
|
|
64
|
+
this.model = new Model(config);
|
|
65
|
+
this.client = new Client(config, this.model);
|
|
66
|
+
this.cached = new Map();
|
|
67
|
+
this.bindings = [];
|
|
68
|
+
this.energyServices = new Map();
|
|
69
|
+
this.energyBound = new Set();
|
|
70
|
+
this.meters = characteristics(api.hap);
|
|
71
|
+
api.on("didFinishLaunching", () => {
|
|
72
|
+
this.discover().catch(() =>
|
|
73
|
+
log.error("CUKTECH initialization failed (details redacted)"),
|
|
74
|
+
);
|
|
75
|
+
});
|
|
76
|
+
api.on("shutdown", () => this.client.stop());
|
|
77
|
+
}
|
|
78
|
+
configureAccessory(a) {
|
|
79
|
+
// Homebridge routes restored cache to this singular platform. Never adopt
|
|
80
|
+
// accessories explicitly associated with a different plugin/platform.
|
|
81
|
+
if (a._associatedPlugin !== PLUGIN || a._associatedPlatform !== PLATFORM) return;
|
|
82
|
+
this.cached.set(a.UUID, a);
|
|
83
|
+
}
|
|
84
|
+
bind(service, type, get, set) {
|
|
85
|
+
if (
|
|
86
|
+
!service.testCharacteristic(type) &&
|
|
87
|
+
!service.optionalCharacteristics.some((c) => c.UUID === type.UUID)
|
|
88
|
+
)
|
|
89
|
+
service.addOptionalCharacteristic(type);
|
|
90
|
+
const ch = service.getCharacteristic(type);
|
|
91
|
+
const wrapped = () => {
|
|
92
|
+
try {
|
|
93
|
+
return get();
|
|
94
|
+
} catch {
|
|
95
|
+
throw new this.api.hap.HapStatusError(
|
|
96
|
+
this.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
ch.onGet(wrapped);
|
|
101
|
+
if (set)
|
|
102
|
+
ch.onSet(async (v) => {
|
|
103
|
+
try {
|
|
104
|
+
await set(v);
|
|
105
|
+
this.update();
|
|
106
|
+
} catch {
|
|
107
|
+
this.update();
|
|
108
|
+
throw new this.api.hap.HapStatusError(
|
|
109
|
+
this.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE,
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
this.bindings.push({ ch, get: wrapped });
|
|
114
|
+
}
|
|
115
|
+
update() {
|
|
116
|
+
if (this.config.exposeEnergy !== false)
|
|
117
|
+
for (const [port, service] of this.energyServices) {
|
|
118
|
+
if (
|
|
119
|
+
!this.energyBound.has(port) &&
|
|
120
|
+
(this.model.energyEntity(port) ||
|
|
121
|
+
service.testCharacteristic(this.meters.energy))
|
|
122
|
+
) {
|
|
123
|
+
this.bind(service, this.meters.energy, () =>
|
|
124
|
+
this.model.energy(port),
|
|
125
|
+
);
|
|
126
|
+
this.energyBound.add(port);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
for (const b of this.bindings) {
|
|
130
|
+
try {
|
|
131
|
+
b.ch.updateValue(b.get());
|
|
132
|
+
} catch (e) {
|
|
133
|
+
b.ch.updateValue(e);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
accessory(key, name) {
|
|
138
|
+
const uuid = this.api.hap.uuid.generate(
|
|
139
|
+
PLUGIN + ":" + this.model.prefix + key,
|
|
140
|
+
);
|
|
141
|
+
this.expected.add(uuid);
|
|
142
|
+
const a =
|
|
143
|
+
this.cached.get(uuid) || new this.api.platformAccessory(name, uuid);
|
|
144
|
+
if (!this.cached.has(uuid)) {
|
|
145
|
+
this.cached.set(uuid, a);
|
|
146
|
+
this.api.registerPlatformAccessories(PLUGIN, PLATFORM, [a]);
|
|
147
|
+
}
|
|
148
|
+
const { Service: S, Characteristic: C } = this.api.hap;
|
|
149
|
+
a.getService(S.AccessoryInformation)
|
|
150
|
+
.setCharacteristic(C.Manufacturer, "CUKTECH")
|
|
151
|
+
.setCharacteristic(C.Model, "10 Ultra")
|
|
152
|
+
.setCharacteristic(C.SerialNumber, "HA-" + this.model.prefix);
|
|
153
|
+
return a;
|
|
154
|
+
}
|
|
155
|
+
async discover(poll = true) {
|
|
156
|
+
this.expected = new Set();
|
|
157
|
+
const { Service: S, Characteristic: C } = this.api.hap;
|
|
158
|
+
for (const port of ["c1", "c2", "c3", "usb_a"]) {
|
|
159
|
+
const a = this.accessory(
|
|
160
|
+
port,
|
|
161
|
+
port === "usb_a" ? "CUKTECH USB-A" : "CUKTECH " + port.toUpperCase(),
|
|
162
|
+
);
|
|
163
|
+
const outlet =
|
|
164
|
+
a.getService(S.Outlet) || a.addService(S.Outlet, a.displayName);
|
|
165
|
+
this.energyServices.set(port, outlet);
|
|
166
|
+
this.bind(
|
|
167
|
+
outlet,
|
|
168
|
+
C.On,
|
|
169
|
+
() => this.model.bool(this.model.id("switch", port + "_output")),
|
|
170
|
+
(v) =>
|
|
171
|
+
this.client.write(this.model.id("switch", port + "_output"), v),
|
|
172
|
+
);
|
|
173
|
+
this.bind(outlet, C.OutletInUse, () => this.model.inUse(port));
|
|
174
|
+
for (const [kind, unit] of [
|
|
175
|
+
["power", "W"],
|
|
176
|
+
["current", "A"],
|
|
177
|
+
["voltage", "V"],
|
|
178
|
+
])
|
|
179
|
+
this.bind(outlet, this.meters[kind], () =>
|
|
180
|
+
this.model.number(this.model.id("sensor", port + "_" + kind), unit),
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
const a = this.accessory("controls", "CUKTECH Controls");
|
|
184
|
+
const service = (name, id) =>
|
|
185
|
+
a.getServiceById(S.Switch, id) || a.addService(S.Switch, name, id);
|
|
186
|
+
const low = service("USB-A Low Current", "low-current");
|
|
187
|
+
this.bind(
|
|
188
|
+
low,
|
|
189
|
+
C.On,
|
|
190
|
+
() => this.model.bool(this.model.id("switch", "usb_a_low_current")),
|
|
191
|
+
(v) =>
|
|
192
|
+
this.client.write(this.model.id("switch", "usb_a_low_current"), v),
|
|
193
|
+
);
|
|
194
|
+
this.energyServices.set("total", low);
|
|
195
|
+
this.bind(low, this.meters.power, () =>
|
|
196
|
+
this.model.number(this.model.id("sensor", "total_power"), "W"),
|
|
197
|
+
);
|
|
198
|
+
for (const [i, option] of SCENES.entries()) {
|
|
199
|
+
const s = service(option, "scene-" + i);
|
|
200
|
+
this.bind(
|
|
201
|
+
s,
|
|
202
|
+
C.On,
|
|
203
|
+
() => this.model.scene() === option,
|
|
204
|
+
(v) => this.client.scene(option, v),
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
const obsolete = [...this.cached.values()].filter(a => !this.expected.has(a.UUID));
|
|
208
|
+
if (obsolete.length) {
|
|
209
|
+
this.api.unregisterPlatformAccessories(PLUGIN, PLATFORM, obsolete);
|
|
210
|
+
for (const a of obsolete) this.cached.delete(a.UUID);
|
|
211
|
+
}
|
|
212
|
+
if (poll) this.client.start(() => this.update());
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
api.registerPlatform(PLUGIN, PLATFORM, CuktechPlatform);
|
|
216
|
+
};
|
package/lib/client.js
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
const fs = require("node:fs");
|
|
3
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
4
|
+
class Client {
|
|
5
|
+
constructor(c, model) {
|
|
6
|
+
this.c = c;
|
|
7
|
+
this.model = model;
|
|
8
|
+
this.queue = Promise.resolve();
|
|
9
|
+
this.polling = null;
|
|
10
|
+
this.stopped = true;
|
|
11
|
+
// Construction permits offline/pre-start writes; shutdown is irreversible.
|
|
12
|
+
this.shutdown = new AbortController();
|
|
13
|
+
this.stopWaiters = new Set();
|
|
14
|
+
this.failures = 0;
|
|
15
|
+
const u = new URL(c.url);
|
|
16
|
+
if (
|
|
17
|
+
u.username ||
|
|
18
|
+
u.password ||
|
|
19
|
+
u.search ||
|
|
20
|
+
u.hash ||
|
|
21
|
+
!["http:", "https:"].includes(u.protocol)
|
|
22
|
+
)
|
|
23
|
+
throw Error("Invalid HA URL");
|
|
24
|
+
if (
|
|
25
|
+
u.protocol === "http:" &&
|
|
26
|
+
!["localhost", "127.0.0.1", "[::1]"].includes(u.hostname) &&
|
|
27
|
+
!c.allowInsecureHttp
|
|
28
|
+
)
|
|
29
|
+
throw Error("Use HTTPS for remote HA");
|
|
30
|
+
this.base = u.href.replace(/\/$/, "");
|
|
31
|
+
}
|
|
32
|
+
token() {
|
|
33
|
+
try {
|
|
34
|
+
let s;
|
|
35
|
+
if (this.c.tokenFile) {
|
|
36
|
+
const st = fs.statSync(this.c.tokenFile);
|
|
37
|
+
if (!st.isFile() || st.mode & 0o077) throw Error();
|
|
38
|
+
s = fs.readFileSync(this.c.tokenFile, "utf8").trim();
|
|
39
|
+
} else s = process.env[this.c.tokenEnv || "CUKTECH_HA_TOKEN"];
|
|
40
|
+
if (!s || /[\r\n]/.test(s)) throw Error();
|
|
41
|
+
return s;
|
|
42
|
+
} catch {
|
|
43
|
+
throw Error(
|
|
44
|
+
"HA credential unavailable (restricted file or environment required)",
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
assertOpen() {
|
|
49
|
+
if (this.shutdown.signal.aborted) throw Error("HA client stopped");
|
|
50
|
+
}
|
|
51
|
+
untilStopped(pending) {
|
|
52
|
+
let cancel;
|
|
53
|
+
const stopped = new Promise((_, reject) => {
|
|
54
|
+
cancel = () => reject(Error("HA client stopped"));
|
|
55
|
+
this.stopWaiters.add(cancel);
|
|
56
|
+
if (this.shutdown.signal.aborted) cancel();
|
|
57
|
+
});
|
|
58
|
+
// Remove settled waiters, rather than retaining a reaction per request until shutdown.
|
|
59
|
+
return Promise.race([pending, stopped]).finally(() => this.stopWaiters.delete(cancel));
|
|
60
|
+
}
|
|
61
|
+
async request(path, data) {
|
|
62
|
+
this.assertOpen();
|
|
63
|
+
try {
|
|
64
|
+
const r = await fetch(this.base + "/api/" + path, {
|
|
65
|
+
method: data ? "POST" : "GET",
|
|
66
|
+
headers: {
|
|
67
|
+
Authorization: "Bearer " + this.token(),
|
|
68
|
+
"Content-Type": "application/json",
|
|
69
|
+
},
|
|
70
|
+
body: data ? JSON.stringify(data) : undefined,
|
|
71
|
+
signal: AbortSignal.any([this.shutdown.signal, AbortSignal.timeout(
|
|
72
|
+
Math.min(30000, Math.max(1000, (this.c.timeoutSeconds || 10) * 1000)),
|
|
73
|
+
)]),
|
|
74
|
+
redirect: "error",
|
|
75
|
+
});
|
|
76
|
+
if (!r.ok) throw Error();
|
|
77
|
+
return await r.json();
|
|
78
|
+
} catch {
|
|
79
|
+
throw Error("HA request failed (credentials/network/status redacted)");
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async refresh() {
|
|
83
|
+
try {
|
|
84
|
+
const xs = await this.request("states");
|
|
85
|
+
if (!Array.isArray(xs)) throw Error();
|
|
86
|
+
this.assertOpen();
|
|
87
|
+
this.model.ingest(xs);
|
|
88
|
+
this.failures = 0;
|
|
89
|
+
} catch {
|
|
90
|
+
this.model.online = false;
|
|
91
|
+
throw Error("HA unavailable");
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
start(onUpdate = () => {}) {
|
|
95
|
+
this.assertOpen();
|
|
96
|
+
this.stopped = false;
|
|
97
|
+
const run = async () => {
|
|
98
|
+
if (this.stopped) return;
|
|
99
|
+
try {
|
|
100
|
+
await this.refresh();
|
|
101
|
+
} catch {
|
|
102
|
+
this.failures = Math.min(this.failures + 1, 6);
|
|
103
|
+
}
|
|
104
|
+
if (this.stopped) return;
|
|
105
|
+
onUpdate();
|
|
106
|
+
const delay = Math.min(
|
|
107
|
+
60000,
|
|
108
|
+
Math.max(2000, (this.c.pollSeconds || 5) * 1000) * 2 ** this.failures,
|
|
109
|
+
);
|
|
110
|
+
this.polling = setTimeout(run, delay);
|
|
111
|
+
this.polling.unref?.();
|
|
112
|
+
};
|
|
113
|
+
void run();
|
|
114
|
+
}
|
|
115
|
+
stop() {
|
|
116
|
+
this.stopped = true;
|
|
117
|
+
clearTimeout(this.polling);
|
|
118
|
+
this.shutdown.abort();
|
|
119
|
+
for (const cancel of this.stopWaiters) cancel();
|
|
120
|
+
this.stopWaiters.clear();
|
|
121
|
+
}
|
|
122
|
+
write(id, value) {
|
|
123
|
+
if (this.shutdown.signal.aborted) return Promise.reject(Error("HA client stopped"));
|
|
124
|
+
const run = async () => {
|
|
125
|
+
this.assertOpen();
|
|
126
|
+
const before = this.model.states.get(id)?.attributes?.last_update;
|
|
127
|
+
const start = Date.now();
|
|
128
|
+
this.model.unconfirmed.add(id);
|
|
129
|
+
const scene = id === this.model.id("select", "charging_scene");
|
|
130
|
+
if (scene) {
|
|
131
|
+
const { SCENES } = require("./model");
|
|
132
|
+
if (!SCENES.includes(value)) throw Error("Invalid scene");
|
|
133
|
+
} else if (!id.startsWith("switch.") || typeof value !== "boolean")
|
|
134
|
+
throw Error("Invalid control");
|
|
135
|
+
await this.request(
|
|
136
|
+
scene
|
|
137
|
+
? "services/select/select_option"
|
|
138
|
+
: `services/switch/turn_${value ? "on" : "off"}`,
|
|
139
|
+
scene ? { entity_id: id, option: value } : { entity_id: id },
|
|
140
|
+
);
|
|
141
|
+
// HA may merge optimistic output state while the service call is pending.
|
|
142
|
+
// Never count request latency toward the post-response exclusion window.
|
|
143
|
+
this.assertOpen();
|
|
144
|
+
const serviceReturned = Date.now();
|
|
145
|
+
const deadline = serviceReturned + (this.c.readbackSeconds ?? 40) * 1000;
|
|
146
|
+
do {
|
|
147
|
+
this.assertOpen();
|
|
148
|
+
await this.untilStopped(this.refresh());
|
|
149
|
+
this.assertOpen();
|
|
150
|
+
const x = this.model.states.get(id);
|
|
151
|
+
const anchor = this.model.states.get(
|
|
152
|
+
this.model.id("sensor", "total_power"),
|
|
153
|
+
);
|
|
154
|
+
const ts = scene
|
|
155
|
+
? anchor?.attributes?.last_update
|
|
156
|
+
: x?.attributes?.last_update;
|
|
157
|
+
const actual = scene
|
|
158
|
+
? this.model.fresh(anchor)
|
|
159
|
+
? x?.state
|
|
160
|
+
: undefined
|
|
161
|
+
: x && this.model.fresh(x)
|
|
162
|
+
? x.state
|
|
163
|
+
: undefined;
|
|
164
|
+
const safeAge = !id.endsWith("_output") || Date.now() - serviceReturned >= 16000;
|
|
165
|
+
if (
|
|
166
|
+
safeAge &&
|
|
167
|
+
ts &&
|
|
168
|
+
ts !== before &&
|
|
169
|
+
Date.parse(ts) > start &&
|
|
170
|
+
actual === (scene ? value : value ? "on" : "off")
|
|
171
|
+
) {
|
|
172
|
+
this.model.unconfirmed.delete(id);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
await this.untilStopped(sleep(Math.min(500, Math.max(1, deadline - Date.now()))));
|
|
176
|
+
} while (Date.now() < deadline);
|
|
177
|
+
throw Error("HA write not confirmed by fresh readback");
|
|
178
|
+
};
|
|
179
|
+
const pending = this.untilStopped(this.queue.then(run));
|
|
180
|
+
this.queue = pending.catch(() => {});
|
|
181
|
+
return pending;
|
|
182
|
+
}
|
|
183
|
+
scene(option, on) {
|
|
184
|
+
if (on)
|
|
185
|
+
return this.write(this.model.id("select", "charging_scene"), option);
|
|
186
|
+
if (this.shutdown.signal.aborted) return Promise.reject(Error("HA client stopped"));
|
|
187
|
+
return this.untilStopped(this.queue.then(() => {
|
|
188
|
+
this.assertOpen();
|
|
189
|
+
if (this.model.scene() === option)
|
|
190
|
+
throw Error("Select another scene; active scene cannot be disabled");
|
|
191
|
+
}));
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
module.exports = { Client };
|
package/lib/model.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
const SCENES = [
|
|
3
|
+
"AI Smart",
|
|
4
|
+
"Digital Ecosystem",
|
|
5
|
+
"Ultra-fast Single Charging",
|
|
6
|
+
"Balanced Output",
|
|
7
|
+
];
|
|
8
|
+
class Model {
|
|
9
|
+
constructor(c = {}) {
|
|
10
|
+
this.prefix = c.prefix || "cuktech_10_ultra_example_";
|
|
11
|
+
this.staleMs = (c.staleSeconds || 90) * 1000;
|
|
12
|
+
this.threshold = c.inUseWatts ?? 0.1;
|
|
13
|
+
this.states = new Map();
|
|
14
|
+
this.unconfirmed = new Set();
|
|
15
|
+
this.energyEntities = c.energyEntities;
|
|
16
|
+
this.online = false;
|
|
17
|
+
}
|
|
18
|
+
ingest(xs) {
|
|
19
|
+
this.states = new Map(xs.map((x) => [x.entity_id, x]));
|
|
20
|
+
this.online = true;
|
|
21
|
+
this.received = Date.now();
|
|
22
|
+
}
|
|
23
|
+
id(domain, suffix) {
|
|
24
|
+
return `${domain}.${this.prefix}${suffix}`;
|
|
25
|
+
}
|
|
26
|
+
fresh(x) {
|
|
27
|
+
if (
|
|
28
|
+
!this.online ||
|
|
29
|
+
!x ||
|
|
30
|
+
Date.now() - this.received > this.staleMs ||
|
|
31
|
+
["unknown", "unavailable"].includes(x.state) ||
|
|
32
|
+
x.attributes?.connected === false
|
|
33
|
+
)
|
|
34
|
+
return false;
|
|
35
|
+
const ts = Date.parse(x.attributes?.last_update);
|
|
36
|
+
return (
|
|
37
|
+
Number.isFinite(ts) &&
|
|
38
|
+
Date.now() - ts <= this.staleMs &&
|
|
39
|
+
ts <= Date.now() + 5000
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
require(id) {
|
|
43
|
+
if (this.unconfirmed.has(id)) throw Error("Control unconfirmed");
|
|
44
|
+
const x = this.states.get(id);
|
|
45
|
+
if (!this.fresh(x)) throw Error("HA state unavailable or stale");
|
|
46
|
+
return x;
|
|
47
|
+
}
|
|
48
|
+
number(id, unit) {
|
|
49
|
+
const x = this.require(id);
|
|
50
|
+
const n = Number(x.state);
|
|
51
|
+
if (
|
|
52
|
+
typeof x.state !== "string" ||
|
|
53
|
+
x.state.trim() === "" ||
|
|
54
|
+
!Number.isFinite(n) ||
|
|
55
|
+
n < 0 ||
|
|
56
|
+
x.attributes.unit_of_measurement !== unit
|
|
57
|
+
)
|
|
58
|
+
throw Error("Invalid telemetry");
|
|
59
|
+
return n;
|
|
60
|
+
}
|
|
61
|
+
energyEntity(port) {
|
|
62
|
+
const explicit = this.energyEntities?.[port];
|
|
63
|
+
const candidates = explicit
|
|
64
|
+
? [explicit]
|
|
65
|
+
: [
|
|
66
|
+
this.id("sensor", port + "_energy"),
|
|
67
|
+
...(port === "usb_a" ? [this.id("sensor", "a_energy")] : []),
|
|
68
|
+
];
|
|
69
|
+
return candidates.find(
|
|
70
|
+
(id) => this.states.get(id)?.attributes?.unit_of_measurement === "kWh",
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
energy(port) {
|
|
74
|
+
this.require(
|
|
75
|
+
this.id("sensor", port === "total" ? "total_power" : port + "_power"),
|
|
76
|
+
);
|
|
77
|
+
const x = this.states.get(this.energyEntity(port));
|
|
78
|
+
const n = Number(x?.state);
|
|
79
|
+
if (
|
|
80
|
+
!x || typeof x.state !== "string" || x.state.trim() === "" ||
|
|
81
|
+
!Number.isFinite(n) || n < 0
|
|
82
|
+
)
|
|
83
|
+
throw Error("Energy unavailable");
|
|
84
|
+
return n;
|
|
85
|
+
}
|
|
86
|
+
inUse(port) {
|
|
87
|
+
return (
|
|
88
|
+
this.number(this.id("sensor", port + "_power"), "W") > this.threshold
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
bool(id) {
|
|
92
|
+
const x = this.require(id);
|
|
93
|
+
if (!["on", "off"].includes(x.state)) throw Error("Invalid switch state");
|
|
94
|
+
return x.state === "on";
|
|
95
|
+
}
|
|
96
|
+
scene() {
|
|
97
|
+
if (this.unconfirmed.has(this.id("select", "charging_scene")))
|
|
98
|
+
throw Error("Control unconfirmed");
|
|
99
|
+
this.require(this.id("sensor", "total_power"));
|
|
100
|
+
const x = this.states.get(this.id("select", "charging_scene"));
|
|
101
|
+
if (!x || !SCENES.includes(x.state)) throw Error("Unknown charging scene");
|
|
102
|
+
return x.state;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
module.exports = { Model, SCENES };
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "homebridge-cuktech-ha",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "CUKTECH 10 Ultra via existing Home Assistant BLE integration",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"homebridge-plugin"
|
|
9
|
+
],
|
|
10
|
+
"engines": {
|
|
11
|
+
"node": ">=22.12.0",
|
|
12
|
+
"homebridge": ">=1.8.0 <3"
|
|
13
|
+
},
|
|
14
|
+
"scripts": {
|
|
15
|
+
"test": "node --test test/*.test.js",
|
|
16
|
+
"smoke": "node scripts/smoke.js"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"index.js",
|
|
20
|
+
"lib",
|
|
21
|
+
"config.schema.json",
|
|
22
|
+
"README.md",
|
|
23
|
+
"CHANGELOG.md",
|
|
24
|
+
"LICENSE",
|
|
25
|
+
"scripts/smoke.js",
|
|
26
|
+
"docs"
|
|
27
|
+
],
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"homebridge": "2.5.1"
|
|
30
|
+
},
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "git+https://github.com/thanhduy1706/homebridge-cuktech-10-ultra.git"
|
|
34
|
+
},
|
|
35
|
+
"homepage": "https://github.com/thanhduy1706/homebridge-cuktech-10-ultra#readme",
|
|
36
|
+
"bugs": {
|
|
37
|
+
"url": "https://github.com/thanhduy1706/homebridge-cuktech-10-ultra/issues"
|
|
38
|
+
}
|
|
39
|
+
}
|
package/scripts/smoke.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
const { Model } = require("../lib/model");
|
|
3
|
+
const { Client } = require("../lib/client");
|
|
4
|
+
(async () => {
|
|
5
|
+
const config = {
|
|
6
|
+
url: process.env.CUKTECH_HA_URL || "http://127.0.0.1:8123",
|
|
7
|
+
prefix: process.env.CUKTECH_HA_PREFIX || "cuktech_10_ultra_example_",
|
|
8
|
+
tokenFile: process.env.CUKTECH_HA_TOKEN_FILE,
|
|
9
|
+
};
|
|
10
|
+
const model = new Model(config);
|
|
11
|
+
const client = new Client(config, model);
|
|
12
|
+
await client.refresh();
|
|
13
|
+
const ports = {};
|
|
14
|
+
for (const p of ["c1", "c2", "c3", "usb_a"]) {
|
|
15
|
+
ports[p] = {
|
|
16
|
+
output: model.bool(model.id("switch", p + "_output")),
|
|
17
|
+
inUse: model.inUse(p),
|
|
18
|
+
powerW: model.number(model.id("sensor", p + "_power"), "W"),
|
|
19
|
+
voltageV: model.number(model.id("sensor", p + "_voltage"), "V"),
|
|
20
|
+
currentA: model.number(model.id("sensor", p + "_current"), "A"),
|
|
21
|
+
energyEntity: model.energyEntity(p),
|
|
22
|
+
};
|
|
23
|
+
if (model.energyEntity(p)) ports[p].energyKWh = model.energy(p);
|
|
24
|
+
}
|
|
25
|
+
const summary = {
|
|
26
|
+
mode: "read-only",
|
|
27
|
+
physicalServiceCalls: 0,
|
|
28
|
+
ports,
|
|
29
|
+
lowCurrent: model.bool(model.id("switch", "usb_a_low_current")),
|
|
30
|
+
scene: model.scene(),
|
|
31
|
+
totalPowerW: model.number(model.id("sensor", "total_power"), "W"),
|
|
32
|
+
totalEnergyKWh: model.energyEntity("total") ? model.energy("total") : null,
|
|
33
|
+
};
|
|
34
|
+
console.log(JSON.stringify(summary, null, 2));
|
|
35
|
+
})().catch(() => {
|
|
36
|
+
console.error(
|
|
37
|
+
"Read-only HA smoke failed: stale/unavailable/invalid entity or request; secrets redacted",
|
|
38
|
+
);
|
|
39
|
+
process.exitCode = 1;
|
|
40
|
+
});
|