-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
255 lines (219 loc) · 5.93 KB
/
main.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package main
import (
"bytes"
"context"
"encoding/xml"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"time"
"code.dny.dev/trafikinfo"
wmp "code.dny.dev/trafikinfo/trv/weathermeasurepoint/v2"
"lib.hemtjan.st/client"
"lib.hemtjan.st/transport/mqtt"
)
var (
version = "unknown"
commit = "unknown"
date = "unknown"
)
type stationNamesFlag []string
func (s *stationNamesFlag) String() string {
return strings.Join(*s, ", ")
}
func (s *stationNamesFlag) Set(value string) error {
*s = append(*s, value)
return nil
}
func main() {
var stationNames stationNamesFlag
flag.Var(&stationNames, "name", "station name to query for, needs to be passed at least 1 time")
apiToken := flag.String("token", "REQUIRED", "Trafikinfo API token")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n\n", os.Args[0])
fmt.Fprintf(os.Stderr, "Parameters:\n\n")
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintf(os.Stderr, "Version: %s, Commit: %s, Date: %s\n", version, commit, date)
fmt.Fprintf(os.Stderr, "\n")
}
mcfg := mqtt.MustFlags(flag.String, flag.Bool)
flag.Parse()
if *apiToken == "REQUIRED" {
log.Fatalln("A token is required to be able to query the Trafikinfo API")
}
if len(stationNames) == 0 {
log.Fatalln("At least one station name is required to be able to query the Trafikinfo API")
}
stationFilters := make([]trafikinfo.Filter, 0, len(stationNames))
for _, station := range stationNames {
stationFilters = append(stationFilters, trafikinfo.Equal("Name", station))
}
req, err := trafikinfo.NewRequest().
APIKey(*apiToken).
Query(
trafikinfo.NewQuery(wmp.ObjectType()).Filter(
trafikinfo.Or(stationFilters...),
).Include(
"Id", "Name",
"Observation.Air.Temperature.Value",
"Observation.Air.RelativeHumidity.Value",
"Observation.Aggregated30minutes.Precipitation.TotalWaterEquivalent.Value",
"Observation.Sample",
),
).Build()
if err != nil {
log.Fatalf("invalid query: %v\n", err)
}
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
data, err := retrieve(ctx, http.DefaultClient, req)
if err != nil {
log.Fatalf("failed to fetch data from API: %s\n", err)
}
log.Println("fetched initial data")
m, err := mqtt.New(ctx, mcfg())
if err != nil {
log.Fatalln(err)
}
go func() {
for {
ok, err := m.Start()
if err != nil {
log.Printf("MQTT Error: %s", err)
}
if !ok && ctx.Err() == nil {
log.Fatalln("MQTT: could not (re)connect")
}
time.Sleep(5 * time.Second)
log.Printf("MQTT: reconnecting")
}
}()
stations := map[string]client.Device{}
for _, item := range data {
station := newWeatherStation(
item.name, item.id, m,
)
stations[item.id] = station
}
if len(stations) != len(stationNames) {
notfound := []string{}
for _, id := range stationNames {
if _, ok := stations[id]; !ok {
notfound = append(notfound, id)
}
}
log.Printf("Station IDs %s could not be found\n", strings.Join(notfound, ", "))
}
update(data, stations)
log.Println("MQTT: published initial sensor data")
loop:
for {
select {
case <-ctx.Done():
log.Println("Received shutdown signal, terminating")
break loop
// Publish after every interval has elapsed
case <-time.After(time.Duration(10 * time.Minute)):
data, err := retrieve(ctx, http.DefaultClient, req)
if err != nil {
log.Printf("failed to fetch data from API: %s\n", err)
continue
}
update(data, stations)
}
}
os.Exit(0)
}
func update(sensors []sensor, stations map[string]client.Device) {
for _, item := range sensors {
station, ok := stations[item.id]
if !ok {
continue
}
if item.tempC != nil {
err := station.Feature("currentTemperature").Update(
strconv.FormatFloat(*item.tempC, 'f', 1, 32),
)
if err != nil {
log.Printf("MQTT: failed to publish temperature: %s\n", err)
}
}
if item.rhPct != nil {
err := station.Feature("currentRelativeHumidity").Update(
strconv.FormatFloat(*item.rhPct, 'f', 1, 32),
)
if err != nil {
log.Printf("MQTT: failed to publish relative humidity: %s\n", err)
}
}
precip := 0.0
if item.precip != nil {
precip = *item.precip * 2
}
err := station.Feature("precipitation").Update(
strconv.FormatFloat(precip, 'f', 1, 32),
)
if err != nil {
log.Printf("MQTT: failed to publish precipitation: %s\n", err)
}
}
}
type sensor struct {
id string
name string
tempC *float64
rhPct *float64
precip *float64
}
func retrieve(ctx context.Context, client *http.Client, body []byte) ([]sensor, error) {
httpReq, err := http.NewRequest(http.MethodPost, trafikinfo.Endpoint, bytes.NewBuffer(body))
if err != nil {
return nil, err
}
httpReq.Header.Set("content-type", "text/xml")
resp, err := client.Do(httpReq)
if err != nil {
return nil, err
}
defer func() {
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var wr wmp.Response
if err := xml.Unmarshal(data, &wr); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
if resp.StatusCode != http.StatusOK || wr.HasErrors() {
return nil, fmt.Errorf("http code: %d, error: %s", resp.StatusCode, wr.ErrorMsg())
}
if numRes := len(wr.Results); numRes != 1 {
return nil, fmt.Errorf("expected 1 query result, got %d", numRes)
}
sensors := []sensor{}
for _, mp := range wr.Results[0].Data {
// Don't bother updating if samples are old. This usually indicates the station is
// malfunctioning or offline for maintenance
if mp.Observation().Sample().Before(time.Now().Add(-1 * time.Hour)) {
continue
}
sensors = append(sensors, sensor{
id: *mp.ID(),
name: *mp.Name(),
tempC: mp.Observation().Air().Temperature().Value(),
rhPct: mp.Observation().Air().RelativeHumidity().Value(),
precip: mp.Observation().Aggregated30minutes().Precipitation().TotalWaterEquivalent().Value(),
})
}
return sensors, nil
}