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.

98 lines
2.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
  1. package services
  2. import (
  3. "context"
  4. "git.aiterp.net/lucifer/new-server/app/config"
  5. "git.aiterp.net/lucifer/new-server/models"
  6. "log"
  7. "strconv"
  8. "time"
  9. )
  10. func StartEventHandler() {
  11. config.EventChannel<-models.Event{Name: "LuciferStarted"}
  12. go func() {
  13. for event := range config.EventChannel {
  14. handleEvent(event)
  15. }
  16. }()
  17. // Dispatch an HourChanged event at every hour
  18. go func() {
  19. drift := time.Now().Add(time.Minute).Truncate(time.Minute).Sub(time.Now())
  20. time.Sleep(drift + time.Millisecond * 5)
  21. for range time.NewTicker(time.Minute).C {
  22. config.EventChannel <- models.Event{Name: "TimeChanged"}
  23. }
  24. }()
  25. }
  26. var loc, _ = time.LoadLocation("Europe/Oslo")
  27. var ctx = context.Background()
  28. var X = false
  29. func handleEvent(event models.Event) {
  30. if !event.HasPayload("hour") {
  31. event.AddPayload("hour", time.Now().In(loc).Format("15"))
  32. }
  33. if !event.HasPayload("minute") {
  34. event.AddPayload("minute", time.Now().In(loc).Format("04"))
  35. }
  36. err := handleSpecial(event)
  37. if err != nil {
  38. log.Printf("Special event handler error (%s): %v", event.Name, err)
  39. return
  40. }
  41. if !X {
  42. log.Println("Unhandled event: " + event.Name)
  43. return
  44. }
  45. handlers, err := config.EventHandlerRepository().FetchAll(ctx)
  46. if err != nil {
  47. log.Printf("Error fetchin event halders: %d", err)
  48. return
  49. }
  50. for _, handler := range handlers {
  51. devices, err := config.DeviceRepository().FetchByReference(ctx, handler.TargetKind, handler.TargetValue)
  52. if err != nil {
  53. log.Printf("Error fetchin event halders: %d", err)
  54. return
  55. }
  56. if !handler.MatchesEvent(event, devices) {
  57. continue
  58. }
  59. }
  60. }
  61. func handleSpecial(event models.Event) error {
  62. switch event.Name {
  63. case models.ENBridgeConnected:
  64. bridgeId, _ := strconv.Atoi(event.Payload["bridgeId"])
  65. bridge, err := config.BridgeRepository().Find(ctx, bridgeId)
  66. if err != nil {
  67. return err
  68. }
  69. devices, err := config.DeviceRepository().FetchByReference(ctx, models.RKBridgeID, event.Payload["bridgeId"])
  70. if err != nil {
  71. return err
  72. }
  73. driver, err := config.DriverProvider().Provide(bridge.Driver)
  74. if err != nil {
  75. return err
  76. }
  77. return driver.Publish(ctx, bridge, devices)
  78. default:
  79. return nil
  80. }
  81. }