Protocol Layer¶
The protocol layer contains auto-generated structures from the official LIFX protocol specification. These classes handle binary serialization and deserialization of LIFX messages.
!!! warning "Auto-Generated Code" Files in the protocol layer are automatically generated from
protocol.yml. Never edit these files directly. To update the protocol, download the latest
protocol.yml from the LIFX public-protocol repository
and run uv run python -m lifx.protocol.generator.
Base Packet¶
The base class for all protocol packets.
Packet
dataclass
¶
Base class for all LIFX protocol packets.
Each packet subclass defines: - PKT_TYPE: ClassVar[int] - The packet type number - _fields: ClassVar[list[dict]] - Field metadata from protocol.yml - Actual field attributes as dataclass fields
| METHOD | DESCRIPTION |
|---|---|
pack |
Pack packet to bytes using field metadata. |
unpack |
Unpack packet from bytes using field metadata. |
| ATTRIBUTE | DESCRIPTION |
|---|---|
as_dict |
Return packet as dictionary. |
Attributes¶
Functions¶
pack
¶
pack() -> bytes
Pack packet to bytes using field metadata.
| RETURNS | DESCRIPTION |
|---|---|
bytes
|
Packed bytes ready to send in a LIFX message payload |
Source code in src/lifx/protocol/base.py
unpack
classmethod
¶
Unpack packet from bytes using field metadata.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Bytes to unpack from
TYPE:
|
offset
|
Offset in bytes to start unpacking
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Packet
|
Packet instance with label fields decoded to strings |
Source code in src/lifx/protocol/base.py
Protocol Header¶
The LIFX protocol header structure (36 bytes).
LifxHeader
dataclass
¶
LifxHeader(
size: int,
protocol: int,
source: int,
target: bytes,
tagged: bool,
ack_required: bool,
res_required: bool,
sequence: int,
pkt_type: int,
)
LIFX protocol header (36 bytes).
| ATTRIBUTE | DESCRIPTION |
|---|---|
size |
Total packet size in bytes (header + payload)
TYPE:
|
protocol |
Protocol number (must be 1024)
TYPE:
|
source |
Unique client identifier
TYPE:
|
target |
Device serial number (6 or 8 bytes, automatically padded to 8 bytes) Note: This is the LIFX serial number, which is often but not always the same as the device's MAC address.
TYPE:
|
tagged |
True for broadcast discovery, False for targeted messages
TYPE:
|
ack_required |
Request acknowledgement from device
TYPE:
|
res_required |
Request response from device
TYPE:
|
sequence |
Sequence number for matching requests/responses
TYPE:
|
pkt_type |
Packet type identifier
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
__post_init__ |
Validate header fields and auto-pad serial number if needed. |
create |
Create a new LIFX header. |
pack |
Pack header into 36 bytes. |
unpack |
Unpack header from bytes. |
__repr__ |
String representation of header. |
Attributes¶
target_serial
property
¶
target_serial: bytes
Get the 6-byte serial number without padding.
| RETURNS | DESCRIPTION |
|---|---|
bytes
|
6-byte serial number |
Functions¶
__post_init__
¶
Validate header fields and auto-pad serial number if needed.
Source code in src/lifx/protocol/header.py
create
classmethod
¶
create(
pkt_type: int,
source: int,
target: bytes = b"\x00" * 6,
tagged: bool = False,
ack_required: bool = False,
res_required: bool = True,
sequence: int = 0,
payload_size: int = 0,
) -> LifxHeader
Create a new LIFX header.
| PARAMETER | DESCRIPTION |
|---|---|
pkt_type
|
Packet type identifier
TYPE:
|
source
|
Unique client identifier
TYPE:
|
target
|
Device serial number (6 or 8 bytes, defaults to broadcast)
TYPE:
|
tagged
|
True for broadcast, False for targeted
TYPE:
|
ack_required
|
Request acknowledgement
TYPE:
|
res_required
|
Request response
TYPE:
|
sequence
|
Sequence number for matching requests/responses
TYPE:
|
payload_size
|
Size of packet payload in bytes
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
LifxHeader
|
LifxHeader instance |
Source code in src/lifx/protocol/header.py
pack
¶
pack() -> bytes
Pack header into 36 bytes.
| RETURNS | DESCRIPTION |
|---|---|
bytes
|
Packed header bytes |
Source code in src/lifx/protocol/header.py
unpack
classmethod
¶
unpack(data: bytes) -> LifxHeader
Unpack header from bytes.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Header bytes (at least 36 bytes)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
LifxHeader
|
LifxHeader instance |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If data is too short or invalid |
Source code in src/lifx/protocol/header.py
__repr__
¶
__repr__() -> str
String representation of header.
Source code in src/lifx/protocol/header.py
Serializer¶
Binary serialization and deserialization utilities.
FieldSerializer
¶
Serializer for structured fields with nested types.
| PARAMETER | DESCRIPTION |
|---|---|
field_definitions
|
Dict mapping field names to structure definitions |
| METHOD | DESCRIPTION |
|---|---|
pack_field |
Pack a structured field. |
unpack_field |
Unpack a structured field. |
get_field_size |
Get the size in bytes of a field structure. |
Source code in src/lifx/protocol/serializer.py
Functions¶
pack_field
¶
Pack a structured field.
| PARAMETER | DESCRIPTION |
|---|---|
field_data
|
Dictionary of field values |
field_name
|
Name of the field structure (e.g., "HSBK")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bytes
|
Packed bytes |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If field_name is unknown |
Source code in src/lifx/protocol/serializer.py
unpack_field
¶
Unpack a structured field.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Bytes to unpack from
TYPE:
|
field_name
|
Name of the field structure
TYPE:
|
offset
|
Offset to start unpacking
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[dict[str, Any], int]
|
Tuple of (field_dict, new_offset) |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If field_name is unknown |
Source code in src/lifx/protocol/serializer.py
get_field_size
¶
Get the size in bytes of a field structure.
| PARAMETER | DESCRIPTION |
|---|---|
field_name
|
Name of the field structure
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Size in bytes |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If field_name is unknown |
Source code in src/lifx/protocol/serializer.py
Protocol Types¶
Common protocol type definitions and enums.
HSBK Type¶
LightHsbk
dataclass
¶
Auto-generated field structure.
| METHOD | DESCRIPTION |
|---|---|
pack |
Pack to bytes. |
unpack |
Unpack from bytes. |
Functions¶
pack
¶
pack() -> bytes
Pack to bytes.
Source code in src/lifx/protocol/protocol_types.py
unpack
classmethod
¶
Unpack from bytes.
Source code in src/lifx/protocol/protocol_types.py
Light Waveform¶
Device Service¶
MultiZone Application Request¶
Firmware Effect¶
Unified enum for all firmware effects (multizone and matrix devices):
Direction¶
Direction enum for MOVE effects:
Packet Definitions¶
The protocol layer includes packet definitions for all LIFX message types. Major categories include:
Device Messages¶
DeviceGetService/DeviceStateService- Service discoveryDeviceGetLabel/DeviceStateLabel- Device labelsDeviceGetPower/DeviceSetPower/DeviceStatePower- Power controlDeviceGetVersion/DeviceStateVersion- Firmware versionDeviceGetLocation/DeviceStateLocation- Location groupsDeviceGetGroup/DeviceStateGroup- Device groupsDeviceGetInfo/DeviceStateInfo- Runtime info (uptime, downtime)
Light Messages¶
LightGet/LightState- Get/set light stateLightSetColor- Set color with transitionLightSetWaveform- Waveform effects (pulse, breathe)LightGetPower/LightSetPower/LightStatePower- Light power controlLightGetInfrared/LightSetInfrared/LightStateInfrared- Infrared control
MultiZone Messages¶
MultiZoneGetColorZones/MultiZoneStateZone/MultiZoneStateMultiZone- Zone stateMultiZoneSetColorZones- Set zone colorsMultiZoneGetMultiZoneEffect/MultiZoneSetMultiZoneEffect- Zone effects
Tile Messages¶
TileGetDeviceChain/TileStateDeviceChain- Tile chain infoTileGet64/TileState64- Get tile stateTileSet64- Set tile colorsTileGetTileEffect/TileSetTileEffect- Tile effects
Protocol Models¶
Protocol data models for working with LIFX serial numbers and HEV cycles.
Serial¶
Type-safe, immutable serial number handling:
Serial
dataclass
¶
Serial(value: bytes)
LIFX device serial number.
Encapsulates a device serial number with conversion methods for different formats. The LIFX serial number is often the same as the device's MAC address, but can differ (particularly the least significant byte may be off by one).
| ATTRIBUTE | DESCRIPTION |
|---|---|
value |
Serial number as 6 bytes
TYPE:
|
Example
# Create from string
serial = Serial.from_string("d073d5123456")
# Convert to protocol format (8 bytes with padding)
protocol_bytes = serial.to_protocol()
# Convert to string
serial_str = serial.to_string() # "d073d5123456"
# Create from protocol format
serial2 = Serial.from_protocol(protocol_bytes)
| METHOD | DESCRIPTION |
|---|---|
__post_init__ |
Validate serial number after initialization. |
from_string |
Create Serial from string format. |
from_protocol |
Create Serial from protocol format (8 bytes with padding). |
to_string |
Convert serial to 12-digit hex string format. |
to_protocol |
Convert serial to 8-byte protocol format with padding. |
__str__ |
Return string representation. |
__repr__ |
Return detailed representation. |
Functions¶
__post_init__
¶
from_string
classmethod
¶
Create Serial from string format.
Accepts 12-digit hex string (with or without separators).
| PARAMETER | DESCRIPTION |
|---|---|
serial
|
12-digit hex string (e.g., "d073d5123456" or "d0:73:d5:12:34:56")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Serial
|
Serial instance |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If serial number is invalid |
TypeError
|
If serial is not a string |
Example
Serial.from_string("d073d5123456") Serial(value=b'\xd0\x73\xd5\x12\x34\x56') Serial.from_string("d0:73:d5:12:34:56") # Also accepts separators Serial(value=b'\xd0\x73\xd5\x12\x34\x56')
Source code in src/lifx/protocol/models.py
from_protocol
classmethod
¶
Create Serial from protocol format (8 bytes with padding).
The LIFX protocol uses 8 bytes for the target field, with the serial number in the first 6 bytes and 2 bytes of padding (zeros) at the end.
| PARAMETER | DESCRIPTION |
|---|---|
padded_serial
|
8-byte serial number from protocol
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Serial
|
Serial instance |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If padded serial is not 8 bytes |
Example
Serial.from_protocol(b"\xd0\x73\xd5\x12\x34\x56\x00\x00") Serial(value=b'\xd0\x73\xd5\x12\x34\x56')
Source code in src/lifx/protocol/models.py
to_string
¶
to_string() -> str
Convert serial to 12-digit hex string format.
| RETURNS | DESCRIPTION |
|---|---|
str
|
Serial number string in format "xxxxxxxxxxxx" (12 hex digits, no separators) |
Example
serial = Serial.from_string("d073d5123456") serial.to_string() 'd073d5123456'
Source code in src/lifx/protocol/models.py
to_protocol
¶
to_protocol() -> bytes
Convert serial to 8-byte protocol format with padding.
The LIFX protocol uses 8 bytes for the target field, with the serial number in the first 6 bytes and 2 bytes of padding (zeros) at the end.
| RETURNS | DESCRIPTION |
|---|---|
bytes
|
8-byte serial number with padding (suitable for protocol) |
Example
serial = Serial.from_string("d073d5123456") serial.to_protocol() b'\xd0\x73\xd5\x12\x34\x56\x00\x00'
Source code in src/lifx/protocol/models.py
HEV Cycle State¶
HEV (High Energy Visible) cleaning cycle state:
HevCycleState
dataclass
¶
HEV cleaning cycle state.
Represents the current state of a HEV (High Energy Visible) cleaning cycle, which uses anti-bacterial UV-C light to sanitize the environment.
| ATTRIBUTE | DESCRIPTION |
|---|---|
duration_s |
Total duration of the cycle in seconds
TYPE:
|
remaining_s |
Remaining time in the current cycle (0 if not running)
TYPE:
|
last_power |
Whether the light was on during the last cycle
TYPE:
|
Example
HEV Configuration¶
HEV cycle configuration:
HevConfig
dataclass
¶
Code Generator¶
The protocol generator reads protocol.yml and generates Python code.
generator
¶
Code generator for LIFX protocol structures.
Downloads the official protocol.yml from the LIFX GitHub repository and generates Python types and packet classes. The YAML is never stored locally, only parsed and converted into protocol classes.
| CLASS | DESCRIPTION |
|---|---|
TypeRegistry |
Registry of all protocol types for validation. |
| FUNCTION | DESCRIPTION |
|---|---|
to_snake_case |
Convert PascalCase or camelCase to snake_case. |
apply_field_name_quirks |
Apply quirks to field names to avoid Python built-ins and reserved words. |
apply_extended_multizone_packet_quirks |
Apply quirks to extended multizone packet names to follow LIFX naming convention. |
apply_tile_effect_parameter_quirk |
Apply local quirk to fix TileEffectParameter structure. |
apply_sensor_packet_quirks |
Add undocumented sensor packets for ambient light level reading. |
apply_firmware_effect_enum_quirk |
Merge MultiZoneEffectType and TileEffectType into FirmwareEffect enum. |
apply_multizone_application_request_quirk |
Suppress MultiZoneExtendedApplicationRequest enum. |
format_long_import |
Format a long import statement across multiple lines. |
format_long_list |
Format a long list across multiple lines. |
parse_field_type |
Parse a field type string. |
camel_to_snake_upper |
Convert CamelCase to UPPER_SNAKE_CASE. |
generate_enum_code |
Generate Python Enum definitions with shortened names. |
convert_type_to_python |
Convert a protocol field type to Python type annotation. |
generate_pack_method |
Generate pack() method code for a field structure or packet. |
generate_unpack_method |
Generate unpack() classmethod code for a field structure or packet. |
generate_field_code |
Generate Python dataclass definitions for field structures. |
generate_nested_packet_code |
Generate nested Python packet class definitions. |
generate_types_file |
Generate complete types.py file. |
generate_packets_file |
Generate complete packets.py file. |
download_protocol |
Download and parse protocol.yml from LIFX GitHub repository. |
validate_protocol_spec |
Validate protocol specification for missing type references. |
should_skip_button_relay |
Check if a name should be skipped (Button or Relay related). |
filter_button_relay_items |
Filter out Button and Relay items from a dictionary. |
filter_button_relay_packets |
Filter out button and relay category packets. |
extract_packets_as_fields |
Extract packets that are used as field types in other structures. |
main |
Main generator entry point. |
Classes¶
TypeRegistry
¶
Registry of all protocol types for validation.
Tracks all defined types (enums, fields, packets, unions) to validate that all type references in the protocol specification are valid.
| METHOD | DESCRIPTION |
|---|---|
register_enum |
Register an enum type. |
register_field |
Register a field structure type. |
register_packet |
Register a packet type. |
register_union |
Register a union type. |
is_enum |
Check if a type is an enum. |
has_type |
Check if a type is defined. |
get_all_types |
Get all registered types. |
Source code in src/lifx/protocol/generator.py
Functions¶
register_field
¶register_field(name: str) -> None
Register a field structure type.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Field structure type name
TYPE:
|
is_enum
¶ has_type
¶Functions¶
to_snake_case
¶
apply_field_name_quirks
¶
Apply quirks to field names to avoid Python built-ins and reserved words.
| PARAMETER | DESCRIPTION |
|---|---|
python_name
|
The Python field name (usually from to_snake_case)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Quirk-adjusted field name |
Quirks applied
- "type" -> "effect_type" (avoids Python built-in)
Source code in src/lifx/protocol/generator.py
apply_extended_multizone_packet_quirks
¶
Apply quirks to extended multizone packet names to follow LIFX naming convention.
In the LIFX protocol, extended multizone packets should follow the standard naming pattern of {Action}{Object} (e.g., GetExtendedColorZones, SetExtendedColorZones).
| PARAMETER | DESCRIPTION |
|---|---|
packet_name
|
Packet name (after category prefix removal)
TYPE:
|
category_class
|
Category class name (e.g., "MultiZone")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Quirk-adjusted packet name |
Quirks applied
- "ExtendedGetColorZones" -> "GetExtendedColorZones"
- "ExtendedSetColorZones" -> "SetExtendedColorZones"
- "ExtendedStateMultiZone" -> "StateExtendedColorZones"
Source code in src/lifx/protocol/generator.py
apply_tile_effect_parameter_quirk
¶
Apply local quirk to fix TileEffectParameter structure.
The upstream protocol.yml doesn't provide enough detail for TileEffectParameter. This quirk replaces it with the correct structure: - TileEffectSkyType (enum, uint8) - 3 reserved bytes - cloudSaturationMin (uint8) - 3 reserved bytes - cloudSaturationMax (uint8) - 23 reserved bytes Total: 32 bytes
| PARAMETER | DESCRIPTION |
|---|---|
fields
|
Dictionary of field definitions |
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
Dictionary with TileEffectParameter quirk applied |
Source code in src/lifx/protocol/generator.py
apply_sensor_packet_quirks
¶
Add undocumented sensor packets for ambient light level reading.
These packets are not documented in the official protocol.yml but are supported by LIFX devices with ambient light sensors.
Quirks applied
- SensorGetAmbientLight (401): Request packet with no parameters
- SensorStateAmbientLight (402): Response packet with lux field (float)
| PARAMETER | DESCRIPTION |
|---|---|
packets
|
Dictionary of packet definitions |
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
Dictionary with sensor packet quirks applied |
Source code in src/lifx/protocol/generator.py
apply_firmware_effect_enum_quirk
¶
apply_firmware_effect_enum_quirk(
enums: dict[str, Any],
fields: dict[str, Any],
compound_fields: dict[str, Any],
) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]
Merge MultiZoneEffectType and TileEffectType into FirmwareEffect enum.
Both MultiZone and Tile effects use the same firmware effect protocol values, so they should share a single enum. This quirk: - Creates FirmwareEffect enum combining values from both - Removes MultiZoneEffectType and TileEffectType - Updates MultiZoneEffectSettings and TileEffectSettings to use FirmwareEffect - Uses clean enum value names (OFF, MOVE, MORPH, FLAME, SKY, RESERVED_*) - Also adds DIRECTION enum for move effect parameter
| PARAMETER | DESCRIPTION |
|---|---|
enums
|
Dictionary of enum definitions |
fields
|
Dictionary of field definitions |
compound_fields
|
Dictionary of compound field definitions |
| RETURNS | DESCRIPTION |
|---|---|
tuple[dict[str, Any], dict[str, Any], dict[str, Any]]
|
Tuple of (enums, fields, compound_fields) with FirmwareEffect enum quirk applied |
Source code in src/lifx/protocol/generator.py
apply_multizone_application_request_quirk
¶
apply_multizone_application_request_quirk(
enums: dict[str, Any], packets: dict[str, Any]
) -> tuple[dict[str, Any], dict[str, Any]]
Suppress MultiZoneExtendedApplicationRequest enum.
Both MultiZoneApplicationRequest and MultiZoneExtendedApplicationRequest have identical values (NO_APPLY=0, APPLY=1, APPLY_ONLY=2), so we suppress the extended version and use the standard one for both SetColorZones and SetExtendedColorZones packets.
| PARAMETER | DESCRIPTION |
|---|---|
enums
|
Dictionary of enum definitions |
packets
|
Dictionary of packet definitions |
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
Tuple of (enums, packets) with MultiZoneExtendedApplicationRequest removed |
dict[str, Any]
|
and packets updated to use MultiZoneApplicationRequest |
Source code in src/lifx/protocol/generator.py
format_long_import
¶
format_long_import(
items: list[str], prefix: str = "from lifx.protocol.protocol_types import "
) -> str
Format a long import statement across multiple lines.
| PARAMETER | DESCRIPTION |
|---|---|
items
|
List of import items (e.g., ["Foo", "Bar as BazAlias"]) |
prefix
|
Import prefix
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Formatted import string with line breaks if needed |
Source code in src/lifx/protocol/generator.py
format_long_list
¶
Format a long list across multiple lines.
| PARAMETER | DESCRIPTION |
|---|---|
items
|
List of dict items to format |
max_line_length
|
Maximum line length before wrapping
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Formatted list string |
Source code in src/lifx/protocol/generator.py
parse_field_type
¶
Parse a field type string.
| PARAMETER | DESCRIPTION |
|---|---|
field_type
|
Field type (e.g., 'uint16', '[32]uint8', '
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Tuple of (base_type, array_count, is_nested) |
int | None
|
|
bool
|
|
tuple[str, int | None, bool]
|
|
Source code in src/lifx/protocol/generator.py
camel_to_snake_upper
¶
generate_enum_code
¶
Generate Python Enum definitions with shortened names.
| PARAMETER | DESCRIPTION |
|---|---|
enums
|
Dictionary of enum definitions |
| RETURNS | DESCRIPTION |
|---|---|
str
|
Python code string |
Source code in src/lifx/protocol/generator.py
convert_type_to_python
¶
Convert a protocol field type to Python type annotation.
| PARAMETER | DESCRIPTION |
|---|---|
field_type
|
Protocol field type string
TYPE:
|
type_aliases
|
Optional dict for type name aliases |
| RETURNS | DESCRIPTION |
|---|---|
str
|
Python type annotation string |
Source code in src/lifx/protocol/generator.py
generate_pack_method
¶
generate_pack_method(
fields_data: list[dict[str, Any]],
class_type: str = "field",
enum_types: set[str] | None = None,
) -> str
Generate pack() method code for a field structure or packet.
| PARAMETER | DESCRIPTION |
|---|---|
fields_data
|
List of field definitions |
class_type
|
Either "field" or "packet"
TYPE:
|
enum_types
|
Set of enum type names for detection |
| RETURNS | DESCRIPTION |
|---|---|
str
|
Python method code string |
Source code in src/lifx/protocol/generator.py
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 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 | |
generate_unpack_method
¶
generate_unpack_method(
class_name: str,
fields_data: list[dict[str, Any]],
class_type: str = "field",
enum_types: set[str] | None = None,
) -> str
Generate unpack() classmethod code for a field structure or packet.
| PARAMETER | DESCRIPTION |
|---|---|
class_name
|
Name of the class
TYPE:
|
fields_data
|
List of field definitions |
class_type
|
Either "field" or "packet"
TYPE:
|
enum_types
|
Set of enum type names for detection |
| RETURNS | DESCRIPTION |
|---|---|
str
|
Python method code string |
Source code in src/lifx/protocol/generator.py
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 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 774 775 776 777 778 779 780 781 782 783 784 785 786 | |
generate_field_code
¶
generate_field_code(
fields: dict[str, Any],
compound_fields: dict[str, Any] | None = None,
unions: dict[str, Any] | None = None,
packets_as_fields: dict[str, Any] | None = None,
enum_types: set[str] | None = None,
) -> tuple[str, dict[str, dict[str, str]]]
Generate Python dataclass definitions for field structures.
| PARAMETER | DESCRIPTION |
|---|---|
fields
|
Dictionary of field definitions |
compound_fields
|
Dictionary of compound field definitions |
unions
|
Dictionary of union definitions (treated as fields) |
packets_as_fields
|
Dictionary of packets that are also used as field types |
enum_types
|
Set of enum type names |
| RETURNS | DESCRIPTION |
|---|---|
str
|
Tuple of (code string, field mappings dict) |
dict[str, dict[str, str]]
|
Field mappings: {ClassName: {python_name: protocol_name}} |
Source code in src/lifx/protocol/generator.py
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 | |
generate_nested_packet_code
¶
generate_nested_packet_code(
packets: dict[str, Any], type_aliases: dict[str, str] | None = None
) -> str
Generate nested Python packet class definitions.
| PARAMETER | DESCRIPTION |
|---|---|
packets
|
Dictionary of packet definitions (grouped by category) |
type_aliases
|
Optional dict mapping type names to their aliases (for collision resolution) |
| RETURNS | DESCRIPTION |
|---|---|
str
|
Python code string with nested packet classes |
Source code in src/lifx/protocol/generator.py
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 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 | |
generate_types_file
¶
generate_types_file(
enums: dict[str, Any],
fields: dict[str, Any],
compound_fields: dict[str, Any] | None = None,
unions: dict[str, Any] | None = None,
packets_as_fields: dict[str, Any] | None = None,
) -> str
Generate complete types.py file.
| PARAMETER | DESCRIPTION |
|---|---|
enums
|
Enum definitions |
fields
|
Field structure definitions |
compound_fields
|
Compound field definitions |
unions
|
Union definitions |
packets_as_fields
|
Packets that are also used as field types |
| RETURNS | DESCRIPTION |
|---|---|
str
|
Complete Python file content |
Source code in src/lifx/protocol/generator.py
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 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 | |
generate_packets_file
¶
generate_packets_file(
packets: dict[str, Any],
fields: dict[str, Any],
compound_fields: dict[str, Any] | None = None,
unions: dict[str, Any] | None = None,
packets_as_fields: dict[str, Any] | None = None,
enums: dict[str, Any] | None = None,
) -> str
Generate complete packets.py file.
| PARAMETER | DESCRIPTION |
|---|---|
packets
|
Packet definitions |
fields
|
Field definitions (for imports) |
compound_fields
|
Compound field definitions (for imports) |
unions
|
Union definitions (for imports) |
packets_as_fields
|
Packets that are also used as field types (for imports) |
enums
|
Enum definitions for detecting enum types |
| RETURNS | DESCRIPTION |
|---|---|
str
|
Complete Python file content |
Source code in src/lifx/protocol/generator.py
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 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 | |
download_protocol
¶
Download and parse protocol.yml from LIFX GitHub repository.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
Parsed protocol dictionary |
| RAISES | DESCRIPTION |
|---|---|
URLError
|
If download fails |
YAMLError
|
If parsing fails |
Source code in src/lifx/protocol/generator.py
validate_protocol_spec
¶
Validate protocol specification for missing type references.
| PARAMETER | DESCRIPTION |
|---|---|
protocol
|
Parsed protocol dictionary |
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
List of error messages (empty if validation passes) |
Source code in src/lifx/protocol/generator.py
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 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 | |
should_skip_button_relay
¶
Check if a name should be skipped (Button or Relay related).
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Type name to check (enum, field, union, packet, or category)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if the name starts with Button or Relay, False otherwise |
Source code in src/lifx/protocol/generator.py
filter_button_relay_items
¶
Filter out Button and Relay items from a dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
items
|
Dictionary of items to filter |
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
Filtered dictionary without Button/Relay items |
Source code in src/lifx/protocol/generator.py
filter_button_relay_packets
¶
Filter out button and relay category packets.
| PARAMETER | DESCRIPTION |
|---|---|
packets
|
Dictionary of packet definitions (grouped by category) |
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
Filtered dictionary without button/relay categories |
Source code in src/lifx/protocol/generator.py
extract_packets_as_fields
¶
Extract packets that are used as field types in other structures.
| PARAMETER | DESCRIPTION |
|---|---|
packets
|
Dictionary of packet definitions |
fields
|
Dictionary of field definitions to scan |
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
Dictionary of packet definitions that are referenced as field types |
Source code in src/lifx/protocol/generator.py
main
¶
Main generator entry point.
Source code in src/lifx/protocol/generator.py
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 1624 1625 1626 1627 1628 | |
Examples¶
Working with Serial Numbers¶
The Serial dataclass provides type-safe, immutable serial number handling:
from lifx.protocol.models import Serial
# Create from string (accepts hex with or without separators)
serial = Serial.from_string("d073d5123456")
serial = Serial.from_string("d0:73:d5:12:34:56") # Also works
# Convert between formats
protocol_bytes = serial.to_protocol() # 8 bytes with padding
serial_string = serial.to_string() # "d073d5123456"
serial_bytes = serial.value # 6 bytes (immutable/frozen)
# Create from protocol format (8 bytes)
serial = Serial.from_protocol(b"\xd0\x73\xd5\x12\x34\x56\x00\x00")
print(serial) # "d073d5123456"
# String representations
print(str(serial)) # "d073d5123456"
print(repr(serial)) # "Serial('d073d5123456')"
Using Protocol Packets Directly¶
from lifx.network.connection import DeviceConnection
from lifx.protocol.packets import LightSetColor, LightGet, LightState
from lifx.protocol.protocol_types import LightHsbk
from lifx.protocol.models import Serial
async def main():
serial = Serial.from_string("d073d5123456")
async with DeviceConnection(serial.to_string(), "192.168.1.100") as conn:
# Create a packet
packet = LightSetColor(
reserved=0,
color=LightHsbk(
hue=240 * 182, saturation=65535, brightness=32768, kelvin=3500
),
duration=1000, # milliseconds
)
# Send without waiting for response
await conn.send_packet(packet)
# Request with response
response = await conn.request_response(LightGet(), LightState)
print(f"Hue: {response.color.hue / 182}°")
Binary Serialization¶
from lifx.protocol.packets import DeviceSetLabel
from lifx.protocol.serializer import Serializer
# Create packet
packet = DeviceSetLabel(label=b"Kitchen Light\0" + b"\0" * 19)
# Serialize to bytes
data = packet.pack()
print(f"Packet size: {len(data)} bytes")
# Deserialize from bytes
unpacked = DeviceSetLabel.unpack(data)
print(f"Label: {unpacked.label.decode('utf-8').rstrip('\0')}")
Protocol Header¶
from lifx.protocol.header import LifxHeader
from lifx.protocol.models import Serial
# Create header with Serial
serial = Serial.from_string("d073d5123456")
header = LifxHeader(
size=36,
protocol=1024,
addressable=True,
tagged=False,
origin=0,
source=0x12345678,
target=serial.to_protocol(), # 8 bytes with padding
reserved1=b"\x00" * 6,
ack_required=False,
res_required=True,
sequence=42,
reserved2=0,
pkt_type=101, # LightGet
reserved3=0,
)
# Serialize
data = header.pack()
print(f"Header: {data.hex()}")
# Deserialize
unpacked_header = LifxHeader.unpack(data)
print(f"Packet type: {unpacked_header.pkt_type}")
print(f"Target serial: {Serial.from_protocol(unpacked_header.target)}")
Protocol Constants¶
Message Types¶
Each packet class has a PKT_TYPE constant defining its protocol message type:
from lifx.protocol.packets import LightSetColor, LightGet, DeviceGetLabel
print(f"LightSetColor type: {LightSetColor.PKT_TYPE}") # 102
print(f"LightGet type: {LightGet.PKT_TYPE}") # 101
print(f"DeviceGetLabel type: {DeviceGetLabel.PKT_TYPE}") # 23
Waveform Types¶
from lifx.protocol.protocol_types import LightWaveform
# Available waveforms
LightWaveform.SAW
LightWaveform.SINE
LightWaveform.HALF_SINE
LightWaveform.TRIANGLE
LightWaveform.PULSE
Firmware Effects¶
from lifx.protocol.protocol_types import FirmwareEffect, Direction
# Available firmware effects (for multizone and matrix devices)
FirmwareEffect.OFF
FirmwareEffect.MOVE # MultiZone only
FirmwareEffect.MORPH # Tile/Matrix only
FirmwareEffect.FLAME # Tile/Matrix only
FirmwareEffect.SKY # Tile/Matrix only
# Direction for MOVE effects
Direction.FORWARD # Move forward through zones
Direction.REVERSED # Move backward through zones
Product Registry¶
The product registry provides automatic device type detection and capability information:
ProductInfo
dataclass
¶
ProductInfo(
pid: int,
name: str,
vendor: int,
capabilities: int,
temperature_range: TemperatureRange | None,
min_ext_mz_firmware: int | None,
)
Information about a LIFX product.
| ATTRIBUTE | DESCRIPTION |
|---|---|
pid |
Product ID
TYPE:
|
name |
Product name
TYPE:
|
vendor |
Vendor ID (always 1 for LIFX)
TYPE:
|
capabilities |
Bitfield of ProductCapability flags
TYPE:
|
temperature_range |
Min/max color temperature in Kelvin
TYPE:
|
min_ext_mz_firmware |
Minimum firmware version for extended multizone
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
has_capability |
Check if product has a specific capability. |
supports_extended_multizone |
Check if extended multizone is supported for given firmware version. |
Attributes¶
has_extended_multizone
property
¶
has_extended_multizone: bool
Check if product supports extended multizone.
Functions¶
has_capability
¶
has_capability(capability: ProductCapability) -> bool
Check if product has a specific capability.
| PARAMETER | DESCRIPTION |
|---|---|
capability
|
Capability to check
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if product has the capability |
Source code in src/lifx/products/registry.py
supports_extended_multizone
¶
Check if extended multizone is supported for given firmware version.
| PARAMETER | DESCRIPTION |
|---|---|
firmware_version
|
Firmware version to check (optional)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if extended multizone is supported |
Source code in src/lifx/products/registry.py
Using the Product Registry¶
from lifx.products import get_product, get_device_class_name
# Get product info by product ID
product_info = get_product(product_id=27)
# Get appropriate device class name
class_name = get_device_class_name(product_id=27) # Returns "Light", "MultiZoneLight", etc.
Protocol Updates¶
To update to the latest LIFX protocol:
- Download the latest
protocol.ymlfrom the LIFX public-protocol repository - Save it to the project root
- Run the generator:
uv run python -m lifx.protocol.generator - Review the generated code changes
- Run tests:
uv run pytest
The generator will automatically:
- Parse the YAML specification
- Generate Python dataclasses for all packet types
- Create enums for protocol constants
- Add serialization/deserialization methods
- Filter out Button/Relay messages (out of scope)