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.
104 lines
2.3 KiB
104 lines
2.3 KiB
package services
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"git.aiterp.net/lucifer/new-server/app/config"
|
|
"git.aiterp.net/lucifer/new-server/models"
|
|
"log"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func StartEventHandler() {
|
|
config.EventChannel<-models.Event{Name: "LuciferStarted"}
|
|
|
|
go func() {
|
|
for event := range config.EventChannel {
|
|
handleEvent(event)
|
|
}
|
|
}()
|
|
|
|
// Generate TimeChanged event
|
|
go func() {
|
|
drift := time.Now().Add(time.Minute).Truncate(time.Minute).Sub(time.Now())
|
|
time.Sleep(drift + time.Millisecond * 5)
|
|
|
|
for range time.NewTicker(time.Minute).C {
|
|
config.EventChannel <- models.Event{Name: "TimeChanged"}
|
|
}
|
|
}()
|
|
}
|
|
|
|
var loc, _ = time.LoadLocation("Europe/Oslo")
|
|
var ctx = context.Background()
|
|
var X = false
|
|
|
|
func handleEvent(event models.Event) {
|
|
if !event.HasPayload("hour") {
|
|
event.AddPayload("hour", time.Now().In(loc).Format("15"))
|
|
}
|
|
if !event.HasPayload("minute") {
|
|
event.AddPayload("minute", time.Now().In(loc).Format("04"))
|
|
}
|
|
|
|
err := handleSpecial(event)
|
|
if err != nil {
|
|
log.Printf("Special event handler error (%s): %v", event.Name, err)
|
|
return
|
|
}
|
|
|
|
if !X {
|
|
paramStrings := make([]string, 0, 8)
|
|
for key, value := range event.Payload {
|
|
paramStrings = append(paramStrings, fmt.Sprintf("%s=%s", key, value))
|
|
}
|
|
|
|
log.Printf("Unhandled event %s(%s)", event.Name, strings.Join(paramStrings, ", "))
|
|
return
|
|
}
|
|
|
|
handlers, err := config.EventHandlerRepository().FetchAll(ctx)
|
|
if err != nil {
|
|
log.Printf("Error fetchin event halders: %d", err)
|
|
return
|
|
}
|
|
|
|
for _, handler := range handlers {
|
|
devices, err := config.DeviceRepository().FetchByReference(ctx, handler.TargetKind, handler.TargetValue)
|
|
if err != nil {
|
|
log.Printf("Error fetchin event halders: %d", err)
|
|
return
|
|
}
|
|
|
|
if !handler.MatchesEvent(event, devices) {
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
|
|
func handleSpecial(event models.Event) error {
|
|
switch event.Name {
|
|
case models.ENBridgeConnected:
|
|
bridgeId, _ := strconv.Atoi(event.Payload["bridgeId"])
|
|
bridge, err := config.BridgeRepository().Find(ctx, bridgeId)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
devices, err := config.DeviceRepository().FetchByReference(ctx, models.RKBridgeID, event.Payload["bridgeId"])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
driver, err := config.DriverProvider().Provide(bridge.Driver)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return driver.Publish(ctx, bridge, devices)
|
|
default:
|
|
return nil
|
|
}
|
|
}
|