-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
102 lines (91 loc) · 2.34 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
package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.einride.tech/can/pkg/candevice"
"go.einride.tech/can/pkg/socketcan"
)
func main() {
log.SetFlags(log.Lmicroseconds | log.LstdFlags)
setup := flag.Bool("setup", false, "configure and set can device up - needs permission")
td := flag.Bool("setdwon", false, "set can device down - needs permission")
dev := flag.String("d", "can0", "name of the can device")
addr := flag.String("l", ":2112", "address to listen on")
flag.Parse()
if *setup {
if err := start(*dev); err != nil {
log.Fatal(err)
}
os.Exit(0)
}
if *td {
if err := stop(*dev); err != nil {
log.Fatal(err)
}
os.Exit(0)
}
metrics := registerMetrics()
http.Handle("/metrics", promhttp.Handler())
go func() { log.Fatal(http.ListenAndServe(*addr, nil)) }()
log.Printf("exporter started")
conn, err := socketcan.DialContext(context.Background(), "can", *dev)
if err != nil {
log.Fatal(err)
}
recv := socketcan.NewReceiver(conn)
for recv.Receive() {
frame := recv.Frame()
if f, ok := frameIDMap[frame.ID]; ok {
metrics[frame.ID].Set(f.dataConverter(frame.Data))
} else {
log.Printf("unknown frame: %s", frame.String())
}
}
}
func registerMetrics() map[uint32]prometheus.Gauge {
metrics := map[uint32]prometheus.Gauge{}
for id, m := range frameIDMap {
if strings.HasPrefix(m.name, "0") || strings.HasPrefix(m.name, "1") {
m.name = "unkn_" + m.name
}
metrics[id] = promauto.NewGauge(prometheus.GaugeOpts{
Name: m.name,
Help: fmt.Sprintf("%s unit: %s", m.name, m.unit),
})
}
return metrics
}
func start(dev string) error {
d, err := candevice.New(dev)
if err != nil {
return fmt.Errorf("failed to create new device: %v", err)
}
err = d.SetBitrate(50000)
if err != nil {
return fmt.Errorf("failed to set bitrate: %v", err)
}
err = d.SetUp()
if err != nil {
return fmt.Errorf("failed to start the can device: %v", err)
}
return nil
}
func stop(dev string) error {
d, err := candevice.New(dev)
if err != nil {
return fmt.Errorf("failed to create new device: %v", err)
}
err = d.SetDown()
if err != nil {
return fmt.Errorf("failed to stop the can device: %v", err)
}
return nil
}