Skip to content

Commit ed85a47

Browse files
committed
Not all SmartHub implementations return cost data.
- Only use and write cost data if it exists in the response from the api.
1 parent c529193 commit ed85a47

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

internal/app/metrics.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,10 @@ func WriteMetrics(records []ElectricUsage, config InfluxConfig) error {
2525
for t := record.StartTime; record.EndTime.After(t); t = t.Add(time.Minute) {
2626
point := influxdb2.NewPointWithMeasurement("electric").
2727
SetTime(t).
28-
AddField("watts", float64(record.WattHours)*multiplier).
29-
AddField("cost", float64(record.CostInCents)/minutes)
28+
AddField("watts", float64(record.WattHours)*multiplier)
29+
if record.CostInCents != nil {
30+
point.AddField("cost", float64(*record.CostInCents)/minutes)
31+
}
3032
points = append(points, point)
3133
}
3234
err := writeApi.WritePoint(context.Background(), points...)

internal/app/parser.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ type ElectricUsage struct {
1414
StartTime time.Time
1515
EndTime time.Time
1616
WattHours int64
17-
CostInCents int64
17+
CostInCents *int64
1818
}
1919

2020
// Response holds the parsed response from the SmartHub poll api.
@@ -116,13 +116,16 @@ func ParseReader(readCloser io.ReadCloser) ([]ElectricUsage, error) {
116116
records := make([]ElectricUsage, len(usageSeries))
117117
for i := range usageSeries {
118118
usage := usageSeries[i]
119-
cost := costSeries[i]
120119
// see note above about "unix timestamps"
121120
start := time.UnixMilli(usage.UnixMillis).Add(time.Second * time.Duration(-offset))
122121
records[i].StartTime = start
123122
records[i].EndTime = start.Add(period)
124123
records[i].WattHours = int64(usage.Value * 1000)
125-
records[i].CostInCents = int64(cost.Value * 100)
124+
}
125+
// note: cost is not returned by all SmartHub implementations. So this is a no-op sometimes.
126+
for i := range costSeries {
127+
cost := int64(costSeries[i].Value * 100)
128+
records[i].CostInCents = &cost
126129
}
127130
return records, nil
128131
}

0 commit comments

Comments
 (0)