lutron-control/discover.go
2026-06-28 08:32:22 -05:00

65 lines
1.5 KiB
Go

package main
import (
"bytes"
"fmt"
"strings"
"time"
)
// discoverWindow is how long to read integration responses per device.
const discoverWindow = 3 * time.Second
// runDiscovery connects to each configured device, asks for its integration IDs,
// prints the responses, and returns. It is a config aid, not part of normal
// operation.
func runDiscovery(devices []*DeviceConfig) {
for _, dc := range devices {
discoverDevice(dc)
}
}
// discoverDevice queries one device for its integration IDs and prints what it
// reports.
func discoverDevice(dc *DeviceConfig) {
fmt.Printf("== %s (%s, integration_id %d) ==\n", dc.Name, dc.Transport, dc.IntegrationID)
conn, err := openTransport(dc)
if err != nil {
fmt.Printf(" connect failed: %s\n", err)
return
}
// Print integration responses until the connection is closed.
done := make(chan struct{})
go func() {
defer close(done)
buf := make([]byte, 0, 256)
tmp := make([]byte, 256)
for {
n, err := conn.Read(tmp)
if err != nil {
return
}
buf = append(buf, tmp[:n]...)
for {
i := bytes.IndexByte(buf, '\n')
if i < 0 {
break
}
line := strings.TrimSpace(strings.ReplaceAll(string(buf[:i]), "QSE>", ""))
buf = buf[i+1:]
if line != "" {
fmt.Printf(" %s\n", line)
}
}
}
}()
// "?INTEGRATIONID,3" with no ID prints info for all integration IDs.
if _, err := conn.Write([]byte("?INTEGRATIONID,3" + qseTerminator)); err != nil {
fmt.Printf(" query failed: %s\n", err)
}
time.Sleep(discoverWindow)
conn.Close()
<-done
}