- Added ListSwitches method to SwitchService in switch_grpc.pb.go. - Implemented SwitchGRPC adapter for ListSwitches in switch.go. - Created SwitchApp for managing switch states and added ListSwitches logic. - Updated core domain with Switch struct and associated methods. - Enhanced LightApp to include ListLights functionality. - Updated protobuf definitions for Switch and Light services to include new request and response messages. - Introduced error handling for unimplemented methods in the gRPC server.
70 lines
1.3 KiB
Go
70 lines
1.3 KiB
Go
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
|
|
}
|