HueBLE 2.3.0__tar.gz → 2.4.1__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.
@@ -0,0 +1,46 @@
1
+ # Copyright (c) 2026 Harvey Lelliott
2
+ # SPDX-License-Identifier: MIT
3
+ """
4
+ HueBLE module.
5
+
6
+ .. moduleauthor:: Harvey Lelliott (flip-dots) <harveylelliott@duck.com>
7
+
8
+ """
9
+
10
+ from .constructs import EffectType
11
+ from .exceptions import (
12
+ CallbackError,
13
+ ConnectionError, # noqa: A004
14
+ HueBleError,
15
+ InitialConnectionError,
16
+ NotConnectedError,
17
+ PairingError,
18
+ ReadError,
19
+ ReadWriteError,
20
+ ServiceDiscoveryError,
21
+ ServicesError,
22
+ ServiceSubscriptionError,
23
+ TimeoutError, # noqa: A004
24
+ WriteError,
25
+ )
26
+ from .light import HueBleLight
27
+ from .scan import discover_lights
28
+
29
+ __all__ = [
30
+ "CallbackError",
31
+ "ConnectionError",
32
+ "EffectType",
33
+ "HueBleError",
34
+ "HueBleLight",
35
+ "InitialConnectionError",
36
+ "NotConnectedError",
37
+ "PairingError",
38
+ "ReadError",
39
+ "ReadWriteError",
40
+ "ServiceDiscoveryError",
41
+ "ServiceSubscriptionError",
42
+ "ServicesError",
43
+ "TimeoutError",
44
+ "WriteError",
45
+ "discover_lights",
46
+ ]
@@ -0,0 +1,108 @@
1
+ # Copyright (c) 2026 Harvey Lelliott
2
+ # SPDX-License-Identifier: MIT
3
+ """
4
+ Constants for HueBLE module.
5
+
6
+ .. moduleauthor:: Harvey Lelliott (flip-dots) <harveylelliott@duck.com>
7
+
8
+ """
9
+
10
+ #: String containing manufacturer. Handle 15.
11
+ UUID_MANUFACTURER = "00002a29-0000-1000-8000-00805f9b34fb"
12
+
13
+ #: String containing model number. Handle 17
14
+ UUID_MODEL = "00002a24-0000-1000-8000-00805f9b34fb"
15
+
16
+ #: String containing firmware version. Handle 19.
17
+ UUID_FW_VERSION = "00002a28-0000-1000-8000-00805f9b34fb"
18
+
19
+ #: String containing Zigbee address. Handle 22.
20
+ UUID_ZIGBEE_ADDRESS = "97fe6561-0001-4f62-86e9-b71ee2da3d22"
21
+
22
+ #: String containing light name. Handle 24
23
+ UUID_NAME = "97fe6561-0003-4f62-86e9-b71ee2da3d22"
24
+
25
+ #: Power state of light. Is subscribable. x00 and x01. Handle 49.
26
+ UUID_POWER = "932c32bd-0002-47a2-835a-a8d455b859dd"
27
+
28
+ #: Brightness of light. Int 0-255. Handle 52.
29
+ UUID_BRIGHTNESS = "932c32bd-0003-47a2-835a-a8d455b859dd"
30
+
31
+ #: Temperature of light. Int 153-500. 0xFFFF when colour enabled. Handle 55.
32
+ UUID_TEMPERATURE = "932c32bd-0004-47a2-835a-a8d455b859dd"
33
+
34
+ #: XY colour of light. Two 16-bit ints. 0xFFFFFFFF when CW/WW. Handle 58.
35
+ UUID_XY_COLOUR = "932c32bd-0005-47a2-835a-a8d455b859dd"
36
+
37
+ #: Colour change and effect endpoint. Uses TLV.
38
+ UUID_EFFECTS = "932c32bd-0007-47a2-835a-a8d455b859dd"
39
+
40
+ # UUID for capability information of the light (e.g min/max colour temp). Uses TLV.
41
+ UUID_CAPABILITY = "932c32bd-0001-47a2-835a-a8d455b859dd"
42
+
43
+ #: This is a UUID that as far as I know only hue lights use and it shows up
44
+ #: under BLE Device details and as such does not require connecting to check
45
+ #: for. The UUID also has the following service data. I am not sure what it
46
+ #: means but it is the same for both of my colour lights with model no LCA006.
47
+ #: \x02\x10\x0e\xbe\x02
48
+ UUID_HUE_IDENTIFIER = "0000fe0f-0000-1000-8000-00805f9b34fb"
49
+
50
+ #: The assumed minimum colour temperature of the light in mireds.
51
+ #: Constant as it us unknown if/where the light exposes this data.
52
+ MIN_MIREDS = 153
53
+
54
+ #: The assumed maximum colour temperature of the light in mireds.
55
+ #: Constant as it us unknown if/where the light exposes this data.
56
+ MAX_MIREDS = 500
57
+
58
+ #: Default max connection attempts in the connect function.
59
+ DEFAULT_CONNECTION_ATTEMPTS_MAX = 3
60
+
61
+ #: Default max time for all connection attempts in connect function.
62
+ DEFAULT_CONNECTION_TIMEOUT = 30
63
+
64
+ #: Default max time before a call to connect times out waiting for
65
+ #: another call to connect to finish its attempt.
66
+ DEFAULT_CONNECTION_WAIT_TIMEOUT = 120
67
+
68
+ #: Default of if making a successful connection to the light triggers
69
+ #: callbacks to be run.
70
+ DEFAULT_ON_CONNECT_RUN_CALLBACKS = True
71
+
72
+ #: Default time to wait for a pairing request to complete.
73
+ DEFAULT_PAIR_TIMEOUT = 15
74
+
75
+ #: Default max time before a call to poll state times out.
76
+ DEFAULT_POLL_STATE_TIMEOUT = 45
77
+
78
+ #: Default of if callbacks should be executed on a call to poll_state
79
+ #: where the state changed.
80
+ DEFAULT_POLL_STATE_CALLBACKS_IF_CHANGED = True
81
+
82
+ #: Default max time before a single read attempt to the light times out and it
83
+ #: will try again. This must be large enough to allow for a connection attempt
84
+ #: if the light is not already connected.
85
+ DEFAULT_READ_GATT_TIMEOUT = 20
86
+
87
+ #: Default max light read attempts before raising an exception.
88
+ DEFAULT_READ_GATT_MAX_ATTEMPTS = 3
89
+
90
+ #: Default max time before a single write attempt to the light times out and it
91
+ #: will try again. This must be large enough to allow for a connection attempt
92
+ #: if the light is not already connected.
93
+ DEFAULT_WRITE_GATT_TIMEOUT = 20
94
+
95
+ #: Default max light write attempts before raising an exception.
96
+ DEFAULT_WRITE_GATT_MAX_ATTEMPTS = 3
97
+
98
+ #: Default of all polls to the light updating the light objects internal state.
99
+ DEFAULT_POLL_WRITES_STATE = True
100
+
101
+ #: Default amount of time to scan for a light for in the discovery method.
102
+ DEFAULT_DISCOVER_TIME = 5
103
+
104
+ #: Default time to wait in the reconnect method between connecting and disconnecting.
105
+ DEFAULT_RECONNECT_DELAY = 3
106
+
107
+ #: Maximum amount of automatic reconnection attempts the program will make.
108
+ DEFAULT_MAX_RECONNECT_ATTEMPTS = -1
@@ -0,0 +1,19 @@
1
+ # Copyright (c) 2026 Harvey Lelliott
2
+ # SPDX-License-Identifier: MIT
3
+ """
4
+ Constructs of HueBLE module.
5
+
6
+ .. moduleauthor:: Harvey Lelliott (flip-dots) <harveylelliott@duck.com>
7
+
8
+ """
9
+
10
+ from .capability import TLV_CAPABILITY, CapabilityTLVTag
11
+ from .effects import TLV_EFFECT, EffectTLVTag, EffectType
12
+
13
+ __all__ = [
14
+ "TLV_CAPABILITY",
15
+ "TLV_EFFECT",
16
+ "CapabilityTLVTag",
17
+ "EffectTLVTag",
18
+ "EffectType",
19
+ ]
@@ -0,0 +1,62 @@
1
+ # Copyright (c) 2026 Harvey Lelliott
2
+ # SPDX-License-Identifier: MIT
3
+ """
4
+ Control constructs for HueBLE module.
5
+
6
+ .. moduleauthor:: Harvey Lelliott (flip-dots) <harveylelliott@duck.com>
7
+
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from enum import IntEnum
13
+
14
+ from construct import (
15
+ Enum as ConstructEnum,
16
+ )
17
+ from construct import (
18
+ ExprAdapter,
19
+ GreedyBytes,
20
+ GreedyRange,
21
+ Int8ul,
22
+ Int16ul,
23
+ Prefixed,
24
+ Struct,
25
+ Switch,
26
+ )
27
+
28
+ from .common import TLVListContainer
29
+
30
+
31
+ class CapabilityTLVTag(IntEnum):
32
+ """
33
+ The TLV tag in Hue capability messages which specifies what data the value contains.
34
+ """
35
+
36
+ MINIMUM_COLOUR_TEMP = 1
37
+ MAXIMUM_COLOUR_TEMP = 2
38
+
39
+
40
+ """The TLV construct for capability API messages made up of a list of TLVs."""
41
+ TLV_CAPABILITY = ExprAdapter(
42
+ GreedyRange(
43
+ Struct(
44
+ "tag" / ConstructEnum(Int8ul, CapabilityTLVTag),
45
+ "value"
46
+ / Prefixed(
47
+ Int8ul,
48
+ Switch(
49
+ lambda ctx: int(ctx.tag),
50
+ {
51
+ CapabilityTLVTag.MINIMUM_COLOUR_TEMP: Int16ul,
52
+ CapabilityTLVTag.MAXIMUM_COLOUR_TEMP: Int16ul,
53
+ },
54
+ default=GreedyBytes,
55
+ ),
56
+ ),
57
+ ),
58
+ ),
59
+ # Wrap the parsed list in custom container for tag lookup and debug logging
60
+ decoder=lambda obj, _: TLVListContainer(obj),
61
+ encoder=lambda obj, _: obj,
62
+ )
@@ -0,0 +1,26 @@
1
+ # Copyright (c) 2026 Harvey Lelliott
2
+ # SPDX-License-Identifier: MIT
3
+ """
4
+ Common construct helpers of HueBLE module.
5
+
6
+ .. moduleauthor:: Harvey Lelliott (flip-dots) <harveylelliott@duck.com>
7
+
8
+ """
9
+
10
+ from enum import IntEnum
11
+ from typing import Any
12
+
13
+ from construct import ListContainer
14
+
15
+
16
+ class TLVListContainer(ListContainer):
17
+ """
18
+ Container of TLV values to allow for dictionary-like access.
19
+ """
20
+
21
+ def get(self, key: IntEnum) -> Any | None: # noqa: ANN401
22
+ """Return the value of the TLV tag or None if not present."""
23
+ for item in self:
24
+ if int(item.tag) == key.value:
25
+ return item.value
26
+ return None
@@ -0,0 +1,121 @@
1
+ # Copyright (c) 2026 Harvey Lelliott
2
+ # SPDX-License-Identifier: MIT
3
+ """
4
+ Effect data constructs for HueBLE module.
5
+
6
+ .. moduleauthor:: Harvey Lelliott (flip-dots) <harveylelliott@duck.com>
7
+
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ from enum import IntEnum
14
+
15
+ from construct import (
16
+ Container,
17
+ ExprAdapter,
18
+ Flag,
19
+ GreedyBytes,
20
+ GreedyRange,
21
+ Int8ul,
22
+ Int16ul,
23
+ Prefixed,
24
+ Struct,
25
+ Switch,
26
+ )
27
+ from construct import (
28
+ Enum as ConstructEnum,
29
+ )
30
+
31
+ from .common import TLVListContainer
32
+
33
+ _LOGGER = logging.getLogger(__name__)
34
+
35
+
36
+ class EffectType(IntEnum):
37
+ """
38
+ The effects supported by Hue lights.
39
+ """
40
+
41
+ NONE = 0
42
+ CANDLE = 1
43
+ FIREPLACE = 2
44
+ PRISM = 3
45
+ SUNRISE = 9
46
+ SPARKLE = 10
47
+ OPAL = 11
48
+ GLISTEN = 12
49
+ SUNSET = 13
50
+ UNDERWATER = 14
51
+ COSMOS = 15
52
+ SUNBEAM = 16
53
+ ENCHANT = 17
54
+
55
+ @classmethod
56
+ def _missing_(cls, value: object) -> EffectType:
57
+ """Return default value when effect unknown.."""
58
+ _LOGGER.warning(
59
+ f"Unknown effect type: '{value}' reported by light, using default of none!",
60
+ )
61
+ return cls.NONE
62
+
63
+
64
+ class EffectTLVTag(IntEnum):
65
+ """
66
+ The TLV tag in Hue effect API messages which specifies what data the value contains.
67
+ """
68
+
69
+ ON_OFF = 1
70
+ BRIGHTNESS = 2
71
+ COLOUR_TEMP = 3
72
+ COLOUR_XY = 4
73
+ TRANSITION = 5
74
+ EFFECT_TYPE = 6
75
+ EFFECT_SPEED = 8
76
+
77
+
78
+ """The TLV construct for effect API messages made up of a list of TLVs."""
79
+ TLV_EFFECT = ExprAdapter(
80
+ GreedyRange(
81
+ Struct(
82
+ "tag" / ConstructEnum(Int8ul, EffectTLVTag),
83
+ "value"
84
+ / Prefixed(
85
+ Int8ul,
86
+ Switch(
87
+ lambda ctx: int(ctx.tag),
88
+ {
89
+ EffectTLVTag.ON_OFF: Flag,
90
+ EffectTLVTag.BRIGHTNESS: Int8ul,
91
+ EffectTLVTag.COLOUR_TEMP: Int16ul,
92
+ EffectTLVTag.COLOUR_XY: ExprAdapter(
93
+ Struct("x" / Int16ul, "y" / Int16ul),
94
+ decoder=lambda c, _: (c["x"] / 0xFFFF, c["y"] / 0xFFFF),
95
+ encoder=lambda v, _: Container(
96
+ x=int(v[0] * 0xFFFF),
97
+ y=int(v[1] * 0xFFFF),
98
+ ),
99
+ ),
100
+ EffectTLVTag.TRANSITION: Int16ul,
101
+ EffectTLVTag.EFFECT_TYPE: ExprAdapter(
102
+ Int8ul,
103
+ decoder=lambda val, _: EffectType(val),
104
+ encoder=lambda obj, _: int(obj),
105
+ ),
106
+ EffectTLVTag.EFFECT_SPEED: Int8ul,
107
+ },
108
+ default=GreedyBytes,
109
+ ),
110
+ ),
111
+ ),
112
+ ),
113
+ # Wrap the parsed list in custom container for tag lookup and debug logging
114
+ decoder=lambda obj, _: TLVListContainer(obj),
115
+ # Use encoder to allow for building messages flat
116
+ encoder=lambda obj, _: (
117
+ [{"tag": k, "value": v} for k, v in sorted(obj.items())]
118
+ if isinstance(obj, dict)
119
+ else obj
120
+ ),
121
+ )
@@ -0,0 +1,186 @@
1
+ # Copyright (c) 2026 Harvey Lelliott
2
+ # SPDX-License-Identifier: MIT
3
+ """
4
+ Exceptions for HueBLE module.
5
+
6
+ .. moduleauthor:: Harvey Lelliott (flip-dots) <harveylelliott@duck.com>
7
+
8
+ """
9
+
10
+ from collections.abc import Callable
11
+
12
+ from bleak.backends.device import BLEDevice
13
+
14
+
15
+ class HueBleError(Exception):
16
+ """
17
+ Base exception of HueBLE.
18
+ """
19
+
20
+
21
+ class ConnectionError(HueBleError): # noqa: A001
22
+ """
23
+ Exception raised when connecting to a device fails.
24
+ """
25
+
26
+ def __init__(self, device: BLEDevice, error: Exception) -> None:
27
+ """Return new :exc:`~HueBLE.ConnectionError`."""
28
+ self.device = device
29
+ self.error = error
30
+ message = (
31
+ "Exception connecting to device "
32
+ f"'{device.name} ({device.address})'. "
33
+ f"E: '{error}'."
34
+ )
35
+ super().__init__(message)
36
+
37
+
38
+ class InitialConnectionError(HueBleError):
39
+ """
40
+ Exception raised when the initial pre-pair pre-communication connect call fails.
41
+ """
42
+
43
+ def __init__(self, device: BLEDevice, error: Exception) -> None:
44
+ """Return new :exc:`~HueBLE.InitialConnectionError`."""
45
+ self.device = device
46
+ self.error = error
47
+ message = (
48
+ "Failed to make an initial connection to the device "
49
+ f"'{device.name} ({device.address})'. "
50
+ f"E: '{error}'."
51
+ )
52
+ super().__init__(message)
53
+
54
+
55
+ class PairingError(HueBleError):
56
+ """
57
+ Exception raised when pairing to a device fails.
58
+ """
59
+
60
+
61
+ class TimeoutError(HueBleError): # noqa: A001
62
+ """
63
+ Exception raised when an operation timed out.
64
+ """
65
+
66
+
67
+ class NotConnectedError(HueBleError):
68
+ """
69
+ Exception raised when not connected to the device for something which requires it.
70
+ """
71
+
72
+
73
+ class ReadWriteError(HueBleError):
74
+ """
75
+ Exception raised when reading or writing a GATT attribute fails.
76
+ """
77
+
78
+
79
+ class ReadError(ReadWriteError):
80
+ """
81
+ Exception raised when reading a GATT attribute fails.
82
+ """
83
+
84
+ def __init__(
85
+ self,
86
+ device: BLEDevice,
87
+ address: str,
88
+ attempt: int,
89
+ error: Exception | None,
90
+ ) -> None:
91
+ """Return new :exc:`~HueBLE.ReadError`."""
92
+ self.device = device
93
+ self.address = address
94
+ self.attempt = attempt
95
+ self.error = error
96
+ message = (
97
+ f"Failed to read '{address}' from "
98
+ f"'{device.name} ({device.address})' after "
99
+ f"{attempt} attempts. E: '{error}'."
100
+ )
101
+ super().__init__(message)
102
+
103
+
104
+ class WriteError(ReadWriteError):
105
+ """
106
+ Exception raised when writing a GATT attribute fails.
107
+ """
108
+
109
+ def __init__(
110
+ self,
111
+ device: BLEDevice,
112
+ address: str,
113
+ data: bytes,
114
+ attempt: int,
115
+ error: Exception | None,
116
+ ) -> None:
117
+ """Return new :exc:`~HueBLE.WriteError`."""
118
+ self.device = device
119
+ self.address = address
120
+ self.data = data
121
+ self.attempt = attempt
122
+ self.error = error
123
+ message = (
124
+ f"Failed to write '{data.hex()}' at '{address}' to "
125
+ f"'{device.name} ({device.address})' after "
126
+ f"{attempt} attempts. E: '{error}'."
127
+ )
128
+ super().__init__(message)
129
+
130
+
131
+ class ServicesError(HueBleError):
132
+ """
133
+ Exception raised when service discovery/subscription fails.
134
+ """
135
+
136
+
137
+ class ServiceDiscoveryError(ServicesError):
138
+ """
139
+ Exception raised when service discovery fails.
140
+ """
141
+
142
+ def __init__(self, device: BLEDevice, error: Exception) -> None:
143
+ """Return new :exc:`~HueBLE.ServiceDiscoveryError`."""
144
+ self.device = device
145
+ self.error = error
146
+ message = (
147
+ "Failed to determine what services the device "
148
+ f"'{device.name} ({device.address})' offers. "
149
+ f"E: '{error}'."
150
+ )
151
+ super().__init__(message)
152
+
153
+
154
+ class ServiceSubscriptionError(ServicesError):
155
+ """
156
+ Exception raised when service subscription fails.
157
+ """
158
+
159
+ def __init__(self, device: BLEDevice, error: Exception) -> None:
160
+ """Return new :exc:`~HueBLE.ServiceSubscriptionError`."""
161
+ self.device = device
162
+ self.error = error
163
+ message = (
164
+ "Failed to subscribe to services offered by the device "
165
+ f"'{device.name} ({device.address})'. "
166
+ f"E: '{error}'."
167
+ )
168
+ super().__init__(message)
169
+
170
+
171
+ class CallbackError(HueBleError):
172
+ """
173
+ Exception raised when a callback raises an error.
174
+ """
175
+
176
+ def __init__(self, device: BLEDevice, function: Callable, error: Exception) -> None:
177
+ """Return new :exc:`~HueBLE.CallbackError`."""
178
+ self.device = device
179
+ self.function = function
180
+ self.error = error
181
+ message = (
182
+ "Exception executing state changed callback on "
183
+ f"'{device.name} ({device.address})'. "
184
+ f"Function: '{function.__name__}'. E: '{error}'."
185
+ )
186
+ super().__init__(message)