-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
100 lines (77 loc) · 1.6 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
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"runtime"
"time"
)
var (
apiHost = flag.String("api", "", "location of smartmeter-api")
apiUrl = ""
)
func main() {
log.Printf("Go version %s running on %s %s", runtime.Version(), runtime.GOOS, runtime.GOARCH)
flag.Parse()
if *apiHost == "" {
*apiHost = os.Getenv("API_HOST")
}
if *apiHost == "" {
log.Fatal("api flag or API_HOST not set")
}
log.Printf("Using API host %s", *apiHost)
apiUrl = fmt.Sprintf("http://%s/meterdata", *apiHost)
for {
log.Println("Starting reading data...")
err := Start()
if err != nil {
log.Println(err)
time.Sleep(4 * time.Second)
continue
}
}
}
func Start() error {
port, err := OpenPort()
if err != nil {
log.Fatalf("error opening port %s", err)
}
meterChan := make(chan *MeterData)
go ReadLoop(port, meterChan)
for {
select {
case data := <-meterChan:
if err := processData(data); err != nil {
return fmt.Errorf("Error in processData: %s", err)
}
case <-time.After(time.Minute):
return errors.New("No data received for 1 minute")
}
}
return nil
}
func processData(data *MeterData) error {
// Parse data first
if err := data.Parse(); err != nil {
return err
}
// Create JSON output
jsonData, err := data.Json()
if err != nil {
return err
}
// Send JSON to our API
resp, err := http.Post(apiUrl, "application/json", bytes.NewReader(jsonData))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Received statuscode %d from API", resp.StatusCode)
}
return nil
}