From ff9f6cb95e9addc21c0f5435de29fb181a170a11 Mon Sep 17 00:00:00 2001 From: Lubos Dolezel Date: Wed, 24 May 2023 17:23:50 +0200 Subject: [PATCH] Fix a crash in State.getLatLong() --- app.go | 5 ++++- state.go | 32 ++++++++++++++++++++++++-------- 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/app.go b/app.go index 4866b56..3497c53 100644 --- a/app.go +++ b/app.go @@ -98,7 +98,10 @@ func NewApp(request NewAppRequest) (*App, error) { wsWriter := &ws.WebsocketWriter{Conn: conn} service := newService(wsWriter, ctx, httpClient) - state := newState(httpClient, request.HomeZoneEntityId) + state, err := newState(httpClient, request.HomeZoneEntityId) + if err != nil { + return nil, err + } return &App{ conn: conn, diff --git a/state.go b/state.go index e07c4b7..b37705c 100644 --- a/state.go +++ b/state.go @@ -2,7 +2,8 @@ package gomeassistant import ( "encoding/json" - "log" + "errors" + "fmt" "time" "github.com/golang-module/carbon" @@ -23,19 +24,34 @@ type EntityState struct { LastChanged time.Time `json:"last_changed"` } -func newState(c *http.HttpClient, homeZoneEntityId string) *State { +func newState(c *http.HttpClient, homeZoneEntityId string) (*State, error) { state := &State{httpClient: c} - state.getLatLong(c, homeZoneEntityId) - return state + err := state.getLatLong(c, homeZoneEntityId) + if err != nil { + return nil, err + } + return state, nil } -func (s *State) getLatLong(c *http.HttpClient, homeZoneEntityId string) { +func (s *State) getLatLong(c *http.HttpClient, homeZoneEntityId string) error { resp, err := s.Get(homeZoneEntityId) if err != nil { - log.Fatalf("Couldn't get latitude/longitude from home assistant entity '%s'. Did you type it correctly? It should be a zone like 'zone.home'.\n", homeZoneEntityId) + return errors.New(fmt.Sprintf("couldn't get latitude/longitude from home assistant entity '%s'. Did you type it correctly? It should be a zone like 'zone.home'.\n", homeZoneEntityId)) } - s.latitude = resp.Attributes["latitude"].(float64) - s.longitude = resp.Attributes["longitude"].(float64) + + if resp.Attributes["latitude"] != nil { + s.latitude = resp.Attributes["latitude"].(float64) + } else { + return errors.New("server returned nil latitude") + } + + if resp.Attributes["longitude"] != nil { + s.longitude = resp.Attributes["longitude"].(float64) + } else { + return errors.New("server returned nil longitude") + } + + return nil } func (s *State) Get(entityId string) (EntityState, error) {