python-rako-2025 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.
@@ -0,0 +1,60 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import logging
5
+ import socket
6
+ from asyncio.trsock import TransportSocket # noqa
7
+ from typing import TypedDict
8
+
9
+ import asyncio_dgram
10
+
11
+ from python_rako.bridge import Bridge, BridgeCommanderHTTP, BridgeCommanderUDP # noqa
12
+ from python_rako.const import RAKO_BRIDGE_DEFAULT_PORT, MessageType, RequestType # noqa
13
+ from python_rako.exceptions import RakoBridgeError # noqa
14
+ from python_rako.model import ( # noqa
15
+ BridgeInfo,
16
+ ChannelLight,
17
+ ChannelStatusMessage,
18
+ LevelCache,
19
+ LevelCacheItem,
20
+ Light,
21
+ RoomChannel,
22
+ RoomLight,
23
+ SceneCache,
24
+ SceneStatusMessage,
25
+ UnsupportedMessage,
26
+ )
27
+
28
+ _LOGGER = logging.getLogger(__name__)
29
+
30
+
31
+ class BridgeDescription(TypedDict, total=False):
32
+ host: str
33
+ port: int
34
+ name: str
35
+ mac: str
36
+
37
+
38
+ async def discover_bridge() -> BridgeDescription:
39
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
40
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
41
+ server = await asyncio_dgram.from_socket(sock)
42
+ await server.send(b"D", ("255.255.255.255", RAKO_BRIDGE_DEFAULT_PORT))
43
+ msg, (host, port) = await server.recv()
44
+ bridge_description: BridgeDescription = {"host": host, "port": port}
45
+ try:
46
+ name, mac = msg.decode("utf8").split()
47
+ bridge_description["name"] = name
48
+ bridge_description["mac"] = mac
49
+ except ValueError:
50
+ raise ValueError(f"Couldn't interpret discovery response message: {msg}")
51
+ return bridge_description
52
+
53
+
54
+ def main() -> None:
55
+ bridge_desc: BridgeDescription = asyncio.run(discover_bridge())
56
+ print(bridge_desc)
57
+
58
+
59
+ if __name__ == "__main__":
60
+ main()
@@ -0,0 +1,2 @@
1
+ """AUTOGENERATED ON RELEASE."""
2
+ __version__ = "0.0.1"
python_rako/bridge.py ADDED
@@ -0,0 +1,283 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import logging
5
+ from typing import Any, AsyncGenerator, Generator, Tuple
6
+
7
+ import aiohttp
8
+ import xmltodict
9
+ from asyncio_dgram.aio import DatagramServer
10
+
11
+ from python_rako.const import (
12
+ COMMAND_SUCCESS_RESPONSE,
13
+ CommandType,
14
+ Flags,
15
+ MessageType,
16
+ RequestType,
17
+ )
18
+ from python_rako.exceptions import RakoBridgeError
19
+ from python_rako.helpers import (
20
+ command_to_byte_list,
21
+ deserialise_byte_list,
22
+ get_dg_commander,
23
+ )
24
+ from python_rako.model import (
25
+ BridgeInfo,
26
+ ChannelLight,
27
+ CommandHTTP,
28
+ CommandLevelHTTP,
29
+ CommandSceneHTTP,
30
+ CommandUDP,
31
+ EOFResponse,
32
+ LevelCache,
33
+ Light,
34
+ RoomLight,
35
+ SceneCache,
36
+ )
37
+
38
+ _LOGGER = logging.getLogger(__name__)
39
+
40
+
41
+ class _BridgeCommander:
42
+ def __init__(self, host: str, port: int):
43
+ self.host = host
44
+ self.port = port
45
+
46
+ async def set_room_scene(self, room_id: int, scene: int) -> None:
47
+ """Set the scene of a room."""
48
+ raise NotImplementedError()
49
+
50
+ async def set_room_brightness(self, room_id: int, brightness: int) -> None:
51
+ """Set the brightness of a room."""
52
+ await self.set_channel_brightness(room_id, 0, brightness)
53
+
54
+ async def set_channel_brightness(
55
+ self, room_id: int, channel_id: int, brightness: int
56
+ ) -> None:
57
+ """Set the brightness of a channel."""
58
+ raise NotImplementedError()
59
+
60
+
61
+ class BridgeCommanderUDP(_BridgeCommander):
62
+ async def set_room_scene(self, room_id: int, scene: int) -> None:
63
+ """Set the scene of a room."""
64
+ command = CommandUDP(
65
+ room=room_id,
66
+ channel=0,
67
+ command=CommandType.SET_SCENE,
68
+ data=[Flags.USE_DEFAULT_FADE_RATE.value, scene],
69
+ )
70
+ await self._send_command(command)
71
+
72
+ async def set_channel_brightness(
73
+ self, room_id: int, channel_id: int, brightness: int
74
+ ) -> None:
75
+ """Set the brightness of a channel."""
76
+ command = CommandUDP(
77
+ room=room_id,
78
+ channel=channel_id,
79
+ command=CommandType.SET_LEVEL,
80
+ data=[Flags.USE_DEFAULT_FADE_RATE.value, brightness],
81
+ )
82
+ await self._send_command(command)
83
+
84
+ async def _send_command(self, command: CommandUDP) -> None:
85
+ _LOGGER.debug("Sending command: %s", command)
86
+ byte_list = command_to_byte_list(command)
87
+ async with get_dg_commander(self.host, self.port) as dg_client:
88
+ _LOGGER.debug("Sending command bytes: %s", byte_list)
89
+ await dg_client.send(bytes(byte_list))
90
+ data, _ = await dg_client.recv()
91
+
92
+ if data.decode("utf8").strip() != COMMAND_SUCCESS_RESPONSE:
93
+ _LOGGER.warning("Bad response after command %s %s", command, data)
94
+
95
+
96
+ class BridgeCommanderHTTP(_BridgeCommander):
97
+ def __init__(self, host: str, port: int, aiohttp_session: aiohttp.ClientSession):
98
+ super().__init__(host, port)
99
+ self.aiohttp_session = aiohttp_session
100
+
101
+ @property
102
+ def _command_url(self) -> str:
103
+ return f"http://{self.host}/rako.cgi"
104
+
105
+ async def set_room_scene(self, room_id: int, scene: int) -> None:
106
+ """Set the scene of a room."""
107
+ command = CommandSceneHTTP(
108
+ room=room_id,
109
+ channel=0,
110
+ scene=scene,
111
+ )
112
+ await self._send_command(command)
113
+
114
+ async def set_channel_brightness(
115
+ self, room_id: int, channel_id: int, brightness: int
116
+ ) -> None:
117
+ """Set the brightness of a channel."""
118
+ command = CommandLevelHTTP(
119
+ room=room_id,
120
+ channel=channel_id,
121
+ level=brightness,
122
+ )
123
+ await self._send_command(command)
124
+
125
+ async def _send_command(self, command: CommandHTTP) -> None:
126
+ params = command.as_params()
127
+ _LOGGER.debug("Posting params %s", params)
128
+ await self.aiohttp_session.post(self._command_url, params=params)
129
+
130
+
131
+ class Bridge:
132
+ def __init__(
133
+ self,
134
+ host: str,
135
+ port: int,
136
+ name: str,
137
+ mac: str,
138
+ bridge_commander: _BridgeCommander | None = None,
139
+ ):
140
+ self.host = host
141
+ self.port = port
142
+ self.name = name
143
+ self.mac = mac
144
+ self._bridge_commander = (
145
+ bridge_commander if bridge_commander else BridgeCommanderUDP(host, port)
146
+ )
147
+ self.level_cache: LevelCache = LevelCache()
148
+ self.scene_cache: SceneCache = SceneCache()
149
+
150
+ @property
151
+ def _discovery_url(self) -> str:
152
+ return f"http://{self.host}/rako.xml"
153
+
154
+ async def get_rako_xml(self, session: aiohttp.ClientSession) -> str:
155
+ async with session.get(self._discovery_url) as response:
156
+ rako_xml: str = await response.text()
157
+ return rako_xml
158
+
159
+ async def discover_lights(
160
+ self, session: aiohttp.ClientSession
161
+ ) -> AsyncGenerator[Light, None]:
162
+ rako_xml = await self.get_rako_xml(session)
163
+ for light in self.get_lights_from_discovery_xml(rako_xml):
164
+ yield light
165
+
166
+ async def get_info(self, session: aiohttp.ClientSession) -> BridgeInfo:
167
+ try:
168
+ rako_xml = await self.get_rako_xml(session)
169
+ info = self.get_bridge_info_from_discovery_xml(rako_xml)
170
+ except (KeyError, ValueError) as ex:
171
+ raise RakoBridgeError(f"unsupported bridge: {ex}")
172
+ except aiohttp.ClientError as ex:
173
+ raise RakoBridgeError(f"cannot connect to bridge: {ex}")
174
+ return info
175
+
176
+ @staticmethod
177
+ def get_bridge_info_from_discovery_xml(xml: str) -> BridgeInfo:
178
+ xml_dict = xmltodict.parse(xml)
179
+ info = xml_dict["rako"].get("info", dict())
180
+ config = xml_dict["rako"].get("config", dict())
181
+ return BridgeInfo(
182
+ version=info.get("version"),
183
+ buildDate=info.get("buildDate"),
184
+ hostName=info.get("hostName"),
185
+ hostIP=info.get("hostIP"),
186
+ hostMAC=info.get("hostMAC"),
187
+ hwStatus=info.get("hwStatus"),
188
+ dbVersion=info.get("dbVersion"),
189
+ requirepassword=config.get("requirepassword"),
190
+ passhash=config.get("passhash"),
191
+ charset=config.get("charset"),
192
+ )
193
+
194
+ @staticmethod
195
+ def get_lights_from_discovery_xml(xml: str) -> Generator[Light, None, None]:
196
+ xml_dict = xmltodict.parse(xml, force_list={'Room'})
197
+ for room in xml_dict["rako"]["rooms"]["Room"]:
198
+ room_id = int(room["@id"])
199
+ room_type = room.get("Type", "Lights")
200
+ if room_type != "Lights":
201
+ _LOGGER.info(
202
+ "Unsupported room type. room_id=%s room_type=%s", room_id, room_type
203
+ )
204
+ continue
205
+ room_title = room["Title"]
206
+ yield RoomLight(room_id, room_title)
207
+ channels_section = room.get("Channel", [])
208
+ channels = (
209
+ channels_section
210
+ if isinstance(channels_section, list)
211
+ else [channels_section]
212
+ )
213
+ for channel in channels:
214
+ channel_id = int(channel["@id"])
215
+ channel_type = channel.get("type", "Default")
216
+ channel_name = channel["Name"]
217
+ channel_levels = channel["Levels"]
218
+ yield ChannelLight(
219
+ room_id,
220
+ room_title,
221
+ channel_id,
222
+ channel_type,
223
+ channel_name,
224
+ channel_levels,
225
+ )
226
+
227
+ async def next_pushed_message(self, dg_listener: DatagramServer) -> Any | None:
228
+ resp = await dg_listener.recv()
229
+ if not resp:
230
+ return None
231
+
232
+ data, (remote_ip, _) = resp
233
+ if remote_ip != self.host:
234
+ return None
235
+
236
+ byte_list = list(data)
237
+ _LOGGER.debug("Received bytes: %s", byte_list)
238
+ message = deserialise_byte_list(byte_list)
239
+ _LOGGER.debug("Deserialised received message as: %s", message)
240
+ return message
241
+
242
+ async def get_cache_state(
243
+ self, cache_type: RequestType = RequestType.SCENE_LEVEL_CACHE
244
+ ) -> Tuple[LevelCache, SceneCache]:
245
+ scene_cache = SceneCache()
246
+ level_cache = LevelCache()
247
+ async with get_dg_commander(self.host, self.port) as dg_client:
248
+ _LOGGER.debug("Requesting cache: %s", cache_type)
249
+ await dg_client.send(bytes([MessageType.QUERY.value, cache_type.value]))
250
+
251
+ while True:
252
+ try:
253
+ data, _ = await asyncio.wait_for(dg_client.recv(), timeout=2.0)
254
+ except asyncio.TimeoutError:
255
+ _LOGGER.warning("Timeout waiting for cache response")
256
+ break
257
+
258
+ response = deserialise_byte_list(list(data))
259
+ if isinstance(response, EOFResponse):
260
+ break
261
+ if isinstance(response, SceneCache):
262
+ scene_cache = response
263
+ if isinstance(response, LevelCache):
264
+ level_cache = response
265
+ _LOGGER.debug("Cache response: %s", response)
266
+
267
+ return level_cache, scene_cache
268
+
269
+ async def set_room_scene(self, room_id: int, scene: int) -> None:
270
+ """Set the scene of a room."""
271
+ await self._bridge_commander.set_room_scene(room_id, scene)
272
+
273
+ async def set_room_brightness(self, room_id: int, brightness: int) -> None:
274
+ """Set the brightness of a room."""
275
+ await self._bridge_commander.set_room_brightness(room_id, brightness)
276
+
277
+ async def set_channel_brightness(
278
+ self, room_id: int, channel_id: int, brightness: int
279
+ ) -> None:
280
+ """Set the brightness of a channel."""
281
+ await self._bridge_commander.set_channel_brightness(
282
+ room_id, channel_id, brightness
283
+ )
python_rako/const.py ADDED
@@ -0,0 +1,59 @@
1
+ from enum import Enum
2
+
3
+ RAKO_BRIDGE_DEFAULT_PORT = 9761
4
+ sentinel = object()
5
+
6
+
7
+ class MessageType(Enum):
8
+ QUERY = ord("Q") # 81
9
+ SCENE_CACHE = ord("C") # 67
10
+ LEVEL_CACHE = ord("X") # 88
11
+ REQUEST = ord("R") # 82
12
+ STATUS = ord("S") # 83
13
+
14
+
15
+ class DataRecordType(Enum):
16
+ DATA = 4
17
+ EOF = 255
18
+
19
+
20
+ class RequestType(Enum):
21
+ SCENE_CACHE = 1
22
+ LEVEL_CACHE = 32
23
+ SCENE_LEVEL_CACHE = 33
24
+
25
+
26
+ class Flags(Enum):
27
+ USE_DEFAULT_FADE_RATE = 1
28
+
29
+
30
+ class CommandType(Enum):
31
+ OFF = 0
32
+ # FADE_UP = 1 # unsupported
33
+ # FADE_DOWN = 2 # unsupported
34
+ SC1_LEGACY = 3
35
+ SC2_LEGACY = 4
36
+ SC3_LEGACY = 5
37
+ SC4_LEGACY = 6
38
+ # IDENT = 8 # unsupported
39
+ LEVEL_SET_LEGACY = 12
40
+ # STORE = 13 # unsupported
41
+ # STOP_FADING = 15 # unsupported
42
+ # CUSTOM_232 = 45 # unsupported
43
+ # HOLIDAY = 47 # unsupported
44
+ SET_SCENE = 49
45
+ # FADE = 50 # unsupported
46
+ SET_LEVEL = 52
47
+
48
+
49
+ COMMAND_SUCCESS_RESPONSE = "AOK"
50
+
51
+
52
+ SCENE_NUMBER_TO_COMMAND = {
53
+ 1: CommandType.SC1_LEGACY,
54
+ 2: CommandType.SC2_LEGACY,
55
+ 3: CommandType.SC3_LEGACY,
56
+ 4: CommandType.SC4_LEGACY,
57
+ 0: CommandType.OFF,
58
+ }
59
+ SCENE_COMMAND_TO_NUMBER = {v: k for k, v in SCENE_NUMBER_TO_COMMAND.items()}
@@ -0,0 +1,2 @@
1
+ class RakoBridgeError(Exception):
2
+ pass
python_rako/helpers.py ADDED
@@ -0,0 +1,204 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from contextlib import asynccontextmanager
5
+ from typing import AsyncIterator
6
+
7
+ import asyncio_dgram
8
+ from asyncio_dgram.aio import DatagramClient, DatagramServer
9
+
10
+ from python_rako.const import (
11
+ SCENE_COMMAND_TO_NUMBER,
12
+ CommandType,
13
+ DataRecordType,
14
+ MessageType,
15
+ sentinel,
16
+ )
17
+ from python_rako.model import (
18
+ ChannelStatusMessage,
19
+ CommandUDP,
20
+ EOFResponse,
21
+ LevelCache,
22
+ LevelCacheItem,
23
+ RoomChannel,
24
+ SceneCache,
25
+ SceneStatusMessage,
26
+ StatusMessage,
27
+ UnsupportedMessage,
28
+ )
29
+
30
+ _LOGGER = logging.getLogger(__name__)
31
+
32
+
33
+ @asynccontextmanager
34
+ async def get_dg_listener(
35
+ port: int, listen_host: str = "0.0.0.0"
36
+ ) -> AsyncIterator[DatagramServer]:
37
+ server: DatagramServer = None
38
+ try:
39
+ server = await asyncio_dgram.bind((listen_host, port))
40
+ yield server
41
+ finally:
42
+ if server:
43
+ server.close()
44
+
45
+
46
+ @asynccontextmanager
47
+ async def get_dg_commander(host: str, port: int) -> AsyncIterator[DatagramClient]:
48
+ client: DatagramClient = None
49
+ try:
50
+ client = await asyncio_dgram.connect((host, port))
51
+ yield client
52
+ finally:
53
+ if client:
54
+ client.close()
55
+
56
+
57
+ def deserialise_byte_list(
58
+ byte_list: list[int],
59
+ ) -> UnsupportedMessage | EOFResponse | StatusMessage | SceneCache | LevelCache:
60
+ try:
61
+ message_type = MessageType(byte_list[0])
62
+ except ValueError:
63
+ _LOGGER.warning("Unsupported UDP message type byte_list=%s", byte_list)
64
+ return UnsupportedMessage()
65
+
66
+ try:
67
+ if message_type == MessageType.STATUS:
68
+ return deserialise_status_message(byte_list)
69
+
70
+ if message_type == MessageType.SCENE_CACHE:
71
+ return deserialise_scene_cache_message(byte_list)
72
+
73
+ if message_type == MessageType.LEVEL_CACHE:
74
+ if byte_list[1] == DataRecordType.EOF.value:
75
+ return EOFResponse()
76
+ if byte_list[1] == DataRecordType.DATA.value:
77
+ return deserialise_level_cache_message(byte_list)
78
+ except (ValueError, KeyError):
79
+ _LOGGER.warning(
80
+ "Unsupported UDP message: message_type=%s, byte_list=%s",
81
+ message_type,
82
+ byte_list,
83
+ )
84
+ return UnsupportedMessage()
85
+
86
+
87
+ def deserialise_status_message(byte_list: list[int]) -> StatusMessage:
88
+ data_length = byte_list[1] - 5
89
+ room = byte_list[2] * 256 + byte_list[3]
90
+ channel = byte_list[4]
91
+ command = CommandType(byte_list[5])
92
+ data = byte_list[6 : 6 + data_length]
93
+ if command in (CommandType.LEVEL_SET_LEGACY, CommandType.SET_LEVEL):
94
+ return ChannelStatusMessage(
95
+ room=room,
96
+ channel=channel,
97
+ brightness=data[1],
98
+ )
99
+
100
+ if command == CommandType.SET_SCENE:
101
+ scene = data[1]
102
+ else:
103
+ # command is one of SC1_LEGACY, SC2_LEGACY, SC3_LEGACY, SC4_LEGACY
104
+ scene = SCENE_COMMAND_TO_NUMBER[command]
105
+
106
+ return SceneStatusMessage(
107
+ room=room,
108
+ channel=channel,
109
+ scene=scene,
110
+ )
111
+
112
+
113
+ def deserialise_level_cache_message(byte_list: list[int]) -> LevelCache:
114
+ scene_cache: dict[RoomChannel, LevelCacheItem] = {}
115
+ it = iter(byte_list)
116
+ next(it) # message type
117
+ for b in it:
118
+ if b != DataRecordType.DATA.value:
119
+ break
120
+ lc = LevelCacheItem(
121
+ next(it), next(it), next(it), {i: next(it) for i in range(1, 18, 1)}
122
+ )
123
+ scene_cache[RoomChannel(lc.room, lc.channel)] = lc
124
+ return LevelCache(scene_cache)
125
+
126
+
127
+ def deserialise_scene_cache_message(byte_list: list[int]) -> SceneCache:
128
+ scene_cache = SceneCache()
129
+ it = iter(byte_list)
130
+ next(it) # message type
131
+ next(it) # undocumented. following bytes?
132
+ for b in it:
133
+ room = next(it, sentinel)
134
+ if room == sentinel:
135
+ continue
136
+ scene_cache[room] = int(b / 4) # type: ignore # pylint: disable=E1137
137
+ return scene_cache
138
+
139
+
140
+ def calc_crc(byte_list: list[int]) -> int:
141
+ return 256 - sum(byte_list) % 256
142
+
143
+
144
+ def command_to_byte_list(command: CommandUDP) -> list[int]:
145
+ checksum_list: list[int] = [
146
+ 5 + len(command.data), # following bytes
147
+ int(command.room / 256), # high room number
148
+ command.room % 256, # low room number
149
+ command.channel, # channel
150
+ command.command.value, # command
151
+ ] + command.data
152
+
153
+ byte_list: list[int] = (
154
+ [
155
+ command.message_type.value,
156
+ ]
157
+ + checksum_list
158
+ + [
159
+ calc_crc(checksum_list),
160
+ ]
161
+ )
162
+
163
+ return byte_list
164
+
165
+
166
+ _scene_brightness = {
167
+ # rako_scene_number: brightness
168
+ 1: 255,
169
+ 2: 192,
170
+ 3: 128,
171
+ 4: 64,
172
+ 0: 0,
173
+ }
174
+
175
+
176
+ def convert_to_brightness(scene_number: int) -> int:
177
+ # scenes can exist outside of 0-4.
178
+ # rather than KeyError, lets return mid-level brightness
179
+ return _scene_brightness.get(scene_number, 128)
180
+
181
+
182
+ _scene_windows = {
183
+ # rako_scene: (brightness_high, brightness_low)
184
+ 1: dict(low=224, high=256), # expect 255 (100%)
185
+ 2: dict(low=160, high=224), # expect 192 (75%)
186
+ 3: dict(low=96, high=160), # expect 128 (50%)
187
+ 4: dict(low=1, high=96), # expect 64 (25%)
188
+ 0: dict(low=0, high=1), # expect 0 (0%)
189
+ }
190
+
191
+
192
+ def convert_to_scene(brightness: int) -> int:
193
+ """
194
+ Return the rako scene of the light.
195
+
196
+ This directly corresponds to the value of the button on the app and is accessed through the
197
+ brightness
198
+ :param brightness: int representing brightness 0-255
199
+ """
200
+
201
+ scene = [
202
+ k for k, v in _scene_windows.items() if v["low"] <= brightness < v["high"]
203
+ ][0]
204
+ return scene
python_rako/model.py ADDED
@@ -0,0 +1,148 @@
1
+ from dataclasses import dataclass
2
+ from typing import Iterable
3
+
4
+ from python_rako.const import CommandType, MessageType
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class RoomChannel:
9
+ room_id: int
10
+ channel_id: int
11
+
12
+
13
+ @dataclass
14
+ class Light:
15
+ room_id: int
16
+ room_title: str
17
+ channel_id: int
18
+
19
+ @property
20
+ def room_channel(self) -> RoomChannel:
21
+ return RoomChannel(self.room_id, self.channel_id)
22
+
23
+
24
+ @dataclass
25
+ class RoomLight(Light):
26
+ channel_id: int = 0
27
+
28
+
29
+ @dataclass
30
+ class ChannelLight(Light):
31
+ channel_type: str
32
+ channel_name: str
33
+ channel_levels: str
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class BridgeInfo:
38
+ version: str
39
+ buildDate: str
40
+ hostName: str
41
+ hostIP: str
42
+ hostMAC: str
43
+ hwStatus: str
44
+ dbVersion: str
45
+ requirepassword: str
46
+ passhash: str
47
+ charset: str
48
+
49
+
50
+ # Message: Bridge to Client
51
+ @dataclass
52
+ class UnsupportedMessage:
53
+ pass
54
+
55
+
56
+ @dataclass
57
+ class EOFResponse:
58
+ pass
59
+
60
+
61
+ @dataclass
62
+ class LevelCacheItem:
63
+ active_deleted_reserved: int
64
+ room: int
65
+ channel: int
66
+ scene_levels: dict[int, int] # scene, level
67
+
68
+
69
+ # pylint: disable=E1101
70
+ class LevelCache(dict[RoomChannel, LevelCacheItem]):
71
+ """dict of: RoomChannel, LevelCacheItem"""
72
+
73
+ def get_channel_level(self, room_channel: RoomChannel, scene: int) -> int:
74
+ level_cache_item = self.get(room_channel)
75
+ if level_cache_item:
76
+ return level_cache_item.scene_levels.get(scene, 0)
77
+ return 0
78
+
79
+ def get_channel_levels(self, room: int, scene: int) -> Iterable[tuple[int, int]]:
80
+ for lci in self.values():
81
+ if lci.room == room:
82
+ brightness = lci.scene_levels.get(scene, 0)
83
+ yield lci.channel, brightness
84
+
85
+
86
+ class SceneCache(dict[int, int]):
87
+ """dict of: room id, scene number"""
88
+
89
+ pass
90
+
91
+
92
+ @dataclass
93
+ class StatusMessage:
94
+ room: int
95
+ channel: int
96
+
97
+
98
+ @dataclass
99
+ class SceneStatusMessage(StatusMessage):
100
+ scene: int
101
+
102
+
103
+ @dataclass
104
+ class ChannelStatusMessage(StatusMessage):
105
+ brightness: int
106
+
107
+
108
+ # Message: Client to Bridge
109
+ @dataclass
110
+ class CommandUDP:
111
+ room: int
112
+ channel: int
113
+ command: CommandType
114
+ data: list[int]
115
+ message_type: MessageType = MessageType.REQUEST
116
+
117
+
118
+ @dataclass
119
+ class CommandHTTP:
120
+ room: int
121
+ channel: int
122
+
123
+ def as_params(self) -> dict[str, int]:
124
+ raise NotImplementedError()
125
+
126
+
127
+ @dataclass
128
+ class CommandSceneHTTP(CommandHTTP):
129
+ scene: int
130
+
131
+ def as_params(self) -> dict[str, int]:
132
+ return {
133
+ "room": self.room,
134
+ "ch": self.channel,
135
+ "sc": self.scene,
136
+ }
137
+
138
+
139
+ @dataclass
140
+ class CommandLevelHTTP(CommandHTTP):
141
+ level: int
142
+
143
+ def as_params(self) -> dict[str, int]:
144
+ return {
145
+ "room": self.room,
146
+ "ch": self.channel,
147
+ "lev": self.level,
148
+ }
python_rako/py.typed ADDED
File without changes
@@ -0,0 +1,174 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-rako-2025
3
+ Version: 0.0.1
4
+ Summary: Asynchronous Python client for Rako Controls Lighting
5
+ Home-page: https://github.com/simonleigh/python-rako
6
+ Author: Simon Leigh
7
+ Author-email: Simon Leigh <simonleigh@users.noreply.github.com>
8
+ Project-URL: Homepage, https://github.com/simonleigh/python-rako
9
+ Project-URL: Repository, https://github.com/simonleigh/python-rako
10
+ Project-URL: Issues, https://github.com/simonleigh/python-rako/issues
11
+ Keywords: rako,controls,api,async,client
12
+ Platform: any
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Natural Language :: English
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: aiohttp>=3.10.0
29
+ Requires-Dist: asyncio-dgram>=2.2.0
30
+ Requires-Dist: xmltodict>=0.13.0
31
+ Dynamic: author
32
+ Dynamic: home-page
33
+ Dynamic: license-file
34
+ Dynamic: platform
35
+ Dynamic: requires-python
36
+
37
+ # Python: Rako Controls API Client
38
+
39
+ [![GitHub Release][releases-shield]][releases]
40
+ ![Project Stage][project-stage-shield]
41
+ ![Project Maintenance][maintenance-shield]
42
+ [![License][license-shield]](LICENSE)
43
+
44
+ [![Build Status][build-shield]][build]
45
+ [![Code Coverage][codecov-shield]][codecov]
46
+ [![Code Quality][code-quality-shield]][code-quality]
47
+
48
+ [![Buy me a coffee][buymeacoffee-shield]][buymeacoffee]
49
+
50
+ Asynchronous Python client for Rako Controls.
51
+
52
+ ## About
53
+
54
+ This package allows you to control and monitor Rako Controls devices
55
+ programmatically. It is mainly created to allow third-party programs to automate
56
+ their behavior.
57
+
58
+ ## Installation
59
+
60
+ ```bash
61
+ pip install python-rako
62
+ ```
63
+
64
+ ## Usage
65
+
66
+ ```python
67
+ import asyncio
68
+
69
+
70
+ async def main():
71
+ # TODO
72
+ pass
73
+
74
+
75
+ if __name__ == "__main__":
76
+ loop = asyncio.get_event_loop()
77
+ loop.run_until_complete(main())
78
+ ```
79
+
80
+ ## Changelog & Releases
81
+
82
+ This repository keeps a change log using [GitHub's releases][releases]
83
+ functionality. The format of the log is based on
84
+ [Keep a Changelog][keepchangelog].
85
+
86
+ Releases are based on [Semantic Versioning][semver], and use the format
87
+ of ``MAJOR.MINOR.PATCH``. In a nutshell, the version will be incremented
88
+ based on the following:
89
+
90
+ - ``MAJOR``: Incompatible or major changes.
91
+ - ``MINOR``: Backwards-compatible new features and enhancements.
92
+ - ``PATCH``: Backwards-compatible bugfixes and package updates.
93
+
94
+ ## Contributing
95
+
96
+ This is an active open-source project. We are always open to people who want to
97
+ use the code or contribute to it.
98
+
99
+ We've set up a separate document for our
100
+ [contribution guidelines](CONTRIBUTING.md).
101
+
102
+ Thank you for being involved! :heart_eyes:
103
+
104
+ ## Setting up development environment
105
+
106
+ In case you'd like to contribute, a `Makefile` has been included to ensure a
107
+ quick start.
108
+
109
+ ```bash
110
+ make venv
111
+ source ./venv/bin/activate
112
+ make dev
113
+ ```
114
+
115
+ Now you can start developing, run `make` without arguments to get an overview
116
+ of all make goals that are available (including description):
117
+
118
+ ```bash
119
+ $ make
120
+ Asynchronous Python client for Rako Controls Lighting.
121
+
122
+ Usage:
123
+ make help Shows this message.
124
+ make dev Set up a development environment.
125
+ make lint Run all linters.
126
+ make lint-black Run linting using black & blacken-docs.
127
+ make lint-flake8 Run linting using flake8 (pycodestyle/pydocstyle).
128
+ make lint-pylint Run linting using PyLint.
129
+ make lint-mypy Run linting using MyPy.
130
+ make test Run tests quickly with the default Python.
131
+ make coverage Check code coverage quickly with the default Python.
132
+ make install Install the package to the active Python's site-packages.
133
+ make clean Removes build, test, coverage and Python artifacts.
134
+ make clean-all Removes all venv, build, test, coverage and Python artifacts.
135
+ make clean-build Removes build artifacts.
136
+ make clean-pyc Removes Python file artifacts.
137
+ make clean-test Removes test and coverage artifacts.
138
+ make clean-venv Removes Python virtual environment artifacts.
139
+ make dist Builds source and wheel package.
140
+ make release Release build on PyP
141
+ make venv Create Python venv environment.
142
+ ```
143
+
144
+ ## Authors & contributors
145
+
146
+ The original setup of this repository is by [Ben Marengo][marengaz].
147
+
148
+ For a full list of all authors and contributors,
149
+ check [the contributor's page][contributors].
150
+
151
+ ## License
152
+
153
+ [License](LICENSE)
154
+
155
+ [build-shield]: https://github.com/marengaz/python-rako/workflows/Continuous%20Integration/badge.svg
156
+ [build]: https://github.com/marengaz/python-rako/actions
157
+ [code-quality-shield]: https://img.shields.io/lgtm/grade/python/g/marengaz/python-rako.svg?logo=lgtm&logoWidth=18
158
+ [code-quality]: https://lgtm.com/projects/g/marengaz/python-rako/context:python
159
+ [codecov-shield]: https://codecov.io/gh/marengaz/python-rako/branch/master/graph/badge.svg
160
+ [codecov]: https://codecov.io/gh/marengaz/python-rako
161
+ [contributors]: https://github.com/marengaz/python-rako/graphs/contributors
162
+ [marengaz]: https://github.com/marengaz
163
+ [keepchangelog]: http://keepachangelog.com/en/1.0.0/
164
+ [license-shield]: https://img.shields.io/github/license/marengaz/python-rako.svg
165
+ [maintenance-shield]: https://img.shields.io/maintenance/yes/2021.svg
166
+ [project-stage-shield]: https://img.shields.io/badge/project%20stage-experimental-yellow.svg
167
+ [releases-shield]: https://img.shields.io/github/release/marengaz/python-rako.svg
168
+ [releases]: https://github.com/marengaz/python-rako/releases
169
+ [semver]: http://semver.org/spec/v2.0.0.html
170
+
171
+ [buymeacoffee-shield]: https://www.buymeacoffee.com/assets/img/guidelines/download-assets-sm-2.svg
172
+ [buymeacoffee]: https://www.buymeacoffee.com/marengaz
173
+ [github-actions-shield]: https://github.com/marengaz/rakomqtt/workflows/Test%20RakoMQTT/badge.svg?branch=master
174
+ [github-actions]: https://github.com/marengaz/rakomqtt/actions?query=workflow%3A%22Test+RakoMQTT%22+branch%3Amaster
@@ -0,0 +1,13 @@
1
+ python_rako/__init__.py,sha256=VC4yyKBNaSrEMEOnUFvjo5UtecfAejNfEVuv_RQcbRU,1652
2
+ python_rako/__version__.py,sha256=HXn4hD8lyXkcmi-Ih0aF7rC1emgHC1se2G9_NxE9GpY,54
3
+ python_rako/bridge.py,sha256=u2noCdFzlALB4MR_xxia-iUY8g5lXv7xsPKBOYbcG8c,9779
4
+ python_rako/const.py,sha256=PO-MEmq8Q6G_Mhv-8UAcdj-LM0dXdFZdR14Qqd88DQg,1197
5
+ python_rako/exceptions.py,sha256=VfpEV7yHM3EWA3Z9hSMr2LdhNnxs3NdjoN0OxHRteJ0,43
6
+ python_rako/helpers.py,sha256=LTKvOo9gVU11Kym2G5j35si9yURb5AFMIweZHbHqzt4,5599
7
+ python_rako/model.py,sha256=EnZbJmJeyzkOtqkpEI5eOZzKFSxvjcycMib6WtQGmX4,2772
8
+ python_rako/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ python_rako_2025-0.0.1.dist-info/licenses/LICENSE,sha256=BU3YBlT_uVhhi08vzf1BVhardfVKviv-7Z-avAvSfx0,1068
10
+ python_rako_2025-0.0.1.dist-info/METADATA,sha256=5xG4gYzD-00UMHnXt9KypHdSsh6xQ7Qp4IXTEuJ5huM,6587
11
+ python_rako_2025-0.0.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
12
+ python_rako_2025-0.0.1.dist-info/top_level.txt,sha256=H8L2l0YJulkcvNu1s0hPBHlMohbeOpsGo8MD6sZo764,12
13
+ python_rako_2025-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Ben Marengo
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.
@@ -0,0 +1 @@
1
+ python_rako