in json-rpc/Sources/LightsdDemo/main.swift [108:195]
func show(_ client: TCPClient) {
let colors: [Color] = [.red, .orange, .yellow, .green, .blue, .purple]
// read lights state
var bulbs: [Lifx]
switch try! client.call(method: "get_light_state", params: RPCObject(["target": "*"])).wait() {
case .failure(let error):
fatalError("get_light_state failed with \(error)")
case .success(let response):
switch response {
case .list(let value):
bulbs = value.map { Lifx($0) }.compactMap { $0 }
default:
fatalError("unexpected reponse with \(response)")
}
}
if 0 == bulbs.count {
fatalError("no bulbs found")
}
off(client, id: "*")
sleep(1)
var bulbIndex = 0
for _ in 0 ..< bulbs.count * 10 {
for (index, bulb) in bulbs.enumerated() {
if index == bulbIndex {
on(client, id: bulb.id, color: .white, transition: 100)
} else {
off(client, id: bulb.id)
}
}
bulbIndex = bulbIndex < bulbs.count - 1 ? bulbIndex + 1 : 0
usleep(300_000)
}
off(client, id: "*")
sleep(1)
bulbIndex = 0
for colorIndex in 0 ..< colors.count {
for _ in 0 ..< bulbs.count {
for (index, bulb) in bulbs.enumerated() {
if index == bulbIndex {
on(client, id: bulb.id, color: colors[colorIndex], transition: 100)
} else {
off(client, id: bulb.id)
}
}
bulbIndex = bulbIndex < bulbs.count - 1 ? bulbIndex + 1 : 0
usleep(300_000)
}
}
off(client, id: "*")
sleep(1)
bulbIndex = 0
var colorIndex = 0
for _ in 0 ..< bulbs.count * colors.count {
for (index, bulb) in bulbs.enumerated() {
if index == bulbIndex {
on(client, id: bulb.id, color: colors[colorIndex], transition: 100)
colorIndex = colorIndex < colors.count - 1 ? colorIndex + 1 : 0
} else {
off(client, id: bulb.id)
}
}
bulbIndex = bulbIndex < bulbs.count - 1 ? bulbIndex + 1 : 0
usleep(300_000)
}
off(client, id: "*")
sleep(1)
var colorsMap: [String: Color] = bulbs.enumerated().reduce(into: [String: Color]()) {
$0[$1.element.id] = $1.offset < colors.count ? colors[$1.offset] : colors.first!
}
while true {
for bulb in bulbs {
let clr = colorsMap[bulb.id] ?? colors.first!
on(client, id: bulb.id, color: clr, transition: 100)
let newIndex = colors.firstIndex(of: clr)! + 1
colorsMap[bulb.id] = newIndex < colors.count ? colors[newIndex] : colors.first!
}
usleep(300_000)
}
}