package services import ( "context" "git.aiterp.net/lucifer/new-server/app/config" "git.aiterp.net/lucifer/new-server/models" "log" "strconv" "time" ) func CheckNewDevices() { go func() { // Wait a bit before the first to let bridges connect. time.Sleep(time.Second * 5) err := checkNewDevices() if err != nil { log.Println("Failed to sync lights:", err) } for range time.NewTicker(time.Second * 30).C { err := checkNewDevices() if err != nil { log.Println("Failed to sync lights:", err) } } }() } func checkNewDevices() error { ctx, cancel := context.WithTimeout(context.Background(), time.Second*27) defer cancel() bridges, err := config.BridgeRepository().FetchAll(ctx) if err != nil { return err } for _, bridge := range bridges { driver, err := config.DriverProvider().Provide(bridge.Driver) if err != nil { log.Println("Unknown/unsupported driver:", bridge.Driver) continue } savedDevices, err := config.DeviceRepository().FetchByReference(ctx, models.RKBridgeID, strconv.Itoa(bridge.ID)) if err != nil { log.Println("Failed to list devices from db:", err) continue } driverDevices, err := driver.ListDevices(ctx, bridge) if err != nil { log.Println("Failed to list devices from driver:", err) continue } foundNewDevices := false SaveLoop: for _, driverDevice := range driverDevices { for _, savedDevice := range savedDevices { if savedDevice.InternalID == driverDevice.InternalID { continue SaveLoop } } log.Println("Saving new device", driverDevice.InternalID) err := config.DeviceRepository().Save(ctx, &driverDevice) if err != nil { log.Println("Failed to save device:", err) continue } foundNewDevices = true } // If new devices were found, publish them so that the driver can be set up. if foundNewDevices { savedDevices, err := config.DeviceRepository().FetchByReference(ctx, models.RKBridgeID, strconv.Itoa(bridge.ID)) if err != nil { log.Println("Failed to fetch devices from db second time:", err) continue } err = driver.Publish(ctx, bridge, savedDevices) if err != nil { log.Println("Failed to list devices from db:", err) continue } } } return nil }