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.

438 lines
10 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. package hue
  2. import (
  3. "context"
  4. "errors"
  5. lucifer3 "git.aiterp.net/lucifer3/server"
  6. "git.aiterp.net/lucifer3/server/device"
  7. "git.aiterp.net/lucifer3/server/events"
  8. "git.aiterp.net/lucifer3/server/internal/color"
  9. "git.aiterp.net/lucifer3/server/internal/gentools"
  10. "golang.org/x/sync/errgroup"
  11. "log"
  12. "math"
  13. "strings"
  14. "sync"
  15. "time"
  16. )
  17. func NewBridge(host string, client *Client) *Bridge {
  18. return &Bridge{
  19. client: client,
  20. host: host,
  21. ctx: context.Background(),
  22. cancel: func() {},
  23. resources: map[string]*ResourceData{},
  24. activeStates: map[string]device.State{},
  25. desiredStates: map[string]device.State{},
  26. colorFlags: map[string]device.ColorFlags{},
  27. hasSeen: map[string]bool{},
  28. triggerCongruenceCheckCh: make(chan struct{}, 2),
  29. }
  30. }
  31. type Bridge struct {
  32. mu sync.Mutex
  33. client *Client
  34. host string
  35. ctx context.Context
  36. cancel context.CancelFunc
  37. resources map[string]*ResourceData
  38. activeStates map[string]device.State
  39. desiredStates map[string]device.State
  40. colorFlags map[string]device.ColorFlags
  41. reachable map[string]bool
  42. hasSeen map[string]bool
  43. triggerCongruenceCheckCh chan struct{}
  44. lastDiscoverCancel context.CancelFunc
  45. }
  46. func (b *Bridge) SearchDevices(timeout time.Duration) error {
  47. discoverCtx, cancel := context.WithCancel(b.ctx)
  48. b.mu.Lock()
  49. if b.lastDiscoverCancel != nil {
  50. b.lastDiscoverCancel()
  51. }
  52. b.lastDiscoverCancel = cancel
  53. b.mu.Unlock()
  54. if timeout <= time.Second*10 {
  55. timeout = time.Second * 10
  56. }
  57. // Spend half the time waiting for devices
  58. // TODO: Wait for v2 endpoint
  59. ctx, cancel := context.WithTimeout(discoverCtx, timeout/2)
  60. defer cancel()
  61. err := b.client.LegacyDiscover(ctx, "sensors")
  62. if err != nil {
  63. return err
  64. }
  65. <-ctx.Done()
  66. if discoverCtx.Err() != nil {
  67. return discoverCtx.Err()
  68. }
  69. // Spend half the time waiting for lights
  70. // TODO: Wait for v2 endpoint
  71. ctx, cancel = context.WithTimeout(discoverCtx, timeout/2)
  72. defer cancel()
  73. err = b.client.LegacyDiscover(ctx, "sensors")
  74. if err != nil {
  75. return err
  76. }
  77. <-ctx.Done()
  78. if discoverCtx.Err() != nil {
  79. return discoverCtx.Err()
  80. }
  81. // Let the main loop get the new light.
  82. return nil
  83. }
  84. func (b *Bridge) RefreshAll() ([]lucifer3.Event, error) {
  85. ctx, cancel := context.WithTimeout(b.ctx, time.Second*15)
  86. defer cancel()
  87. allResources, err := b.client.AllResources(ctx)
  88. if err != nil {
  89. return nil, err
  90. }
  91. resources := make(map[string]*ResourceData, len(allResources))
  92. for i := range allResources {
  93. resources[allResources[i].ID] = &allResources[i]
  94. }
  95. b.mu.Lock()
  96. hasSeen := b.hasSeen
  97. reachable := b.reachable
  98. b.mu.Unlock()
  99. hasSeen = gentools.CopyMap(hasSeen)
  100. reachable = gentools.CopyMap(reachable)
  101. colorFlags := make(map[string]device.ColorFlags)
  102. activeStates := make(map[string]device.State)
  103. newEvents := make([]lucifer3.Event, 0, 0)
  104. for id, res := range resources {
  105. if res.Type == "device" && res.Metadata.Archetype != "bridge_v2" {
  106. hwState, hwEvent := res.GenerateEvent(b.host, resources)
  107. if !hasSeen[id] {
  108. newEvents = append(newEvents, hwState, hwEvent, events.DeviceReady{ID: hwState.ID})
  109. hasSeen[id] = true
  110. } else {
  111. newEvents = append(newEvents, hwState)
  112. }
  113. activeStates[id] = hwState.State
  114. colorFlags[id] = hwState.ColorFlags
  115. reachable[id] = !hwState.Unreachable
  116. }
  117. }
  118. b.mu.Lock()
  119. b.resources = resources
  120. b.hasSeen = hasSeen
  121. b.colorFlags = colorFlags
  122. b.activeStates = activeStates
  123. b.reachable = reachable
  124. b.mu.Unlock()
  125. return newEvents, nil
  126. }
  127. func (b *Bridge) ApplyPatches(resources []ResourceData) (events []lucifer3.Event, shouldRefresh bool) {
  128. b.mu.Lock()
  129. resourceMap := b.resources
  130. activeStates := b.activeStates
  131. reachable := b.reachable
  132. colorFlags := b.colorFlags
  133. b.mu.Unlock()
  134. mapCopy := gentools.CopyMap(resourceMap)
  135. activeStatesCopy := gentools.CopyMap(activeStates)
  136. reachableCopy := gentools.CopyMap(reachable)
  137. colorFlagsCopy := gentools.CopyMap(colorFlags)
  138. for _, resource := range resources {
  139. if mapCopy[resource.ID] != nil {
  140. mapCopy[resource.ID] = mapCopy[resource.ID].WithPatch(resource)
  141. } else {
  142. log.Println(resource.ID, resource.Type, "not seen!")
  143. shouldRefresh = true
  144. }
  145. }
  146. for _, resource := range resources {
  147. if resource.Owner != nil && resource.Owner.Kind == "device" {
  148. if parent, ok := mapCopy[resource.Owner.ID]; ok {
  149. hwState, _ := parent.GenerateEvent(b.host, mapCopy)
  150. events = append(events, hwState)
  151. activeStatesCopy[resource.Owner.ID] = hwState.State
  152. reachableCopy[resource.Owner.ID] = !hwState.Unreachable
  153. if hwState.ColorFlags != 0 {
  154. colorFlagsCopy[resource.Owner.ID] = hwState.ColorFlags
  155. }
  156. }
  157. }
  158. }
  159. b.mu.Lock()
  160. b.resources = mapCopy
  161. b.activeStates = activeStatesCopy
  162. b.reachable = reachableCopy
  163. b.colorFlags = colorFlagsCopy
  164. b.mu.Unlock()
  165. return
  166. }
  167. func (b *Bridge) SetStates(patch map[string]device.State) {
  168. b.mu.Lock()
  169. newStates := gentools.CopyMap(b.desiredStates)
  170. resources := b.resources
  171. b.mu.Unlock()
  172. prefix := "hue:" + b.host + ":"
  173. for id, state := range patch {
  174. if !strings.HasPrefix(id, prefix) {
  175. continue
  176. }
  177. id = id[len(prefix):]
  178. resource := resources[id]
  179. if resource == nil {
  180. continue
  181. }
  182. if !state.Empty() {
  183. newStates[id] = resource.FixState(state, resources)
  184. } else {
  185. delete(newStates, id)
  186. }
  187. }
  188. b.mu.Lock()
  189. b.desiredStates = newStates
  190. b.mu.Unlock()
  191. b.triggerCongruenceCheck()
  192. }
  193. func (b *Bridge) Run(ctx context.Context, bus *lucifer3.EventBus) interface{} {
  194. hwEvents, err := b.RefreshAll()
  195. if err != nil {
  196. return errors.New("failed to connect to bridge")
  197. }
  198. go b.makeCongruentLoop(ctx)
  199. bus.RunEvents(hwEvents)
  200. sse := b.client.SSE(ctx)
  201. step := time.NewTicker(time.Second * 30)
  202. defer step.Stop()
  203. for {
  204. select {
  205. case updates, ok := <-sse:
  206. {
  207. if !ok {
  208. return errors.New("SSE lost connection")
  209. }
  210. newEvents, shouldUpdate := b.ApplyPatches(
  211. gentools.Flatten(gentools.Map(updates, func(update SSEUpdate) []ResourceData {
  212. return update.Data
  213. })),
  214. )
  215. bus.RunEvents(newEvents)
  216. if shouldUpdate {
  217. hwEvents, err := b.RefreshAll()
  218. if err != nil {
  219. return errors.New("failed to refresh states")
  220. }
  221. bus.RunEvents(hwEvents)
  222. }
  223. b.triggerCongruenceCheck()
  224. }
  225. case <-step.C:
  226. hwEvents, err := b.RefreshAll()
  227. if err != nil {
  228. return nil
  229. }
  230. bus.RunEvents(hwEvents)
  231. b.triggerCongruenceCheck()
  232. case <-ctx.Done():
  233. {
  234. return nil
  235. }
  236. }
  237. }
  238. }
  239. func (b *Bridge) makeCongruentLoop(ctx context.Context) {
  240. for range b.triggerCongruenceCheckCh {
  241. if ctx.Err() != nil {
  242. break
  243. }
  244. // Make sure this loop takes half a second
  245. rateLimit := time.After(time.Second / 2)
  246. // Take states
  247. b.mu.Lock()
  248. resources := b.resources
  249. desiredStates := b.desiredStates
  250. activeStates := b.activeStates
  251. reachable := b.reachable
  252. colorFlags := b.colorFlags
  253. b.mu.Unlock()
  254. newActiveStates := make(map[string]device.State, 0)
  255. updates := make(map[string]ResourceUpdate)
  256. for id, desired := range desiredStates {
  257. active, activeOK := activeStates[id]
  258. lightID := resources[id].ServiceID("light")
  259. if !reachable[id] || !activeOK || lightID == nil {
  260. log.Println("No light", !reachable[id], !activeOK, lightID == nil)
  261. continue
  262. }
  263. light := resources[*lightID]
  264. if light == nil {
  265. log.Println("No light", *lightID)
  266. continue
  267. }
  268. // Handle power first
  269. if desired.Power != nil && active.Power != nil && *desired.Power != *active.Power {
  270. updates["light/"+*lightID] = ResourceUpdate{Power: gentools.Ptr(*desired.Power)}
  271. newActiveState := activeStates[id]
  272. newActiveState.Power = gentools.Ptr(*desired.Power)
  273. newActiveStates[id] = newActiveState
  274. continue
  275. }
  276. if active.Power != nil && !*active.Power {
  277. // Don't do more with shut-off-light.
  278. continue
  279. }
  280. updated := false
  281. update := ResourceUpdate{}
  282. newActiveState := activeStates[id]
  283. if active.Color != nil && desired.Color != nil {
  284. ac := *active.Color
  285. dc := *desired.Color
  286. if !dc.IsKelvin() || !colorFlags[id].IsWarmWhite() {
  287. dc, _ = dc.ToXY()
  288. dc.XY = gentools.Ptr(light.Color.Gamut.Conform(*dc.XY))
  289. }
  290. if dc.XY != nil {
  291. if ac.K != nil {
  292. ac.K = gentools.Ptr(1000000 / (1000000 / *ac.K))
  293. }
  294. acXY, _ := ac.ToXY()
  295. dist := dc.XY.DistanceTo(*acXY.XY)
  296. if dist > 0.0002 {
  297. update.ColorXY = gentools.Ptr(*dc.XY)
  298. updated = true
  299. }
  300. } else {
  301. dcMirek := 1000000 / *dc.K
  302. if dcMirek < light.ColorTemperature.MirekSchema.MirekMinimum {
  303. dcMirek = light.ColorTemperature.MirekSchema.MirekMinimum
  304. } else if dcMirek > light.ColorTemperature.MirekSchema.MirekMaximum {
  305. dcMirek = light.ColorTemperature.MirekSchema.MirekMaximum
  306. }
  307. acMirek := 0
  308. if ac.K != nil {
  309. acMirek = 1000000 / *ac.K
  310. }
  311. if acMirek != dcMirek {
  312. newActiveState.Color = &color.Color{K: gentools.Ptr(*dc.K)}
  313. update.Mirek = &dcMirek
  314. updated = true
  315. }
  316. }
  317. }
  318. if active.Intensity != nil && desired.Intensity != nil {
  319. if math.Abs(*active.Intensity-*desired.Intensity) >= 0.01 {
  320. update.Brightness = gentools.Ptr(*desired.Intensity * 100)
  321. newActiveState.Intensity = gentools.Ptr(*desired.Intensity)
  322. updated = true
  323. }
  324. }
  325. if updated {
  326. update.TransitionDuration = gentools.Ptr(time.Millisecond * 101)
  327. updates["light/"+*lightID] = update
  328. newActiveStates[id] = newActiveState
  329. }
  330. }
  331. if len(updates) > 0 {
  332. timeout, cancel := context.WithTimeout(ctx, time.Second)
  333. eg, ctx := errgroup.WithContext(timeout)
  334. for key := range updates {
  335. update := updates[key]
  336. split := strings.SplitN(key, "/", 2)
  337. link := ResourceLink{Kind: split[0], ID: split[1]}
  338. eg.Go(func() error {
  339. return b.client.UpdateResource(ctx, link, update)
  340. })
  341. }
  342. err := eg.Wait()
  343. if err != nil {
  344. log.Println("Failed to run update", err)
  345. }
  346. b.mu.Lock()
  347. activeStates = b.activeStates
  348. b.mu.Unlock()
  349. activeStates = gentools.CopyMap(activeStates)
  350. for id, state := range newActiveStates {
  351. activeStates[id] = state
  352. }
  353. b.mu.Lock()
  354. b.activeStates = activeStates
  355. b.mu.Unlock()
  356. cancel()
  357. }
  358. // Wait the remaining time for the rate limit
  359. <-rateLimit
  360. }
  361. }
  362. func (b *Bridge) triggerCongruenceCheck() {
  363. select {
  364. case b.triggerCongruenceCheckCh <- struct{}{}:
  365. default:
  366. }
  367. }