Network Layer¶
The network layer provides low-level operations for communicating with LIFX devices over UDP.
For the consumer-facing discovery journey (discover(), discover_udp(),
discover_mdns(), targeted lookup, method selection and limitations), see the
Discovery Guide. This page documents the
low-level discovery, transport and connection primitives underneath it.
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/udp.py
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 | |
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 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 instance of the appropriate type |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If a concrete device constructor no longer accepts the shared discovery arguments. |
AttributeError
|
If an internal device capability or metadata contract is broken. |
Example
Source code in src/lifx/network/discovery/udp.py
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 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 | |
__eq__
¶
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 |
mDNS discovery¶
The canonical low-level mDNS namespace is lifx.network.discovery.mdns.
The former lifx.network.mdns package remains as a thin import-compatibility
surface and contains no duplicate implementation.
discover_devices_mdns
async
¶
discover_devices_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 = DEFAULT_MAX_RETRIES,
) -> AsyncGenerator[Light, None]
Discover LIFX devices via mDNS and yield device instances.
This is the high-level API that yields fully-typed device instances (Light, MatrixLight, MultiZoneLight, etc.) based on product capabilities.
Devices that are not lights (relays, buttons without color) are automatically filtered out and not yielded.
| 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:
|
device_timeout
|
Request timeout for created devices
TYPE:
|
max_retries
|
Maximum retry attempts for device requests
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
AsyncGenerator[Light, None]
|
Device instances (Light, MatrixLight, etc.) as they are discovered |
Example
Source code in src/lifx/network/discovery/mdns/discovery.py
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. |
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
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 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | |
send
async
¶
send(data: bytes, address: SocketAddress) -> None
Send data to a specific address.
The destination's address family is checked against the socket's
before the datagram is handed to asyncio. A mismatch is a permanent
configuration error, but the socket reports it as a gaierror,
an OSError subclass that :meth:_UdpProtocol.error_received
deliberately swallows along with every genuine peer error. Without
this check an unreachable-by-construction address is
indistinguishable from a sleeping device: the caller waits out the
full retry schedule and is told only that it timed out. Checking
first costs one parse and names the actual problem.
This is a pre-send guard and nothing more. The routing of errors
that arrive from the network is untouched: EHOSTUNREACH, EHOSTDOWN
and ENETUNREACH still reach error_received and still leave the
endpoint alive.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Bytes to send
TYPE:
|
address
|
Tuple of (host, port)
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
LifxNetworkError
|
If the socket is not open, the destination's address family does not match the socket's, an IPv6 zone identifier cannot be resolved, or the send fails. |
Source code in src/lifx/network/transport.py
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 | |
receive
async
¶
Receive data from socket with size validation.
| PARAMETER | DESCRIPTION |
|---|---|
timeout
|
Timeout in seconds
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[bytes, SocketAddress]
|
Tuple of (data, address) where address is (host, port) |
| RAISES | DESCRIPTION |
|---|---|
LifxTimeoutError
|
If no data received within timeout |
LifxNetworkError
|
If socket is not open or receive fails |
LifxProtocolError
|
If packet size is invalid |
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 |
|---|---|
thread_connection |
The device's own report of whether replies travel over Thread.
TYPE:
|
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
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 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 | |
Attributes¶
thread_connection
property
¶
thread_connection: bool | None
The device's own report of whether replies travel over Thread.
None until a correlated response has been observed. Set from
LifxHeader.thread_connection (frame address byte 22, bit 3) only
after source/sequence/serial validation succeeds, so stray traffic on
the shared socket can never assert a transport for this device.
A device's radio operates in either WiFi or Thread mode and cannot change without a firmware crossgrade, so this value is invariant for a given device once observed.
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
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 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | |
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
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 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 | |
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.