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.

66 lines
1.4 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
  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. "time"
  8. )
  9. func StartEventHandler() {
  10. config.EventChannel<-models.Event{Name: "LuciferStarted"}
  11. go func() {
  12. for event := range config.EventChannel {
  13. handleEvent(event)
  14. }
  15. }()
  16. // Dispatch an HourChanged event at every hour
  17. go func() {
  18. drift := time.Now().Add(time.Minute).Truncate(time.Minute).Sub(time.Now())
  19. time.Sleep(drift + time.Millisecond * 5)
  20. for range time.NewTicker(time.Minute).C {
  21. config.EventChannel <- models.Event{Name: "TimeChanged"}
  22. }
  23. }()
  24. }
  25. var loc, _ = time.LoadLocation("Europe/Oslo")
  26. var ctx = context.Background()
  27. var X = false
  28. func handleEvent(event models.Event) {
  29. if !event.HasPayload("hour") {
  30. event.AddPayload("hour", time.Now().In(loc).Format("15"))
  31. }
  32. if !event.HasPayload("minute") {
  33. event.AddPayload("minute", time.Now().In(loc).Format("04"))
  34. }
  35. if !X {
  36. log.Println("Unhandled event: " + event.Name)
  37. return
  38. }
  39. handlers, err := config.EventHandlerRepository().FetchAll(ctx)
  40. if err != nil {
  41. log.Printf("Error fetchin event halders: %d", err)
  42. return
  43. }
  44. for _, handler := range handlers {
  45. devices, err := config.DeviceRepository().FetchByReference(ctx, handler.TargetKind, handler.TargetValue)
  46. if err != nil {
  47. log.Printf("Error fetchin event halders: %d", err)
  48. return
  49. }
  50. if !handler.MatchesEvent(event, devices) {
  51. continue
  52. }
  53. }
  54. }