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.

116 lines
2.4 KiB

  1. package publisher
  2. import (
  3. "git.aiterp.net/lucifer/new-server/models"
  4. "time"
  5. )
  6. type Scene struct {
  7. data *models.Scene
  8. group string
  9. startTime time.Time
  10. endTime time.Time
  11. interval time.Duration
  12. roleMap map[int]int
  13. roleList map[int][]models.Device
  14. due bool
  15. }
  16. func (s *Scene) UpdateScene(data models.Scene) {
  17. }
  18. func (s *Scene) UpsertDevice(device models.Device) {
  19. if s.data == nil {
  20. s.roleMap[device.ID] = -1
  21. s.roleList[-1] = append(s.roleList[-1], device)
  22. return
  23. }
  24. oldIndex, hasOldIndex := s.roleMap[device.ID]
  25. newIndex := s.data.RoleIndex(&device)
  26. if hasOldIndex {
  27. if oldIndex == newIndex {
  28. for i, device2 := range s.roleList[newIndex] {
  29. if device2.ID == device.ID {
  30. s.roleList[newIndex][i] = device
  31. s.data.Roles[oldIndex].ApplyOrder(s.roleList[oldIndex])
  32. break
  33. }
  34. }
  35. return
  36. } else {
  37. for i, device2 := range s.roleList[oldIndex] {
  38. if device2.ID == device.ID {
  39. s.roleList[oldIndex] = append(s.roleList[oldIndex][:i], s.roleList[oldIndex][i+1:]...)
  40. break
  41. }
  42. }
  43. }
  44. }
  45. s.roleList[newIndex] = append(s.roleList[newIndex], device)
  46. s.data.Roles[newIndex].ApplyOrder(s.roleList[newIndex])
  47. }
  48. func (s *Scene) RemoveDevice(device models.Device) {
  49. roleIndex, hasRoleIndex := s.roleMap[device.ID]
  50. if !hasRoleIndex {
  51. return
  52. }
  53. for i, device2 := range s.roleList[roleIndex] {
  54. if device2.ID == device.ID {
  55. s.roleList[roleIndex] = append(s.roleList[roleIndex][:i], s.roleList[roleIndex][i+1:]...)
  56. break
  57. }
  58. }
  59. }
  60. func (s *Scene) Run() []models.Device {
  61. if s.data == nil {
  62. return []models.Device{}
  63. }
  64. intervalNumber := int64(0)
  65. intervalMax := int64(1)
  66. if s.interval > 0 {
  67. intervalNumber = int64(time.Since(s.startTime) / s.interval)
  68. if !s.endTime.IsZero() {
  69. intervalMax = int64(s.endTime.Sub(s.startTime) / s.interval)
  70. } else {
  71. intervalMax = intervalNumber + 1
  72. }
  73. }
  74. updatedDevices := make([]models.Device, 0, 16)
  75. for i, list := range s.roleList {
  76. if i == -1 {
  77. continue
  78. }
  79. role := s.data.Roles[i]
  80. for j, device := range list {
  81. newState := role.ApplyEffect(&device, models.SceneRunContext{
  82. Index: j,
  83. Length: len(list),
  84. IntervalNumber: intervalNumber,
  85. IntervalMax: intervalMax,
  86. })
  87. err := device.SetState(newState)
  88. if err != nil {
  89. continue
  90. }
  91. updatedDevices = append(updatedDevices, device)
  92. }
  93. }
  94. return updatedDevices
  95. }