-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpayload.go
105 lines (88 loc) · 2.48 KB
/
payload.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package messagix
import (
"github.com/0xzer/messagix/byter"
"github.com/0xzer/messagix/packets"
)
type Payload interface {
Write() ([]byte, error)
}
type ConnectPayload struct {
ProtocolName string `lengthType:"uint16"`
ProtocolLevel uint8
ConnectFlags uint8
KeepAliveTime uint16
ClientId string `lengthType:"uint16"`
JSONData string `lengthType:"uint16"`
}
func (cp *ConnectPayload) Write() ([]byte, error) {
return byter.NewWriter().WriteFromStruct(cp)
}
func (c *Client) NewConnectRequest(jsonData string, connectFlags uint8) ([]byte, error) {
payload := &ConnectPayload{
ProtocolName: protocolName,
ProtocolLevel: uint8(protocolLevel),
ConnectFlags: connectFlags,
KeepAliveTime: uint16(keepAliveTimeout),
ClientId: protocolClientId,
JSONData: jsonData,
}
packet := &packets.ConnectPacket{}
request := &Request{
PacketByte: packet.Compress(),
}
return request.Write(payload)
}
type PublishPayload struct {
Topic Topic `lengthType:"uint16"`
PacketId uint16
JSONData string `lengthType:""`
}
func (pb *PublishPayload) Write() ([]byte, error) {
return byter.NewWriter().WriteFromStruct(pb)
}
func (c *Client) NewPublishRequest(topic Topic, jsonData string, packetByte byte, packetId uint16) ([]byte, uint16, error) {
payload := &PublishPayload{
Topic: topic,
PacketId: packetId,
JSONData: jsonData,
}
c.socket.responseHandler.addPacketChannel(packetId)
c.socket.responseHandler.addRequestChannel(packetId)
request := &Request{
PacketByte: packetByte,
}
reqBytes, err := request.Write(payload)
if err != nil {
c.socket.responseHandler.deleteDetails(packetId, PacketChannel)
c.socket.responseHandler.deleteDetails(packetId, RequestChannel)
return nil, 0, err
}
return reqBytes, packetId, nil
}
type SubscribePayload struct {
PacketId uint16
Topic Topic `lengthType:"uint16"`
QoSLevel packets.QoS
}
func (sb *SubscribePayload) Write() ([]byte, error) {
return byter.NewWriter().WriteFromStruct(sb)
}
func (c *Client) NewSubscribeRequest(topic Topic, qos packets.QoS) ([]byte, uint16, error) {
packetByte := &packets.SubscribePacket{}
packetId := c.socket.SafePacketId()
c.socket.responseHandler.addPacketChannel(packetId)
payload := &SubscribePayload{
PacketId: packetId,
Topic: topic,
QoSLevel: qos,
}
request := &Request{
PacketByte: packetByte.Compress(),
}
reqBytes, err := request.Write(payload)
if err != nil {
c.socket.responseHandler.deleteDetails(packetId, PacketChannel)
return nil, 0, err
}
return reqBytes, packetId, nil
}