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.

88 lines
1.8 KiB

3 years ago
  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. fwSpamTime time.Time
  19. acksPending []uint8
  20. }
  21. func (s *State) generateUpdate() []Payload {
  22. if s.deviceState == nil || s.lightState == nil {
  23. return nil
  24. }
  25. results := make([]Payload, 0, 0)
  26. if s.deviceState.Power != s.lightState.On {
  27. results = append(results, &SetLightPower{On: s.deviceState.Power, TransitionTime: time.Millisecond * 100})
  28. }
  29. if !s.deviceState.Power {
  30. return results
  31. }
  32. c := s.deviceState.Color
  33. l := s.lightState
  34. di := s.deviceState.Intensity
  35. k := c.Kelvin
  36. if k == 0 {
  37. k = 4000
  38. }
  39. if !equalish(c.Hue, l.Hue) || !equalish(c.Saturation, l.Sat) || !equalish(di, l.Bri) || k != l.Kelvin {
  40. results = append(results, &SetColor{
  41. Hue: c.Hue,
  42. Sat: c.Saturation,
  43. Bri: di,
  44. Kelvin: k,
  45. TransitionTime: time.Millisecond * 150,
  46. })
  47. }
  48. return results
  49. }
  50. func (s *State) handleAck(seq uint8) {
  51. for i, pendingAck := range s.acksPending {
  52. if pendingAck == seq {
  53. s.acksPending = append(s.acksPending[:i], s.acksPending[i+1:]...)
  54. break
  55. }
  56. }
  57. if len(s.acksPending) == 0 {
  58. s.lightStateTime = time.Now()
  59. prevLabel := ""
  60. if s.lightState != nil {
  61. prevLabel = s.lightState.Label
  62. }
  63. s.lightState = &LightState{
  64. Hue: s.deviceState.Color.Hue,
  65. Sat: s.deviceState.Color.Saturation,
  66. Bri: s.deviceState.Intensity,
  67. Kelvin: s.deviceState.Color.Kelvin,
  68. On: s.deviceState.Power,
  69. Label: prevLabel,
  70. }
  71. }
  72. }
  73. func equalish(a, b float64) bool {
  74. return math.Abs(a-b) < 0.005
  75. }