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.

59 lines
1.2 KiB

4 years ago
  1. package services
  2. import (
  3. "context"
  4. "git.aiterp.net/lucifer/server3/app/config"
  5. "git.aiterp.net/lucifer/server3/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. for {
  19. now := time.Now()
  20. nextHour := now.Add(time.Hour).Truncate(time.Hour)
  21. time.Sleep(nextHour.Sub(now))
  22. config.EventChannel <- models.Event{Name: "HourChanged"}
  23. }
  24. }()
  25. }
  26. var loc, _ = time.LoadLocation("Europe/Oslo")
  27. var ctx = context.Background()
  28. func handleEvent(event models.Event) {
  29. if !event.HasPayload("hour") {
  30. event.AddPayload("hour", time.Now().In(loc).Format("15"))
  31. }
  32. handlers, err := config.EventHandlerRepository().FetchAll(ctx)
  33. if err != nil {
  34. log.Printf("Error fetchin event halders: %d", err)
  35. return
  36. }
  37. for _, handler := range handlers {
  38. devices, err := config.DeviceRepository().FetchByReference(ctx, handler.TargetKind, handler.TargetValue)
  39. if err != nil {
  40. log.Printf("Error fetchin event halders: %d", err)
  41. return
  42. }
  43. if !handler.MatchesEvent(event, devices) {
  44. continue
  45. }
  46. panic("panik")
  47. }
  48. }