High-Level API¶
The high-level API provides simplified functions for common LIFX operations. These are the recommended entry points for most users.
Discovery Functions¶
All discovery functions return devices whose state has not been initialised
yet — async with device does that. Devices start with fetch_wifi_info and
fetch_ambient_light off, so set either property before entering the context
manager for the reading to be included in the initial state. See
Opt-In State Fields on Discovered Devices.
discover
async
¶
discover(
timeout: float = DISCOVERY_TIMEOUT,
broadcast_address: str = "255.255.255.255",
port: int = LIFX_UDP_PORT,
max_response_time: float = MAX_RESPONSE_TIME,
idle_timeout_multiplier: float = IDLE_TIMEOUT_MULTIPLIER,
device_timeout: float = DEFAULT_REQUEST_TIMEOUT,
max_retries: int | None = DEFAULT_MAX_RETRIES,
known_devices: Iterable[Device] | None = None,
) -> AsyncGenerator[Device, None]
Discover LIFX devices and yield them as they are found.
| PARAMETER | DESCRIPTION |
|---|---|
timeout
|
Discovery timeout in seconds (default 15.0)
TYPE:
|
broadcast_address
|
Broadcast address to use (default "255.255.255.255")
TYPE:
|
port
|
Port to use (default LIFX_UDP_PORT)
TYPE:
|
max_response_time
|
Max time to wait for responses
TYPE:
|
idle_timeout_multiplier
|
Idle timeout multiplier
TYPE:
|
device_timeout
|
request timeout set on discovered devices
TYPE:
|
max_retries
|
max retries per request set on discovered devices
TYPE:
|
known_devices
|
device objects you already hold. A discovery result
whose serial matches one of them moves that object to the
reported address (see |
| YIELDS | DESCRIPTION |
|---|---|
AsyncGenerator[Device, None]
|
Device instances as they are discovered |
Note
Internal device-class construction errors are logged and isolated to that responder so the remaining discovery sweep can continue.
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
LifxNetworkError
|
If the validated destination cannot be resolved to a native socket address or the discovery transport fails. |
Example
Source code in src/lifx/api.py
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 | |
discover_mdns
async
¶
discover_mdns(
timeout: float = DISCOVERY_TIMEOUT,
max_response_time: float = MAX_RESPONSE_TIME,
idle_timeout_multiplier: float = IDLE_TIMEOUT_MULTIPLIER,
device_timeout: float = DEFAULT_REQUEST_TIMEOUT,
max_retries: int | None = DEFAULT_MAX_RETRIES,
known_devices: Iterable[Device] | None = None,
) -> AsyncGenerator[Device, None]
Discover LIFX devices via mDNS and yield them as they are found.
Uses mDNS/DNS-SD discovery with the _lifx._udp.local service type. Device type metadata in DNS-SD responses avoids a separate LIFX product query for every device.
The IPv4 multicast query is sent from an ephemeral source port and the transport accepts legacy-unicast replies addressed directly to that socket. It does not join the multicast group and does not receive unsolicited announcements. Each call observes direct traffic delivered to its per-call socket during the sweep and has its own non-reusable discovery cache, but it does not authenticate or correlate responders with outstanding queries. An mDNS result proves an advertisement exists, not that the device is currently reachable; see the discovery guide's Limitations section for detail, including how discover()'s mDNS candidates verify reachability with a correlated device request.
Each yielded device reports connectivity from its mDNS TXT record:
Connectivity.THREAD only after an exact positive Thread report, and
Connectivity.WIFI for every other construction or discovery outcome.
Once the device answers any request, its own frame address report
supersedes this in both directions. This descriptive value does not
authenticate the device or change its routing, retry, or tuning
behaviour.
| PARAMETER | DESCRIPTION |
|---|---|
timeout
|
Discovery timeout in seconds (default 15.0)
TYPE:
|
max_response_time
|
Max time to wait for responses
TYPE:
|
idle_timeout_multiplier
|
Idle timeout multiplier
TYPE:
|
device_timeout
|
request timeout set on discovered devices
TYPE:
|
max_retries
|
max retries per request set on discovered devices
TYPE:
|
known_devices
|
device objects you already hold. A discovery result
whose serial matches one of them moves that object to the
reported address (see |
| YIELDS | DESCRIPTION |
|---|---|
AsyncGenerator[Device, None]
|
Device instances (Light, MatrixLight, MultiZoneLight, etc.) |
AsyncGenerator[Device, None]
|
as they are discovered |
Example
Source code in src/lifx/api.py
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 | |
find_by_serial
async
¶
find_by_serial(
serial: str,
timeout: float = DISCOVERY_TIMEOUT,
broadcast_address: str = "255.255.255.255",
port: int = LIFX_UDP_PORT,
max_response_time: float = MAX_RESPONSE_TIME,
idle_timeout_multiplier: float = IDLE_TIMEOUT_MULTIPLIER,
device_timeout: float = DEFAULT_REQUEST_TIMEOUT,
max_retries: int | None = DEFAULT_MAX_RETRIES,
device: Device | None = None,
) -> Device | None
Find a specific device by serial number.
| PARAMETER | DESCRIPTION |
|---|---|
serial
|
Serial number as hex string (with or without separators)
TYPE:
|
timeout
|
Discovery timeout in seconds (default DISCOVERY_TIMEOUT)
TYPE:
|
broadcast_address
|
Broadcast address to use (default "255.255.255.255")
TYPE:
|
port
|
Port to use (default LIFX_UDP_PORT)
TYPE:
|
max_response_time
|
Max time to wait for responses
TYPE:
|
idle_timeout_multiplier
|
Idle timeout multiplier
TYPE:
|
device_timeout
|
request timeout set on discovered device
TYPE:
|
max_retries
|
max retries per request set on discovered device
TYPE:
|
device
|
an existing device object for this serial. If the serial is
found at a different address, that object is moved there (see
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Device | None
|
Device instance if found, None otherwise |
Note
Internal device-class construction errors are logged and return
None rather than escaping this lookup.
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
LifxNetworkError
|
If the validated destination cannot be resolved to a native socket address or the discovery transport fails. |
Example
Source code in src/lifx/api.py
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 | |
find_by_label
async
¶
find_by_label(
label: str,
exact_match: bool = False,
timeout: float = DISCOVERY_TIMEOUT,
broadcast_address: str = "255.255.255.255",
port: int = LIFX_UDP_PORT,
max_response_time: float = MAX_RESPONSE_TIME,
idle_timeout_multiplier: float = IDLE_TIMEOUT_MULTIPLIER,
device_timeout: float = DEFAULT_REQUEST_TIMEOUT,
max_retries: int | None = DEFAULT_MAX_RETRIES,
) -> AsyncGenerator[Device]
Find LIFX devices by label (name).
Uses a protocol trick by broadcasting GetLabel instead of GetService, which returns all device labels in StateLabel responses. This is more efficient than querying each device individually.
| PARAMETER | DESCRIPTION |
|---|---|
label
|
Device label to search for (case-insensitive)
TYPE:
|
exact_match
|
If True, match label exactly and yield at most one device; if False, match substring and yield all matching devices (default False)
TYPE:
|
timeout
|
Discovery timeout in seconds (default DISCOVERY_TIMEOUT)
TYPE:
|
broadcast_address
|
Broadcast address to use (default "255.255.255.255")
TYPE:
|
port
|
Port to use (default LIFX_UDP_PORT)
TYPE:
|
max_response_time
|
Max time to wait for responses
TYPE:
|
idle_timeout_multiplier
|
Idle timeout multiplier
TYPE:
|
device_timeout
|
request timeout set on discovered device(s)
TYPE:
|
max_retries
|
max retries per request set on discovered device(s)
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
AsyncGenerator[Device]
|
Matching Device instance(s) |
Note
Internal device-class construction errors are logged and isolated to that responder so remaining matches can still be yielded.
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
LifxNetworkError
|
If the validated destination cannot be resolved to a native socket address or the discovery transport fails. |
Example
# Find all devices with "Living" in the label
async for device in find_by_label("Living"):
async with device:
await device.set_power(True)
# Find device by exact label match (yields at most one)
async for device in find_by_label("Living Room", exact_match=True):
async with device:
await device.set_power(True)
Source code in src/lifx/api.py
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 | |
find_by_ip
async
¶
find_by_ip(
ip: str,
timeout: float = DISCOVERY_TIMEOUT,
port: int = LIFX_UDP_PORT,
max_response_time: float = MAX_RESPONSE_TIME,
idle_timeout_multiplier: float = IDLE_TIMEOUT_MULTIPLIER,
device_timeout: float = DEFAULT_REQUEST_TIMEOUT,
max_retries: int | None = DEFAULT_MAX_RETRIES,
) -> Device | None
Find a LIFX device by IP address.
Uses targeted discovery by sending the request to the validated IPv4 or IPv6 literal, which means only that device will respond (if it exists). Zoned IPv6 link-local literals are supported when they include their interface identifier. This is more efficient than broadcasting to all devices and filtering.
| PARAMETER | DESCRIPTION |
|---|---|
ip
|
Validated IPv4 or IPv6 device address literal, including a zoned link-local IPv6 literal
TYPE:
|
timeout
|
Discovery timeout in seconds (default DISCOVERY_TIMEOUT)
TYPE:
|
port
|
Port to use (default LIFX_UDP_PORT)
TYPE:
|
max_response_time
|
Max time to wait for responses
TYPE:
|
idle_timeout_multiplier
|
Idle timeout multiplier
TYPE:
|
device_timeout
|
request timeout set on discovered device
TYPE:
|
max_retries
|
max retries per request set on discovered device
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Device | None
|
Device instance if found, None otherwise |
Note
Internal device-class construction errors are logged and return
None rather than escaping this lookup.
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
LifxNetworkError
|
If the validated destination cannot be resolved to a native socket address or the discovery transport fails. |
Example
Source code in src/lifx/api.py
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 | |
Device Group¶
DeviceGroup
¶
DeviceGroup(
devices: Sequence[
Device | Light | HevLight | InfraredLight | MultiZoneLight | MatrixLight
],
)
A group of devices for batch operations.
Provides convenient methods to control multiple devices simultaneously.
Example
| PARAMETER | DESCRIPTION |
|---|---|
devices
|
List of Device instances
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
__aenter__ |
Enter async context manager. |
__aexit__ |
Exit async context manager and close all device connections. |
__iter__ |
Iterate over devices in the group. |
__len__ |
Get number of devices in the group. |
__getitem__ |
Get device by index. |
set_power |
Set power state for all devices in the group. |
set_color |
Set color for all Light devices in the group. |
set_brightness |
Set brightness for all Light devices in the group. |
pulse |
Pulse waveform for all Light devices. |
organize_by_location |
Organize devices by location label. |
organize_by_group |
Organize devices by group label. |
filter_by_location |
Filter devices to a specific location. |
filter_by_group |
Filter devices to a specific group. |
get_unassigned_devices |
Get devices without location or group assigned. |
apply_theme |
Apply a theme to all devices in the group. |
apply_mood |
Paint a theme across the group the way the LIFX app paints a mood. |
animate_mood |
Start each light's mood effect; bulbs share one colour loop. |
invalidate_metadata_cache |
Clear all cached location and group metadata. |
| ATTRIBUTE | DESCRIPTION |
|---|---|
devices |
Get all the devices in the group.
TYPE:
|
lights |
Get all Light devices in the group. |
hev_lights |
Get the HEV lights in the group. |
infrared_lights |
Get the Infrared lights in the group.
TYPE:
|
multizone_lights |
Get all MultiZone light devices in the group.
TYPE:
|
matrix_lights |
Get all Matrix light devices in the group.
TYPE:
|
Source code in src/lifx/api.py
Attributes¶
devices
property
¶
devices: Sequence[
Device | HevLight | InfraredLight | Light | MultiZoneLight | MatrixLight
]
Get all the devices in the group.
infrared_lights
property
¶
infrared_lights: list[InfraredLight]
Get the Infrared lights in the group.
multizone_lights
property
¶
multizone_lights: list[MultiZoneLight]
Get all MultiZone light devices in the group.
matrix_lights
property
¶
matrix_lights: list[MatrixLight]
Get all Matrix light devices in the group.
Methods:¶
__aenter__
async
¶
__aenter__() -> DeviceGroup
__aexit__
async
¶
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None
Exit async context manager and close all device connections.
Source code in src/lifx/api.py
__iter__
¶
__iter__() -> Iterator[
Device | Light | HevLight | InfraredLight | MultiZoneLight | MatrixLight
]
__getitem__
¶
__getitem__(
index: int,
) -> Device | Light | HevLight | InfraredLight | MultiZoneLight | MatrixLight
set_power
async
¶
Set power state for all devices in the group.
| PARAMETER | DESCRIPTION |
|---|---|
on
|
True to turn on, False to turn off
TYPE:
|
duration
|
Transition duration in seconds (default 0.0)
TYPE:
|
Example
Source code in src/lifx/api.py
set_color
async
¶
Set color for all Light devices in the group.
| PARAMETER | DESCRIPTION |
|---|---|
color
|
HSBK color to set
TYPE:
|
duration
|
Transition duration in seconds (default 0.0)
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the color's kelvin is outside the range of any light in the group. Nothing is sent to any light. |
Example
Source code in src/lifx/api.py
set_brightness
async
¶
Set brightness for all Light devices in the group.
| PARAMETER | DESCRIPTION |
|---|---|
brightness
|
Brightness level (0.0-1.0)
TYPE:
|
duration
|
Transition duration in seconds (default 0.0)
TYPE:
|
Example
Source code in src/lifx/api.py
pulse
async
¶
Pulse waveform for all Light devices.
| PARAMETER | DESCRIPTION |
|---|---|
color
|
Color to pulse to
TYPE:
|
period
|
Period of one cycle in seconds
TYPE:
|
cycles
|
Number of cycles
TYPE:
|
Example
Source code in src/lifx/api.py
organize_by_location
async
¶
organize_by_location(
include_unassigned: bool = False,
) -> dict[str, DeviceGroup]
Organize devices by location label.
Fetches location metadata if not cached and groups devices by location label.
| PARAMETER | DESCRIPTION |
|---|---|
include_unassigned
|
Include "Unassigned" group
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, DeviceGroup]
|
Dictionary mapping location labels to DeviceGroup instances |
Example
Source code in src/lifx/api.py
organize_by_group
async
¶
organize_by_group(include_unassigned: bool = False) -> dict[str, DeviceGroup]
Organize devices by group label.
Fetches group metadata if not cached and groups devices by group label.
| PARAMETER | DESCRIPTION |
|---|---|
include_unassigned
|
Include "Unassigned" group
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, DeviceGroup]
|
Dictionary mapping group labels to DeviceGroup instances |
Example
Source code in src/lifx/api.py
filter_by_location
async
¶
filter_by_location(label: str, case_sensitive: bool = False) -> DeviceGroup
Filter devices to a specific location.
| PARAMETER | DESCRIPTION |
|---|---|
label
|
Location label to filter by
TYPE:
|
case_sensitive
|
If True, performs case-sensitive matching (default False)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DeviceGroup
|
DeviceGroup containing devices in the specified location |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If location label not found |
Example
Source code in src/lifx/api.py
filter_by_group
async
¶
filter_by_group(label: str, case_sensitive: bool = False) -> DeviceGroup
Filter devices to a specific group.
| PARAMETER | DESCRIPTION |
|---|---|
label
|
Group label to filter by
TYPE:
|
case_sensitive
|
If True, performs case-sensitive matching (default False)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DeviceGroup
|
DeviceGroup containing devices in the specified group |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If group label not found |
Example
Source code in src/lifx/api.py
get_unassigned_devices
¶
Get devices without location or group assigned.
| PARAMETER | DESCRIPTION |
|---|---|
metadata_type
|
Type of metadata to check ("location" or "group")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[Device]
|
List of devices without the specified metadata type |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If metadata hasn't been fetched yet |
Example
Source code in src/lifx/api.py
apply_theme
async
¶
Apply a theme to all devices in the group.
Each device applies the theme according to its capabilities:
- Light: Selects random color from theme
- MultiZoneLight: Distributes colors evenly across zones
- MatrixLight (and CeilingLight): Uses interpolation for smooth gradients
- Other devices: No action (themes only apply to color devices)
Each device is painted exactly once, using the most specific
apply_theme() implementation for its class.
| PARAMETER | DESCRIPTION |
|---|---|
theme
|
Theme to apply
TYPE:
|
power_on
|
Turn on devices if True
TYPE:
|
duration
|
Transition duration in seconds
TYPE:
|
Example
Source code in src/lifx/api.py
apply_mood
async
¶
apply_mood(theme: Theme) -> None
Paint a theme across the group the way the LIFX app paints a mood.
Each light paints by its kind, as Light.apply_mood() describes.
Bulbs share the theme's distinct colours, shuffled and dealt one per
bulb in turn. Lights are turned on only when every colour light in
the group is off. Lights already running a mood effect restart it
with this theme instead.
| PARAMETER | DESCRIPTION |
|---|---|
theme
|
Theme to paint
TYPE:
|
Source code in src/lifx/api.py
animate_mood
async
¶
animate_mood(theme: Theme) -> None
Start each light's mood effect; bulbs share one colour loop.
Every light is turned on if it is off. The bulbs' loop is rescaled to
the brightest bulb. Stop the animation with stop_effect() on each
light, which puts back what that light showed before it started.
| PARAMETER | DESCRIPTION |
|---|---|
theme
|
Theme to animate
TYPE:
|
Source code in src/lifx/api.py
invalidate_metadata_cache
¶
Clear all cached location and group metadata.
Use this if you've changed device locations/groups and want to re-fetch.
Example
devices = []
async for device in discover():
devices.append(device)
group = DeviceGroup(devices)
# First organization
by_location = await group.organize_by_location()
# ... change device locations ...
# Clear cache and re-organize
group.invalidate_metadata_cache()
by_location = await group.organize_by_location()
Source code in src/lifx/api.py
Organizational Groupings¶
Dataclasses for organizing devices by location or group. Returned by DeviceGroup.organize_by_location() and DeviceGroup.organize_by_group().
LocationGrouping¶
Location-based device grouping returned by DeviceGroup.organize_by_location().
LocationGrouping
dataclass
¶
Organizational structure for location-based grouping.
GroupGrouping¶
Group-based device grouping returned by DeviceGroup.organize_by_group().
GroupGrouping
dataclass
¶
Organizational structure for group-based grouping.
Examples¶
Simple Discovery¶
from lifx import discover, DeviceGroup, Colors
async def main():
count: int = 0
async for device in discover():
count += 1
await device.set_power(True)
await device.set_color(Colors.BLUE)
print(f"Found {count} devices")
Find by Serial Number¶
from lifx import find_by_serial
async def main():
# Find specific device by serial number
device = await find_by_serial("d073d5123456")
if device:
async with device:
await device.set_power(True)
Find by Label¶
from lifx import find_by_label, Colors
async def main():
# Find all devices with "Living" in the label (substring match)
async for device in find_by_label("Living"): # May match "Living Room", "Living Area", etc.
await device.set_power(True)
# Find device with exact label match
async for device in find_by_label("Living Room", exact_match=True):
await device.set_color(Colors.WARM)
break # exact_match returns at most one device
Find by IP Address¶
from lifx import find_by_ip
async def main():
# Find device at specific IP address
device = await find_by_ip("192.168.1.100")
if device:
async with device:
await device.set_power(True)
Device Watcher¶
Continuous discovery with added, updated and removed events. See the
discovery guide.
DeviceWatcher
¶
DeviceWatcher(
*,
sweep_interval: float = DEFAULT_SWEEP_INTERVAL,
silence_threshold: float | None = None,
mdns: bool = False,
broadcast_address: str = _DEFAULT_BROADCAST,
port: int = LIFX_UDP_PORT,
discovery_timeout: float = DISCOVERY_TIMEOUT,
idle_timeout_multiplier: float = IDLE_TIMEOUT_MULTIPLIER,
device_timeout: float = DEFAULT_REQUEST_TIMEOUT,
max_retries: int | None = DEFAULT_MAX_RETRIES,
max_queue_size: int = DEFAULT_MAX_QUEUE_SIZE,
high_frequency_polling: bool = False,
high_frequency_interval: float = DEFAULT_HIGH_FREQUENCY_INTERVAL,
low_frequency_polling: bool = False,
low_frequency_interval: float = DEFAULT_LOW_FREQUENCY_INTERVAL,
enable_thread: bool = False,
)
Track LIFX devices continuously and report what changes.
On entry the watcher runs an initial discovery. After that it sweeps every
sweep_interval seconds through the process-wide sweep coordinator,
optionally with an mDNS leg for Thread and IPv6 devices. It builds each
device through the normal discovery path and returns the same object for
a serial every time. A device that reappears at another address is moved
in place (see :meth:lifx.devices.base.Device.update_address) and
reported as one UPDATED event.
Events are read as an async iterator (async for event in watcher) or
through callbacks registered with :meth:add_listener. The iterator's
queue is bounded: when it is full the oldest event is dropped and
:attr:dropped_events increments, so a slow consumer never blocks a
sweep. Callbacks see every event, in order, at the moment it happens.
A device is silent, and REMOVED is emitted, once it has answered
nothing (a discovery reply or any request on its connection) for longer
than silence_threshold. The device object is kept; when it answers
again ADDED is emitted for the same object.
The watcher listens, discovers and, only when asked, reads. It never writes color or power. Two optional polls are off by default:
- High-frequency polling reads color and power, plus zones on a multizone
light and tiles on a matrix light. A device evidenced as Thread is not
polled this way unless
enable_threadis True, the same opt-in the software effect path uses. - Low-frequency polling reads label, host firmware, wifi firmware (not on a Thread device, which cannot answer it), group and location.
Each poll refreshes the device's cached state and is reported as
UPDATED with the changed fields. A poll that fails is logged and does
not stop other devices or mark the device silent; silence still comes only
from the liveness threshold. The first reading of a field is a baseline
and is not reported.
Example
| PARAMETER | DESCRIPTION |
|---|---|
sweep_interval
|
Seconds between sweeps. Must be positive.
TYPE:
|
silence_threshold
|
Seconds of silence before a device is removed. Defaults to the larger of 30 and five sweep intervals.
TYPE:
|
mdns
|
Also discover through mDNS on each sweep.
TYPE:
|
broadcast_address
|
Broadcast address for UDP discovery. May be reassigned; the new value applies from the next sweep.
TYPE:
|
port
|
UDP port for discovery. May be reassigned like
TYPE:
|
discovery_timeout
|
Overall timeout of each sweep, in seconds.
TYPE:
|
idle_timeout_multiplier
|
Idle timeout multiplier for each sweep.
TYPE:
|
device_timeout
|
Request timeout set on devices the watcher builds.
TYPE:
|
max_retries
|
Max retries per request set on those devices.
TYPE:
|
max_queue_size
|
Events held for the iterator. Must be positive.
TYPE:
|
high_frequency_polling
|
Poll color, power, zones and tiles.
TYPE:
|
high_frequency_interval
|
Seconds between those polls. Must be positive.
TYPE:
|
low_frequency_polling
|
Poll label, firmware, group and location.
TYPE:
|
low_frequency_interval
|
Seconds between those polls. Must be positive.
TYPE:
|
enable_thread
|
Also poll Thread devices at high frequency.
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
get |
Return the object for |
add_listener |
Call |
get_event_nowait |
Pop the oldest queued event, or |
__aexit__ |
Stop sweeping. Device objects stay open for whoever holds them. |
sweep |
Run one discovery sweep now and update liveness. |
| ATTRIBUTE | DESCRIPTION |
|---|---|
devices |
The devices that are currently answering, one object per serial. |
running |
Whether the periodic sweep task is alive.
TYPE:
|
sweep_count |
How many sweeps have completed.
TYPE:
|
dropped_events |
Events dropped from the iterator queue because it was full.
TYPE:
|
Source code in src/lifx/watcher.py
Attributes¶
devices
property
¶
The devices that are currently answering, one object per serial.
dropped_events
property
¶
dropped_events: int
Events dropped from the iterator queue because it was full.
Methods:¶
get
¶
Return the object for serial, silent or not, or None.
| PARAMETER | DESCRIPTION |
|---|---|
serial
|
Device serial, with or without separators, any case.
TYPE:
|
Source code in src/lifx/watcher.py
add_listener
¶
add_listener(listener: EventListener) -> Callable[[], None]
Call listener(event) for every event from now on.
The callback runs synchronously inside the sweep, so keep it quick. An exception it raises is logged and does not stop other consumers.
| RETURNS | DESCRIPTION |
|---|---|
Callable[[], None]
|
A function that removes the listener. |
Source code in src/lifx/watcher.py
get_event_nowait
¶
get_event_nowait() -> DeviceEvent | None
__aexit__
async
¶
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None
Stop sweeping. Device objects stay open for whoever holds them.
Source code in src/lifx/watcher.py
sweep
async
¶
Run one discovery sweep now and update liveness.
The periodic task calls this; call it yourself to force a sweep. Sweeps never overlap.
Source code in src/lifx/watcher.py
DeviceEvent
dataclass
¶
DeviceEvent(
type: DeviceEventType,
serial: str,
device: Device[Any],
changes: Mapping[str, tuple[object, object]] = (
lambda: MappingProxyType({})
)(),
)
One change reported by a :class:DeviceWatcher.
| ATTRIBUTE | DESCRIPTION |
|---|---|
type |
What happened.
TYPE:
|
serial |
The device serial, 12 lowercase hex digits.
TYPE:
|
device |
The device object. It is the same object on every event for this serial. |
changes |
For |
DeviceEventType
¶
Bases: StrEnum
What happened to a device.
| ATTRIBUTE | DESCRIPTION |
|---|---|
ADDED |
First seen, or answering again after a
|
UPDATED |
A tracked field changed; see :attr:
|
REMOVED |
Silent for longer than the silence threshold. The object is kept.
|
Attributes¶
ADDED
class-attribute
instance-attribute
¶
First seen, or answering again after a REMOVED.
UPDATED
class-attribute
instance-attribute
¶
A tracked field changed; see :attr:DeviceEvent.changes.
REMOVED
class-attribute
instance-attribute
¶
Silent for longer than the silence threshold. The object is kept.