kubegate 0.1.0__tar.gz

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.
kubegate-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Frane Bandov
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
kubegate-0.1.0/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ kubegate
2
+ Copyright 2026 Frane Bandov
3
+
4
+ Licensed under the Apache License, Version 2.0.
5
+ Not affiliated with Key Automation or any brand (AVO, Easy, Levada).
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: kubegate
3
+ Version: 0.1.0
4
+ Summary: Control Key Automation KUBE gate modules (AVO, Easy, Key Automation, Levada) over BLE and cloud.
5
+ Author-email: Frane Bandov <frane.bandov@gmail.com>
6
+ License: Apache-2.0
7
+ Keywords: kube,avo,easy,levada,key automation,gate,ble,home assistant
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Requires-Dist: bleak>=0.21
13
+ Requires-Dist: cryptography>=41
14
+ Provides-Extra: cloud
15
+ Requires-Dist: aiohttp>=3.9; extra == "cloud"
16
+ Provides-Extra: cli
17
+ Dynamic: license-file
18
+
19
+ # kubegate — control your KUBE gate from Python / Home Assistant
20
+
21
+ Local **BLE** and (soon) cloud control for gate automations built on the
22
+ **Key Automation KUBE** WiFi/BLE module — sold under several brands:
23
+
24
+ > **AVO · Easy · Key Automation · Levada**
25
+
26
+ Many owners don't realise their "AVO" or "Levada" gate app is the same KUBE
27
+ platform underneath. If your gate uses one of these apps, this library talks to it.
28
+
29
+ This repo hosts the reusable protocol library (`kubegate`). The Home Assistant
30
+ integration lives in [`ha-kube`](../ha-kube) and builds on it.
31
+
32
+ ## Status
33
+ - ✅ **Local BLE**: handshake, encrypted commands (open / close / pedestrian / light), live status — reverse-engineered and verified against real devices.
34
+ - 🚧 **Cloud (remote)**: crypto and command format solved; the RTDB relay path is being finalised.
35
+ - 🚧 **Account discovery**: log in with your brand account to auto-import gates, passkeys and keys.
36
+
37
+ ## Install
38
+ ```bash
39
+ pip install -e .
40
+ ```
41
+
42
+ ## Quick start (BLE)
43
+ ```bash
44
+ python -m kubegate.cli scan
45
+ python -m kubegate.cli status --addr <ADDR> --passkey 0000000000012345
46
+ python -m kubegate.cli open --addr <ADDR> --passkey 0000000000012345
47
+ ```
48
+
49
+ ```python
50
+ import asyncio
51
+ from kubegate.ble import KubeBleDevice
52
+
53
+ async def main():
54
+ async with KubeBleDevice("<ADDR>", "0000000000012345") as gate:
55
+ await gate.action("open")
56
+ print(gate.status)
57
+
58
+ asyncio.run(main())
59
+ ```
60
+
61
+ ## Protocol (short)
62
+ ```
63
+ enckey1 = AES128_ECB(passkey, serial) # constant per device
64
+ enckey2 = AES128_ECB(passkey, nonce XOR enckey1) # per-connection XOR pad
65
+ token = (nonce XOR enckey1) XOR enckey2 # auth, written to f1170005
66
+ frames: @LLLL<body># , body = name or name={json}; whole frame XOR enckey2
67
+ action: cact={"cmd":"C30B","val":N} (N: 8 open · 4 close · 128 pedestrian · 256 light)
68
+ ```
69
+
70
+ The `passkey` is a 16-digit, zero-padded number from your account/installation.
71
+
72
+ ## License
73
+ Apache-2.0. Not affiliated with Key Automation or any brand listed above.
@@ -0,0 +1,55 @@
1
+ # kubegate — control your KUBE gate from Python / Home Assistant
2
+
3
+ Local **BLE** and (soon) cloud control for gate automations built on the
4
+ **Key Automation KUBE** WiFi/BLE module — sold under several brands:
5
+
6
+ > **AVO · Easy · Key Automation · Levada**
7
+
8
+ Many owners don't realise their "AVO" or "Levada" gate app is the same KUBE
9
+ platform underneath. If your gate uses one of these apps, this library talks to it.
10
+
11
+ This repo hosts the reusable protocol library (`kubegate`). The Home Assistant
12
+ integration lives in [`ha-kube`](../ha-kube) and builds on it.
13
+
14
+ ## Status
15
+ - ✅ **Local BLE**: handshake, encrypted commands (open / close / pedestrian / light), live status — reverse-engineered and verified against real devices.
16
+ - 🚧 **Cloud (remote)**: crypto and command format solved; the RTDB relay path is being finalised.
17
+ - 🚧 **Account discovery**: log in with your brand account to auto-import gates, passkeys and keys.
18
+
19
+ ## Install
20
+ ```bash
21
+ pip install -e .
22
+ ```
23
+
24
+ ## Quick start (BLE)
25
+ ```bash
26
+ python -m kubegate.cli scan
27
+ python -m kubegate.cli status --addr <ADDR> --passkey 0000000000012345
28
+ python -m kubegate.cli open --addr <ADDR> --passkey 0000000000012345
29
+ ```
30
+
31
+ ```python
32
+ import asyncio
33
+ from kubegate.ble import KubeBleDevice
34
+
35
+ async def main():
36
+ async with KubeBleDevice("<ADDR>", "0000000000012345") as gate:
37
+ await gate.action("open")
38
+ print(gate.status)
39
+
40
+ asyncio.run(main())
41
+ ```
42
+
43
+ ## Protocol (short)
44
+ ```
45
+ enckey1 = AES128_ECB(passkey, serial) # constant per device
46
+ enckey2 = AES128_ECB(passkey, nonce XOR enckey1) # per-connection XOR pad
47
+ token = (nonce XOR enckey1) XOR enckey2 # auth, written to f1170005
48
+ frames: @LLLL<body># , body = name or name={json}; whole frame XOR enckey2
49
+ action: cact={"cmd":"C30B","val":N} (N: 8 open · 4 close · 128 pedestrian · 256 light)
50
+ ```
51
+
52
+ The `passkey` is a 16-digit, zero-padded number from your account/installation.
53
+
54
+ ## License
55
+ Apache-2.0. Not affiliated with Key Automation or any brand listed above.
@@ -0,0 +1,20 @@
1
+ """kubegate — control Key Automation KUBE gate modules (AVO, Easy, Key Automation, Levada).
2
+
3
+ Local BLE control is fully supported. Cloud (remote) control and account-based
4
+ discovery are provided by the `cloud` module.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from .const import ACTIONS
9
+ from .crypto import SessionKeys, encrypt_data, xor
10
+ from .protocol import action_frame, build_frame, info_frame, init_frame, iter_frames
11
+ from .vendors import VENDORS, DEFAULT_VENDOR, Vendor, get_vendor
12
+
13
+ __all__ = [
14
+ "ACTIONS",
15
+ "SessionKeys", "encrypt_data", "xor",
16
+ "action_frame", "build_frame", "info_frame", "init_frame", "iter_frames",
17
+ "VENDORS", "DEFAULT_VENDOR", "Vendor", "get_vendor",
18
+ ]
19
+
20
+ __version__ = "0.1.0"
@@ -0,0 +1,115 @@
1
+ """Local BLE transport for a KUBE gate (bleak)."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import logging
6
+ from typing import Callable
7
+
8
+ from bleak import BleakClient, BleakScanner
9
+ from bleak.backends.device import BLEDevice
10
+
11
+ from . import const
12
+ from .crypto import SessionKeys
13
+ from .protocol import action_frame, info_frame, init_frame, iter_frames
14
+
15
+ _LOGGER = logging.getLogger(__name__)
16
+ _NAME_HINTS = ("KUBE", "AVO", "LEVADA", "EASY")
17
+
18
+
19
+ async def discover(timeout: float = 8.0) -> list[BLEDevice]:
20
+ """Return BLE devices that look like a KUBE gate module."""
21
+ found: list[BLEDevice] = []
22
+ devices = await BleakScanner.discover(timeout=timeout, return_adv=True)
23
+ for dev, adv in devices.values():
24
+ uuids = [u.lower() for u in (adv.service_uuids or [])]
25
+ name = (dev.name or "").upper()
26
+ if any(const.UUID_SUFFIX in u for u in uuids) or any(h in name for h in _NAME_HINTS):
27
+ found.append(dev)
28
+ return found
29
+
30
+
31
+ class KubeBleDevice:
32
+ """Connect to a KUBE gate over BLE and send encrypted commands."""
33
+
34
+ def __init__(self, address: str, passkey: str) -> None:
35
+ self.address = address
36
+ self.passkey = passkey
37
+ self._client: BleakClient | None = None
38
+ self._keys: SessionKeys | None = None
39
+ self._rx = bytearray()
40
+ self._status: dict[str, dict] = {}
41
+ self._listeners: list[Callable[[str, dict], None]] = []
42
+
43
+ # ---- lifecycle ----
44
+ async def connect(self) -> None:
45
+ self._client = BleakClient(self.address)
46
+ await self._client.connect()
47
+ await self._handshake()
48
+
49
+ async def disconnect(self) -> None:
50
+ if self._client and self._client.is_connected:
51
+ try:
52
+ await self._client.stop_notify(const.CHAR_STATUS)
53
+ except Exception: # noqa: BLE001
54
+ pass
55
+ await self._client.disconnect()
56
+ self._client = None
57
+ self._keys = None
58
+
59
+ async def _handshake(self) -> None:
60
+ cli = self._client
61
+ assert cli is not None
62
+ serial_raw = await cli.read_gatt_char(const.CHAR_SERIAL)
63
+ serial = serial_raw.decode("latin1")
64
+ nonce = bytes(await cli.read_gatt_char(const.CHAR_NONCE))
65
+ self._keys = SessionKeys(self.passkey, serial, nonce)
66
+ await cli.write_gatt_char(const.CHAR_TOKEN, self._keys.token, response=False)
67
+ await cli.start_notify(const.CHAR_STATUS, self._on_notify)
68
+ # init + info (mirrors the app's startup)
69
+ await self._write(init_frame())
70
+ await asyncio.sleep(0.3)
71
+ await self._write(info_frame())
72
+ await asyncio.sleep(0.4)
73
+
74
+ # ---- io ----
75
+ async def _write(self, frame: bytes) -> None:
76
+ assert self._client and self._keys
77
+ await self._client.write_gatt_char(
78
+ const.CHAR_COMMAND, self._keys.encrypt(frame), response=False
79
+ )
80
+
81
+ def _on_notify(self, _handle, data: bytearray) -> None:
82
+ assert self._keys
83
+ self._rx.extend(self._keys.decrypt(bytes(data)))
84
+ frames, self._rx[:] = iter_frames(bytes(self._rx))
85
+ for name, payload in frames:
86
+ if isinstance(payload, dict):
87
+ self._status[name] = payload
88
+ for cb in self._listeners:
89
+ cb(name, payload if isinstance(payload, dict) else {})
90
+
91
+ # ---- public api ----
92
+ def add_listener(self, cb: Callable[[str, dict], None]) -> None:
93
+ self._listeners.append(cb)
94
+
95
+ async def action(self, name: str) -> None:
96
+ """Send a gate action: open / close / pedestrian / light."""
97
+ if name not in const.ACTIONS:
98
+ raise ValueError(f"unknown action {name!r}; use {list(const.ACTIONS)}")
99
+ await self._write(action_frame(const.ACTIONS[name]))
100
+
101
+ async def refresh(self) -> dict[str, dict]:
102
+ await self._write(info_frame())
103
+ await asyncio.sleep(0.5)
104
+ return dict(self._status)
105
+
106
+ @property
107
+ def status(self) -> dict[str, dict]:
108
+ return dict(self._status)
109
+
110
+ async def __aenter__(self) -> "KubeBleDevice":
111
+ await self.connect()
112
+ return self
113
+
114
+ async def __aexit__(self, *exc) -> None:
115
+ await self.disconnect()
@@ -0,0 +1,45 @@
1
+ """Tiny CLI: scan, status, and send gate actions over BLE.
2
+
3
+ python -m kubegate.cli scan
4
+ python -m kubegate.cli status --addr <ADDR> --passkey 0000000000012345
5
+ python -m kubegate.cli open --addr <ADDR> --passkey 0000000000012345
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import asyncio
11
+
12
+ from .ble import KubeBleDevice, discover
13
+ from .const import ACTIONS
14
+
15
+
16
+ async def _run(args) -> None:
17
+ if args.cmd == "scan":
18
+ for d in await discover():
19
+ print(f"{d.address} {d.name}")
20
+ return
21
+
22
+ dev = KubeBleDevice(args.addr, args.passkey)
23
+ async with dev:
24
+ if args.cmd == "status":
25
+ print(await dev.refresh())
26
+ else: # open/close/pedestrian/light
27
+ await dev.action(args.cmd)
28
+ print(f"sent: {args.cmd}")
29
+ await asyncio.sleep(1.5)
30
+ print(dev.status.get("cinf", {}))
31
+
32
+
33
+ def main() -> None:
34
+ p = argparse.ArgumentParser(prog="kubegate")
35
+ p.add_argument("cmd", choices=["scan", "status", *ACTIONS])
36
+ p.add_argument("--addr")
37
+ p.add_argument("--passkey")
38
+ args = p.parse_args()
39
+ if args.cmd != "scan" and (not args.addr or not args.passkey):
40
+ p.error("--addr and --passkey are required for this command")
41
+ asyncio.run(_run(args))
42
+
43
+
44
+ if __name__ == "__main__":
45
+ main()
@@ -0,0 +1,226 @@
1
+ """Cloud transport + account discovery for KUBE gates.
2
+
3
+ Covers:
4
+ * Firebase auth — email/password fully headless; Google/Apple via a refresh
5
+ token obtained once through the brand's web login (the token is then used
6
+ headlessly, no browser needed afterwards).
7
+ * Firestore discovery — read the user's installations and auto-import every
8
+ gate (passkey, serial, MAC, vendor) plus the RSA installation keypair.
9
+ * Cloud command envelope — RSA-encrypt the same frames used over BLE and
10
+ sign them with the installation private key.
11
+
12
+ Network uses aiohttp so it drops straight into Home Assistant.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import base64
17
+ import time
18
+ from dataclasses import dataclass, field
19
+
20
+ import aiohttp
21
+ from cryptography.hazmat.primitives import hashes
22
+ from cryptography.hazmat.primitives.asymmetric import padding, rsa
23
+ from cryptography.hazmat.primitives.asymmetric.utils import Prehashed
24
+
25
+ from .vendors import Vendor, get_vendor
26
+
27
+ IDENTITY = "https://identitytoolkit.googleapis.com/v1"
28
+ SECURETOKEN = "https://securetoken.googleapis.com/v1"
29
+ FIRESTORE = "https://firestore.googleapis.com/v1"
30
+
31
+
32
+ # --------------------------------------------------------------------------- #
33
+ # auth
34
+ # --------------------------------------------------------------------------- #
35
+ @dataclass
36
+ class Credentials:
37
+ id_token: str
38
+ refresh_token: str
39
+ uid: str
40
+ expires_at: float = 0.0
41
+
42
+ @property
43
+ def expired(self) -> bool:
44
+ return time.time() >= self.expires_at - 60
45
+
46
+
47
+ class FirebaseAuth:
48
+ def __init__(self, vendor: Vendor, session: aiohttp.ClientSession) -> None:
49
+ self.vendor = vendor
50
+ self._s = session
51
+ self.creds: Credentials | None = None
52
+
53
+ async def sign_in_password(self, email: str, password: str) -> Credentials:
54
+ url = f"{IDENTITY}/accounts:signInWithPassword?key={self.vendor.api_key}"
55
+ async with self._s.post(url, json={
56
+ "email": email, "password": password, "returnSecureToken": True,
57
+ }) as r:
58
+ data = await r.json()
59
+ if "idToken" not in data:
60
+ raise AuthError(data.get("error", {}).get("message", "login failed"))
61
+ self.creds = Credentials(
62
+ id_token=data["idToken"], refresh_token=data["refreshToken"],
63
+ uid=data["localId"], expires_at=time.time() + int(data["expiresIn"]),
64
+ )
65
+ return self.creds
66
+
67
+ async def from_refresh_token(self, refresh_token: str) -> Credentials:
68
+ """Use a refresh token captured from a Google/Apple web login."""
69
+ url = f"{SECURETOKEN}/token?key={self.vendor.api_key}"
70
+ async with self._s.post(url, data={
71
+ "grant_type": "refresh_token", "refresh_token": refresh_token,
72
+ }) as r:
73
+ data = await r.json()
74
+ if "id_token" not in data:
75
+ raise AuthError(data.get("error", {}).get("message", "refresh failed"))
76
+ self.creds = Credentials(
77
+ id_token=data["id_token"], refresh_token=data["refresh_token"],
78
+ uid=data["user_id"], expires_at=time.time() + int(data["expires_in"]),
79
+ )
80
+ return self.creds
81
+
82
+ async def valid_token(self) -> str:
83
+ if not self.creds:
84
+ raise AuthError("not authenticated")
85
+ if self.creds.expired:
86
+ await self.from_refresh_token(self.creds.refresh_token)
87
+ return self.creds.id_token
88
+
89
+
90
+ class AuthError(Exception):
91
+ pass
92
+
93
+
94
+ # --------------------------------------------------------------------------- #
95
+ # firestore helpers (REST value decoding)
96
+ # --------------------------------------------------------------------------- #
97
+ def _decode(v: dict):
98
+ if "stringValue" in v: return v["stringValue"]
99
+ if "integerValue" in v: return int(v["integerValue"])
100
+ if "booleanValue" in v: return v["booleanValue"]
101
+ if "doubleValue" in v: return v["doubleValue"]
102
+ if "nullValue" in v: return None
103
+ if "geoPointValue" in v: return (v["geoPointValue"].get("latitude"), v["geoPointValue"].get("longitude"))
104
+ if "timestampValue" in v: return v["timestampValue"]
105
+ if "mapValue" in v: return {k: _decode(x) for k, x in v["mapValue"].get("fields", {}).items()}
106
+ if "arrayValue" in v: return [_decode(x) for x in v["arrayValue"].get("values", [])]
107
+ return v
108
+
109
+
110
+ def _fields(doc: dict) -> dict:
111
+ return {k: _decode(v) for k, v in doc.get("fields", {}).items()}
112
+
113
+
114
+ # --------------------------------------------------------------------------- #
115
+ # discovery
116
+ # --------------------------------------------------------------------------- #
117
+ @dataclass
118
+ class KubeGate:
119
+ vendor_key: str
120
+ installation_id: str
121
+ name: str
122
+ serial: str = "" # central serial (cFFFC)
123
+ mac: str = "" # BLE/wifi MAC
124
+ passkey: str = "" # 16-digit BLE passkey
125
+ key_p: str = "" # RSA prime p (base36) — cloud
126
+ key_q: str = "" # RSA prime q (base36) — cloud
127
+ raw: dict = field(default_factory=dict) # full installation doc (for relay-node discovery)
128
+
129
+
130
+ class KubeCloud:
131
+ def __init__(self, vendor_key: str, session: aiohttp.ClientSession) -> None:
132
+ self.vendor = get_vendor(vendor_key)
133
+ self._s = session
134
+ self.auth = FirebaseAuth(self.vendor, session)
135
+
136
+ def _db(self) -> str:
137
+ return f"{FIRESTORE}/projects/{self.vendor.project_id}/databases/(default)/documents"
138
+
139
+ async def _get(self, path: str) -> dict:
140
+ token = await self.auth.valid_token()
141
+ async with self._s.get(f"{self._db()}/{path}",
142
+ headers={"Authorization": f"Bearer {token}"}) as r:
143
+ return await r.json()
144
+
145
+ async def _query(self, collection: str, field_path: str, value: str) -> list[dict]:
146
+ token = await self.auth.valid_token()
147
+ body = {"structuredQuery": {
148
+ "from": [{"collectionId": collection}],
149
+ "where": {"fieldFilter": {
150
+ "field": {"fieldPath": field_path}, "op": "EQUAL",
151
+ "value": {"stringValue": value}}}}}
152
+ async with self._s.post(f"{self._db()}:runQuery", json=body,
153
+ headers={"Authorization": f"Bearer {token}"}) as r:
154
+ return [row["document"] for row in await r.json() if "document" in row]
155
+
156
+ async def rsa_keys(self) -> tuple[str, str]:
157
+ """Return (keyP, keyQ) from the user's doc."""
158
+ uid = self.auth.creds.uid # type: ignore[union-attr]
159
+ doc = await self._get(f"users/{uid}")
160
+ keys = _fields(doc).get("keys", {})
161
+ return keys.get("keyP", ""), keys.get("keyQ", "")
162
+
163
+ async def discover(self, email: str) -> list[KubeGate]:
164
+ """Auto-import all gates owned by this account."""
165
+ key_p, key_q = await self.rsa_keys()
166
+ gates: list[KubeGate] = []
167
+ docs = []
168
+ for fieldpath in ("clientOwner.email", "proData.ownerEmail"):
169
+ docs += await self._query("installations", fieldpath, email)
170
+ seen = set()
171
+ for doc in docs:
172
+ iid = doc["name"].rsplit("/", 1)[-1]
173
+ if iid in seen:
174
+ continue
175
+ seen.add(iid)
176
+ f = _fields(doc)
177
+ info = f.get("info", {})
178
+ cig = f.get("cig", {})
179
+ central = cig.get("central", {}) if isinstance(cig, dict) else {}
180
+ gates.append(KubeGate(
181
+ vendor_key=self.vendor.key,
182
+ installation_id=iid,
183
+ name=info.get("name") or f.get("proData", {}).get("instName", iid),
184
+ serial=str(central.get("sn", "")),
185
+ mac=str(central.get("mac", "") or f.get("androidMac", "")),
186
+ passkey=str(f.get("passkey", "") or central.get("passkey", "")),
187
+ key_p=key_p, key_q=key_q,
188
+ raw=f,
189
+ ))
190
+ return gates
191
+
192
+
193
+ # --------------------------------------------------------------------------- #
194
+ # cloud command envelope (RSA)
195
+ # --------------------------------------------------------------------------- #
196
+ def _rsa_from_pq(key_p: str, key_q: str) -> rsa.RSAPrivateKey:
197
+ p = int(key_p, 36); q = int(key_q, 36)
198
+ n = p * q; e = 65537
199
+ d = pow(e, -1, (p - 1) * (q - 1))
200
+ dmp1 = d % (p - 1); dmq1 = d % (q - 1); iqmp = pow(q, -1, p)
201
+ pub = rsa.RSAPublicNumbers(e, n)
202
+ return rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp, pub).private_key()
203
+
204
+
205
+ def build_envelope(frame: bytes, email: str, key_p: str, key_q: str,
206
+ tms: int | None = None) -> dict:
207
+ """Build the signed cloud command envelope for a KUBE frame.
208
+
209
+ NOTE: msg is RSA-PKCS1v1.5-encrypted with the installation public key and
210
+ `sign` is an RSA signature over mail+msg+tms. The signature digest is still
211
+ to be confirmed against a captured sample (SHA-256 assumed).
212
+ """
213
+ priv = _rsa_from_pq(key_p, key_q)
214
+ pub = priv.public_key()
215
+ msg_b64 = base64.b64encode(
216
+ pub.encrypt(frame, padding.PKCS1v15())
217
+ ).decode()
218
+ tms = tms or int(time.time())
219
+ signed = f"{email}{msg_b64}{tms}".encode()
220
+ sig = priv.sign(signed, padding.PKCS1v15(), hashes.SHA256())
221
+ return {
222
+ "mail": email,
223
+ "msg": msg_b64,
224
+ "tms": tms,
225
+ "sign": base64.b64encode(sig).decode(),
226
+ }
@@ -0,0 +1,36 @@
1
+ """Constants for the KUBE gate protocol (Key Automation KUBE module)."""
2
+ from __future__ import annotations
3
+
4
+ # GATT service / characteristics (UUID suffix is shared by the whole service)
5
+ UUID_SUFFIX = "-0190-4567-8fab-4d4158a4eeaf"
6
+
7
+
8
+ def _c(short: str) -> str:
9
+ return f"{short}{UUID_SUFFIX}"
10
+
11
+
12
+ CHAR_STATUS = _c("f1110021") # read + notify: encrypted status frames
13
+ CHAR_COMMAND = _c("f1110022") # write-without-response: encrypted command frames
14
+ CHAR_MODEL = _c("f1110023") # read: model string, e.g. "KUBEWF"
15
+ CHAR_NONCE = _c("f1170002") # read: per-connection 16-byte nonce
16
+ CHAR_SERIAL = _c("f1170003") # read: serial/mac ascii, e.g. "0000AABBCCDDEEFF"
17
+ CHAR_TOKEN = _c("f1170005") # write: auth token (handshake)
18
+
19
+ # Gate action values (central command "C30B"). Match the app's "com" capability bitmask.
20
+ CMD_OPEN = 8 # OPEN_CLOSE_TOGGLE (opens from closed)
21
+ CMD_CLOSE = 4
22
+ CMD_PEDESTRIAN = 128
23
+ CMD_LIGHT = 256
24
+
25
+ ACTIONS = {
26
+ "open": CMD_OPEN,
27
+ "close": CMD_CLOSE,
28
+ "pedestrian": CMD_PEDESTRIAN,
29
+ "light": CMD_LIGHT,
30
+ }
31
+
32
+ CENTRAL_CMD = "C30B" # action opcode used in {"cmd": CENTRAL_CMD, "val": N}
33
+
34
+ # Frame delimiters
35
+ FRAME_START = b"@"
36
+ FRAME_END = b"#"
@@ -0,0 +1,60 @@
1
+ """KUBE BLE crypto — session key derivation and frame XOR.
2
+
3
+ Reverse-engineered and verified against live device captures. The scheme:
4
+
5
+ enckey1 = AES_ECB(passkey, serial) # constant per device
6
+ enckey2 = AES_ECB(passkey, nonce XOR enckey1) # the XOR pad for this session
7
+ token = (nonce XOR enckey1) XOR enckey2 # written to the auth characteristic
8
+
9
+ All AES is AES-128/ECB. `encrypt_data` mirrors the app's padding exactly:
10
+ printable (UTF-8) inputs are zero-*prefixed* (zfill) to 16 chars; binary inputs
11
+ are right-justified with b"0" to 16 bytes. Inputs longer than 16 are truncated.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
16
+ from cryptography.hazmat.backends import default_backend
17
+
18
+
19
+ def _pad16(buf: bytes) -> bytes:
20
+ """Match the app's CipherHelper.encryptData padding."""
21
+ try:
22
+ s = buf.decode("utf-8")
23
+ except UnicodeDecodeError:
24
+ return buf[:16] if len(buf) > 16 else buf.rjust(16, b"0")
25
+ s = s[:16] if len(s) > 16 else s.zfill(16)
26
+ return s.encode("utf-8")
27
+
28
+
29
+ def encrypt_data(key: bytes, data: bytes) -> bytes:
30
+ """AES-128/ECB single block, with the app's 16-byte padding on both inputs."""
31
+ k = _pad16(key)
32
+ d = _pad16(data)
33
+ cipher = Cipher(algorithms.AES(k), modes.ECB(), backend=default_backend())
34
+ enc = cipher.encryptor()
35
+ return enc.update(d) + enc.finalize()
36
+
37
+
38
+ def xor(data: bytes, pad: bytes) -> bytes:
39
+ """Repeating-key XOR (pad repeats every len(pad) bytes)."""
40
+ n = len(pad)
41
+ return bytes(data[i] ^ pad[i % n] for i in range(len(data)))
42
+
43
+
44
+ class SessionKeys:
45
+ """Derived keys for one BLE connection."""
46
+
47
+ __slots__ = ("enckey1", "enckey2", "token")
48
+
49
+ def __init__(self, passkey: str, serial: str, nonce: bytes) -> None:
50
+ pk = passkey.encode("utf-8")
51
+ self.enckey1 = encrypt_data(pk, serial.encode("utf-8"))
52
+ x = xor(nonce, self.enckey1)
53
+ self.enckey2 = encrypt_data(pk, x) # the XOR pad
54
+ self.token = xor(x, self.enckey2) # auth token for CHAR_TOKEN
55
+
56
+ def encrypt(self, frame: bytes) -> bytes:
57
+ return xor(frame, self.enckey2)
58
+
59
+ def decrypt(self, data: bytes) -> bytes:
60
+ return xor(data, self.enckey2)
@@ -0,0 +1,59 @@
1
+ """KUBE application-layer frames.
2
+
3
+ Frame wire format (before XOR): @LLLL<body>#
4
+ LLLL = uppercase hex length of <body> (4 chars)
5
+ body = <name> or <name>={json}
6
+
7
+ The same frames are used over BLE (XOR-encrypted) and over the cloud relay
8
+ (RSA-encrypted), so this module is transport-agnostic.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import re
14
+ from typing import Any
15
+
16
+ from .const import CENTRAL_CMD
17
+
18
+ _FRAME_RE = re.compile(rb"@([0-9A-Fa-f]{4})(.*?)#", re.S)
19
+
20
+
21
+ def build_frame(body: str) -> bytes:
22
+ b = body.encode("utf-8")
23
+ return b"@" + f"{len(b):04X}".encode("ascii") + b + b"#"
24
+
25
+
26
+ def action_frame(val: int) -> bytes:
27
+ """Gate action frame, e.g. open/close/pedestrian/light (val from const.ACTIONS)."""
28
+ body = "cact=" + json.dumps({"cmd": CENTRAL_CMD, "val": val}, separators=(",", ":"))
29
+ return build_frame(body)
30
+
31
+
32
+ def info_frame() -> bytes:
33
+ return build_frame("cinf")
34
+
35
+
36
+ def init_frame() -> bytes:
37
+ return build_frame("kbinf")
38
+
39
+
40
+ def iter_frames(buffer: bytes):
41
+ """Yield (name, payload) for each complete frame in buffer; returns leftover.
42
+
43
+ payload is a parsed dict when the body is `name={json}`, else None.
44
+ Use the returned leftover as the prefix for the next chunk.
45
+ """
46
+ out = []
47
+ pos = 0
48
+ for m in _FRAME_RE.finditer(buffer):
49
+ pos = m.end()
50
+ body = m.group(2)
51
+ name, _, rest = body.partition(b"=")
52
+ payload: Any = None
53
+ if rest:
54
+ try:
55
+ payload = json.loads(rest.decode("utf-8", "ignore"))
56
+ except (ValueError, UnicodeDecodeError):
57
+ payload = rest.decode("utf-8", "ignore")
58
+ out.append((name.decode("ascii", "ignore"), payload))
59
+ return out, buffer[pos:]
@@ -0,0 +1,76 @@
1
+ """Gate state decoding (the `cstate`/`rstate` field in the `cinf` status frame).
2
+
3
+ Code table adapted from the KUBE central firmware (also surfaced by the
4
+ community HA integration). Treat the open/closed grouping as the mapping to
5
+ verify per firmware: capture `cinf.cstate` on your gate when it is physically
6
+ open vs closed and adjust `is_open` / `is_closed` if needed.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ CSTATE_LABELS: dict[int, str] = {
11
+ 0: "Door stopped",
12
+ 1: "Opening",
13
+ 2: "Open",
14
+ 3: "Waiting reclosing timeout",
15
+ 4: "Partial opening",
16
+ 5: "Partial open reached",
17
+ 6: "Waiting for partial reclosing",
18
+ 7: "Closing",
19
+ 8: "Closed",
20
+ 9: "Partial closing",
21
+ 10: "Photocell 1 activated while closing, reopening",
22
+ 11: "Photocell 2 activated, movement stopped",
23
+ 12: "Executed stop while opening",
24
+ 13: "Executed stop while closing",
25
+ 17: "Leaf 1 impact with obstacle",
26
+ 24: "Leaf 1 opening",
27
+ 25: "Leaf 1 stop in opening",
28
+ 26: "Leaf 2 opening",
29
+ 27: "Leaf 1 and 2 stop in opening",
30
+ 28: "Leaf 2 stop in opening",
31
+ 29: "Leaf 1 closing",
32
+ 30: "Leaf 2 closing",
33
+ 31: "Leaf 2 stop in closing",
34
+ 32: "Limit switch error: is leaf half open?",
35
+ 34: "Error learning, procedure stopped",
36
+ 40: "Aeration opening",
37
+ 42: "Waiting for aeration reclosing",
38
+ }
39
+
40
+ _OPENING = {1, 4, 24, 26, 40}
41
+ _CLOSING = {7, 9, 29, 30}
42
+ _OPEN = {2, 5}
43
+ _CLOSED = {8}
44
+
45
+
46
+ def label(cstate: int) -> str:
47
+ return CSTATE_LABELS.get(cstate, f"Unknown ({cstate})")
48
+
49
+
50
+ def is_opening(cstate: int) -> bool:
51
+ return cstate in _OPENING
52
+
53
+
54
+ def is_closing(cstate: int) -> bool:
55
+ return cstate in _CLOSING
56
+
57
+
58
+ def is_open(cstate: int) -> bool:
59
+ return cstate in _OPEN
60
+
61
+
62
+ def is_closed(cstate: int) -> bool:
63
+ return cstate in _CLOSED
64
+
65
+
66
+ def ha_cover_state(cstate: int) -> str:
67
+ """Map to a Home Assistant cover state string."""
68
+ if is_opening(cstate):
69
+ return "opening"
70
+ if is_closing(cstate):
71
+ return "closing"
72
+ if is_open(cstate):
73
+ return "open"
74
+ if is_closed(cstate):
75
+ return "closed"
76
+ return "open" # safest default for a gate in an indeterminate/stopped state
@@ -0,0 +1,72 @@
1
+ """KUBE vendor registry.
2
+
3
+ The same Key Automation "KUBE" gate module is sold under several brands, each
4
+ with its own Firebase backend. Most users only know their brand name (AVO,
5
+ Easy, Levada, ...) and not that it is a KUBE device underneath.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class Vendor:
14
+ key: str # internal flavor id
15
+ name: str # user-facing brand name
16
+ project_id: str # Firebase project id
17
+ api_key: str # Firebase Web API key (public, shipped in the app)
18
+ rtdb_url: str # Realtime Database URL (ESP command relay)
19
+ cf_command_ack: str # cloud function: command acknowledgement
20
+ cf_users_public_keys: str
21
+ cf_update_params_wifi: str
22
+
23
+ @property
24
+ def auth_domain(self) -> str:
25
+ return f"{self.project_id}.firebaseapp.com"
26
+
27
+
28
+ VENDORS: dict[str, Vendor] = {
29
+ "avo": Vendor(
30
+ key="avo", name="AVO",
31
+ project_id="kube-avo-8af76",
32
+ api_key="AIzaSyBxL23ZBOyPEQjm57R0jd9k497PKy0v7QA",
33
+ rtdb_url="https://kube-avo-8af76-default-rtdb.europe-west1.firebasedatabase.app/",
34
+ cf_command_ack="https://commandack-bwyaa2lafq-ew.a.run.app",
35
+ cf_users_public_keys="https://getuserspublickeys-bwyaa2lafq-ew.a.run.app",
36
+ cf_update_params_wifi="https://updateparamswifi-bwyaa2lafq-ew.a.run.app",
37
+ ),
38
+ "easy": Vendor(
39
+ key="easy", name="Easy",
40
+ project_id="kube-easy",
41
+ api_key="AIzaSyCuTwB438roZ0pR94i3qKbZZqDOqhwxszg",
42
+ rtdb_url="https://kube-easy-default-rtdb.europe-west1.firebasedatabase.app/",
43
+ cf_command_ack="https://commandack-66nl7dppiq-ew.a.run.app",
44
+ cf_users_public_keys="https://getuserspublickeys-66nl7dppiq-ew.a.run.app",
45
+ cf_update_params_wifi="https://updateparamswifi-66nl7dppiq-ew.a.run.app",
46
+ ),
47
+ "key": Vendor(
48
+ key="key", name="Key Automation",
49
+ project_id="kube-key",
50
+ api_key="AIzaSyCVTeI0HLRmCoo99vWRzNng4UDwsE_z11g",
51
+ rtdb_url="https://kube-key-default-rtdb.europe-west1.firebasedatabase.app/",
52
+ cf_command_ack="https://commandack-gnsdtkydiq-ew.a.run.app",
53
+ cf_users_public_keys="https://getuserspublickeys-gnsdtkydiq-ew.a.run.app",
54
+ cf_update_params_wifi="https://updateparamswifi-gnsdtkydiq-ew.a.run.app",
55
+ ),
56
+ # Levada ships with an empty RTDB/CF config in the app build we have; its
57
+ # API key is included so login/discovery can still be attempted. Cloud
58
+ # relay may be inactive for this brand.
59
+ "levada": Vendor(
60
+ key="levada", name="Levada",
61
+ project_id="kube-levada",
62
+ api_key="AIzaSyDu1Ww1d_5qAlCoEKXRGI9iuz8CsEyhewQ",
63
+ rtdb_url="",
64
+ cf_command_ack="", cf_users_public_keys="", cf_update_params_wifi="",
65
+ ),
66
+ }
67
+
68
+ DEFAULT_VENDOR = "avo"
69
+
70
+
71
+ def get_vendor(key: str) -> Vendor:
72
+ return VENDORS[key.lower()]
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: kubegate
3
+ Version: 0.1.0
4
+ Summary: Control Key Automation KUBE gate modules (AVO, Easy, Key Automation, Levada) over BLE and cloud.
5
+ Author-email: Frane Bandov <frane.bandov@gmail.com>
6
+ License: Apache-2.0
7
+ Keywords: kube,avo,easy,levada,key automation,gate,ble,home assistant
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Requires-Dist: bleak>=0.21
13
+ Requires-Dist: cryptography>=41
14
+ Provides-Extra: cloud
15
+ Requires-Dist: aiohttp>=3.9; extra == "cloud"
16
+ Provides-Extra: cli
17
+ Dynamic: license-file
18
+
19
+ # kubegate — control your KUBE gate from Python / Home Assistant
20
+
21
+ Local **BLE** and (soon) cloud control for gate automations built on the
22
+ **Key Automation KUBE** WiFi/BLE module — sold under several brands:
23
+
24
+ > **AVO · Easy · Key Automation · Levada**
25
+
26
+ Many owners don't realise their "AVO" or "Levada" gate app is the same KUBE
27
+ platform underneath. If your gate uses one of these apps, this library talks to it.
28
+
29
+ This repo hosts the reusable protocol library (`kubegate`). The Home Assistant
30
+ integration lives in [`ha-kube`](../ha-kube) and builds on it.
31
+
32
+ ## Status
33
+ - ✅ **Local BLE**: handshake, encrypted commands (open / close / pedestrian / light), live status — reverse-engineered and verified against real devices.
34
+ - 🚧 **Cloud (remote)**: crypto and command format solved; the RTDB relay path is being finalised.
35
+ - 🚧 **Account discovery**: log in with your brand account to auto-import gates, passkeys and keys.
36
+
37
+ ## Install
38
+ ```bash
39
+ pip install -e .
40
+ ```
41
+
42
+ ## Quick start (BLE)
43
+ ```bash
44
+ python -m kubegate.cli scan
45
+ python -m kubegate.cli status --addr <ADDR> --passkey 0000000000012345
46
+ python -m kubegate.cli open --addr <ADDR> --passkey 0000000000012345
47
+ ```
48
+
49
+ ```python
50
+ import asyncio
51
+ from kubegate.ble import KubeBleDevice
52
+
53
+ async def main():
54
+ async with KubeBleDevice("<ADDR>", "0000000000012345") as gate:
55
+ await gate.action("open")
56
+ print(gate.status)
57
+
58
+ asyncio.run(main())
59
+ ```
60
+
61
+ ## Protocol (short)
62
+ ```
63
+ enckey1 = AES128_ECB(passkey, serial) # constant per device
64
+ enckey2 = AES128_ECB(passkey, nonce XOR enckey1) # per-connection XOR pad
65
+ token = (nonce XOR enckey1) XOR enckey2 # auth, written to f1170005
66
+ frames: @LLLL<body># , body = name or name={json}; whole frame XOR enckey2
67
+ action: cact={"cmd":"C30B","val":N} (N: 8 open · 4 close · 128 pedestrian · 256 light)
68
+ ```
69
+
70
+ The `passkey` is a 16-digit, zero-padded number from your account/installation.
71
+
72
+ ## License
73
+ Apache-2.0. Not affiliated with Key Automation or any brand listed above.
@@ -0,0 +1,20 @@
1
+ LICENSE
2
+ NOTICE
3
+ README.md
4
+ pyproject.toml
5
+ kubegate/__init__.py
6
+ kubegate/ble.py
7
+ kubegate/cli.py
8
+ kubegate/cloud.py
9
+ kubegate/const.py
10
+ kubegate/crypto.py
11
+ kubegate/protocol.py
12
+ kubegate/states.py
13
+ kubegate/vendors.py
14
+ kubegate.egg-info/PKG-INFO
15
+ kubegate.egg-info/SOURCES.txt
16
+ kubegate.egg-info/dependency_links.txt
17
+ kubegate.egg-info/entry_points.txt
18
+ kubegate.egg-info/requires.txt
19
+ kubegate.egg-info/top_level.txt
20
+ tests/test_crypto.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ kubegate = kubegate.cli:main
@@ -0,0 +1,7 @@
1
+ bleak>=0.21
2
+ cryptography>=41
3
+
4
+ [cli]
5
+
6
+ [cloud]
7
+ aiohttp>=3.9
@@ -0,0 +1 @@
1
+ kubegate
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kubegate"
7
+ version = "0.1.0"
8
+ description = "Control Key Automation KUBE gate modules (AVO, Easy, Key Automation, Levada) over BLE and cloud."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "Frane Bandov", email = "frane.bandov@gmail.com" }]
13
+ keywords = ["kube", "avo", "easy", "levada", "key automation", "gate", "ble", "home assistant"]
14
+ dependencies = ["bleak>=0.21", "cryptography>=41"]
15
+
16
+ [project.optional-dependencies]
17
+ cloud = ["aiohttp>=3.9"]
18
+ cli = []
19
+
20
+ [project.scripts]
21
+ kubegate = "kubegate.cli:main"
22
+
23
+ [tool.setuptools]
24
+ packages = ["kubegate"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,39 @@
1
+ """Protocol tests.
2
+
3
+ Uses a public test vector and *synthetic* (leak-free) session fixtures — no real
4
+ device passkey/serial. The session fixtures are self-consistent: they are
5
+ produced by the verified algorithm for a fake passkey/serial, so they still
6
+ pin the full SessionKeys derivation.
7
+ """
8
+ from kubegate.crypto import SessionKeys, encrypt_data, xor
9
+ from kubegate.protocol import action_frame, iter_frames
10
+
11
+
12
+ def test_encrypt_data_vector():
13
+ # Public AES/ECB padding vector (passkey as 16-char ascii).
14
+ pk = b"0000000000086828"
15
+ nonce = bytes.fromhex("D9D6884D3CFC8DE26E89E3872B8C3756")
16
+ ek1 = bytes.fromhex("EBEECD750ECDC9DA5BBBA5B51FCF7656")
17
+ assert encrypt_data(pk, xor(nonce, ek1)).hex() == "2444214d74f23fb7633d14b83f7b540f"
18
+
19
+
20
+ # Synthetic (fake passkey/serial) — (nonce, token, pad)
21
+ _PASS, _SER = "0000000000012345", "0000AABBCCDDEEFF"
22
+ _SESSIONS = [
23
+ ("00112233445566778899aabbccddeeff", "87778d89fed0261c489b374fa358c072", "916f5a6d9f8115eb88cd6f1610a769a3"),
24
+ ("0f1e2d3c4b5a69788796a5b4c3d2e1f0", "dc238f011db134e0c113074bda04b7b2", "c53457ea73ef08180e4a501d66f4116c"),
25
+ ("deadbeef00112233445566778899aabb", "8574695bc671ba6d7d552c637daff385", "4dd02263e364cdde71cfb8f68a141e10"),
26
+ ]
27
+
28
+
29
+ def test_session_derivation():
30
+ for nonce, token, pad in _SESSIONS:
31
+ s = SessionKeys(_PASS, _SER, bytes.fromhex(nonce))
32
+ assert s.enckey2.hex() == pad
33
+ assert s.token.hex() == token
34
+
35
+
36
+ def test_action_frame():
37
+ assert action_frame(8) == b'@001Bcact={"cmd":"C30B","val":8}#'
38
+ frames, _ = iter_frames(action_frame(8))
39
+ assert frames == [("cact", {"cmd": "C30B", "val": 8})]