chore(mochi): change hook from connection to subscription

This commit is contained in:
Leandro Antônio Farias Machado 2023-04-13 09:23:24 -03:00
parent 058b47d461
commit 0aa5ca5413

View File

@ -12,6 +12,7 @@ import (
"log" "log"
"os" "os"
"os/signal" "os/signal"
"strings"
"syscall" "syscall"
"github.com/mochi-co/mqtt/v2" "github.com/mochi-co/mqtt/v2"
@ -121,7 +122,7 @@ func (h *MyHook) ID() string {
func (h *MyHook) Provides(b byte) bool { func (h *MyHook) Provides(b byte) bool {
return bytes.Contains([]byte{ return bytes.Contains([]byte{
mqtt.OnConnect, mqtt.OnSubscribed,
}, []byte{b}) }, []byte{b})
} }
@ -130,12 +131,15 @@ func (h *MyHook) Init(config any) error {
return nil return nil
} }
func (h *MyHook) OnConnect(cl *mqtt.Client, pk packets.Packet) { func (h *MyHook) OnSubscribed(cl *mqtt.Client, pk packets.Packet, reasonCodes []byte) {
log.Println("new connection") // Verifies if it's a device who is subscribed
if strings.Contains(pk.Filters[0].Filter, "oktopus/v1/agent") {
var clUser string var clUser string
if len(cl.Properties.Props.User) > 0 { if len(cl.Properties.Props.User) > 0 {
clUser = cl.Properties.Props.User[0].Val clUser = cl.Properties.Props.User[0].Val
} }
if clUser != "" { if clUser != "" {
log.Println("new device:", clUser) log.Println("new device:", clUser)
err := server.Publish("oktopus/devices", []byte(clUser), false, 1) err := server.Publish("oktopus/devices", []byte(clUser), false, 1)
@ -144,4 +148,5 @@ func (h *MyHook) OnConnect(cl *mqtt.Client, pk packets.Packet) {
} }
} }
}
} }