forked from basvdlei/gotsmart
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gotsmart.go
94 lines (85 loc) · 2.18 KB
/
gotsmart.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
package main
import (
"bufio"
"fmt"
"github.com/metskem/gotsmart/conf"
"log"
"net/http"
"strings"
"time"
"github.com/metskem/gotsmart/crc16"
"github.com/metskem/gotsmart/dsmr"
dsmrprometheus "github.com/metskem/gotsmart/dsmr/prometheus"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/tarm/serial"
)
type frameupdate struct {
Frame string
Time time.Time
}
func (f *frameupdate) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "text/plain; charset=utf-8")
w.Header().Add("Last-Modified", f.Time.Format(http.TimeFormat))
w.Write([]byte(f.Frame))
}
func (f *frameupdate) Update(frame string) {
f.Frame = strings.Replace(frame, "\r", "", -1)
f.Time = time.Now()
}
func (f *frameupdate) Process(br *bufio.Reader, collector *dsmrprometheus.DSMRCollector) {
for {
if b, err := br.Peek(1); err == nil {
if string(b) != "/" {
fmt.Printf("Ignoring garbage character: %c\n", b)
br.ReadByte()
continue
}
} else {
continue
}
frame, err := br.ReadBytes('!')
if err != nil {
fmt.Printf("Error: %v\n", err)
continue
}
bcrc, err := br.ReadBytes('\n')
if err != nil {
fmt.Printf("Error: %v\n", err)
continue
}
// Check CRC
mcrc := strings.ToUpper(strings.TrimSpace(string(bcrc)))
crc := fmt.Sprintf("%04X", crc16.Checksum(frame))
if mcrc != crc {
fmt.Printf("CRC mismatch: %q != %q\n", mcrc, crc)
continue
}
f.Update(string(frame))
dsmrFrame, err := dsmr.ParseFrame(string(frame))
if err != nil {
log.Printf("could not parse frame: %v\n", err)
continue
}
collector.Update(dsmrFrame)
}
}
func main() {
conf.Init()
serialConfig := &serial.Config{Name: *conf.DeviceFlag, Baud: *conf.BaudFlag, Size: byte(*conf.BitsFlag), Parity: conf.Parity}
p, err := serial.OpenPort(serialConfig)
if err != nil {
log.Fatal(err)
}
br := bufio.NewReader(p)
collector := &dsmrprometheus.DSMRCollector{}
prometheus.MustRegister(collector)
f := &frameupdate{}
go f.Process(br, collector)
http.Handle("/metrics", promhttp.Handler())
http.Handle("/", f)
err = http.ListenAndServe(*conf.AddrFlag, nil)
if err != nil {
log.Fatal(err)
}
}