rakopy 0.0.1__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.
rakopy/__init__.py ADDED
File without changes
rakopy/__version__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
rakopy/consts.py ADDED
@@ -0,0 +1,3 @@
1
+ """Constants for rakopy module."""
2
+
3
+ DEFAULT_PORT = 9762
rakopy/errors.py ADDED
@@ -0,0 +1,7 @@
1
+ """Errors for rakopy module."""
2
+
3
+ class ConfigValidationError(Exception):
4
+ """Exception when configuration validation fails."""
5
+
6
+ class SendCommandError(Exception):
7
+ """Exception when send command fails."""
rakopy/hub.py ADDED
@@ -0,0 +1,416 @@
1
+ """Core implementation of rakopi module."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import json
6
+ from typing import Any, AsyncGenerator, List
7
+ from rakopy.consts import DEFAULT_PORT
8
+ from rakopy.errors import ConfigValidationError, SendCommandError
9
+ from rakopy.model import (
10
+ Channel,
11
+ ChannelLevel,
12
+ HubStatus,
13
+ Level,
14
+ LevelChangedEvent,
15
+ LevelInfo,
16
+ Room,
17
+ Scene,
18
+ SceneChangedEvent
19
+ )
20
+
21
+ class Hub:
22
+ """Class to integrate with Rako Hub."""
23
+ def __init__(
24
+ self,
25
+ client_name: str,
26
+ host: str,
27
+ port: int = DEFAULT_PORT
28
+ ):
29
+ host = host.strip()
30
+ if not host:
31
+ raise ConfigValidationError("RakoHub: host parameter cannot be empty.")
32
+
33
+ if port < 0 or port > 65535:
34
+ raise ConfigValidationError("RakoHub: port should be between 0 and 65535.")
35
+
36
+ if not client_name:
37
+ raise ConfigValidationError("RakoHub: client_name parameter cannot be empty.")
38
+
39
+ self.host = host
40
+ self.port = port
41
+ self.client_name = client_name
42
+
43
+ self._reader = None
44
+ self._writer = None
45
+
46
+ async def get_hub_status(self) -> HubStatus:
47
+ """
48
+ Get Rako Hub status.
49
+ """
50
+ await self._reconnect()
51
+
52
+ request = {
53
+ "name": "status",
54
+ "payload": {}
55
+ }
56
+
57
+ self._writer.write(str.encode(json.dumps(request) + "\r\n"))
58
+ await self._writer.drain()
59
+
60
+ response = await self._reader.readline()
61
+ json_data = json.loads(response)
62
+
63
+ return HubStatus(
64
+ product_type= json_data["payload"]["productType"],
65
+ protocol_version= int(json_data["payload"]["protocolVersion"]),
66
+ id= json_data["payload"]["hubId"],
67
+ mac_address= json_data["payload"]["mac;"],
68
+ version= json_data["payload"]["hubVersion"]
69
+ )
70
+
71
+ async def get_levels(self, room_id: int = None) -> List[Level]:
72
+ """
73
+ Get levels for all the channels in a room.
74
+ If room_id is not specified, returns levels for all the rooms.
75
+ """
76
+ return await self._query("LEVEL", self._to_level, room_id)
77
+
78
+ async def get_rooms(self, room_id: int = None) -> List[Room]:
79
+ """
80
+ Get room by its id.
81
+ If room_id is not specified, returns all rooms.
82
+ """
83
+ return await self._query("SCENECHANNEL", self._to_room, room_id)
84
+
85
+ async def set_level(self, room_id: int, channel_id: int, level: int) -> None:
86
+ """
87
+ Set level for a given room and channel.
88
+ """
89
+ action = {
90
+ "command": "levelrate",
91
+ "level": level
92
+ }
93
+
94
+ request = self._build_send_request(room_id, channel_id, action)
95
+
96
+ await self._send(request)
97
+
98
+ async def set_rgb(
99
+ self,
100
+ room_id: int,
101
+ channel_id: int,
102
+ red: int,
103
+ green: int,
104
+ blue: int,
105
+ rgb_excludes_brightness: bool = False,
106
+ level: int = None
107
+ ) -> None:
108
+ """
109
+ Set RGB for a given room and channel.
110
+ """
111
+ color_send_type = "SEND_COLOR_AND_LEVEL"
112
+ if rgb_excludes_brightness and not level:
113
+ color_send_type = "SEND_COLOR_ONLY"
114
+
115
+ request = {
116
+ "name": "send-color",
117
+ "payload": {
118
+ "room": room_id,
119
+ "channel": channel_id,
120
+ "colorSendType": color_send_type,
121
+ "red": red,
122
+ "green": green,
123
+ "blue": blue,
124
+ "rgbExcludesBrightness": rgb_excludes_brightness,
125
+ "level": level
126
+ }
127
+ }
128
+
129
+ await self._send(request)
130
+
131
+ async def set_scene(self, room_id: int, channel_id: int, scene: int) -> None:
132
+ """
133
+ Set a scene for a given room and channel.
134
+ """
135
+ action = {
136
+ "command": "scene",
137
+ "scene": scene
138
+ }
139
+
140
+ request = self._build_send_request(room_id, channel_id, action)
141
+
142
+ await self._send(request)
143
+
144
+ async def set_temperature(
145
+ self,
146
+ room_id: int,
147
+ channel_id: int,
148
+ temperature: int,
149
+ level: int = None
150
+ ) -> None:
151
+ """
152
+ Set a colour temperature and level for a given room and channel.
153
+ """
154
+ color_send_type = "SEND_COLOR_ONLY"
155
+ if level:
156
+ color_send_type = "SEND_COLOR_AND_LEVEL"
157
+
158
+ request = {
159
+ "name": "send-colorTemp",
160
+ "payload": {
161
+ "room": room_id,
162
+ "channel": channel_id,
163
+ "colorSendType": color_send_type,
164
+ "temperature": temperature,
165
+ "level": level
166
+ }
167
+ }
168
+
169
+ await self._send(request)
170
+
171
+ async def start_fading_down(self, room_id: int, channel_id: int) -> None:
172
+ """
173
+ Start fading down brightness for a given room and channel
174
+ """
175
+ action = {
176
+ "command": "fade",
177
+ "down": True
178
+ }
179
+
180
+ request = self._build_send_request(room_id, channel_id, action)
181
+
182
+ await self._send(request)
183
+
184
+ async def start_fading_up(self, room_id: int, channel_id: int) -> None:
185
+ """
186
+ Start fading up brightness for a given room and channel.
187
+ """
188
+ action = {
189
+ "command": "fade",
190
+ "down": False
191
+ }
192
+
193
+ request = self._build_send_request(room_id, channel_id, action)
194
+
195
+ await self._send(request)
196
+
197
+ async def stop_fading(self, room_id: int, channel_id: int) -> None:
198
+ """
199
+ Stop fading brightness for a given room and channel
200
+ """
201
+ action = {
202
+ "command": "stop"
203
+ }
204
+
205
+ request = self._build_send_request(room_id, channel_id, action)
206
+
207
+ await self._send(request)
208
+
209
+ async def store_scene(self, room_id: int, channel_id: int, scene: int) -> None:
210
+ """
211
+ Store current levels as a scene for a given room and channel.
212
+ """
213
+ action = {
214
+ "command": "store",
215
+ "scene": scene
216
+ }
217
+
218
+ request = self._build_send_request(room_id, channel_id, action)
219
+
220
+ await self._send(request)
221
+
222
+ async def get_events(self) -> AsyncGenerator:
223
+ """
224
+ Subscribe and listen to events from Hub asynchronously.
225
+ """
226
+ reader, writer = await asyncio.open_connection(self.host, self.port)
227
+
228
+ payload = {
229
+ "version": 2,
230
+ "client_name": self.client_name,
231
+ "subscriptions": ["TRACKER"]
232
+ }
233
+ request = f"SUB,JSON,{json.dumps(payload)}\r\n"
234
+
235
+ writer.write(str.encode(request))
236
+ await writer.drain()
237
+
238
+ while True:
239
+ response = await reader.readline()
240
+ json_data = json.loads(response)
241
+ if json_data["name"] == "tracker":
242
+ if json_data["type"] == "scene":
243
+ yield SceneChangedEvent(
244
+ room_id= json_data["payload"]["roomId"],
245
+ channel_id= json_data["payload"]["channelId"],
246
+ scene_id= json_data["payload"]["scene"],
247
+ active_scene_id= json_data["payload"]["activeScene"],
248
+ )
249
+ elif json_data["type"] == "level":
250
+ level_changed_event = LevelChangedEvent(
251
+ room_id= json_data["payload"]["roomId"],
252
+ channel_id= json_data["payload"]["channelId"],
253
+ current_level= json_data["payload"]["currentLevel"],
254
+ target_level= json_data["payload"]["targetLevel"],
255
+ time_to_take= json_data["payload"]["timeToTake"],
256
+ temporary= json_data["payload"]["temporary"],
257
+ )
258
+ yield level_changed_event
259
+
260
+ async def _query(self, query_type: str, func, room_id: int = None):
261
+ """
262
+ Executes query and returns result.
263
+ """
264
+ await self._reconnect()
265
+
266
+ if room_id is None:
267
+ room_id = 0
268
+
269
+ request = {
270
+ "name": "query",
271
+ "payload": {
272
+ "queryType": query_type,
273
+ "roomId": room_id
274
+ }
275
+ }
276
+
277
+ self._writer.write(str.encode(json.dumps(request) + "\r\n"))
278
+ await self._writer.drain()
279
+
280
+ response = (await self._reader.readline()).decode()
281
+ json_data = json.loads(response)
282
+
283
+ result = []
284
+ for data in json_data["payload"]:
285
+ result.append(func(data))
286
+
287
+ return result
288
+
289
+ async def _reconnect(self) -> None:
290
+ """
291
+ Try to reconnect to the Rako Hub if the connection was not previously
292
+ established or was closed.
293
+ """
294
+ if (self._writer is None or
295
+ self._writer.transport is None or
296
+ self._writer.transport.is_closing()
297
+ ):
298
+ self._reader, self._writer = await asyncio.open_connection(self.host, self.port)
299
+
300
+ payload = {
301
+ "version": 2,
302
+ "client_name": self.client_name,
303
+ "subscriptions": []
304
+ }
305
+ request = f"SUB,JSON,{json.dumps(payload)}\r\n"
306
+
307
+ self._writer.write(str.encode(request))
308
+ await self._writer.drain()
309
+
310
+ await self._reader.readline()
311
+
312
+ async def _send(self, request: Any) -> None:
313
+ """
314
+ Sends a command.
315
+ """
316
+ await self._reconnect()
317
+
318
+ self._writer.write(str.encode(json.dumps(request) + "\r\n"))
319
+ await self._writer.drain()
320
+
321
+ response = (await self._reader.readline()).decode()
322
+ json_data = json.loads(response)
323
+ if json_data["name"] == "error":
324
+ raise SendCommandError(
325
+ f"Failed to send {0} command. Error: {1}", request, json_data["payload"]
326
+ )
327
+
328
+ @staticmethod
329
+ def _build_send_request(room_id: int, channel_id: int, action: Any):
330
+ """
331
+ Returns a send command request.
332
+ """
333
+ return {
334
+ "name": "send",
335
+ "payload": {
336
+ "room": room_id,
337
+ "channel": channel_id,
338
+ "action": action
339
+ }
340
+ }
341
+
342
+ @staticmethod
343
+ def _to_level(data: Any) -> Level:
344
+ """
345
+ Converts list of str to Level.
346
+ """
347
+ channel_levels = []
348
+ for channel_level in data["channel"]:
349
+ level_info_data = channel_level["levelInfo"]
350
+ if level_info_data:
351
+ level_info = LevelInfo(
352
+ kelvin= level_info_data["kelvin"],
353
+ red= level_info_data["red"],
354
+ green= level_info_data["green"],
355
+ blue= level_info_data["blue"]
356
+ )
357
+ else:
358
+ level_info = None
359
+
360
+ channel_levels.append(
361
+ ChannelLevel(
362
+ channel_id= channel_level["channelId"],
363
+ current_level= channel_level["currentLevel"],
364
+ target_level= channel_level["targetLevel"],
365
+ level_info= level_info
366
+ )
367
+ )
368
+
369
+ return Level(
370
+ room_id= data["roomId"],
371
+ current_scene_id= data["currentScene"],
372
+ channel_levels= channel_levels
373
+ )
374
+
375
+ @staticmethod
376
+ def _to_room(data: Any) -> Room:
377
+ """
378
+ Converts JSON data to Room.
379
+ """
380
+ channels = []
381
+ for channel in data["channel"]:
382
+ channels.append(
383
+ Channel(
384
+ id= channel["channelId"],
385
+ title= channel["title"],
386
+ type= channel["type"],
387
+ color_type= channel["colorType"],
388
+ color_title= channel["colorTitle"],
389
+ multi_channel_component= channel["multiChannelComponent"]
390
+ )
391
+ )
392
+
393
+ scenes = []
394
+ scenes.append(
395
+ Scene(
396
+ id= 0,
397
+ title= "Off"
398
+ )
399
+ )
400
+
401
+ for scene in data["scene"]:
402
+ scenes.append(
403
+ Scene(
404
+ id= scene["sceneId"],
405
+ title= scene["title"]
406
+ )
407
+ )
408
+
409
+ return Room(
410
+ id= data["roomId"],
411
+ title= data["title"],
412
+ type= data["type"],
413
+ mode= data["mode"],
414
+ channels= channels,
415
+ scenes= scenes
416
+ )
rakopy/model.py ADDED
@@ -0,0 +1,80 @@
1
+ """Data models for rakopy module."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import List
5
+
6
+ @dataclass
7
+ class HubStatus:
8
+ """Hub status data model."""
9
+ product_type: str
10
+ protocol_version: int
11
+ id: str
12
+ mac_address: str
13
+ version: str
14
+
15
+ @dataclass
16
+ class Channel:
17
+ """Channel data model."""
18
+ id: int
19
+ title: str
20
+ type: str
21
+ color_type: str
22
+ color_title: str
23
+ multi_channel_component: str
24
+
25
+ @dataclass
26
+ class Scene:
27
+ """Scene data model."""
28
+ id: int
29
+ title: int
30
+
31
+ @dataclass
32
+ class Room:
33
+ """Room data model."""
34
+ id: int
35
+ title: str
36
+ type: str
37
+ mode: str
38
+ channels: List[Channel]
39
+ scenes: List[Scene]
40
+
41
+ @dataclass
42
+ class LevelInfo:
43
+ """Channel level info data model."""
44
+ kelvin: int
45
+ red: int
46
+ green: int
47
+ blue: int
48
+
49
+ @dataclass
50
+ class ChannelLevel:
51
+ """Channel level data model."""
52
+ channel_id: int
53
+ current_level: int
54
+ target_level: int
55
+ level_info: LevelInfo
56
+
57
+ @dataclass
58
+ class Level:
59
+ """Level data model."""
60
+ room_id: int
61
+ current_scene_id: int
62
+ channel_levels: List[ChannelLevel]
63
+
64
+ @dataclass
65
+ class LevelChangedEvent:
66
+ """Level changed event data model."""
67
+ room_id: int
68
+ channel_id: int
69
+ current_level: int
70
+ target_level: int
71
+ time_to_take: int
72
+ temporary: bool
73
+
74
+ @dataclass
75
+ class SceneChangedEvent:
76
+ """Scene changed event data model."""
77
+ room_id: int
78
+ channel_id: int
79
+ scene_id: int
80
+ active_scene_id: int
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.3
2
+ Name: rakopy
3
+ Version: 0.0.1
4
+ Summary: RakoPy is a Python library that allows you to control Rako Controls system programmatically.
5
+ Project-URL: Homepage, https://github.com/princekama/rakopy
6
+ Project-URL: Issues, https://github.com/princekama/rakopy/issues
7
+ Author: @princekama
8
+ License-File: LICENSE
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.12
13
+ Description-Content-Type: text/markdown
14
+
15
+ # RakoPy
16
+ RakoPy is a Python library that allows you to control [Rako Controls](https://rakocontrols.com) system programmatically.
@@ -0,0 +1,10 @@
1
+ rakopy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ rakopy/__version__.py,sha256=sXLh7g3KC4QCFxcZGBTpG2scR7hmmBsMjq6LqRptkRg,22
3
+ rakopy/consts.py,sha256=sDuGelZuQ5KdX_vff_Tjhm1CoTFKVDhp20Q07hz6TYQ,56
4
+ rakopy/errors.py,sha256=J0zt7gXx5gnDGrwDkkMUh9B1rrdLI4N4NY_585LSOL4,211
5
+ rakopy/hub.py,sha256=qxVfpn8P76avvr2mRGl-eB5HIi-C7RPrjtCQTWItk80,12465
6
+ rakopy/model.py,sha256=zcoytOoKnDX7W5xGPNU3OgE6K7rPt2qBNYyV2HE0QDM,1450
7
+ rakopy-0.0.1.dist-info/METADATA,sha256=xJAL2Ru8hYwa4FIdQZ-QkEC8Miw98g0HuSRAp-VEkMM,660
8
+ rakopy-0.0.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
9
+ rakopy-0.0.1.dist-info/licenses/LICENSE,sha256=uPBTqYt4nzqqWTK7FEFdqendTljsBFG-DhRi01KM6vM,1076
10
+ rakopy-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.25.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Prince Kamalanathan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.