maeqtt/session/utils.go

42 lines
860 B
Go
Raw Normal View History

2021-10-16 23:38:23 +02:00
package session
import (
"encoding/base64"
"fmt"
"math/rand"
"time"
"badat.dev/maeqtt/v2/mqtt/packets"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func genClientID() *string {
buf := make([]byte, 32)
_, err := rand.Read(buf)
if err != nil {
// I don't think this can actually happen but just in case panic
panic(fmt.Errorf("Failed to generate a client id, %e", err))
}
id := "Client_rand_" + base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(buf)
return &id
}
2021-10-17 20:58:16 +02:00
func (s *Session) Disconnect(code packets.DisconnectReasonCode) {
// If disconnetion fails that means we are already disconnected, great!
_ = s.Connection.sendPacket(packets.DisconnectPacket{
2021-10-16 23:38:23 +02:00
ReasonCode: code,
})
2021-10-17 20:58:16 +02:00
_ = s.Connection.close()
2021-10-16 23:38:23 +02:00
s.onDisconnect()
}
func (s *Session) getFreePacketId() uint16 {
s.freePacketID += 1
return s.freePacketID
}