Network Layer¶
The network layer provides low-level operations for communicating with LIFX devices over UDP.
Discovery¶
Functions for discovering LIFX devices on the local network.
discover_devices
async
¶
discover_devices(
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 = DEFAULT_MAX_RETRIES,
) -> AsyncGenerator[DiscoveredDevice, None]
Discover LIFX devices on the local network.
Sends a broadcast DeviceGetService packet and yields devices as they respond.
The packet is re-broadcast several times on an escalating schedule within
the discovery window, so devices behind a lossy access point that miss
the first broadcast are still found. Implements DoS protection via
timeout, source validation, and serial validation. Serial validation and
per-serial deduplication are enforced inside _discover_with_packet,
so every caller of that shared generator benefits.
Note
On a populated network, generator completion now typically takes
longer than a single broadcast alone would: re-broadcasts continue
for several seconds into the window, and the generator then waits
out the ~4 s idle window (max_response_time ×
idle_timeout_multiplier) after the last response -- still well
inside DISCOVERY_TIMEOUT (15 s). Streaming consumers
(async for) see the first devices at unchanged latency; only
overall completion moves later, because later re-broadcasts
legitimately keep finding new devices and resetting the idle
window.
The idle window measures network silence, not elapsed wall time:
time the consumer spends inside the async for body is excluded,
so a slow consumer no longer shortens the sweep. timeout
(default 15 s) is the bound that still applies to it.
| PARAMETER | DESCRIPTION |
|---|---|
timeout
|
Discovery timeout in seconds
TYPE:
|
broadcast_address
|
Broadcast address to use
TYPE:
|
port
|
UDP 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:
|
| YIELDS | DESCRIPTION |
|---|---|
AsyncGenerator[DiscoveredDevice, None]
|
DiscoveredDevice instances as they are discovered |
AsyncGenerator[DiscoveredDevice, None]
|
(deduplicated by serial number) |
Example
Source code in src/lifx/network/discovery.py
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 | |
DiscoveredDevice
dataclass
¶
DiscoveredDevice(
serial: str,
ip: str,
port: int = LIFX_UDP_PORT,
timeout: float = DEFAULT_REQUEST_TIMEOUT,
max_retries: int = DEFAULT_MAX_RETRIES,
first_seen: float = time(),
response_time: float = 0.0,
)
Information about a discovered LIFX device.
| ATTRIBUTE | DESCRIPTION |
|---|---|
serial |
Device serial number as 12-digit hex string (e.g., "d073d5123456")
TYPE:
|
ip |
Device IP address
TYPE:
|
port |
Device UDP port
TYPE:
|
first_seen |
Timestamp when device was first discovered
TYPE:
|
response_time |
Response time in seconds, anchored at the first broadcast (time since discovery began). A device answering a later re-broadcast reports a proportionally larger value.
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
create_device |
Create appropriate device instance based on product capabilities. |
__hash__ |
Hash based on serial number for deduplication. |
__eq__ |
Equality based on serial number. |
Methods:¶
create_device
async
¶
create_device() -> Device | None
Create appropriate device instance based on product capabilities.
Queries the device for its product ID and uses the product registry to instantiate the appropriate device class (Device, Light, HevLight, InfraredLight, MultiZoneLight, MatrixLight, or CeilingLight) based on the product capabilities.
This is the single source of truth for device type detection and instantiation across the library.
| RETURNS | DESCRIPTION |
|---|---|
Device | None
|
Device instance of the appropriate type |
| RAISES | DESCRIPTION |
|---|---|
LifxDeviceNotFoundError
|
If device doesn't respond |
LifxTimeoutError
|
If device query times out |
LifxProtocolError
|
If device returns invalid data |
Example
Source code in src/lifx/network/discovery.py
__eq__
¶
discover_lifx_services
async
¶
discover_lifx_services(
timeout: float = DISCOVERY_TIMEOUT,
max_response_time: float = MAX_RESPONSE_TIME,
idle_timeout_multiplier: float = IDLE_TIMEOUT_MULTIPLIER,
) -> AsyncGenerator[LifxServiceRecord, None]
Discover LIFX devices via mDNS and yield service records.
Sends an mDNS PTR query for _lifx._udp.local and yields service records as devices respond. Records are deduplicated by serial number.
This is the low-level API that provides raw mDNS data. For device instances, use discover_devices_mdns() instead.
| PARAMETER | DESCRIPTION |
|---|---|
timeout
|
Overall discovery timeout in seconds
TYPE:
|
max_response_time
|
Maximum expected response time
TYPE:
|
idle_timeout_multiplier
|
Multiplier for idle timeout
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
AsyncGenerator[LifxServiceRecord, None]
|
LifxServiceRecord for each discovered device |
Example
Source code in src/lifx/network/mdns/discovery.py
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | |
LifxServiceRecord
dataclass
¶
Information about a LIFX device discovered via mDNS.
| ATTRIBUTE | DESCRIPTION |
|---|---|
serial |
Device serial number as 12-digit hex string (e.g., "d073d5123456")
TYPE:
|
ip |
Device IP address
TYPE:
|
port |
Device UDP port (typically 56700)
TYPE:
|
product_id |
Product ID from TXT record 'p' field
TYPE:
|
firmware |
Firmware version from TXT record 'fw' field
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
__hash__ |
Hash based on serial number for deduplication. |
__eq__ |
Equality based on serial number. |
DiscoveryResponse¶
Response dataclass from custom discovery broadcasts (using packets other than GetService).
DiscoveryResponse
dataclass
¶
DiscoveryResponse(
serial: str,
ip: str,
port: int,
response_time: float,
response_payload: dict[str, Any],
)
Response from a discovery broadcast using a custom packet.
| ATTRIBUTE | DESCRIPTION |
|---|---|
serial |
Device serial number
TYPE:
|
ip |
Device IP address
TYPE:
|
port |
UDP source port the device responded from (
TYPE:
|
response_time |
Response time in seconds, anchored at the first broadcast (time since discovery began). A device answering a later re-broadcast reports a proportionally larger value.
TYPE:
|
response_payload |
Unpacked State packet fields as key/value dict |
UDP Transport¶
Low-level UDP transport for sending and receiving LIFX protocol messages.
UdpTransport
¶
UdpTransport(
ip_address: str = DEFAULT_IP_ADDRESS,
port: int = 0,
broadcast: bool = False,
peer: PeerInfo | None = None,
)
UDP transport for sending and receiving LIFX packets.
This class provides a simple interface for UDP communication with LIFX devices. It uses asyncio for async I/O operations.
| PARAMETER | DESCRIPTION |
|---|---|
port
|
Local port to bind to (0 for automatic assignment)
TYPE:
|
broadcast
|
Enable broadcast mode for device discovery
TYPE:
|
peer
|
Device this socket talks to, included in warning logs so an unreachable-peer error names the device. Held by reference, so a serial learned after open() shows up in later records. Left unset for the shared broadcast socket, which has no single peer.
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
open |
Open the UDP socket. |
send |
Send data to a specific address. |
receive |
Receive data from socket with size validation. |
receive_many |
Receive multiple packets within timeout period. |
close |
Close the UDP socket. |
| ATTRIBUTE | DESCRIPTION |
|---|---|
is_open |
Check if socket is open.
TYPE:
|
Source code in src/lifx/network/transport.py
Attributes¶
Methods:¶
open
async
¶
Open the UDP socket.
Source code in src/lifx/network/transport.py
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 | |
send
async
¶
Send data to a specific address.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Bytes to send
TYPE:
|
address
|
Tuple of (host, port) |
| RAISES | DESCRIPTION |
|---|---|
NetworkError
|
If socket is not open or send fails |
Source code in src/lifx/network/transport.py
receive
async
¶
Receive data from socket with size validation.
| PARAMETER | DESCRIPTION |
|---|---|
timeout
|
Timeout in seconds
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[bytes, tuple[str, int]]
|
Tuple of (data, address) where address is (host, port) |
| RAISES | DESCRIPTION |
|---|---|
LifxTimeoutError
|
If no data received within timeout |
NetworkError
|
If socket is not open or receive fails |
ProtocolError
|
If packet size is invalid |
Source code in src/lifx/network/transport.py
receive_many
async
¶
receive_many(
timeout: float = 5.0, max_packets: int | None = None
) -> list[tuple[bytes, tuple[str, int]]]
Receive multiple packets within timeout period.
| PARAMETER | DESCRIPTION |
|---|---|
timeout
|
Total timeout in seconds
TYPE:
|
max_packets
|
Maximum number of packets to receive (None for unlimited)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[tuple[bytes, tuple[str, int]]]
|
List of (data, address) tuples |
| RAISES | DESCRIPTION |
|---|---|
NetworkError
|
If socket is not open |
.. deprecated:: 5.5.0
:meth:receive_many is deprecated and will be removed in v6.0.
Use :meth:receive in a loop, or the public discovery API in
:mod:lifx.api (e.g. :func:~lifx.api.discover), for
multi-response collection.
Source code in src/lifx/network/transport.py
close
async
¶
Close the UDP socket.
Source code in src/lifx/network/transport.py
Examples¶
Device Discovery¶
from lifx.network.discovery import discover_devices
async def main():
# Discover all devices on the network
async for device in discover_devices():
print(f"Found: {device.serial} at {device.ip}")
print(f" Port: {device.port}")
Concurrency¶
Requests on a Single Connection¶
Each DeviceConnection correlates responses to their requests — a background receiver routes each reply to the request that sent it, so requests on one connection never mix:
import asyncio
from lifx.network.connection import DeviceConnection
from lifx.protocol.packets import Light, Device
async def main():
conn = DeviceConnection(serial="d073d5123456", ip="192.168.1.100")
# Requests on the same connection (responses correlated per request)
state = await conn.request(Light.GetColor())
power = await conn.request(Light.GetPower())
label = await conn.request(Device.GetLabel())
# Connection automatically closes when done
await conn.close()
Concurrent Requests on Different Devices¶
import asyncio
from lifx.network.connection import DeviceConnection
async def main():
conn1 = DeviceConnection(serial="d073d5000001", ip="192.168.1.100")
conn2 = DeviceConnection(serial="d073d5000002", ip="192.168.1.101")
# Fully parallel - different UDP sockets
result1, result2 = await asyncio.gather(
conn1.request(Light.GetColor()),
conn2.request(Light.GetColor())
)
# Clean up connections
await conn1.close()
await conn2.close()
Connection Management¶
DeviceConnection
¶
DeviceConnection(
serial: str,
ip: str,
port: int = LIFX_UDP_PORT,
max_retries: int = DEFAULT_MAX_RETRIES,
timeout: float = DEFAULT_REQUEST_TIMEOUT,
)
Connection to a LIFX device.
This class manages the UDP transport and request/response lifecycle for a single device. Connections are opened lazily on first request and remain open until explicitly closed.
Features:
- Lazy connection opening (no context manager required)
- Async generator-based request/response streaming
- Automatic retransmits on an escalating schedule within each request's timeout, listening for a reply throughout
- Response correlation: a background receiver routes each reply to its request, so concurrent requests never mix
- Automatic sequence number management
Example
With context manager (recommended for cleanup):
async with DeviceConnection(...) as conn:
state = await conn.request(packets.Light.GetColor())
# Connection automatically closed on exit
This is lightweight - doesn't actually create a connection. Connection is opened lazily on first request.
| PARAMETER | DESCRIPTION |
|---|---|
serial
|
Device serial number as 12-digit hex string (e.g., 'd073d5123456')
TYPE:
|
ip
|
Device IP address
TYPE:
|
port
|
Device UDP port (default LIFX_UDP_PORT)
TYPE:
|
max_retries
|
Maximum number of retransmits within the timeout (default: 8). Total transmissions are at most max_retries + 1; after the cap is reached the request keeps listening for a reply until the timeout expires instead of failing early. Whichever of the retransmit cap and the timeout is reached first wins.
TYPE:
|
timeout
|
Default timeout for requests in seconds (default: 16.0). The timeout is an overall limit on the whole request: all waiting -- transmissions, retransmit gaps, and the final listen window -- counts against it, so a request can never take materially longer than the timeout it was given.
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
__aenter__ |
Enter async context manager. |
__aexit__ |
Exit async context manager and close connection. |
open |
Open connection to device. |
close |
Close connection to device. |
send_packet |
Send a packet to the device. |
receive_packet |
Receive a packet from the device. |
request_stream |
Send request and yield unpacked responses. |
request |
Send request and get single response (convenience wrapper). |
| ATTRIBUTE | DESCRIPTION |
|---|---|
serial |
Serial of the device this connection talks to.
TYPE:
|
is_open |
Check if connection is open.
TYPE:
|
Source code in src/lifx/network/connection.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
Attributes¶
serial
property
¶
serial: str
Serial of the device this connection talks to.
A connection opened without a serial (000000000000) reports the
real one as soon as a reply carries it, which is what callers such as
Device.from_ip() read straight after their first request. That is
deliberately sooner than the connection adopts it as its correlation
identity: see :meth:_adopt_learned_serial.
Methods:¶
__aenter__
async
¶
__aexit__
async
¶
__aexit__(
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: object,
) -> None
Exit async context manager and close connection.
open
async
¶
Open connection to device.
Opens the UDP transport for sending and receiving packets. Called automatically on first request if not already open.
Source code in src/lifx/network/connection.py
close
async
¶
Close connection to device.
Source code in src/lifx/network/connection.py
send_packet
async
¶
send_packet(
packet: Any,
source: int | None = None,
sequence: int = 0,
ack_required: bool = False,
res_required: bool = False,
) -> None
Send a packet to the device.
| PARAMETER | DESCRIPTION |
|---|---|
packet
|
Packet dataclass instance
TYPE:
|
source
|
Client source identifier (optional, allocated if None)
TYPE:
|
sequence
|
Sequence number (default: 0)
TYPE:
|
ack_required
|
Request acknowledgement
TYPE:
|
res_required
|
Request response
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ConnectionError
|
If connection is not open or send fails |
Source code in src/lifx/network/connection.py
receive_packet
async
¶
receive_packet(timeout: float = 0.5) -> tuple[LifxHeader, bytes]
Receive a packet from the device.
Note
This method does not validate the source IP address. Validation is instead performed using the LIFX protocol's built-in target field (serial number) and sequence number matching in request_stream() and request_ack_stream(). This approach is more reliable in complex network configurations (NAT, multiple interfaces, bridges, etc.) while maintaining security through proper protocol-level validation.
| PARAMETER | DESCRIPTION |
|---|---|
timeout
|
Timeout in seconds
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[LifxHeader, bytes]
|
Tuple of (header, payload) |
| RAISES | DESCRIPTION |
|---|---|
ConnectionError
|
If connection is not open |
TimeoutError
|
If no response within timeout |
Source code in src/lifx/network/connection.py
request_stream
async
¶
request_stream(
packet: Any, timeout: float | None = None
) -> AsyncGenerator[Any, None]
Send request and yield unpacked responses.
This is an async generator that handles the complete request/response cycle including packet type detection, response unpacking, and label decoding. Connection is opened automatically if not already open.
Single response (most common): async for response in conn.request_stream(GetLabel()): process(response) break # Exit immediately
Multiple responses
async for state in conn.request_stream(GetColorZones()): process(state) # Continues until timeout
| PARAMETER | DESCRIPTION |
|---|---|
packet
|
Packet instance to send
TYPE:
|
timeout
|
Request timeout in seconds
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
AsyncGenerator[Any, None]
|
Unpacked response packet instances (including StateUnhandled if device |
AsyncGenerator[Any, None]
|
doesn't support the command) |
AsyncGenerator[Any, None]
|
For SET packets: yields True (acknowledgement) or False (StateUnhandled) |
| RAISES | DESCRIPTION |
|---|---|
LifxTimeoutError
|
If request times out |
LifxProtocolError
|
If response invalid |
LifxConnectionError
|
If connection fails |
Example
# GET request yields unpacked packets
async for state in conn.request_stream(packets.Light.GetColor()):
color = HSBK.from_protocol(state.color)
label = state.label # Already decoded to string
break
# SET request yields True (acknowledgement) or False (StateUnhandled)
async for result in conn.request_stream(
packets.Light.SetColor(color=hsbk, duration=1000)
):
if result:
# Acknowledgement received
pass
else:
# Device doesn't support this command
pass
break
# Multi-response GET - stream all responses
async for state in conn.request_stream(
packets.MultiZone.GetExtendedColorZones()
):
# Process each zone state
pass
Source code in src/lifx/network/connection.py
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 | |
request
async
¶
Send request and get single response (convenience wrapper).
This is a convenience method that returns the first response from request_stream(). It's equivalent to: await anext(conn.request_stream(packet))
Most device operations use this method since they expect a single response. Connection is opened automatically if not already open.
| PARAMETER | DESCRIPTION |
|---|---|
packet
|
Packet instance to send
TYPE:
|
timeout
|
Request timeout in seconds
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
Single unpacked response packet (including StateUnhandled if device |
Any
|
doesn't support the command) |
Any
|
For SET packets: True (acknowledgement) or False (StateUnhandled) |
| RAISES | DESCRIPTION |
|---|---|
LifxTimeoutError
|
If no response within timeout |
LifxProtocolError
|
If response invalid |
LifxConnectionError
|
If connection fails |
Example
# GET request returns unpacked packet
state = await conn.request(packets.Light.GetColor())
color = HSBK.from_protocol(state.color)
label = state.label # Already decoded to string
# SET request returns True or False
success = await conn.request(
packets.Light.SetColor(color=hsbk, duration=1000)
)
if not success:
# Device doesn't support this command (returned StateUnhandled)
pass
Source code in src/lifx/network/connection.py
Performance Considerations¶
Connection Lifecycle¶
- Connections open lazily on first request
- Each device owns its own connection (no shared pool)
- Connections close explicitly via
close()or context manager exit - Low memory overhead (one UDP socket per device)
- A connection whose UDP endpoint dies is rebuilt on the next request. Only genuine endpoint death triggers this: a device that is asleep, slow or off the network produces per-datagram errors and ordinary request timeouts, which leave the socket alone.
Response Handling¶
- Responses matched by sequence number
- Async generator-based streaming for efficient multi-response protocols
- Immediate exit for single-response requests (no wasted timeout)
- Retry logic with exponential backoff and jitter
Rate Limiting¶
The library intentionally does not implement rate limiting to keep the core library simple. Applications should implement their own rate limiting if needed. According to the LIFX protocol specification, devices can handle approximately 20 messages per second.