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 | None = 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
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 774 775 | |
DiscoveredDevice
dataclass
¶
DiscoveredDevice(
serial: str,
ip: str,
port: int = LIFX_UDP_PORT,
timeout: float = DEFAULT_REQUEST_TIMEOUT,
max_retries: int | None = 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 | None = 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
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 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 405 406 | |
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
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 532 533 | |
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 | None = 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: None, no cap). With no cap the request keeps retransmitting on the gap schedule until the timeout, so a device that wakes late in the budget is still asked again. With a cap, 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. 0 sends once and never retransmits.
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 |
|---|---|
update_address |
Point this connection at a new endpoint without failing anything. |
__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). |
echo |
Send an echo request and wait for the response carrying |
| ATTRIBUTE | DESCRIPTION |
|---|---|
thread_connection |
The device's own report of whether replies travel over Thread.
TYPE:
|
last_response_at |
When this connection last received a correlated response.
TYPE:
|
address_epoch |
How many times this connection's endpoint has changed.
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
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 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 | |
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.
last_response_at
property
¶
last_response_at: float | None
When this connection last received a correlated response.
None until one arrives. The value comes from
:func:monotonic_now. Only a response that matched a pending request
counts: a stray, stale-epoch or unmatched datagram does not.
address_epoch
property
¶
address_epoch: int
How many times this connection's endpoint has changed.
Starts at 0 and increases by one for each :meth:update_address that
moved the device. It is a counter for observers (a watcher can tell a
move happened); it is not a correlation key.
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:¶
update_address
¶
Point this connection at a new endpoint without failing anything.
This is the connection-level half of endpoint migration. It only
rebinds where packets go and who is believed; it re-reads nothing
and sends nothing. Callers that hold a device object should use
:meth:lifx.devices.base.Device.update_address, which applies the
same endpoint to the device's own ip and port too.
On a change the address epoch increments, ip/port and the send
address are replaced, and the endpoint just left is remembered so a
late datagram from it is dropped (debug-logged as
stale_epoch_response) instead of being correlated. Requests in
flight are not failed: each keeps listening and its next
retransmission goes to the new endpoint. A move across address
families (IPv4 to IPv6 or back) rebinds the socket on the next send.
The observed transport report survives.
Replies are dropped only when they come from an endpoint this connection has left; a reply from any other source is not rejected for its address. This is not a "current address only" rule: a connection that never moved keeps correlating on source, sequence and serial alone, as before.
An IPv6 zone change counts as a move, because the zone selects the interface the packet leaves on.
| PARAMETER | DESCRIPTION |
|---|---|
ip
|
New device IP address (IPv4 or IPv6 literal, optionally zoned).
TYPE:
|
port
|
New device UDP port.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
|
bool
|
current (a no-op that logs nothing). |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the address or port is not a usable device endpoint. The connection is left unchanged. |
Source code in src/lifx/network/connection.py
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 | |
__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
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 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 | |
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
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 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 | |
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
echo
async
¶
Send an echo request and wait for the response carrying payload.
Uses the connection's normal retransmission. A response whose payload differs from the one sent is ignored rather than accepted.
| PARAMETER | DESCRIPTION |
|---|---|
payload
|
The 64-byte payload to echo
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bytes
|
The echoed payload |
| RAISES | DESCRIPTION |
|---|---|
LifxTimeoutError
|
If no matching response arrives before the deadline |
LifxConnectionError
|
If connection fails |
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.