lifxlan

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 25, 2025 License: MIT Imports: 15 Imported by: 0

README

LIFX LAN

lifxlan is simple Go library for interacting with LIFX devices via the LIFX LAN Protocol.

Installation

go get github.com/murphy28/lifxlan

Features
  • Discover LIFX devices over the LAN
  • Ping devices
  • Rename Devices
  • View device product info
  • Turn devices on and off
  • Set device color using RGB, HSV, Hex Colors, or by passing in a color from go-colorful
Example

In the example below, a new LIFX client is created, device discovery runs for 5 seconds, all discovered devices are turned on, and the device named "Nightstand" is set to a purple color.

package main

import (
	"fmt"
	"time"

	"github.com/murphy28/lifxlan"
)

func main() {

	// Create a new LIFX client
	lifx, err := lifxlan.NewClient()
	if err != nil {
		fmt.Println("Error creating LIFX client:", err)
		return
	}
	defer lifx.Close()

	// Discover LIFX devices on the network
	err = lifx.Discover(5 * time.Second)
	if err != nil {
		fmt.Println("Error discovering LIFX devices:", err)
		return
	}

	// Get the list of devices
	devices := lifx.GetDevices()

	// Turn on all devices
	for _, device := range devices {
		device.TurnOn()
	}

	// Set an individual device to a specific color
	lifx.SetColor("Nightstand", lifxlan.NewColorFromRGB(144, 48, 240), 5*time.Second)

}

For more detailed documentation, check out the wiki!

Supported Devices

This library was built with standard LIFX bulbs in mind. I do not own any of the fancier LIFX devices, but support will come if I get the chance. All code was tested on the LIFX Color.

While there are no concrete plans to support other LIFX devices, there are other libraries that may fit your needs.

Documentation

Index

Constants

View Source
const (
	LifxPort   = 56700       // Default UDP port for LIFX LAN protocol
	HeaderSize = 8 + 16 + 12 // Frame Header + Frame Address + Protocol Header Size
	Protocol   = 1024        // LIFX Protocol Number
)

Variables

View Source
var BroadcastAddress = net.UDPAddr{IP: net.IPv4bcast, Port: LifxPort}
View Source
var (
	ProductsByVendorIDAndProductID map[int]map[int]Product
)

Functions

func BuildDiscoveryPacket

func BuildDiscoveryPacket(source uint32) []byte

BuildDiscoveryPacket creates a discovery packet

func BuildEchoRequestPacket

func BuildEchoRequestPacket(source uint32, target []byte, echo []byte) []byte

func BuildGetLabelPacket

func BuildGetLabelPacket(source uint32, target []byte) []byte

BuildGetLabelPacket creates a packet to get the label of a device

func BuildGetVersionPacket

func BuildGetVersionPacket(source uint32, target []byte) []byte

BuildGetVersionPacket creates a packet to get the version of a device

func BuildSetColorPacket

func BuildSetColorPacket(source uint32, target []byte, color LIFXColor, duration time.Duration) []byte

BuildSetColorPacket creates a packet to set the color of a device

func BuildSetLabelPacket

func BuildSetLabelPacket(source uint32, target []byte, label string) []byte

BuildSetLabelPacket creates a packet to set the label of a device

func BuildSetPowerPacket

func BuildSetPowerPacket(source uint32, target []byte, on bool) []byte

BuildSetPowerPacket creates a packet to set the power state of a device

func InitializeProducts

func InitializeProducts() error

func PrintProduct

func PrintProduct(product Product)

func SanitizeLabel

func SanitizeLabel(label string) string

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient() (*Client, error)

func (*Client) BroadcastPacket

func (c *Client) BroadcastPacket(packet []byte) error

BroadcastPacket sends a packet to the broadcast address

func (*Client) ClearDevices

func (c *Client) ClearDevices()

ClearDevices clears the list of discovered devices

func (*Client) Close

func (c *Client) Close() error

Close closes the UDP connection

func (*Client) Discover

func (c *Client) Discover(timeout time.Duration) error

Discover sends a discovery packet and listens for responses

func (*Client) ExportJSON

func (c *Client) ExportJSON() string

ExportJSON exports the discovered devices as a JSON string

func (*Client) GetDeviceByLabel

func (c *Client) GetDeviceByLabel(label string) (*Device, error)

func (*Client) GetDeviceLabels

func (c *Client) GetDeviceLabels() []string

GetDeviceLabels returns a list of labels for all discovered devices

func (*Client) GetDevices

func (c *Client) GetDevices() []Device

Devices returns the list of discovered devices

func (*Client) LoadDevices

func (c *Client) LoadDevices(jsonData string) error

LoadDevices loads devices from a JSON string

func (*Client) RefreshDeviceInfo

func (c *Client) RefreshDeviceInfo()

func (*Client) Send

func (c *Client) Send(packet []byte, addr *net.UDPAddr) error

Send sends a packet to a specific address

func (*Client) SendAndWait

func (c *Client) SendAndWait(packet []byte, addr *net.UDPAddr, expectedType PacketType, timeout time.Duration) ([]byte, error)

SendAndWait sends a packet and waits for a response

func (*Client) SetColor

func (c *Client) SetColor(label string, color LIFXColor, duration time.Duration) error

SetColor sets the color of the device that matches the given label

func (*Client) SetLabel

func (c *Client) SetLabel(oldLabel, newLabel string) error

SetLabel sets the label of the device that matches the given label

func (*Client) TurnOff

func (c *Client) TurnOff(label string) error

TurnOff turns on the device that matches the given label

func (*Client) TurnOn

func (c *Client) TurnOn(label string) error

TurnOn turns on the device that matches the given label

type Device

type Device struct {
	MAC []byte `json:"mac"`
	IP  net.IP `json:"ip"`

	Label   string  `json:"label"`
	Product Product `json:"product"`
	// contains filtered or unexported fields
}

func NewDevice

func NewDevice(mac []byte, ip net.IP, c *Client) *Device

func (*Device) ExportDeviceJSON

func (d *Device) ExportDeviceJSON() string

ExportJSON exports the device information as a JSON string using marshall

func (*Device) GetLabel

func (d *Device) GetLabel() (string, error)

func (*Device) GetMACAddress

func (d *Device) GetMACAddress() string

func (*Device) GetProduct

func (d *Device) GetProduct() (Product, error)

func (*Device) Ping

func (d *Device) Ping() bool

func (*Device) RefreshInfo

func (d *Device) RefreshInfo() error

RefreshInfo refreshes the device information by getting the label and product details

func (*Device) Send

func (d *Device) Send(packet []byte) error

func (*Device) SendAndWait

func (d *Device) SendAndWait(packet []byte, pktType PacketType, duration time.Duration) ([]byte, error)

func (*Device) SetColor

func (d *Device) SetColor(color LIFXColor, duration time.Duration) error

func (*Device) SetLabel

func (d *Device) SetLabel(label string) error

func (*Device) TurnOff

func (d *Device) TurnOff() error

func (*Device) TurnOn

func (d *Device) TurnOn() error

func (*Device) UDPAddr

func (d *Device) UDPAddr() *net.UDPAddr

type Features

type Features struct {
	Hev               bool   `json:"hev"`
	Color             bool   `json:"color"`
	Chain             bool   `json:"chain"`
	Matrix            bool   `json:"matrix"`
	Relays            bool   `json:"relays"`
	Buttons           bool   `json:"buttons"`
	Infrared          bool   `json:"infrared"`
	Multizone         bool   `json:"multizone"`
	TemperatureRange  [2]int `json:"temperature_range"` // [min, max] in Kelvin
	ExtendedMultizone bool   `json:"extended_multizone"`
}
type Header [HeaderSize]byte

Header represents a 36-byte LIFX protocol header (https://lan.developer.lifx.com/docs/packet-contents#header)

func DefaultHeader

func DefaultHeader(source uint32, target []byte, packetType PacketType, payloadSize uint16) *Header

func NewHeader

func NewHeader(source uint32) *Header

func ParseHeader

func ParseHeader(data []byte) (*Header, error)

ParseHeader parses the first 36 bytes into a Header struct

func (*Header) AckRequired

func (h *Header) AckRequired() bool

AckRequired returns true if the ack required bit (bit 1 of byte 15) is set

func (*Header) Addressable

func (h *Header) Addressable() bool

Addressable returns true if the addressable bit is set

func (*Header) PackHeader

func (h *Header) PackHeader() []byte

PackHeader converts the header to a byte slice

func (*Header) Protocol

func (h *Header) Protocol() uint16

Protocol returns the protocol number

func (*Header) ResponseRequired

func (h *Header) ResponseRequired() bool

ResponseRequired returns true if the response required bit (bit 0 of byte 15) is set

func (*Header) Sequence

func (h *Header) Sequence() uint8

Sequence returns the sequence number

func (*Header) SetAckRequired

func (h *Header) SetAckRequired(ackRequired bool)

SetAckRequired sets the ack required bit to a boolean value

func (*Header) SetAddressable

func (h *Header) SetAddressable(addressable bool)

SetAddressable sets the addressable bit to a boolean value

func (*Header) SetResponseRequired

func (h *Header) SetResponseRequired(responseRequired bool)

SetResponseRequired sets the response required bit to a boolean value

func (*Header) SetSequence

func (h *Header) SetSequence(sequence uint8)

SetSequence sets the sequence number

func (*Header) SetSize

func (h *Header) SetSize(size uint16)

SetSize sets the total message size

func (*Header) SetSource

func (h *Header) SetSource(source uint32)

SetSource sets the client source identifier

func (*Header) SetTagged

func (h *Header) SetTagged(tagged bool)

SetTagged sets the tagged bit to a boolean value

func (*Header) SetTarget

func (h *Header) SetTarget(mac []byte)

SetTarget sets the target MAC address from bytes

func (*Header) SetType

func (h *Header) SetType(packetType PacketType)

SetType sets the packet type

func (*Header) Size

func (h *Header) Size() uint16

Size returns the total message size

func (*Header) Source

func (h *Header) Source() uint32

Source returns the client source identifier

func (*Header) Tagged

func (h *Header) Tagged() bool

Tagged returns true if the tagged bit is set

func (*Header) Target

func (h *Header) Target() []byte

Target returns the 6-byte MAC address as a byte slice

func (*Header) Type

func (h *Header) Type() PacketType

Type returns the payload type

type LIFXColor

type LIFXColor struct {
	// contains filtered or unexported fields
}

func ColorfulToLifxColor

func ColorfulToLifxColor(color colorful.Color) LIFXColor

func NewColor

func NewColor(hue, saturation, brightness, kelvin uint16) LIFXColor

func NewColorFromHSV

func NewColorFromHSV(h, s, v float64) LIFXColor

func NewColorFromHex

func NewColorFromHex(hex string) (LIFXColor, error)

func NewColorFromRGB

func NewColorFromRGB(r, g, b uint8) LIFXColor

func (*LIFXColor) GetBrightness

func (c *LIFXColor) GetBrightness() float64

func (*LIFXColor) GetHue

func (c *LIFXColor) GetHue() float64

func (*LIFXColor) GetKelvin

func (c *LIFXColor) GetKelvin() float64

func (*LIFXColor) GetSaturation

func (c *LIFXColor) GetSaturation() float64

func (*LIFXColor) SetBrightness

func (c *LIFXColor) SetBrightness(brightness float64)

func (*LIFXColor) SetHue

func (c *LIFXColor) SetHue(hue float64)

func (*LIFXColor) SetKelvin

func (c *LIFXColor) SetKelvin(kelvin float64)

func (*LIFXColor) SetSaturation

func (c *LIFXColor) SetSaturation(saturation float64)

type PacketType

type PacketType uint16
const (
	GetService PacketType = 2 // Discovery Request

	GetHostFirmware PacketType = 14
	GetWifiInfo     PacketType = 16
	GetWifiFirmware PacketType = 18
	GetPower        PacketType = 20
	GetLabel        PacketType = 23
	GetVersion      PacketType = 32
	GetInfo         PacketType = 34
	GetLocation     PacketType = 48
	GetGroup        PacketType = 51
	EchoRequest     PacketType = 58

	GetColor                 PacketType = 101
	GetLightPower            PacketType = 116
	GetInfrared              PacketType = 120
	GetHevCycle              PacketType = 142
	GetHevCycleConfiguration PacketType = 145
	GetLastHevCycleResult    PacketType = 148

	GetColorZones         PacketType = 502
	GetMultiZoneEffect    PacketType = 507
	GetExtendedColorZones PacketType = 511

	GetRPower PacketType = 816

	GetDeviceChain        PacketType = 701
	Get64                 PacketType = 707
	GetTileEffect         PacketType = 718
	SensorGetAmbientLight PacketType = 401
)
const (
	SetPower    PacketType = 21
	SetLabel    PacketType = 24
	SetReboot   PacketType = 38
	SetLocation PacketType = 49
	SetGroup    PacketType = 52

	SetColor                 PacketType = 102
	SetWaveform              PacketType = 103
	SetLightPower            PacketType = 117
	SetWafeformOptional      PacketType = 119
	SetInfrared              PacketType = 122
	SetHevCycle              PacketType = 143
	SetHevCycleConfiguration PacketType = 146

	SetColorZones         PacketType = 501
	SetMultiZoneEffect    PacketType = 508
	SetExtendedColorZones PacketType = 510

	SetRPower PacketType = 817

	SetUserPosition PacketType = 703
	Set64           PacketType = 715
	SetTileEffect   PacketType = 719
)
const (
	Acknowledgement PacketType = 45 // Returned when `ack_required=1` is specified.

	StateService PacketType = 3 // Discovery Response

	StateHostFirmware PacketType = 15
	StateWifiInfo     PacketType = 17
	StateWifiFirmware PacketType = 19
	StatePower        PacketType = 22
	StateLabel        PacketType = 25
	StateVersion      PacketType = 33
	StateInfo         PacketType = 35
	StateLocation     PacketType = 50
	StateGroup        PacketType = 53
	EchoResponse      PacketType = 59
	StateUnhandled    PacketType = 223

	LightState                 PacketType = 107
	StateLightPower            PacketType = 118
	StateInfrared              PacketType = 121
	StateHevCycle              PacketType = 144
	StateHevCycleConfiguration PacketType = 147
	StateLastHevCycleResult    PacketType = 149

	StateZone               PacketType = 503
	StateMultiZone          PacketType = 506
	StateMultiZoneEffect    PacketType = 509
	StateExtendedColorZones PacketType = 512

	StateRPower PacketType = 818

	StateDeviceChain  PacketType = 702
	State64           PacketType = 711
	StateTileEffect   PacketType = 720
	StateAmbientLight PacketType = 402
)

type Product

type Product struct {
	ProductID int      `json:"pid"`
	Name      string   `json:"name"`
	Features  Features `json:"features"`
	Upgrades  []struct {
		Major    int      `json:"major"`
		Minor    int      `json:"minor"`
		Features Features `json:"features"`
	}
}

func GetProduct

func GetProduct(vendorID, productID int) (Product, error)

GetProduct returns the product information for a given vendor ID and product ID

type Vendor

type Vendor struct {
	VendorID int       `json:"vid"`
	Name     string    `json:"name"`
	Defaults Features  `json:"defaults"`
	Products []Product `json:"products"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL