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.

67 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. return
  37. }
  38. handlers, err := config.EventHandlerRepository().FetchAll(ctx)
  39. if err != nil {
  40. log.Printf("Error fetchin event halders: %d", err)
  41. return
  42. }
  43. for _, handler := range handlers {
  44. devices, err := config.DeviceRepository().FetchByReference(ctx, handler.TargetKind, handler.TargetValue)
  45. if err != nil {
  46. log.Printf("Error fetchin event halders: %d", err)
  47. return
  48. }
  49. if !handler.MatchesEvent(event, devices) {
  50. continue
  51. }
  52. }
  53. log.Println("Unhandled event: " + event.Name)
  54. }