swift-lifx

一个现代 Swift 库,用于控制 LIFX 智能灯

目前处于 alpha 阶段,支持 LAN 协议的部分功能,但尚未支持 LIFX Cloud。

安装

使用 Swift Package Manager 将此仓库添加到您的 Xcode 项目中。

用法

基本用法

import Lifx

let client = try! LifxLanClient()

func example() {
    
    //To control a device with a known address
    let device = LifxDevice(macAddress: MacAddr("D0:73:D5:15:00:00"), ipAddress: "10.0.0.44")

    //Turn the light on
    client.setPower(true, for: device)

    //Set the color to red
    client.setColor(.red, for: device)
    
    //Set a custom color and brightness level
    client.setColor(HSBK(hue: 240/360, saturation: 1.0, brightness: 0.75), for: device)

    //Set the color to white with a specific color temperature
    client.setColor(HSBK(brightness: 1.0, colorTemperature: .coolDaylight), for: device)

}

发现示例

import Lifx

class Example: LifxLanClientDelegate {
    let client: LifxLanClient
    
    init() throws {
        client = try LifxLanClient()
        client.delegate = self
        client.startRefreshing()
    }
    
    func lifxClient(_ client: LifxLanClient, didAdd device: LifxDevice) {
        print("Discovered device \(device)")
    }
    
    func lifxClient(_ client: LifxLanClient, didUpdate device: LifxDevice) {
        if let label = device.label, let location = device.location {
            print("Device \(device) is named \(label) and located at \(location)")
        }
    }
}

SwiftUI 示例

该库可以将其发现状态作为 ObservableObject 提供,并支持双向动态状态更新。 如果您修改 LifxDevice 对象上的属性,它将影响实际灯光,反之亦然。

import Lifx
import SwiftUI

struct ExampleView: View {
    @EnvironmentObject var lifx: LifxState
    
    var body: some View {
        List(lifx.devices) { device in
            PowerSwitch(device: device)
        }
    }
}

struct PowerSwitch: View {
    @ObservedObject var device: LifxDevice
    
    var isOn: Binding<Bool> {
        Binding(get: {
            return self.device.powerOn == true
        }, set: {
            self.device.powerOn = $0
        })
    }
    
    var body: some View {
        Toggle(isOn: isOn) {
            Text(device.label ?? device.ipAddress)
        }
            .toggleStyle(SwitchToggleStyle())
            .disabled(device.powerOn == nil)
    }
}

您将像这样实例化上述视图层级结构(例如,在您的 AppDelegate 中)

let client = try! LifxLanClient()

let view = ExampleView()
    .environmentObject(client.state)

client.startRefreshing()