You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

291 lines
5.7 KiB

package hue
import (
"bytes"
"context"
"encoding/json"
"fmt"
"git.aiterp.net/lucifer/new-server/models"
"golang.org/x/sync/errgroup"
"io"
"net/http"
"strings"
"sync"
)
type Bridge struct {
mu sync.Mutex
host string
token string
externalID int
lightStates []*hueLightState
sensorStates []*hueSensorState
}
func (b *Bridge) Refresh(ctx context.Context) error {
lightMap, err := b.getLights(ctx)
if err != nil {
return err
}
b.mu.Lock()
for index, light := range lightMap {
var state *hueLightState
for _, existingState := range b.lightStates {
if existingState.index == index {
state = existingState
}
}
if state == nil {
state = &hueLightState{
index: index,
uniqueID: light.Uniqueid,
externalID: -1,
info: light,
}
b.lightStates = append(b.lightStates, state)
} else {
if light.Uniqueid != state.uniqueID {
state.uniqueID = light.Uniqueid
state.externalID = -1
}
}
state.CheckStaleness(light.State)
}
b.mu.Unlock()
sensorMap, err := b.getSensors(ctx)
if err != nil {
return err
}
b.mu.Lock()
for index, sensor := range sensorMap {
var state *hueSensorState
for _, existingState := range b.sensorStates {
if existingState.index == index {
state = existingState
}
}
if state == nil {
state = &hueSensorState{
index: index,
uniqueID: sensor.UniqueID,
externalID: -1,
}
b.sensorStates = append(b.sensorStates, state)
} else {
if sensor.UniqueID != state.uniqueID {
state.uniqueID = sensor.UniqueID
state.externalID = -1
}
}
}
b.mu.Unlock()
return nil
}
func (b *Bridge) SyncStale(ctx context.Context) error {
indices := make([]int, 0, 4)
inputs := make([]LightStateInput, 0, 4)
eg, ctx := errgroup.WithContext(ctx)
b.mu.Lock()
for _, state := range b.lightStates {
if !state.stale {
continue
}
indices = append(indices, state.index)
inputs = append(inputs, state.input)
}
b.mu.Unlock()
if len(inputs) == 0 {
return nil
}
for i, input := range inputs {
index := indices[i]
inputCopy := input
eg.Go(func() error { return b.putLightState(ctx, index, inputCopy) })
}
return eg.Wait()
}
func (b *Bridge) SyncSensors(ctx context.Context) ([]models.Event, error) {
sensorMap, err := b.getSensors(ctx)
if err != nil {
return nil, err
}
var events []models.Event
b.mu.Lock()
for idx, sensorData := range sensorMap {
for _, state := range b.sensorStates {
if idx == state.index {
event := state.Update(sensorData)
if event != nil {
events = append(events, *event)
}
break
}
}
}
b.mu.Unlock()
return events, nil
}
func (b *Bridge) StartDiscovery(ctx context.Context, model string) error {
return b.post(ctx, model, nil, nil)
}
func (b *Bridge) putLightState(ctx context.Context, index int, input LightStateInput) error {
return b.put(ctx, fmt.Sprintf("lights/%d/state", index), input, nil)
}
func (b *Bridge) getToken(ctx context.Context) (string, error) {
result := make([]CreateUserResponse, 0, 1)
err := b.post(ctx, "", CreateUserInput{DeviceType: "git.aiterp.net/lucifer"}, &result)
if err != nil {
return "", err
}
if len(result) == 0 || result[0].Error != nil {
return "", errLinkButtonNotPressed
}
if result[0].Success == nil {
return "", models.ErrUnexpectedResponse
}
return result[0].Success.Username, nil
}
func (b *Bridge) getLights(ctx context.Context) (map[int]LightData, error) {
result := make(map[int]LightData, 16)
err := b.get(ctx, "lights", &result)
if err != nil {
return nil, err
}
return result, nil
}
func (b *Bridge) getSensors(ctx context.Context) (map[int]SensorData, error) {
result := make(map[int]SensorData, 16)
err := b.get(ctx, "sensors", &result)
if err != nil {
return nil, err
}
return result, nil
}
func (b *Bridge) get(ctx context.Context, resource string, target interface{}) error {
if b.token != "" {
resource = b.token + "/" + resource
}
req, err := http.NewRequest("GET", fmt.Sprintf("http://%s/api/%s", b.host, resource), nil)
if err != nil {
return err
}
res, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return err
}
defer res.Body.Close()
return json.NewDecoder(res.Body).Decode(target)
}
func (b *Bridge) post(ctx context.Context, resource string, body interface{}, target interface{}) error {
rb, err := reqBody(body)
if err != nil {
return err
}
if b.token != "" {
resource = b.token + "/" + resource
}
req, err := http.NewRequest("POST", fmt.Sprintf("http://%s/api/%s", b.host, resource), rb)
if err != nil {
return err
}
res, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return err
}
defer res.Body.Close()
if target == nil {
return nil
}
return json.NewDecoder(res.Body).Decode(target)
}
func (b *Bridge) put(ctx context.Context, resource string, body interface{}, target interface{}) error {
rb, err := reqBody(body)
if err != nil {
return err
}
if b.token != "" {
resource = b.token + "/" + resource
}
req, err := http.NewRequest("PUT", fmt.Sprintf("http://%s/api/%s", b.host, resource), rb)
if err != nil {
return err
}
res, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return err
}
defer res.Body.Close()
if target == nil {
return nil
}
return json.NewDecoder(res.Body).Decode(target)
}
func reqBody(body interface{}) (io.Reader, error) {
if body == nil {
return nil, nil
}
switch v := body.(type) {
case []byte:
return bytes.NewReader(v), nil
case string:
return strings.NewReader(v), nil
case io.Reader:
return v, nil
default:
jsonData, err := json.Marshal(v)
if err != nil {
return nil, err
}
return bytes.NewReader(jsonData), nil
}
}