Skip to content

Commit

Permalink
style(hass): code improvements
Browse files Browse the repository at this point in the history
- rename `interface{}` to `any`
- fix spelling mistakes
- format imports
  • Loading branch information
joshuar committed Dec 12, 2023
1 parent 62ecac3 commit 9f8ab52
Show file tree
Hide file tree
Showing 11 changed files with 45 additions and 47 deletions.
2 changes: 1 addition & 1 deletion internal/hass/api/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ package api

//go:generate moq -out mock_Agent_test.go . Agent
type Agent interface {
GetConfig(string, interface{}) error
GetConfig(string, any) error
}
2 changes: 1 addition & 1 deletion internal/hass/api/device.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ type DeviceInfo interface {
OsName() string
OsVersion() string
SupportsEncryption() bool
AppData() interface{}
AppData() any
MarshalJSON() ([]byte, error)
}
22 changes: 11 additions & 11 deletions internal/hass/api/registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,17 +73,17 @@ func (rr *RegistrationResponse) GenerateWebsocketURL(host string) string {
}

type RegistrationRequest struct {
AppData interface{} `json:"app_data,omitempty"`
DeviceID string `json:"device_id"`
AppID string `json:"app_id"`
AppName string `json:"app_name"`
AppVersion string `json:"app_version"`
DeviceName string `json:"device_name"`
Manufacturer string `json:"manufacturer"`
Model string `json:"model"`
OsName string `json:"os_name"`
OsVersion string `json:"os_version"`
SupportsEncryption bool `json:"supports_encryption"`
AppData any `json:"app_data,omitempty"`
DeviceID string `json:"device_id"`
AppID string `json:"app_id"`
AppName string `json:"app_name"`
AppVersion string `json:"app_version"`
DeviceName string `json:"device_name"`
Manufacturer string `json:"manufacturer"`
Model string `json:"model"`
OsName string `json:"os_name"`
OsVersion string `json:"os_version"`
SupportsEncryption bool `json:"supports_encryption"`
}

func RegisterWithHass(ctx context.Context, agent Agent, device DeviceInfo) (*RegistrationResponse, error) {
Expand Down
6 changes: 3 additions & 3 deletions internal/hass/api/registration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ func TestRegisterWithHass(t *testing.T) {
mockServer := newMockServer(t)

goodRegConfig := &AgentConfigMock{
GetFunc: func(s string, ifaceVal interface{}) error {
GetFunc: func(s string, ifaceVal any) error {
v := ifaceVal.(*string)
switch s {
case config.PrefHost:
Expand All @@ -192,7 +192,7 @@ func TestRegisterWithHass(t *testing.T) {
}

badRegServer := &AgentConfigMock{
GetFunc: func(s string, ifaceVal interface{}) error {
GetFunc: func(s string, ifaceVal any) error {
v := ifaceVal.(*string)
switch s {
case config.PrefHost:
Expand All @@ -208,7 +208,7 @@ func TestRegisterWithHass(t *testing.T) {
}

badRegToken := &AgentConfigMock{
GetFunc: func(s string, ifaceVal interface{}) error {
GetFunc: func(s string, ifaceVal any) error {
v := ifaceVal.(*string)
switch s {
case config.PrefHost:
Expand Down
6 changes: 3 additions & 3 deletions internal/hass/api/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func marshalJSON(request Request, secret string) ([]byte, error) {
EncryptedData: request.RequestData(),
})
} else {
return nil, errors.New("encrypted request recieved without secret")
return nil, errors.New("encrypted request received without secret")
}
} else {
return json.Marshal(&UnencryptedRequest{
Expand All @@ -70,8 +70,8 @@ type EncryptedRequest struct {
Encrypted bool `json:"encrypted"`
}

func ExecuteRequest(ctx context.Context, request Request) chan interface{} {
responseCh := make(chan interface{}, 1)
func ExecuteRequest(ctx context.Context, request Request) chan any {
responseCh := make(chan any, 1)
defer close(responseCh)
cfg, ok := FromContext(ctx)
if !ok {
Expand Down
2 changes: 1 addition & 1 deletion internal/hass/api/request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func TestExecuteRequest(t *testing.T) {
tests := []struct {
name string
args args
want chan interface{}
want chan any
}{
{
name: "default test",
Expand Down
14 changes: 7 additions & 7 deletions internal/hass/api/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func parseUpdateResponse(buf *bytes.Buffer) (*SensorResponse, error) {
}
for k, v := range r {
log.Trace().Str("id", k).Msg("Parsing response for sensor.")
r, err := assertAs[map[string]interface{}](v)
r, err := assertAs[map[string]any](v)
if err != nil {
return nil, err
}
Expand All @@ -63,7 +63,7 @@ func parseUpdateResponse(buf *bytes.Buffer) (*SensorResponse, error) {
return nil, err
}
log.Trace().Str("id", k).Msg("Unsuccessful response.")
responseErr, err := assertAs[map[string]interface{}](r["error"])
responseErr, err := assertAs[map[string]any](r["error"])
if err != nil {
return nil, errors.New("unknown error")
} else {
Expand All @@ -82,7 +82,7 @@ func parseUpdateResponse(buf *bytes.Buffer) (*SensorResponse, error) {
return nil, errors.New("unknown response structure")
}

func parseResponse(t RequestType, buf *bytes.Buffer) (interface{}, error) {
func parseResponse(t RequestType, buf *bytes.Buffer) (any, error) {
switch t {
case RequestTypeUpdateLocation:
return buf.Bytes(), nil
Expand All @@ -97,20 +97,20 @@ func parseResponse(t RequestType, buf *bytes.Buffer) (interface{}, error) {
}
}

func parseAsMap(buf *bytes.Buffer) (map[string]interface{}, error) {
var r interface{}
func parseAsMap(buf *bytes.Buffer) (map[string]any, error) {
var r any
err := json.Unmarshal(buf.Bytes(), &r)
if err != nil {
return nil, fmt.Errorf("could not unmarshal response (%s)", buf.String())
}
rMap, ok := r.(map[string]interface{})
rMap, ok := r.(map[string]any)
if !ok {
return nil, errors.New("could not parse response as map")
}
return rMap, nil
}

func assertAs[T any](thing interface{}) (T, error) {
func assertAs[T any](thing any) (T, error) {
if asT, ok := thing.(T); !ok {
return *new(T), errors.New("could not assert value")
} else {
Expand Down
17 changes: 8 additions & 9 deletions internal/hass/api/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@ import (

"github.com/cenkalti/backoff/v4"
"github.com/joshuar/go-hass-agent/internal/agent/config"
"github.com/rs/zerolog/log"

"github.com/lxzan/gws"
"github.com/rs/zerolog/log"
)

const PingInterval = time.Minute
Expand All @@ -30,19 +29,19 @@ type websocketMsg struct {
}

type websocketResponse struct {
Result interface{} `json:"result,omitempty"`
Result any `json:"result,omitempty"`
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error,omitempty"`
Type string `json:"type"`
HAVersion string `json:"ha_version,omitempty"`
Notification struct {
Data interface{} `json:"data,omitempty"`
Message string `json:"message"`
Title string `json:"title,omitempty"`
ConfirmID string `json:"confirm_id,omitempty"`
Target []string `json:"target,omitempty"`
Data any `json:"data,omitempty"`
Message string `json:"message"`
Title string `json:"title,omitempty"`
ConfirmID string `json:"confirm_id,omitempty"`
Target []string `json:"target,omitempty"`
} `json:"event,omitempty"`
ID uint64 `json:"id,omitempty"`
Success bool `json:"success,omitempty"`
Expand Down Expand Up @@ -86,7 +85,7 @@ func StartWebsocket(ctx context.Context, settings Agent, notifyCh chan [2]string

type webSocketData struct {
conn *gws.Conn
data interface{}
data any
}

type WebSocket struct {
Expand Down
9 changes: 4 additions & 5 deletions internal/hass/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,19 @@ import (
"encoding/json"
"sync"

"github.com/rs/zerolog/log"

"github.com/joshuar/go-hass-agent/internal/hass/api"
"github.com/perimeterx/marshmallow"
"github.com/rs/zerolog/log"
)

type haConfig struct {
rawConfigProps map[string]interface{}
rawConfigProps map[string]any
haConfigProps
mu sync.Mutex
}

type haConfigProps struct {
Entities map[string]map[string]interface{} `json:"entities"`
Entities map[string]map[string]any `json:"entities"`
UnitSystem struct {
Length string `json:"length"`
Mass string `json:"mass"`
Expand Down Expand Up @@ -80,7 +79,7 @@ func GetHassConfig(ctx context.Context) (*haConfig, error) {
return h, nil
}

func (h *haConfig) GetRegisteredEntities() map[string]map[string]interface{} {
func (h *haConfig) GetRegisteredEntities() map[string]map[string]any {
return h.Entities
}

Expand Down
2 changes: 1 addition & 1 deletion internal/hass/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func FindServers(ctx context.Context) []string {

resolver, err := zeroconf.NewResolver(nil)
if err != nil {
log.Debug().Err(err).Msg("Failed to initialize resolver.")
log.Debug().Err(err).Msg("Failed to initialise resolver.")
} else {
entries := make(chan *zeroconf.ServiceEntry)
go func(results <-chan *zeroconf.ServiceEntry) {
Expand Down
10 changes: 5 additions & 5 deletions internal/hass/sensor/sensor.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ type SensorRegistrationInfo struct {
// SensorUpdateInfo is the JSON structure required to update HA with the current
// sensor state.
type SensorUpdateInfo struct {
StateAttributes interface{} `json:"attributes,omitempty"`
State interface{} `json:"state"`
Icon string `json:"icon,omitempty"`
Type string `json:"type"`
UniqueID string `json:"unique_id"`
StateAttributes any `json:"attributes,omitempty"`
State any `json:"state"`
Icon string `json:"icon,omitempty"`
Type string `json:"type"`
UniqueID string `json:"unique_id"`
}

type SensorState struct {
Expand Down

0 comments on commit 9f8ab52

Please sign in to comment.