Skip to content

Commit 200ff0f

Browse files
committed
fix time issues, just about prod ready
- don't allow date configurations that won't work - fix tz issues with times and dates - use UnixMilli() to compare with existing timestamps - parse tz correctly from victoria metrics export output
1 parent e01f569 commit 200ff0f

File tree

2 files changed

+27
-17
lines changed

2 files changed

+27
-17
lines changed

internal/app/main.go

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,44 +43,57 @@ func Main() {
4343
if err != nil {
4444
log.Fatal(err)
4545
}
46+
if config.ExtractDays > 45 || config.ExtractDays < 2 {
47+
log.Fatal("ExtractDays must be between 2 and 45 per smarthub")
48+
}
4649

4750
// parse time flags
4851
startFlag := flag.String("start", "", "Start date of period to extract from electric co.")
4952
endFlag := flag.String("end", "", "End date of period to extract from electric co.")
5053
flag.Parse()
5154
var startDate, endDate time.Time
5255
if *startFlag != "" {
53-
startDate, err = time.Parse("2006-01-02", *startFlag)
56+
startDate, err = time.ParseInLocation("2006-01-02", *startFlag, time.Local)
5457
if err != nil {
5558
log.Fatal(err)
5659
}
5760
if *endFlag == "" {
5861
log.Fatal("start and end parameters must both be provided")
5962
}
60-
endDate, err = time.Parse("2006-01-02", *endFlag)
63+
endDate, err = time.ParseInLocation("2006-01-02", *endFlag, time.Local)
6164
if err != nil {
6265
log.Fatal(err)
6366
}
67+
if endDate.Sub(startDate).Hours() > 24*45 {
68+
log.Fatal("start and end parameters must define a period of no more than 45 days")
69+
}
70+
// endDate should be the last minute of the day for the VictoriaMetrics query.
71+
endDate = endDate.Add((24 * time.Hour) - time.Minute)
6472
} else {
65-
endDate = time.Now().Truncate(24 * time.Hour)
66-
startDate = endDate.Add(time.Duration(-config.ExtractDays) * 24 * time.Hour)
73+
// yesterday
74+
year, month, day := time.Now().Date()
75+
// endDate should be the last minute of the day for the VictoriaMetrics query.
76+
endDate = time.Date(year, month, day, 23, 59, 0, 0, time.Local)
77+
// subtract N days and 1 minute to get the start date
78+
startDate = endDate.Add(time.Duration(-config.ExtractDays) * 48 * time.Hour).Add(time.Minute)
6779
}
6880

69-
path, err := DownloadCsv(config, startDate.Format("01/02/2006"), endDate.Format("01/02/2002"))
81+
path, err := DownloadCsv(config, startDate.Format("01/02/2006"), endDate.Format("01/02/2006"))
7082
if err != nil {
7183
log.Fatal(err)
7284
}
7385
fmt.Printf("file downloaded: %s", path)
7486

75-
// parse csv
7687
records, err := ParseCsv(path)
7788
if err != nil {
7889
log.Fatal(err)
7990
}
80-
fmt.Printf("%+v", records)
8191
existingPoints, err := QueryPreviousMetrics(startDate, endDate, config.InfluxDB)
8292
if err != nil {
8393
log.Fatal(err)
8494
}
85-
WriteMetrics(records, config.InfluxDB, existingPoints)
95+
err = WriteMetrics(records, config.InfluxDB, existingPoints)
96+
if err != nil {
97+
log.Fatal(err)
98+
}
8699
}

internal/app/metrics.go

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,14 @@ type MetricLine struct {
1717
Timestamps []int64
1818
}
1919

20-
func WriteMetrics(records []*ElectricUsage, config InfluxDB, existingPoints map[int64]struct{}) {
20+
func WriteMetrics(records []*ElectricUsage, config InfluxDB, existingPoints map[int64]struct{}) error {
2121
client := influxdb2.NewClient(config.Host, config.User+":"+config.Password)
2222
writeApi := client.WriteAPIBlocking("", config.Database)
2323
points := make([]*write.Point, 0, 15*2*len(records))
2424
for _, record := range records {
2525
divisor := record.EndTime.Sub(record.StartTime).Minutes()
2626
for t := record.StartTime; record.EndTime.After(t); t = t.Add(time.Minute) {
27-
if _, ok := existingPoints[t.Unix()]; ok {
27+
if _, ok := existingPoints[t.UnixMilli()]; ok {
2828
continue
2929
}
3030
watts := influxdb2.NewPointWithMeasurement("electric").
@@ -37,18 +37,15 @@ func WriteMetrics(records []*ElectricUsage, config InfluxDB, existingPoints map[
3737
}
3838
}
3939

40-
err := writeApi.WritePoint(context.Background(), points...)
41-
if err != nil {
42-
log.Fatal(err)
43-
}
40+
return writeApi.WritePoint(context.Background(), points...)
4441
}
4542

4643
func QueryPreviousMetrics(startTime time.Time, endTime time.Time, config InfluxDB) (map[int64]struct{}, error) {
4744
client := &http.Client{}
4845
v := url.Values{
49-
"match[]": {"sensor_temperature"},
50-
"start": {startTime.Format("2006-01-02T15:04:05+07:00")},
51-
"end": {endTime.Format("2006-01-02T15:04:05+07:00")},
46+
"match[]": {"electric_usage"},
47+
"start": {startTime.Format(`2006-01-02T15:04:05Z07:00`)},
48+
"end": {endTime.Format("2006-01-02T15:04:05Z07:00")},
5249
}
5350
req, err := http.NewRequest("POST", config.Host+"/api/v1/export", strings.NewReader(v.Encode()))
5451
if err != nil {

0 commit comments

Comments
 (0)