Skip to content

Commit

Permalink
feat(mqtt): improve connection handling
Browse files Browse the repository at this point in the history
  • Loading branch information
adutchak committed Apr 9, 2024
1 parent 1e4ff5b commit 389d50c
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 10 deletions.
11 changes: 6 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,7 @@ func main() {
}
l.Info("starting recognizer")

mqttClient, err := mqttclient.GetMqttClient(configuration)
if err != nil {
l.Errorf("Error getting mqttClient %v", err)
}
mqttClient := mqttclient.GetMqttClient(configuration)
doneChan := make(chan bool)
go func(doneChan chan bool) {
defer func() {
Expand All @@ -75,11 +72,15 @@ func main() {
continue
}

l.Info("Connecting to MQTT server")
err = mqttclient.ConnectToMqtt(mqttClient)
if err != nil {
l.Error("Failed to connect to MQTT", err)
}
defer mqttClient.Disconnect(250)
defer func() {
l.Info("Disconnecting from MQTT server")
mqttClient.Disconnect(250)
}()

sourceBytes, err := os.ReadFile(configuration.TargetImagePath)
if err != nil {
Expand Down
7 changes: 2 additions & 5 deletions pkg/mqttclient/mqttclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err
fmt.Printf("Connect lost: %v", err)
}

func GetMqttClient(configuration *config.Config) (mqtt.Client, error) {
func GetMqttClient(configuration *config.Config) mqtt.Client {
broker := configuration.MqttBroker
port := configuration.MqttPort
opts := mqtt.NewClientOptions()
Expand All @@ -32,10 +32,7 @@ func GetMqttClient(configuration *config.Config) (mqtt.Client, error) {
opts.OnConnect = connectHandler
opts.OnConnectionLost = connectLostHandler
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
return client, token.Error()
}
return client, nil
return client
}

func ConnectToMqtt(client mqtt.Client) error {
Expand Down

0 comments on commit 389d50c

Please sign in to comment.