package app import ( "context" "strings" "sync" "gitea.nik4nao.com/nik/home-services/ha-gateway/internal/core/domain" "gitea.nik4nao.com/nik/home-services/ha-gateway/internal/core/ports/driven" ) type SwitchApp struct { ha driven.HAClient mu sync.RWMutex cache []domain.Switch } func NewSwitchApp(ha driven.HAClient) *SwitchApp { return &SwitchApp{ha: ha} } func (a *SwitchApp) Refresh(ctx context.Context) error { all, err := a.ha.ListStates(ctx) if err != nil { return err } var switches []domain.Switch for _, s := range all { if !strings.HasPrefix(s.EntityID, "switch.") { continue } switches = append(switches, haStateToSwitch(s)) } a.mu.Lock() a.cache = switches a.mu.Unlock() return nil } func (a *SwitchApp) ListSwitches(ctx context.Context) ([]domain.Switch, error) { a.mu.RLock() c := a.cache a.mu.RUnlock() if c == nil { if err := a.Refresh(ctx); err != nil { return nil, err } a.mu.RLock() c = a.cache a.mu.RUnlock() } return c, nil } func haStateToSwitch(s *driven.HAState) domain.Switch { sw := domain.Switch{ EntityID: domain.EntityID(s.EntityID), State: s.State, } if v, ok := s.Attributes["friendly_name"].(string); ok { sw.FriendlyName = v } if v, ok := s.Attributes["device_class"].(string); ok { sw.DeviceClass = v } return sw }