Added ssl/tls support
This commit is contained in:
1 parent
349287cf8c
commit
4de23d2cc9
7 files changed
+74
-14
No files matched your search
+13
-5
@@ -1,29 +1,37 @@
|
||||
package mqtt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"MQTTLogger/config"
|
||||
"MQTTLogger/internal/csv"
|
||||
"crypto/tls"
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func NewClient(logger *zap.Logger, config *config.Config, csvHelper *csv.Helper) mqtt.Client {
|
||||
func NewClient(logger *zap.Logger, config *config.Config, csvHelper *csv.Helper, tlsConfig *tls.Config) mqtt.Client {
|
||||
|
||||
var f mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
|
||||
csvHelper.AddEntry(time.Now().UTC().Format("2006-01-02 15:04:05"), msg.Topic(), string(msg.Payload()))
|
||||
}
|
||||
|
||||
opts := mqtt.NewClientOptions().AddBroker(config.URI).SetClientID("mqtt-logger")
|
||||
randomClientID := "mqtt-logger-" + fmt.Sprint(rand.Int())
|
||||
logger.Info("Creating MQTT client", zap.String("clientID", randomClientID))
|
||||
opts := mqtt.NewClientOptions().AddBroker(config.URI).SetClientID(randomClientID)
|
||||
if tlsConfig != nil {
|
||||
opts.SetTLSConfig(tlsConfig)
|
||||
}
|
||||
opts.SetKeepAlive(2 * time.Second)
|
||||
opts.SetDefaultPublishHandler(f)
|
||||
opts.SetPingTimeout(1 * time.Second)
|
||||
// TODO: Check this option and see if it solves the re-subscribe on reconnect issue
|
||||
// opts.SetCleanSession(false)
|
||||
opts.SetPingTimeout(1 * time.Second)
|
||||
opts.SetConnectionNotificationHandler(func(client mqtt.Client, notification mqtt.ConnectionNotification) {
|
||||
switch n := notification.(type) {
|
||||
case mqtt.ConnectionNotificationConnected:
|
||||
logger.Info("Connected to MQTT broker")
|
||||
// Re-susbcribe to topics on reconnect
|
||||
StartListening(logger, config, client)
|
||||
case mqtt.ConnectionNotificationConnecting:
|
||||
logger.Info("connecting", zap.Bool("isReconnect", n.IsReconnect), zap.Int("attempt", n.Attempt))
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package mqtt
|
||||
|
||||
import (
|
||||
"MQTTLogger/config"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"os"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func NewTLSConfig(logger *zap.Logger, config *config.Config) *tls.Config {
|
||||
|
||||
if config.CACert == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
certpool := x509.NewCertPool()
|
||||
pemCerts, err := os.ReadFile(config.CACert)
|
||||
if err == nil {
|
||||
certpool.AppendCertsFromPEM(pemCerts)
|
||||
} else {
|
||||
logger.Fatal("error loading CA cert", zap.Error(err))
|
||||
}
|
||||
|
||||
return &tls.Config{
|
||||
RootCAs: certpool,
|
||||
// We use the provided cert not the one server sends.
|
||||
ClientAuth: tls.NoClientCert,
|
||||
ClientCAs: nil,
|
||||
InsecureSkipVerify: true, // I know
|
||||
Certificates: nil,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user