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.

216 lines
5.1 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. if !handler.IsWithinTimeRange() {
  81. continue
  82. }
  83. devices, err := config.DeviceRepository().FetchByReference(ctx, handler.TargetKind, handler.TargetValue)
  84. if err != nil {
  85. log.Printf("Error fetchin' event devices: %s", err)
  86. return
  87. }
  88. if !handler.MatchesEvent(event, devices) {
  89. continue
  90. }
  91. if handler.OneShot {
  92. deadHandlers = append(deadHandlers, handler)
  93. }
  94. if handler.Priority > highestPriority {
  95. highestPriority = handler.Priority
  96. prioritizedEvent = handler.Actions.FireEvent
  97. }
  98. for _, device := range devices {
  99. _, ok := actions[device.ID]
  100. if !ok {
  101. allDevices = append(allDevices, device)
  102. actions[device.ID] = handler.Actions
  103. priorities[device.ID] = handler.Priority
  104. } else if handler.Priority > priorities[device.ID] {
  105. actions[device.ID] = handler.Actions
  106. priorities[device.ID] = handler.Priority
  107. }
  108. }
  109. }
  110. if prioritizedEvent != nil {
  111. responses = append(responses, *prioritizedEvent)
  112. }
  113. for i, device := range allDevices {
  114. action := actions[device.ID]
  115. newState := models.NewDeviceState{}
  116. newState.Color = action.SetColor
  117. newState.Power = action.SetPower
  118. if action.SetIntensity != nil {
  119. newState.Intensity = action.SetIntensity
  120. } else if action.AddIntensity != nil {
  121. newIntensity := math.Max(0, math.Min(1, device.State.Intensity+*action.AddIntensity))
  122. newState.Intensity = &newIntensity
  123. }
  124. if action.SetTemperature != nil {
  125. newState.Temperature = action.SetTemperature
  126. }
  127. err = allDevices[i].SetState(newState)
  128. if err != nil {
  129. log.Println("Error updating state for device", device.ID, "err:", err)
  130. }
  131. }
  132. config.PublishChannel <- allDevices
  133. wg := sync.WaitGroup{}
  134. for _, device := range allDevices {
  135. wg.Add(1)
  136. go func(device models.Device) {
  137. err := config.DeviceRepository().Save(context.Background(), &device, models.SMState)
  138. if err != nil {
  139. log.Println("Failed to save device for state:", err)
  140. }
  141. wg.Done()
  142. }(device)
  143. }
  144. for _, handler := range deadHandlers {
  145. wg.Add(1)
  146. go func(handler models.EventHandler) {
  147. err := config.EventHandlerRepository().Delete(context.Background(), &handler)
  148. if err != nil {
  149. log.Println("Failed to delete spent one-shot event handler:", err)
  150. }
  151. wg.Done()
  152. }(handler)
  153. }
  154. wg.Wait()
  155. return
  156. }
  157. func handleSpecial(event models.Event) error {
  158. switch event.Name {
  159. case models.ENBridgeConnected:
  160. bridgeId, _ := strconv.Atoi(event.Payload["bridgeId"])
  161. bridge, err := config.BridgeRepository().Find(ctx, bridgeId)
  162. if err != nil {
  163. return err
  164. }
  165. devices, err := config.DeviceRepository().FetchByReference(ctx, models.RKBridgeID, event.Payload["bridgeId"])
  166. if err != nil {
  167. return err
  168. }
  169. driver, err := config.DriverProvider().Provide(bridge.Driver)
  170. if err != nil {
  171. return err
  172. }
  173. return driver.Publish(ctx, bridge, devices)
  174. default:
  175. return nil
  176. }
  177. }