-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathplant.go
64 lines (55 loc) · 1.51 KB
/
plant.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package growatt
import (
"regexp"
"strconv"
"time"
)
// Plant represents the data structure for a Growatt plant
type Plant struct {
Earned string
Name string
ID int
HasStorage bool
EnergyToday float64 // in kilowatthours
EnergyTotal float64 // in kilowatthours
CurrentPower float64 // in watts
}
// TimeEnergy is the amount of power the plant generated at a certain time
type TimeEnergy struct {
Timestamp time.Time
Power float64 // in watts
}
// plantData represents how plant data is returned from the API
type plantData struct {
PlantMoneyText string `json:"plantMoneyText"`
PlantName string `json:"plantName"`
PlantID string `json:"plantId"`
IsHaveStorage string `json:"isHaveStorage"`
TodayEnergy string `json:"todayEnergy"`
TotalEnergy string `json:"totalEnergy"`
CurrentPower string `json:"currentPower"`
}
func parsePower(pwr string) float64 {
wattRe := regexp.MustCompile(`^(?i)([0-9.]+)(?: k?Wh?)?$`)
match := wattRe.FindStringSubmatch(pwr)
if len(match) != 2 {
return 0.0
}
result, err := strconv.ParseFloat(match[1], 64)
if err != nil {
return 0.0
}
return result
}
func parsePlantData(p plantData) Plant {
plantID, _ := strconv.ParseInt(p.PlantID, 10, 64)
return Plant{
Earned: p.PlantMoneyText,
Name: p.PlantName,
ID: int(plantID),
HasStorage: (p.IsHaveStorage == "true"),
EnergyToday: parsePower(p.TodayEnergy),
EnergyTotal: parsePower(p.TotalEnergy),
CurrentPower: parsePower(p.CurrentPower),
}
}