pyatomberg 0.1.0__py3-none-any.whl

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.
pyatomberg/client.py ADDED
@@ -0,0 +1,230 @@
1
+ """Unified Atomberg client for device discovery, commands, and telemetry."""
2
+
3
+ import logging
4
+ from typing import Any
5
+
6
+ import aiohttp
7
+
8
+ from pyatomberg.auth.cognito import CognitoOAuthHandler
9
+ from pyatomberg.auth.developer import DeveloperTokenHandler
10
+ from pyatomberg.const import DEVELOPER_API_BASE
11
+ from pyatomberg.exceptions import AtombergAuthError, AtombergConnectionError
12
+ from pyatomberg.fan.device import AtombergFan
13
+ from pyatomberg.fan.udp_listener import AtombergUDPListener
14
+
15
+ _LOGGER = logging.getLogger(__name__)
16
+
17
+
18
+ class AtombergClient:
19
+ """Unified client for Atomberg smart home devices."""
20
+
21
+ def __init__(
22
+ self,
23
+ developer_token: str | None = None,
24
+ api_key: str | None = None,
25
+ cognito_handler: CognitoOAuthHandler | None = None,
26
+ session: aiohttp.ClientSession | None = None,
27
+ base_url: str = DEVELOPER_API_BASE,
28
+ enable_udp_listener: bool = False,
29
+ ) -> None:
30
+ """Initialize AtombergClient."""
31
+ self._base_url = base_url.rstrip("/")
32
+ self._session = session
33
+ self._owns_session = session is None
34
+ self._fans: dict[str, AtombergFan] = {}
35
+
36
+ if developer_token:
37
+ self._auth_handler: DeveloperTokenHandler | CognitoOAuthHandler = (
38
+ DeveloperTokenHandler(
39
+ refresh_token=developer_token,
40
+ api_key=api_key,
41
+ session=self._session,
42
+ base_url=self._base_url,
43
+ )
44
+ )
45
+ elif cognito_handler:
46
+ self._auth_handler = cognito_handler
47
+ else:
48
+ raise AtombergAuthError("Either developer_token or cognito_handler must be provided")
49
+
50
+ self._udp_listener: AtombergUDPListener | None = None
51
+ if enable_udp_listener:
52
+ self._udp_listener = AtombergUDPListener(callback=self._handle_udp_state)
53
+
54
+ @property
55
+ def auth_handler(self) -> DeveloperTokenHandler | CognitoOAuthHandler:
56
+ """Return the active authentication handler."""
57
+ return self._auth_handler
58
+
59
+ @property
60
+ def fans(self) -> dict[str, AtombergFan]:
61
+ """Return dictionary of known fans keyed by device_id."""
62
+ return self._fans
63
+
64
+ async def __aenter__(self) -> "AtombergClient":
65
+ """Async context manager entry."""
66
+ if self._session is None:
67
+ self._session = aiohttp.ClientSession()
68
+ if isinstance(self._auth_handler, DeveloperTokenHandler):
69
+ self._auth_handler._session = self._session
70
+ if self._udp_listener:
71
+ await self._udp_listener.start()
72
+ return self
73
+
74
+ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
75
+ """Async context manager exit."""
76
+ await self.close()
77
+
78
+ async def close(self) -> None:
79
+ """Close client sessions and background listeners."""
80
+ if self._udp_listener and self._udp_listener.is_running:
81
+ await self._udp_listener.stop()
82
+ if self._owns_session and self._session and not self._session.closed:
83
+ await self._session.close()
84
+
85
+ def _handle_udp_state(self, device_id: str, payload: dict[str, Any]) -> None:
86
+ """Handle real-time UDP broadcast packets received from local network."""
87
+ fan = self._fans.get(device_id)
88
+ if fan:
89
+ fan.update_from_dict(payload)
90
+ _LOGGER.debug("Updated fan %s from local UDP broadcast", device_id)
91
+ else:
92
+ _LOGGER.debug("Received broadcast for unregistered fan: %s", device_id)
93
+
94
+ async def start_udp_listener(self) -> None:
95
+ """Start local UDP broadcast listener on port 5625."""
96
+ if not self._udp_listener:
97
+ self._udp_listener = AtombergUDPListener(callback=self._handle_udp_state)
98
+ await self._udp_listener.start()
99
+
100
+ async def stop_udp_listener(self) -> None:
101
+ """Stop local UDP broadcast listener."""
102
+ if self._udp_listener:
103
+ await self._udp_listener.stop()
104
+
105
+ async def _get_session(self) -> aiohttp.ClientSession:
106
+ """Ensure active aiohttp session."""
107
+ if self._session is None or self._session.closed:
108
+ self._session = aiohttp.ClientSession()
109
+ if isinstance(self._auth_handler, DeveloperTokenHandler):
110
+ self._auth_handler._session = self._session
111
+ return self._session
112
+
113
+ async def get_fans(self, update_states: bool = True) -> list[AtombergFan]:
114
+ """Discover and retrieve registered ceiling fans."""
115
+ session = await self._get_session()
116
+ headers = await self._auth_handler.get_auth_headers()
117
+ url = f"{self._base_url}/get_list_of_devices"
118
+
119
+ try:
120
+ async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=15)) as resp:
121
+ data: dict[str, Any] = await resp.json(content_type=None)
122
+ if resp.status != 200 or not data.get("status", True):
123
+ error_msg = data.get("message") or f"HTTP {resp.status}"
124
+ raise AtombergConnectionError(f"Failed to fetch devices: {error_msg}")
125
+
126
+ devices_raw = (
127
+ data.get("devices")
128
+ or data.get("data", {}).get("devices")
129
+ or data.get("data")
130
+ or []
131
+ )
132
+
133
+ discovered_fans: list[AtombergFan] = []
134
+ for item in devices_raw:
135
+ if not isinstance(item, dict):
136
+ continue
137
+ device_id = item.get("device_id") or item.get("id")
138
+ if not device_id:
139
+ continue
140
+ name = item.get("device_name") or item.get("name") or str(device_id)
141
+ model_name = item.get("model") or item.get("series")
142
+
143
+ if device_id in self._fans:
144
+ fan = self._fans[device_id]
145
+ fan.name = name
146
+ fan.model_name = model_name
147
+ else:
148
+ fan = AtombergFan(
149
+ device_id=str(device_id),
150
+ name=str(name),
151
+ client=self,
152
+ model_name=model_name,
153
+ raw_data=item,
154
+ )
155
+ self._fans[device_id] = fan
156
+ discovered_fans.append(fan)
157
+
158
+ if update_states and discovered_fans:
159
+ try:
160
+ await self.get_device_states("all")
161
+ except Exception as err:
162
+ _LOGGER.warning("Could not refresh initial device states: %s", err)
163
+
164
+ return discovered_fans
165
+ except aiohttp.ClientError as err:
166
+ raise AtombergConnectionError(f"Network error querying device list: {err}") from err
167
+
168
+ async def get_device_states(self, device_id: str = "all") -> dict[str, Any]:
169
+ """Query state for a specific device or all devices."""
170
+ session = await self._get_session()
171
+ headers = await self._auth_handler.get_auth_headers()
172
+ url = f"{self._base_url}/get_device_state"
173
+ params = {"device_id": device_id}
174
+
175
+ try:
176
+ async with session.get(
177
+ url,
178
+ headers=headers,
179
+ params=params,
180
+ timeout=aiohttp.ClientTimeout(total=15),
181
+ ) as resp:
182
+ data: dict[str, Any] = await resp.json(content_type=None)
183
+ if resp.status != 200 or not data.get("status", True):
184
+ error_msg = data.get("message") or f"HTTP {resp.status}"
185
+ raise AtombergConnectionError(f"Failed to get device state: {error_msg}")
186
+
187
+ state_data = data.get("data") or data.get("state") or data
188
+ if isinstance(state_data, dict):
189
+ # Check if multi-device dictionary or single device
190
+ if device_id != "all" and device_id in self._fans:
191
+ self._fans[device_id].update_from_dict(state_data)
192
+ else:
193
+ for d_id, d_state in state_data.items():
194
+ if isinstance(d_state, dict) and d_id in self._fans:
195
+ self._fans[d_id].update_from_dict(d_state)
196
+ elif isinstance(state_data, list):
197
+ for d_state in state_data:
198
+ if isinstance(d_state, dict):
199
+ d_id = d_state.get("device_id")
200
+ if d_id and d_id in self._fans:
201
+ self._fans[d_id].update_from_dict(d_state)
202
+
203
+ return data
204
+ except aiohttp.ClientError as err:
205
+ raise AtombergConnectionError(f"Network error getting device state: {err}") from err
206
+
207
+ async def send_command(self, device_id: str, command: dict[str, Any]) -> dict[str, Any]:
208
+ """Send control command to a device via developer API."""
209
+ session = await self._get_session()
210
+ headers = await self._auth_handler.get_auth_headers()
211
+ url = f"{self._base_url}/send_command"
212
+ payload = {
213
+ "device_id": device_id,
214
+ "command": command,
215
+ }
216
+
217
+ try:
218
+ async with session.post(
219
+ url,
220
+ json=payload,
221
+ headers=headers,
222
+ timeout=aiohttp.ClientTimeout(total=15),
223
+ ) as resp:
224
+ data: dict[str, Any] = await resp.json(content_type=None)
225
+ if resp.status != 200 or not data.get("status", True):
226
+ error_msg = data.get("message") or f"HTTP {resp.status}"
227
+ raise AtombergConnectionError(f"Failed to send command: {error_msg}")
228
+ return data
229
+ except aiohttp.ClientError as err:
230
+ raise AtombergConnectionError(f"Network error sending command: {err}") from err
pyatomberg/const.py ADDED
@@ -0,0 +1,43 @@
1
+ """Constants for pyatomberg."""
2
+
3
+ from typing import Final
4
+
5
+ # Cloud & Authentication Endpoints
6
+ COGNITO_REGION: Final[str] = "ap-south-1"
7
+ COGNITO_USER_POOL_ID: Final[str] = "ap-south-1_fMZyKIlR2"
8
+ COGNITO_CLIENT_ID: Final[str] = "3cr9rf3urr1jvpn46fsd377uv0"
9
+ COGNITO_DOMAIN: Final[str] = "auth.atomberg-iot.com"
10
+ COGNITO_AUTHORIZE_URL: Final[str] = f"https://{COGNITO_DOMAIN}/oauth2/authorize"
11
+ COGNITO_TOKEN_URL: Final[str] = f"https://{COGNITO_DOMAIN}/oauth2/token"
12
+ COGNITO_REDIRECT_URI: Final[str] = "https://app.atomberg-iot.com"
13
+
14
+ SERVER_API_BASE: Final[str] = "https://server.atomberg-iot.com"
15
+ DEVELOPER_API_BASE: Final[str] = "https://api.developer.atomberg-iot.com/v2"
16
+
17
+ # Fan Local Subnet UDP Port
18
+ FAN_UDP_PORT: Final[int] = 5625
19
+ FAN_UDP_MAGIC_PREFIX: Final[bytes] = b"PROXY TCP4 "
20
+
21
+ # Smart Lock (Haosj BLE) GATT Profile
22
+ LOCK_SERVICE_UUID: Final[str] = "0000fff0-0000-1000-8000-00805f9b34fb"
23
+ LOCK_WRITE_CHAR_UUID: Final[str] = "0000fff1-0000-1000-8000-00805f9b34fb"
24
+ LOCK_NOTIFY_CHAR_UUID: Final[str] = "0000fff2-0000-1000-8000-00805f9b34fb"
25
+
26
+ # Haosj HSJ Cryptography and Framing
27
+ HSJ_HEADER: Final[bytes] = b"HSJ"
28
+ HSJ_FACTORY_KEY: Final[bytes] = b"mQ3cJOATdERLW1a5"
29
+
30
+ # HSJ Command Categories
31
+ HSJ_CMD_HEARTBEAT: Final[int] = 0x0001
32
+ HSJ_CMD_STATUS: Final[int] = 0x0002
33
+ HSJ_CMD_UNLOCK: Final[int] = 0x0003
34
+ HSJ_CMD_EVENT_LOG: Final[int] = 0x000A
35
+ HSJ_CMD_PAIRING: Final[int] = 0x000F
36
+
37
+ # HSJ Unlock Credential Categories
38
+ HSJ_EVENT_APP_REMOTE: Final[int] = 0x00
39
+ HSJ_EVENT_FINGERPRINT: Final[int] = 0x01
40
+ HSJ_EVENT_PIN: Final[int] = 0x02
41
+ HSJ_EVENT_NFC: Final[int] = 0x04
42
+ HSJ_EVENT_ACCESS_DENIED: Final[int] = 0x36
43
+ HSJ_EVENT_AUTO_LOCK: Final[int] = 0x3D
pyatomberg/crypto.py ADDED
@@ -0,0 +1,83 @@
1
+ """Cryptographic and CRC routines for Atomberg protocols."""
2
+
3
+ from cryptography.hazmat.backends import default_backend
4
+ from cryptography.hazmat.primitives import padding
5
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
6
+
7
+ from pyatomberg.exceptions import AtombergCryptoError
8
+
9
+
10
+ def calculate_modbus_crc16(data: bytes) -> int:
11
+ """Calculate Modbus CRC-16 checksum (Polynomial 0xA001, Initial 0xFFFF).
12
+
13
+ Returns integer in range 0x0000 - 0xFFFF.
14
+ """
15
+ crc = 0xFFFF
16
+ for byte in data:
17
+ crc ^= byte
18
+ for _ in range(8):
19
+ if crc & 0x0001:
20
+ crc = (crc >> 1) ^ 0xA001
21
+ else:
22
+ crc >>= 1
23
+ return crc & 0xFFFF
24
+
25
+
26
+ def verify_modbus_crc16(data_with_crc: bytes) -> bool:
27
+ """Verify data ending with a 2-byte little-endian Modbus CRC-16."""
28
+ if len(data_with_crc) < 2:
29
+ return False
30
+ payload = data_with_crc[:-2]
31
+ expected_crc = int.from_bytes(data_with_crc[-2:], byteorder="little")
32
+ return calculate_modbus_crc16(payload) == expected_crc
33
+
34
+
35
+ def encrypt_aes_ecb(plaintext: bytes, key: bytes, pad: bool = True) -> bytes:
36
+ """Encrypt plaintext using AES-128 in ECB mode.
37
+
38
+ Key must be exactly 16 bytes.
39
+ If pad is True, PKCS#7 padding is applied.
40
+ """
41
+ if len(key) != 16:
42
+ raise AtombergCryptoError(f"AES-128 key must be exactly 16 bytes, got {len(key)}")
43
+
44
+ if pad:
45
+ padder = padding.PKCS7(128).padder()
46
+ padded_data = padder.update(plaintext) + padder.finalize()
47
+ else:
48
+ if len(plaintext) % 16 != 0:
49
+ raise AtombergCryptoError(
50
+ f"Plaintext length ({len(plaintext)}) must be a multiple of 16 when pad=False"
51
+ )
52
+ padded_data = plaintext
53
+
54
+ cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())
55
+ encryptor = cipher.encryptor()
56
+ return encryptor.update(padded_data) + encryptor.finalize()
57
+
58
+
59
+ def decrypt_aes_ecb(ciphertext: bytes, key: bytes, unpad: bool = True) -> bytes:
60
+ """Decrypt ciphertext using AES-128 in ECB mode.
61
+
62
+ Key must be exactly 16 bytes. Ciphertext length must be a multiple of 16.
63
+ If unpad is True, PKCS#7 unpadding is removed.
64
+ """
65
+ if len(key) != 16:
66
+ raise AtombergCryptoError(f"AES-128 key must be exactly 16 bytes, got {len(key)}")
67
+ if len(ciphertext) == 0 or len(ciphertext) % 16 != 0:
68
+ raise AtombergCryptoError(
69
+ f"Ciphertext length ({len(ciphertext)}) must be a non-zero multiple of 16"
70
+ )
71
+
72
+ cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())
73
+ decryptor = cipher.decryptor()
74
+ decrypted = decryptor.update(ciphertext) + decryptor.finalize()
75
+
76
+ if unpad:
77
+ try:
78
+ unpadder = padding.PKCS7(128).unpadder()
79
+ return unpadder.update(decrypted) + unpadder.finalize()
80
+ except ValueError as err:
81
+ raise AtombergCryptoError(f"PKCS#7 unpadding failed: {err}") from err
82
+
83
+ return decrypted
@@ -0,0 +1,28 @@
1
+ """Exceptions for pyatomberg."""
2
+
3
+ class AtombergError(Exception):
4
+ """Base exception for all pyatomberg errors."""
5
+
6
+
7
+ class AtombergAuthError(AtombergError):
8
+ """Raised when authentication fails or token is expired/invalid."""
9
+
10
+
11
+ class AtombergConnectionError(AtombergError):
12
+ """Raised when communication with cloud or local device fails."""
13
+
14
+
15
+ class AtombergDeviceOfflineError(AtombergConnectionError):
16
+ """Raised when a device is offline or unreachable."""
17
+
18
+
19
+ class AtombergBLEError(AtombergError):
20
+ """Raised when a Bluetooth Low Energy operation fails."""
21
+
22
+
23
+ class AtombergCryptoError(AtombergError):
24
+ """Raised when cryptographic operations or CRC verification fails."""
25
+
26
+
27
+ class AtombergPairingError(AtombergError):
28
+ """Raised when lock pairing or key exchange fails."""
@@ -0,0 +1,6 @@
1
+ """Ceiling fan support for pyatomberg."""
2
+
3
+ from pyatomberg.fan.device import AtombergFan
4
+ from pyatomberg.fan.udp_listener import AtombergUDPListener, parse_fan_datagram
5
+
6
+ __all__ = ["AtombergFan", "AtombergUDPListener", "parse_fan_datagram"]
@@ -0,0 +1,151 @@
1
+ """Atomberg smart BLDC ceiling fan device controller."""
2
+
3
+ from typing import TYPE_CHECKING, Any, Callable
4
+
5
+ from pyatomberg.models.device import AtombergDeviceModel, DeviceType, FanState
6
+
7
+ if TYPE_CHECKING:
8
+ from pyatomberg.client import AtombergClient
9
+
10
+
11
+ class AtombergFan(AtombergDeviceModel):
12
+ """Represents an Atomberg smart ceiling fan (Renesa, Aris, Studio+, etc.)."""
13
+
14
+ def __init__(
15
+ self,
16
+ device_id: str,
17
+ name: str,
18
+ client: "AtombergClient | None" = None,
19
+ model_name: str | None = None,
20
+ is_online: bool = True,
21
+ raw_data: dict[str, Any] | None = None,
22
+ ) -> None:
23
+ """Initialize an AtombergFan instance."""
24
+ super().__init__(
25
+ device_id=device_id,
26
+ name=name,
27
+ device_type=DeviceType.FAN,
28
+ is_online=is_online,
29
+ model_name=model_name,
30
+ raw_data=raw_data or {},
31
+ )
32
+ self.client = client
33
+ self.state = FanState()
34
+ self._update_callbacks: list[Callable[["AtombergFan"], None]] = []
35
+
36
+ if raw_data:
37
+ self.update_from_dict(raw_data)
38
+
39
+ def register_callback(self, callback: Callable[["AtombergFan"], None]) -> None:
40
+ """Register a callback for state changes."""
41
+ if callback not in self._update_callbacks:
42
+ self._update_callbacks.append(callback)
43
+
44
+ def unregister_callback(self, callback: Callable[["AtombergFan"], None]) -> None:
45
+ """Unregister a state change callback."""
46
+ if callback in self._update_callbacks:
47
+ self._update_callbacks.remove(callback)
48
+
49
+ def _notify_callbacks(self) -> None:
50
+ """Notify registered listeners of a state change."""
51
+ for cb in self._update_callbacks:
52
+ try:
53
+ cb(self)
54
+ except Exception:
55
+ pass
56
+
57
+ def update_from_dict(self, data: dict[str, Any]) -> None:
58
+ """Update live state from cloud response or local UDP broadcast packet."""
59
+ if "power" in data:
60
+ self.state.power = bool(data["power"])
61
+
62
+ if "speed" in data:
63
+ try:
64
+ self.state.speed = int(data["speed"])
65
+ except (ValueError, TypeError):
66
+ pass
67
+
68
+ if "sleep" in data:
69
+ self.state.sleep = bool(data["sleep"])
70
+
71
+ if "timer" in data or "timer_hours" in data:
72
+ val = data.get("timer_hours", data.get("timer", 0))
73
+ try:
74
+ self.state.timer_hours = int(val)
75
+ except (ValueError, TypeError):
76
+ pass
77
+
78
+ if "led" in data or "led_brightness" in data:
79
+ val = data.get("led_brightness", data.get("led"))
80
+ try:
81
+ self.state.led_brightness = int(val) if val is not None else None
82
+ except (ValueError, TypeError):
83
+ pass
84
+
85
+ if "light_mode" in data:
86
+ self.state.light_mode = str(data["light_mode"])
87
+
88
+ if "last_seen" in data:
89
+ try:
90
+ self.state.last_seen = float(data["last_seen"])
91
+ except (ValueError, TypeError):
92
+ pass
93
+
94
+ if "online" in data:
95
+ self.is_online = bool(data["online"])
96
+
97
+ self._notify_callbacks()
98
+
99
+ async def send_command(self, command: dict[str, Any]) -> dict[str, Any]:
100
+ """Dispatch command to this fan via client."""
101
+ if not self.client:
102
+ raise RuntimeError("AtombergFan has no associated client to send commands")
103
+ return await self.client.send_command(self.device_id, command)
104
+
105
+ async def turn_on(self, speed: int | None = None) -> None:
106
+ """Turn the fan on, optionally setting speed (1-6)."""
107
+ cmd: dict[str, Any] = {"power": True}
108
+ if speed is not None:
109
+ cmd["speed"] = max(1, min(6, speed))
110
+ await self.send_command(cmd)
111
+ self.state.power = True
112
+ if speed is not None:
113
+ self.state.speed = cmd["speed"]
114
+ self._notify_callbacks()
115
+
116
+ async def turn_off(self) -> None:
117
+ """Turn the fan off."""
118
+ await self.send_command({"power": False})
119
+ self.state.power = False
120
+ self._notify_callbacks()
121
+
122
+ async def set_speed(self, speed: int) -> None:
123
+ """Set the fan speed between 1 and 6."""
124
+ valid_speed = max(1, min(6, speed))
125
+ await self.send_command({"power": True, "speed": valid_speed})
126
+ self.state.power = True
127
+ self.state.speed = valid_speed
128
+ self._notify_callbacks()
129
+
130
+ async def set_sleep(self, sleep: bool) -> None:
131
+ """Toggle sleep mode."""
132
+ await self.send_command({"sleep": sleep})
133
+ self.state.sleep = sleep
134
+ self._notify_callbacks()
135
+
136
+ async def set_timer(self, hours: int) -> None:
137
+ """Set fan shutdown timer in hours (0 to disable)."""
138
+ await self.send_command({"timer_hours": hours})
139
+ self.state.timer_hours = hours
140
+ self._notify_callbacks()
141
+
142
+ async def set_led(self, brightness: int, light_mode: str | None = None) -> None:
143
+ """Set LED brightness (0-100) and optional light mode."""
144
+ cmd: dict[str, Any] = {"led": max(0, min(100, brightness))}
145
+ if light_mode:
146
+ cmd["light_mode"] = light_mode
147
+ await self.send_command(cmd)
148
+ self.state.led_brightness = cmd["led"]
149
+ if light_mode:
150
+ self.state.light_mode = light_mode
151
+ self._notify_callbacks()