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.

213 lines
5.0 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. if action.SetTemperature != nil {
  122. newState.Temperature = action.SetTemperature
  123. }
  124. err = allDevices[i].SetState(newState)
  125. if err != nil {
  126. log.Println("Error updating state for device", device.ID, "err:", err)
  127. }
  128. }
  129. config.PublishChannel <- allDevices
  130. wg := sync.WaitGroup{}
  131. for _, device := range allDevices {
  132. wg.Add(1)
  133. go func(device models.Device) {
  134. err := config.DeviceRepository().Save(context.Background(), &device, models.SMState)
  135. if err != nil {
  136. log.Println("Failed to save device for state:", err)
  137. }
  138. wg.Done()
  139. }(device)
  140. }
  141. for _, handler := range deadHandlers {
  142. wg.Add(1)
  143. go func(handler models.EventHandler) {
  144. err := config.EventHandlerRepository().Delete(context.Background(), &handler)
  145. if err != nil {
  146. log.Println("Failed to delete spent one-shot event handler:", err)
  147. }
  148. wg.Done()
  149. }(handler)
  150. }
  151. wg.Wait()
  152. return
  153. }
  154. func handleSpecial(event models.Event) error {
  155. switch event.Name {
  156. case models.ENBridgeConnected:
  157. bridgeId, _ := strconv.Atoi(event.Payload["bridgeId"])
  158. bridge, err := config.BridgeRepository().Find(ctx, bridgeId)
  159. if err != nil {
  160. return err
  161. }
  162. devices, err := config.DeviceRepository().FetchByReference(ctx, models.RKBridgeID, event.Payload["bridgeId"])
  163. if err != nil {
  164. return err
  165. }
  166. driver, err := config.DriverProvider().Provide(bridge.Driver)
  167. if err != nil {
  168. return err
  169. }
  170. return driver.Publish(ctx, bridge, devices)
  171. default:
  172. return nil
  173. }
  174. }