Skip to content

Commit

Permalink
init tests and mqtt client init refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
BlenderistDev committed Aug 28, 2024
1 parent 0ed2315 commit 68c097c
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 25 deletions.
4 changes: 4 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ func main() {
panic(fmt.Errorf("error while creating container: %w", err))
}

if err = cont.Mqtt.Connect(); err != nil {
panic(fmt.Errorf("error while connecting to mqtt: %w", err))
}

entityManagerDone := cont.EntityManager.Run()
policyDone := cont.PolicyStorage.Run()

Expand Down
10 changes: 7 additions & 3 deletions internal/app/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,18 @@ import (
"keeneticToMqtt/internal/storages/policy"
)

// Container with dependencies.
type Container struct {
Logger *slog.Logger
Config *config.Config
ClientListService *clientlist.ClientList
DiscoveryService *discovery.Discovery
EntityManager *homeassistant.EntityManager
PolicyStorage *policy.Storage
Mqtt *mqtt.Client
}

// NewContainer creates new Container.
func NewContainer() (*Container, error) {
cont := Container{}

Expand All @@ -45,17 +48,18 @@ func NewContainer() (*Container, error) {

cookie, _ := cookiejar.New(&cookiejar.Options{})

cont.Mqtt = mqtt.NewClient(cont.Config.Mqtt.Host, cont.Config.Mqtt.ClientID, cont.Config.Mqtt.Login, cont.Config.Mqtt.Password, cont.Logger)

authClient := auth.NewAuth(cont.Config.Keenetic.Host, cont.Config.Keenetic.Login, cont.Config.Keenetic.Password, cookie)
keeneticClient := keenetic.NewKeenetic(authClient, cookie, cont.Config.Keenetic.Host, cont.Config.Keenetic.Login, cont.Config.Keenetic.Password, cont.Logger)
policyClient := accessupdate.NewAccessUpdate(cont.Config.Keenetic.Host, keeneticClient)
policyList := policylist.NewPolicyList(cont.Config.Keenetic.Host, keeneticClient)
listClient := list.NewList(cont.Config.Keenetic.Host, keeneticClient)
mqttClient := mqtt.NewClient(cont.Config.Mqtt.Host, cont.Config.Mqtt.ClientID, cont.Config.Mqtt.Login, cont.Config.Mqtt.Password, cont.Logger)

cont.PolicyStorage = policy.NewStorage(policyList, time.Second*10, cont.Logger)

cont.ClientListService = clientlist.NewClientList(listClient, cont.Config.Homeassistant.WhiteList)
cont.DiscoveryService = discovery.NewDiscovery("", cont.Config.Homeassistant.DeviceID, mqttClient)
cont.DiscoveryService = discovery.NewDiscovery("", cont.Config.Homeassistant.DeviceID, cont.Mqtt)

clientPolicy := clientpolicy.NewClientPolicy(cont.Config.Mqtt.BaseTopic, cont.DiscoveryService, policyClient, cont.PolicyStorage)
clientPermit := clientpermit.NewClientPermit(cont.Config.Mqtt.BaseTopic, cont.DiscoveryService, policyClient)
Expand All @@ -70,7 +74,7 @@ func NewContainer() (*Container, error) {
rxBytes,
},
cont.ClientListService,
mqttClient,
cont.Mqtt,
cont.Config.Homeassistant.UpdateInterval,
cont.Logger,
)
Expand Down
23 changes: 23 additions & 0 deletions internal/app/init_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package app

import (
"os"
"testing"

"github.com/stretchr/testify/assert"
)

func TestNewContainer(t *testing.T) {
f, _ := os.Create("config.yml")
defer func() {
_ = os.RemoveAll(f.Name())
}()
_ = os.Setenv("CONFIG_PATH", f.Name())

_, err := NewContainer()
assert.Nil(t, err)

_ = os.Setenv("CONFIG_PATH", "")
_, err = NewContainer()
assert.Error(t, err)
}
41 changes: 19 additions & 22 deletions internal/clients/mqtt/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package mqtt

import (
"fmt"
"os"
"time"

mqtt "github.com/eclipse/paho.mqtt.golang"
Expand All @@ -18,39 +17,37 @@ type Client struct {
topicPrefix string
client mqtt.Client
logger logger
broker string
}

func NewClient(broker, clientID, username, password string, log logger) *Client {
var f mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("TOPIC: %s\n", msg.Topic())
fmt.Printf("MSG: %s\n", msg.Payload())
}

opts := mqtt.NewClientOptions().AddBroker(broker).SetClientID(clientID)
opts.SetKeepAlive(2 * time.Second)
opts.SetDefaultPublishHandler(f)
opts.SetPingTimeout(1 * time.Second)
opts.SetUsername(username)
opts.SetPassword(password)
opts := mqtt.
NewClientOptions().
AddBroker(broker).
SetClientID(clientID).
SetKeepAlive(2 * time.Second).
SetPingTimeout(1 * time.Second).
SetUsername(username).
SetPassword(password)

c := mqtt.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}

if token := c.Subscribe("go-mqtt/sample", 0, func(client mqtt.Client, message mqtt.Message) {
fmt.Printf(string(message.Payload()))
}); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}

return &Client{
client: c,
logger: log,
broker: broker,
}
}

func (c *Client) Connect() error {
if token := c.client.Connect(); token.Wait() && token.Error() != nil {
return token.Error()
}
c.logger.Info("connected to mqtt", "broker", c.broker)

return nil
}

func (c *Client) SendMessage(topic, message string, retained bool) {
c.logger.Debug("start sending mqtt message",
"topic", topic,
Expand Down

0 comments on commit 68c097c

Please sign in to comment.