Skip to content

Commit

Permalink
Merge pull request #3 from poolski/add-more-logging
Browse files Browse the repository at this point in the history
Add better logging
  • Loading branch information
poolski authored Jan 16, 2024
2 parents ba26080 + de376a6 commit 9474712
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 9 deletions.
28 changes: 21 additions & 7 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type APIResponse struct {
Type string `json:"type"` // Type is the type of the response.
Success bool `json:"success"` // Success indicates whether the response was successful or not.
Result struct {
SmartMeterElectricityImport []struct {
ImportedElectricity []struct {
Start int `json:"start"`
End int `json:"end"`
Change float64 `json:"change"` // Change is the amount of electricity imported.
Expand Down Expand Up @@ -87,31 +87,33 @@ func (c *Client) Connect() error {
log.Info().Msgf("connecting to %s", dialURL.String())
conn, _, err := dialer.Dial(dialURL.String(), nil)
if err != nil {
return err
return fmt.Errorf("dial: %w", err)
}
log.Info().Msg("connected")

// Read the initial message
var initMsg map[string]any
if err := conn.ReadJSON(&initMsg); err != nil {
return err
return fmt.Errorf("initial message: %w", err)
}

// Send the authentication message
if err := conn.WriteJSON(map[string]string{
"type": "auth",
"access_token": viper.GetString("api_key"),
}); err != nil {
return err
return fmt.Errorf("auth message: %w", err)
}

// Read the authentication response
var authResp map[string]any
if err := conn.ReadJSON(&authResp); err != nil {
return err
return fmt.Errorf("auth response: %w", err)
}
if authResp["type"] != "auth_ok" {
return fmt.Errorf("authentication failed: %v", authResp["message"])
}
log.Info().Msg("authenticated")

c.Conn = conn
return nil
Expand Down Expand Up @@ -240,12 +242,18 @@ func getResults(c *Client) ([][]float64, error) {

offset := time.Duration((i+1)*24) * time.Hour
start := time.Now().Add(-offset).Truncate(24 * time.Hour).Format("2006-01-02T15:04:05.000Z")

sensorID := viper.GetString("sensor_id")
if sensorID == "" {
return nil, fmt.Errorf("sensor_id is required")
}

msg := map[string]interface{}{
"id": c.MessageID,
"type": "recorder/statistics_during_period",
"start_time": start,
"end_time": time.Now().Truncate(24 * time.Hour).Format("2006-01-02T15:04:05.000Z"),
"statistic_ids": []string{"sensor.smart_meter_electricity_import_2"},
"statistic_ids": []string{sensorID},
"period": "hour",
"types": []string{"change"},
"units": map[string]string{
Expand All @@ -266,9 +274,15 @@ func getResults(c *Client) ([][]float64, error) {
if !data.Success {
return nil, fmt.Errorf("api response error: %v", data.Error)
}

if len(data.Result.ImportedElectricity) != hoursInADay {
return nil, fmt.Errorf("expected %d sets of results, got %d", hoursInADay, len(data.Result.ImportedElectricity))
}

changeSlice := make([]float64, hoursInADay)
log.Debug().Msgf("got %d results", len(data.Result.ImportedElectricity))
for j := range changeSlice {
changeSlice[j] = data.Result.SmartMeterElectricityImport[j].Change
changeSlice[j] = data.Result.ImportedElectricity[j].Change
}
results[i] = changeSlice
}
Expand Down
4 changes: 3 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,16 +94,18 @@ func initConfig() {
func promtUserConfig() error {
urlPrompt := prompter.Prompt("Home Assistant URL - e.g. http://localhost:8123", "")
token := prompter.Password("Home Assistant Long-Lived Access Token")
sensor := prompter.Prompt("Power sensor entity ID - e.g. sensor.power", "")

haURL, err := url.Parse(urlPrompt)
if haURL.Scheme == "" {
haURL.Scheme = "http"
}
if err != nil {
return err
return fmt.Errorf("parsing URL: %w", err)
}

viper.Set("api_key", token)
viper.Set("url", haURL.String())
viper.Set("sensor", sensor)
return nil
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.20

require (
github.com/gorilla/websocket v1.5.0
github.com/olekukonko/tablewriter v0.0.5
github.com/rs/zerolog v1.30.0
github.com/spf13/cobra v1.7.0
github.com/spf13/viper v1.16.0
Expand All @@ -21,7 +22,6 @@ require (
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/olekukonko/tablewriter v0.0.5
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/spf13/afero v1.9.5 // indirect
github.com/spf13/cast v1.5.1 // indirect
Expand Down

0 comments on commit 9474712

Please sign in to comment.