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.

209 lines
4.9 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package services
  2. import (
  3. "context"
  4. "fmt"
  5. "git.aiterp.net/lucifer/new-server/app/config"
  6. "git.aiterp.net/lucifer/new-server/models"
  7. "log"
  8. "math"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. )
  15. func StartEventHandler() {
  16. config.EventChannel <- models.Event{Name: "LuciferStarted"}
  17. go func() {
  18. for event := range config.EventChannel {
  19. responses := handleEvent(event)
  20. for _, response := range responses {
  21. handleEvent(response)
  22. }
  23. }
  24. }()
  25. // Generate TimeChanged event
  26. go func() {
  27. drift := time.Now().Add(time.Minute).Truncate(time.Minute).Sub(time.Now())
  28. time.Sleep(drift + time.Millisecond*5)
  29. for range time.NewTicker(time.Minute).C {
  30. config.EventChannel <- models.Event{Name: "TimeChanged", Payload: map[string]string{
  31. "weekdayName": time.Now().In(loc).Format("Monday"),
  32. "month": time.Now().In(loc).Format("01"),
  33. "year": time.Now().In(loc).Format("2006"),
  34. }}
  35. }
  36. }()
  37. }
  38. var loc, _ = time.LoadLocation("Europe/Oslo")
  39. var ctx = context.Background()
  40. func handleEvent(event models.Event) (responses []models.Event) {
  41. var deadHandlers []models.EventHandler
  42. startTime := time.Now()
  43. defer func() {
  44. duration := time.Since(startTime)
  45. if duration > time.Millisecond*250 {
  46. log.Println(event.Name, "took long to handle:", duration)
  47. }
  48. }()
  49. if !event.HasPayload("hour") {
  50. event.AddPayload("hour", time.Now().In(loc).Format("15"))
  51. }
  52. if !event.HasPayload("minute") {
  53. event.AddPayload("minute", time.Now().In(loc).Format("04"))
  54. }
  55. err := handleSpecial(event)
  56. if err != nil {
  57. log.Printf("Special event handler error (%s): %v", event.Name, err)
  58. return
  59. }
  60. paramStrings := make([]string, 0, 8)
  61. for key, value := range event.Payload {
  62. paramStrings = append(paramStrings, fmt.Sprintf("%s=%s", key, value))
  63. }
  64. sort.Strings(paramStrings)
  65. log.Printf("Event %s(%s)", event.Name, strings.Join(paramStrings, ", "))
  66. handlers, err := config.EventHandlerRepository().FetchAll(ctx)
  67. if err != nil {
  68. log.Printf("Error fetchin' event halders: %s", err)
  69. return
  70. }
  71. allDevices := make([]models.Device, 0, 16)
  72. actions := make(map[int]models.EventAction, 16)
  73. priorities := make(map[int]int, 16)
  74. highestPriority := 0
  75. var prioritizedEvent *models.Event
  76. for _, handler := range handlers {
  77. if handler.EventName != event.Name {
  78. continue
  79. }
  80. devices, err := config.DeviceRepository().FetchByReference(ctx, handler.TargetKind, handler.TargetValue)
  81. if err != nil {
  82. log.Printf("Error fetchin' event devices: %s", err)
  83. return
  84. }
  85. if !handler.MatchesEvent(event, devices) {
  86. continue
  87. }
  88. if handler.OneShot {
  89. deadHandlers = append(deadHandlers, handler)
  90. }
  91. if handler.Priority > highestPriority {
  92. highestPriority = handler.Priority
  93. prioritizedEvent = handler.Actions.FireEvent
  94. }
  95. for _, device := range devices {
  96. _, ok := actions[device.ID]
  97. if !ok {
  98. allDevices = append(allDevices, device)
  99. actions[device.ID] = handler.Actions
  100. priorities[device.ID] = handler.Priority
  101. } else if handler.Priority > priorities[device.ID] {
  102. actions[device.ID] = handler.Actions
  103. priorities[device.ID] = handler.Priority
  104. }
  105. }
  106. }
  107. if prioritizedEvent != nil {
  108. responses = append(responses, *prioritizedEvent)
  109. }
  110. for i, device := range allDevices {
  111. action := actions[device.ID]
  112. newState := models.NewDeviceState{}
  113. newState.Color = action.SetColor
  114. newState.Power = action.SetPower
  115. if action.SetIntensity != nil {
  116. newState.Intensity = action.SetIntensity
  117. } else if action.AddIntensity != nil {
  118. newIntensity := math.Max(0, math.Min(1, device.State.Intensity+*action.AddIntensity))
  119. newState.Intensity = &newIntensity
  120. }
  121. err = allDevices[i].SetState(newState)
  122. if err != nil {
  123. log.Println("Error updating state for device", device.ID, "err:", err)
  124. }
  125. }
  126. config.PublishChannel <- allDevices
  127. wg := sync.WaitGroup{}
  128. for _, device := range allDevices {
  129. wg.Add(1)
  130. go func(device models.Device) {
  131. err := config.DeviceRepository().Save(context.Background(), &device)
  132. if err != nil {
  133. log.Println("Failed to save device for state:", err)
  134. }
  135. wg.Done()
  136. }(device)
  137. }
  138. for _, handler := range deadHandlers {
  139. wg.Add(1)
  140. go func(handler models.EventHandler) {
  141. err := config.EventHandlerRepository().Delete(context.Background(), &handler)
  142. if err != nil {
  143. log.Println("Failed to delete spent one-shot event handler:", err)
  144. }
  145. wg.Done()
  146. }(handler)
  147. }
  148. wg.Wait()
  149. return
  150. }
  151. func handleSpecial(event models.Event) error {
  152. switch event.Name {
  153. case models.ENBridgeConnected:
  154. bridgeId, _ := strconv.Atoi(event.Payload["bridgeId"])
  155. bridge, err := config.BridgeRepository().Find(ctx, bridgeId)
  156. if err != nil {
  157. return err
  158. }
  159. devices, err := config.DeviceRepository().FetchByReference(ctx, models.RKBridgeID, event.Payload["bridgeId"])
  160. if err != nil {
  161. return err
  162. }
  163. driver, err := config.DriverProvider().Provide(bridge.Driver)
  164. if err != nil {
  165. return err
  166. }
  167. return driver.Publish(ctx, bridge, devices)
  168. default:
  169. return nil
  170. }
  171. }