Author SHA1 Message Date
gisle 01975c74a9 fix scene reassignment on expiry not working.
continuous-integration/drone/push Build is passing
2021-10-08 15:14:38 +02:00
gisle cdf5173503 fixed a rare hue driver crash on startup and crash if an event sets an invalid scene id.
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2021-10-06 20:10:57 +02:00
gisle def494ba45 scene stuff is ready for prime time now.
continuous-integration/drone/push Build is passing
2021-10-06 20:00:58 +02:00
gisle 1b7e495a59 more scene stuff. There's still no command and API to push scenes and unassign (aside from setting a temporary scene and waiting it out).
continuous-integration/drone/push Build is passing
2021-10-05 20:11:53 +02:00
gisle 07173e4e56 Merge branch 'asmodeus' into feature-scenesystem
continuous-integration/drone/push Build is passing
2021-10-04 20:14:16 +02:00
gisle 7b0028ee2b new scene system is kind of working. I haven't tested changing between scenes and Transition effect yet, though.
continuous-integration/drone/push Build is passing
2021-10-04 20:13:57 +02:00
gisle d23a7327ef Merge branch 'asmodeus' into feature-scenesystem
continuous-integration/drone/push Build is failing
2021-10-03 18:42:33 +02:00
gisle a3695a3ddd some more work.
continuous-integration/drone/push Build is failing
2021-09-28 21:57:28 +02:00
gisle ffa757f742 rewrite of publishing mechanism to make scenes first-class.
continuous-integration/drone/push Build is failing
2021-09-26 22:15:49 +02:00
gisle f87c69efc7 this does not work, it needs massive changes.
continuous-integration/drone/push Build is passing
2021-09-26 16:20:02 +02:00
gisle b4fd6df454 Merge branch 'asmodeus' into feature-scenesystem
continuous-integration/drone/push Build is failing
2021-09-26 10:51:28 +02:00
gisle 44716c84d1 scene system so far.
continuous-integration/drone/push Build is failing
2021-09-25 19:04:54 +02:00
6 changed files with 36 additions and 262 deletions
+6 -4
View File
@@ -137,10 +137,12 @@ func Devices(r gin.IRoutes) {
config.PublishChannel <- devices
err = config.DeviceRepository().SaveMany(ctxOf(c), models.SMState, devices)
if err != nil {
log.Println("Failed to save devices states")
}
go func() {
err = config.DeviceRepository().SaveMany(ctxOf(c), models.SMState, devices)
if err != nil {
log.Println("Failed to save devices states")
}
}()
return withSceneState(devices), nil
}))
+13 -2
View File
@@ -110,16 +110,19 @@ func (p *Publisher) Run() {
ticker := time.NewTicker(time.Millisecond * 100)
deleteList := make([]int, 0, 8)
updatedList := make([]models.Device, 0, 16)
reassignList := make([]models.Device, 0, 16)
for range ticker.C {
deleteList = deleteList[:0]
updatedList = updatedList[:0]
reassignList = reassignList[:0]
p.mu.Lock()
for i, scene := range p.scenes {
if (!scene.endTime.IsZero() && time.Now().After(scene.endTime)) || scene.Empty() {
deleteList = append(deleteList, i-len(deleteList))
updatedList = append(updatedList, scene.AllDevices()...)
reassignList = append(reassignList, scene.AllDevices()...)
log.Printf("Removing scene instance for %s (%d)", scene.data.Name, scene.data.ID)
@@ -139,6 +142,14 @@ func (p *Publisher) Run() {
p.scenes = append(p.scenes[:i], p.scenes[i+1:]...)
}
for _, device := range reassignList {
p.reassignDevice(device)
if p.sceneAssignment[device.ID] != nil {
p.sceneAssignment[device.ID].UpsertDevice(device)
}
}
for _, device := range updatedList {
if !p.started[device.BridgeID] {
p.started[device.BridgeID] = true
@@ -159,10 +170,10 @@ func (p *Publisher) Run() {
// should trigger an update.
func (p *Publisher) reassignDevice(device models.Device) bool {
var selectedAssignment *models.DeviceSceneAssignment
for _, assignment := range device.SceneAssignments {
for i, assignment := range device.SceneAssignments {
duration := time.Duration(assignment.DurationMS) * time.Millisecond
if duration <= 0 || time.Now().Before(assignment.StartTime.Add(duration)) {
selectedAssignment = &assignment
selectedAssignment = &device.SceneAssignments[i]
}
}
+15 -133
View File
@@ -6,11 +6,10 @@ import (
"encoding/json"
"fmt"
"git.aiterp.net/lucifer/new-server/models"
"golang.org/x/sync/errgroup"
"io"
"log"
"net"
"net/http"
"strconv"
"strings"
"sync"
"time"
@@ -98,17 +97,17 @@ func (b *Bridge) Refresh(ctx context.Context) error {
func (b *Bridge) SyncStale(ctx context.Context) error {
indices := make([]int, 0, 4)
arrayIndices := make([]int, 0, 4)
inputs := make([]LightStateInput, 0, 4)
eg, ctx := errgroup.WithContext(ctx)
b.mu.Lock()
for i, state := range b.lightStates {
for _, state := range b.lightStates {
if !state.stale {
continue
}
indices = append(indices, state.index)
arrayIndices = append(arrayIndices, i)
inputs = append(inputs, state.input)
}
b.mu.Unlock()
@@ -117,85 +116,24 @@ func (b *Bridge) SyncStale(ctx context.Context) error {
return nil
}
groups := make([]*syncGroup, 0, 4)
for i := range inputs {
input := inputs[i]
for i, input := range inputs {
iCopy := i
index := indices[i]
inputCopy := input
found := false
for _, group := range groups {
if group.State.Equal(input) {
group.Indexes = append(group.Indexes, indices[i])
group.ArrayIndexes = append(group.ArrayIndexes, arrayIndices[i])
found = true
}
}
if !found {
groups = append(groups, &syncGroup{
GroupIndex: -1,
State: input,
Indexes: []int{indices[i]},
ArrayIndexes: []int{arrayIndices[i]},
})
}
}
groupMap, err := b.getGroups(ctx)
if err != nil {
return err
}
for id, data := range groupMap {
for _, group := range groups {
if group.Matches(&data) {
group.GroupIndex = id
break
}
}
}
for _, group := range groups {
if group.GroupIndex == -1 {
data := GroupData{
Name: "lucifer_auto_group",
Lights: []string{},
}
for _, idx := range group.Indexes {
data.Lights = append(data.Lights, strconv.Itoa(idx))
}
id, err := b.postGroup(ctx, data)
eg.Go(func() error {
err := b.putLightState(ctx, index, inputCopy)
if err != nil {
return err
}
group.GroupIndex = id
}
b.lightStates[iCopy].stale = false
return nil
})
}
log.Println("Updating", len(inputs), "lights on Hue bridge", b.externalID, "in", len(groups), "groups")
for _, group := range groups {
err := b.putGroupLightState(ctx, group.GroupIndex, group.State)
if err != nil {
return err
}
b.mu.Lock()
for _, arrayIndex := range group.ArrayIndexes {
b.lightStates[arrayIndex].stale = false
}
b.mu.Unlock()
if groupMap[group.GroupIndex].Name == "lucifer_auto_group" {
err := b.deleteGroup(ctx, group.GroupIndex)
if err != nil {
log.Println("Could not delete temporary group", err)
}
}
}
return nil
return eg.Wait()
}
func (b *Bridge) SyncSensors(ctx context.Context) ([]models.Event, error) {
@@ -232,10 +170,6 @@ func (b *Bridge) putLightState(ctx context.Context, index int, input LightStateI
return b.put(ctx, fmt.Sprintf("lights/%d/state", index), input, nil)
}
func (b *Bridge) putGroupLightState(ctx context.Context, index int, input LightStateInput) error {
return b.put(ctx, fmt.Sprintf("groups/%d/action", 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)
@@ -273,34 +207,6 @@ func (b *Bridge) getSensors(ctx context.Context) (map[int]SensorData, error) {
return result, nil
}
func (b *Bridge) getGroups(ctx context.Context) (map[int]GroupData, error) {
result := make(map[int]GroupData, 16)
err := b.get(ctx, "groups", &result)
if err != nil {
return nil, err
}
return result, nil
}
func (b *Bridge) postGroup(ctx context.Context, input GroupData) (int, error) {
var res []struct {
Success struct {
ID string `json:"id"`
} `json:"success"`
}
err := b.post(ctx, "groups", input, &res)
id, _ := strconv.Atoi(res[0].Success.ID)
return id, err
}
func (b *Bridge) deleteGroup(ctx context.Context, index int) error {
return b.delete(ctx, "groups/"+strconv.Itoa(index), nil)
}
func (b *Bridge) get(ctx context.Context, resource string, target interface{}) error {
if b.token != "" {
resource = b.token + "/" + resource
@@ -320,30 +226,6 @@ func (b *Bridge) get(ctx context.Context, resource string, target interface{}) e
return json.NewDecoder(res.Body).Decode(target)
}
func (b *Bridge) delete(ctx context.Context, resource string, target interface{}) error {
if b.token != "" {
resource = b.token + "/" + resource
}
req, err := http.NewRequest("DELETE", fmt.Sprintf("http://%s/api/%s", b.host, resource), nil)
if err != nil {
return err
}
res, err := httpClient.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) post(ctx context.Context, resource string, body interface{}, target interface{}) error {
rb, err := reqBody(body)
if err != nil {
-88
View File
@@ -3,14 +3,8 @@ package hue
import (
"encoding/xml"
"errors"
"strconv"
)
type GroupData struct {
Name string `json:"name"`
Lights []string `json:"lights"`
}
type DiscoveryEntry struct {
Id string `json:"id"`
InternalIPAddress string `json:"internalipaddress"`
@@ -89,58 +83,6 @@ type LightStateInput struct {
TransitionTime *int `json:"transitiontime,omitempty"`
}
func (input *LightStateInput) Equal(other LightStateInput) bool {
if (input.On != nil) != (other.On != nil) {
return false
} else if input.On != nil && *input.On != *other.On {
return false
}
if (input.Bri != nil) != (other.Bri != nil) {
return false
} else if input.Bri != nil && *input.Bri != *other.Bri {
return false
}
if (input.Hue != nil) != (other.Hue != nil) {
return false
} else if input.Hue != nil && *input.Hue != *other.Hue {
return false
}
if (input.Sat != nil) != (other.Sat != nil) {
return false
} else if input.Sat != nil && *input.Sat != *other.Sat {
return false
}
if (input.Effect != nil) != (other.Effect != nil) {
return false
} else if input.Effect != nil && *input.Effect != *other.Effect {
return false
}
if (input.XY != nil) != (other.XY != nil) {
return false
} else if input.XY != nil && *input.XY != *other.XY {
return false
}
if (input.CT != nil) != (other.CT != nil) {
return false
} else if input.CT != nil && *input.CT != *other.CT {
return false
}
if (input.Alert != nil) != (other.Alert != nil) {
return false
} else if input.Alert != nil && *input.Alert != *other.Alert {
return false
}
return true
}
type LightData struct {
State LightState `json:"state"`
Type string `json:"type"`
@@ -250,36 +192,6 @@ type BridgeDeviceInfo struct {
} `xml:"device"`
}
type syncGroup struct {
GroupIndex int
State LightStateInput
Indexes []int
ArrayIndexes []int
}
func (sg *syncGroup) Matches(group *GroupData) bool {
if len(sg.Indexes) != len(group.Lights) {
return false
}
for _, idx := range sg.Indexes {
found := false
for _, idx2 := range group.Lights {
n := strconv.Itoa(idx)
if n == idx2 {
found = true
break
}
}
if !found {
return false
}
}
return true
}
var buttonNames = []string{"On", "DimUp", "DimDown", "Off"}
var errLinkButtonNotPressed = errors.New("link button not pressed")
+1 -34
View File
@@ -1,7 +1,6 @@
package hue
import (
"encoding/json"
"git.aiterp.net/lucifer/new-server/models"
"strconv"
"time"
@@ -17,37 +16,12 @@ type hueLightState struct {
stale bool
}
func (s *hueLightState) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Index int `json:"index"`
UniqueID string `json:"uniqueId"`
ExternalID int `json:"externalId"`
Info LightData `json:"info"`
Input LightStateInput `json:"input"`
Stale bool `json:"stale"`
}{
Index: s.index,
UniqueID: s.uniqueID,
ExternalID: s.externalID,
Info: s.info,
Input: s.input,
Stale: s.stale,
})
}
func (s *hueLightState) Update(state models.DeviceState) {
input := LightStateInput{}
if state.Power {
input.On = ptrBool(true)
if state.Color.IsKelvin() {
input.CT = ptrInt(1000000 / state.Color.Kelvin)
if *input.CT < s.info.Capabilities.Control.CT.Min {
*input.CT = s.info.Capabilities.Control.CT.Min
}
if *input.CT > s.info.Capabilities.Control.CT.Max {
*input.CT = s.info.Capabilities.Control.CT.Max
}
if s.input.CT == nil || *s.input.CT != *input.CT {
s.stale = true
}
@@ -93,13 +67,6 @@ func (s *hueLightState) Update(state models.DeviceState) {
}
func (s *hueLightState) CheckStaleness(state LightState) {
if s.input.On == nil || state.On != *s.input.On {
s.stale = true
}
if !state.On {
return
}
if state.ColorMode == "xy" {
s.stale = true
if s.input.CT == nil && s.input.Hue == nil {
@@ -113,7 +80,7 @@ func (s *hueLightState) CheckStaleness(state LightState) {
s.stale = true
}
} else {
if s.input.Hue == nil || state.Hue != *s.input.Hue || s.input.Sat == nil || state.Sat != *s.input.Sat {
if s.input.Hue == nil || state.Hue != *s.input.Hue || s.input.Sat == nil || state.Sat == *s.input.Sat {
s.stale = true
}
}
+1 -1
View File
@@ -171,7 +171,7 @@ func (c *EventCondition) checkDevice(key string, device Device) (matches bool, s
return c.matches(strconv.FormatFloat(device.State.Temperature, 'f', -1, 64)), false
case "scene":
if len(device.SceneAssignments) == 0 {
return false, false
return c.matches("-1"), false
}
sceneId := -1