82 lines
1.9 KiB
Go
82 lines
1.9 KiB
Go
package packets
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
|
|
"badat.dev/maeqtt/v2/mqtt/types"
|
|
)
|
|
|
|
type PacketVisitor interface {
|
|
visitConnect(ConnectPacket)
|
|
visitPublish(PublishPacket)
|
|
visitDisconnect(DisconnectPacket)
|
|
}
|
|
|
|
type ClientPacket interface {
|
|
visit(PacketVisitor)
|
|
}
|
|
|
|
type ServerPacket interface {
|
|
Encode() (bytes.Buffer, error)
|
|
}
|
|
|
|
type PacketType byte
|
|
|
|
const (
|
|
PacketTypeReserved PacketType = 0 // Forbidden
|
|
PacketTypeConnect = 1
|
|
PacketTypeConnack = 2
|
|
PacketTypePublish = 3
|
|
PacketTypePuback = 4
|
|
PacketTypePubrec = 5
|
|
PacketTypePubrel = 6
|
|
PacketTypePubcomp = 7
|
|
PacketTypeSubscribe = 8
|
|
PacketTypeSuback = 9
|
|
PacketTypeUnsubscribe = 10
|
|
PacketTypeUnsuback = 11
|
|
PacketTypePingreq = 12
|
|
PacketTypePingresp = 13
|
|
PacketTypeDisconnect = 14
|
|
PacketTypeAuth = 15
|
|
)
|
|
|
|
func ReadPacket(r *bufio.Reader) (*ClientPacket, error) {
|
|
println("AAAA")
|
|
fixedHeader, err := r.ReadByte()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
println("BBB")
|
|
|
|
highestFourBits := uint((fixedHeader >> 4) & 0b1111)
|
|
lowerFourBits := uint(fixedHeader & 0b1111)
|
|
|
|
dataLength, err := types.DecodeVariableByteInt(r)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
reader := io.LimitReader(r, int64(dataLength))
|
|
control := controlPacket{
|
|
packetType: PacketType(highestFourBits),
|
|
flags: lowerFourBits,
|
|
reader: reader,
|
|
}
|
|
|
|
var packet ClientPacket
|
|
switch control.packetType {
|
|
case PacketTypeConnect:
|
|
packet, err = parseConnectPacket(control)
|
|
case PacketTypePublish:
|
|
packet, err = parsePublishPacket(control)
|
|
case PacketTypeDisconnect:
|
|
packet, err = parseDisconnectPacket(control)
|
|
default:
|
|
return nil, fmt.Errorf("Unknown packet type %v", control.packetType)
|
|
}
|
|
|
|
return &packet, err
|
|
}
|