forked from openfaas/mqtt-connector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
171 lines (138 loc) · 4.85 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
// Copyright (c) OpenFaaS Author(s) 2019. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package main
import (
"flag"
"fmt"
"log"
"os"
"strings"
"time"
MQTT "github.com/eclipse/paho.mqtt.golang"
"github.com/openfaas-incubator/connector-sdk/types"
"github.com/openfaas/faas-provider/auth"
)
func main() {
var (
err error
gatewayUsername string
gatewayPassword string
gatewayFlag string
trimChannelKey bool
asyncInvoke bool
asyncCallbackURL string
rebuildInterval time.Duration
)
flag.StringVar(&gatewayUsername, "gw-username", "", "Username for the gateway")
flag.StringVar(&gatewayPassword, "gw-password", "", "Password for gateway")
flag.StringVar(&gatewayFlag, "gateway", "", "gateway")
flag.BoolVar(&trimChannelKey, "trim-channel-key", false, "Trim channel key when using emitter.io MQTT broker")
flag.BoolVar(&asyncInvoke, "async-invoke", false, "Invoke via queueing using NATS and the function's async endpoint")
flag.StringVar(&asyncCallbackURL, "async-callback-url", "", "Callback URL for asynchronous invocations")
topic := flag.String("topic", "", "The topic name to/from which to publish/subscribe")
broker := flag.String("broker", "tcp://iot.eclipse.org:1883", "The broker URI. ex: tcp://10.10.1.1:1883")
password := flag.String("password", "", "The password (optional)")
user := flag.String("user", "", "The User (optional)")
id := flag.String("id", "testgoid", "The ClientID (optional)")
cleansess := flag.Bool("clean", false, "Set Clean Session (default false)")
qos := flag.Int("qos", 0, "The Quality of Service 0,1,2 (default 0)")
rebuildIntervalStr := flag.String("rebuild_interval", "10s", "Interval between rebuilding map of functions vs. topics (default 10s)")
flag.Parse()
var creds *auth.BasicAuthCredentials
if len(gatewayPassword) > 0 {
creds = &auth.BasicAuthCredentials{
User: gatewayUsername,
Password: gatewayPassword,
}
} else {
creds = types.GetCredentials()
}
gatewayURL := os.Getenv("gateway_url")
if len(gatewayFlag) > 0 {
gatewayURL = gatewayFlag
}
if len(gatewayURL) == 0 {
log.Panicln(`a value must be set for env "gatewayURL" or via the -gateway flag for your OpenFaaS gateway`)
return
}
if rebuildInterval, err = time.ParseDuration(*rebuildIntervalStr); err != nil {
log.Printf("Invalid rebuild interval (%v)", err)
rebuildInterval = time.Second * 10
}
namespace := os.Getenv("namespace")
config := &types.ControllerConfig{
RebuildInterval: rebuildInterval,
GatewayURL: gatewayURL,
PrintResponse: true,
PrintResponseBody: true,
TopicAnnotationDelimiter: ",",
AsyncFunctionInvocation: asyncInvoke,
AsyncFunctionCallbackURL: asyncCallbackURL,
Namespace: namespace,
}
if len(namespace) == 0 {
namespace = "<all>"
}
log.Printf("MQTT Connector:\n"+
"\tNamespace: %s\n"+
"\tTopic: %s\n"+
"\tBroker: %s\n"+
"\tAsync: %v\n"+
"\tAsync Callback: %v\n"+
"\tRebuild Interval: %v\n",
namespace, *topic, *broker, asyncInvoke, asyncCallbackURL, rebuildInterval)
controller := types.NewController(creds, config)
receiver := ResponseReceiver{}
controller.Subscribe(&receiver)
controller.BeginMapBuilder()
opts := MQTT.NewClientOptions()
opts.AddBroker(*broker)
opts.SetClientID(*id)
opts.SetUsername(*user)
opts.SetPassword(*password)
opts.SetCleanSession(*cleansess)
receiveCount := 0
choke := make(chan [2]string)
msgHandler := func(client MQTT.Client, msg MQTT.Message) {
choke <- [2]string{msg.Topic(), string(msg.Payload())}
}
client := MQTT.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
// Splits the topic list and creates a subscription per topic
for _, t := range strings.Split(*topic, ",") {
t = strings.TrimSpace(t)
if token := client.Subscribe(t, byte(*qos), msgHandler); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
}
for {
incoming := <-choke
topic := incoming[0]
data := []byte(incoming[1])
if trimChannelKey {
log.Printf("Topic before trim: %s\n", topic)
index := strings.Index(topic, "/")
topic = topic[index+1:]
}
log.Printf("Invoking (%s) on topic: %q, value: %q\n", gatewayURL, topic, data)
controller.Invoke(topic, &data)
receiveCount++
}
client.Disconnect(1250)
}
// ResponseReceiver enables connector to receive results from the
// function invocation
type ResponseReceiver struct {
}
// Response is triggered by the controller when a message is
// received from the function invocation
func (ResponseReceiver) Response(res types.InvokerResponse) {
if res.Error != nil {
log.Printf("tester got error: %s", res.Error.Error())
} else {
log.Printf("tester got result: [%d] %s => %s (%d) bytes", res.Status, res.Topic, res.Function, len(*res.Body))
}
}