-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcec-client-mqtt-bridge.go
64 lines (50 loc) · 1.52 KB
/
cec-client-mqtt-bridge.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 main
import (
"bufio"
"fmt"
"io"
"os"
"regexp"
MQTT "github.com/eclipse/paho.mqtt.golang"
)
func mqtt2cecHandler(client MQTT.Client, msg MQTT.Message) {
fmt.Printf("%s\n", msg.Payload())
}
func main() {
// Config MQTT
opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883").SetClientID("cec-client-mqtt")
opts.SetCleanSession(true)
// Connect
mqttClient := MQTT.NewClient(opts)
if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
// MQTT to CEC-CLIENT
if token := mqttClient.Subscribe("cec/client/tx", 0, mqtt2cecHandler); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
// CEC-CLIENT to MQTT
stdin := bufio.NewReader(os.Stdin)
// Regex to get message topic & contents
rTopicContents := regexp.MustCompile(`^([A-Z]*)\:\s*\[.{18}(.*)`)
// Init message to be published
for {
// Get CEC message
cecMessage, err := stdin.ReadString('\n')
// Check for errors
if err == io.EOF {
os.Exit(0)
}
// Find topic & contents
matches := rTopicContents.FindStringSubmatch(cecMessage)
switch len(matches) {
case 0:
mqttClient.Publish("cec/client/rx/UNKNOWN", 0, false, cecMessage)
case 3:
if matches[1] == "TRAFFIC" {
mqttClient.Publish("cec/client/rx/"+matches[1], 0, false, matches[2])
}
}
}
}