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.

440 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(*active.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 == false {
  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.XY != nil {
  292. dist := math.Abs(ac.XY.X-dc.XY.X) + math.Abs(ac.XY.Y-dc.XY.Y)
  293. if dist > 0.0002 {
  294. update.ColorXY = gentools.Ptr(*dc.XY)
  295. updated = true
  296. }
  297. } else {
  298. newActiveState.Color = &color.Color{XY: gentools.Ptr(*dc.XY)}
  299. update.ColorXY = gentools.Ptr(*dc.XY)
  300. updated = true
  301. }
  302. } else {
  303. dcMirek := 1000000 / *dc.K
  304. if dcMirek < light.ColorTemperature.MirekSchema.MirekMinimum {
  305. dcMirek = light.ColorTemperature.MirekSchema.MirekMinimum
  306. } else if dcMirek > light.ColorTemperature.MirekSchema.MirekMaximum {
  307. dcMirek = light.ColorTemperature.MirekSchema.MirekMaximum
  308. }
  309. acMirek := 0
  310. if ac.K != nil {
  311. acMirek = 1000000 / *ac.K
  312. }
  313. if acMirek != dcMirek {
  314. newActiveState.Color = &color.Color{K: gentools.Ptr(*dc.K)}
  315. update.Mirek = &dcMirek
  316. updated = true
  317. }
  318. }
  319. }
  320. if active.Intensity != nil && desired.Intensity != nil {
  321. if math.Abs(*active.Intensity-*desired.Intensity) >= 0.01 {
  322. update.Brightness = gentools.Ptr(*desired.Intensity * 100)
  323. newActiveState.Intensity = gentools.Ptr(*desired.Intensity)
  324. updated = true
  325. }
  326. }
  327. if updated {
  328. update.TransitionDuration = gentools.Ptr(time.Millisecond * 101)
  329. updates["light/"+*lightID] = update
  330. newActiveStates[id] = newActiveState
  331. }
  332. }
  333. if len(updates) > 0 {
  334. timeout, cancel := context.WithTimeout(ctx, time.Second)
  335. eg, ctx := errgroup.WithContext(timeout)
  336. for key := range updates {
  337. update := updates[key]
  338. split := strings.SplitN(key, "/", 2)
  339. link := ResourceLink{Kind: split[0], ID: split[1]}
  340. eg.Go(func() error {
  341. return b.client.UpdateResource(ctx, link, update)
  342. })
  343. }
  344. err := eg.Wait()
  345. if err != nil {
  346. log.Println("Failed to run update", err)
  347. }
  348. b.mu.Lock()
  349. activeStates = b.activeStates
  350. b.mu.Unlock()
  351. activeStates = gentools.CopyMap(activeStates)
  352. for id, state := range newActiveStates {
  353. activeStates[id] = state
  354. }
  355. b.mu.Lock()
  356. b.activeStates = activeStates
  357. b.mu.Unlock()
  358. cancel()
  359. }
  360. // Wait the remaining time for the rate limit
  361. <-rateLimit
  362. }
  363. }
  364. func (b *Bridge) triggerCongruenceCheck() {
  365. select {
  366. case b.triggerCongruenceCheckCh <- struct{}{}:
  367. default:
  368. }
  369. }