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.

248 lines
6.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
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/app/services/publisher"
  7. "git.aiterp.net/lucifer/new-server/models"
  8. "log"
  9. "math"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. )
  16. func StartEventHandler() {
  17. config.EventChannel <- models.Event{Name: "LuciferStarted"}
  18. go func() {
  19. for event := range config.EventChannel {
  20. responses := handleEvent(event)
  21. for _, response := range responses {
  22. handleEvent(response)
  23. }
  24. }
  25. }()
  26. // Generate TimeChanged event
  27. go func() {
  28. drift := time.Now().Add(time.Minute).Truncate(time.Minute).Sub(time.Now())
  29. time.Sleep(drift + time.Millisecond*5)
  30. for range time.NewTicker(time.Minute).C {
  31. config.EventChannel <- models.Event{Name: "TimeChanged", Payload: map[string]string{
  32. "weekdayName": time.Now().In(loc).Format("Monday"),
  33. "month": time.Now().In(loc).Format("01"),
  34. "year": time.Now().In(loc).Format("2006"),
  35. }}
  36. }
  37. }()
  38. }
  39. var loc, _ = time.LoadLocation("Europe/Oslo")
  40. var ctx = context.Background()
  41. func handleEvent(event models.Event) (responses []models.Event) {
  42. var deadHandlers []models.EventHandler
  43. startTime := time.Now()
  44. defer func() {
  45. duration := time.Since(startTime)
  46. if duration > time.Millisecond*250 {
  47. log.Println(event.Name, "took long to handle:", duration)
  48. }
  49. }()
  50. if !event.HasPayload("hour") {
  51. event.AddPayload("hour", time.Now().In(loc).Format("15"))
  52. }
  53. if !event.HasPayload("minute") {
  54. event.AddPayload("minute", time.Now().In(loc).Format("04"))
  55. }
  56. err := handleSpecial(event)
  57. if err != nil {
  58. log.Printf("Special event handler error (%s): %v", event.Name, err)
  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. if action.SetScene != nil {
  132. action.SetScene.StartTime = time.Now()
  133. allDevices[i].SceneAssignments = []models.DeviceSceneAssignment{*action.SetScene}
  134. }
  135. if action.PushScene != nil {
  136. action.PushScene.StartTime = time.Now()
  137. allDevices[i].SceneAssignments = append(allDevices[i].SceneAssignments, *action.PushScene)
  138. }
  139. }
  140. config.PublishChannel <- allDevices
  141. wg := sync.WaitGroup{}
  142. if len(allDevices) > 0 {
  143. wg.Add(1)
  144. go func() {
  145. err := config.DeviceRepository().SaveMany(context.Background(), models.SMState, allDevices)
  146. if err != nil {
  147. log.Println("Failed to save devices' state:", err)
  148. }
  149. wg.Done()
  150. }()
  151. }
  152. for _, handler := range deadHandlers {
  153. wg.Add(1)
  154. go func(handler models.EventHandler) {
  155. err := config.EventHandlerRepository().Delete(context.Background(), &handler)
  156. if err != nil {
  157. log.Println("Failed to delete spent one-shot event handler:", err)
  158. }
  159. wg.Done()
  160. }(handler)
  161. }
  162. wg.Wait()
  163. return
  164. }
  165. func handleSpecial(event models.Event) error {
  166. switch event.Name {
  167. case models.ENBridgeConnected:
  168. bridgeId, _ := strconv.Atoi(event.Payload["bridgeId"])
  169. bridge, err := config.BridgeRepository().Find(ctx, bridgeId)
  170. if err != nil {
  171. return err
  172. }
  173. devices, err := config.DeviceRepository().FetchByReference(ctx, models.RKBridgeID, event.Payload["bridgeId"])
  174. if err != nil {
  175. return err
  176. }
  177. driver, err := config.DriverProvider().Provide(bridge.Driver)
  178. if err != nil {
  179. return err
  180. }
  181. return driver.Publish(ctx, bridge, devices)
  182. case models.ENSensorPresenceStarted, models.ENSensorPresenceEnded, models.ENSensorTemperature:
  183. id, _ := strconv.Atoi(event.Payload["deviceId"])
  184. updateTime, _ := strconv.ParseInt(event.Payload["lastUpdated"], 10, 64)
  185. state := models.SceneSensor{
  186. ID: id,
  187. UpdateTime: time.Unix(updateTime, 0),
  188. }
  189. switch event.Name {
  190. case models.ENSensorPresenceStarted:
  191. presence := true
  192. state.Presence = &presence
  193. case models.ENSensorPresenceEnded:
  194. presence := false
  195. state.Presence = &presence
  196. case models.ENSensorTemperature:
  197. temperature, _ := strconv.ParseFloat(event.Payload["temperature"], 64)
  198. state.Temperature = &temperature
  199. }
  200. publisher.Global().UpdateSensor(state)
  201. return nil
  202. default:
  203. return nil
  204. }
  205. }