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.

87 lines
1.8 KiB

  1. package lifx
  2. import (
  3. "git.aiterp.net/lucifer/new-server/models"
  4. "math"
  5. "time"
  6. )
  7. type State struct {
  8. target string
  9. externalId int
  10. lightState *LightState
  11. firmware *StateHostFirmware
  12. version *StateVersion
  13. deviceState *models.DeviceState
  14. discoveredTime time.Time
  15. lightStateTime time.Time
  16. requestTime time.Time
  17. updateTime time.Time
  18. acksPending []uint8
  19. }
  20. func (s *State) generateUpdate() []Payload {
  21. if s.deviceState == nil || s.lightState == nil {
  22. return nil
  23. }
  24. results := make([]Payload, 0, 0)
  25. if s.deviceState.Power != s.lightState.On {
  26. results = append(results, &SetLightPower{On: s.deviceState.Power, TransitionTime: time.Millisecond * 100})
  27. }
  28. if !s.deviceState.Power {
  29. return results
  30. }
  31. c := s.deviceState.Color
  32. l := s.lightState
  33. di := s.deviceState.Intensity
  34. k := c.Kelvin
  35. if k == 0 {
  36. k = 4000
  37. }
  38. if !equalish(c.Hue, l.Hue) || !equalish(c.Saturation, l.Sat) || !equalish(di, l.Bri) || k != l.Kelvin {
  39. results = append(results, &SetColor{
  40. Hue: c.Hue,
  41. Sat: c.Saturation,
  42. Bri: di,
  43. Kelvin: k,
  44. TransitionTime: time.Millisecond * 150,
  45. })
  46. }
  47. return results
  48. }
  49. func (s *State) handleAck(seq uint8) {
  50. for i, pendingAck := range s.acksPending {
  51. if pendingAck == seq {
  52. s.acksPending = append(s.acksPending[:i], s.acksPending[i+1:]...)
  53. break
  54. }
  55. }
  56. if len(s.acksPending) == 0 {
  57. s.lightStateTime = time.Now()
  58. prevLabel := ""
  59. if s.lightState != nil {
  60. prevLabel = s.lightState.Label
  61. }
  62. s.lightState = &LightState{
  63. Hue: s.deviceState.Color.Hue,
  64. Sat: s.deviceState.Color.Saturation,
  65. Bri: s.deviceState.Intensity,
  66. Kelvin: s.deviceState.Color.Kelvin,
  67. On: s.deviceState.Power,
  68. Label: prevLabel,
  69. }
  70. }
  71. }
  72. func equalish(a, b float64) bool {
  73. return math.Abs(a-b) < 0.005
  74. }