-
Notifications
You must be signed in to change notification settings - Fork 1
/
message.go
104 lines (86 loc) · 1.86 KB
/
message.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
package ktmt
import (
"context"
"sync"
"github.com/eleztian/ktmt/packets"
)
type Message interface {
Topic() string
ClientID() string
MessageID() MId
Qos() byte
Duplicate() bool
Retained() bool
Payload() []byte
Ack()
}
type message struct {
topic string
client string
messageID MId
qos byte
duplicate bool
retained bool
payload []byte
once sync.Once
ack func()
}
func (m *message) ClientID() string {
return m.client
}
func (m *message) Topic() string {
return m.topic
}
func (m *message) MessageID() MId {
return m.messageID
}
func (m *message) Qos() byte {
return m.qos
}
func (m *message) Duplicate() bool {
return m.duplicate
}
func (m *message) Retained() bool {
return m.retained
}
func (m *message) Payload() []byte {
return m.payload
}
func (m *message) Ack() {
m.once.Do(m.ack)
}
func MessageFromPublish(p *packets.PublishPacket, cid string, ack func()) Message {
return &message{
duplicate: p.Dup,
qos: p.Qos,
retained: p.Retain,
topic: p.TopicName,
messageID: MId(p.MessageID),
payload: p.Payload,
ack: ack,
client: cid,
}
}
func NewConnectMsg(cid string, cleanSession bool, keepalive uint16) *packets.ConnectPacket {
m := packets.NewControlPacket(packets.Connect).(*packets.ConnectPacket)
m.CleanSession = cleanSession
m.ClientIdentifier = cid
m.Keepalive = keepalive
return m
}
func AckFunc(ctx context.Context, cl ConnectionLayer, packet *packets.PublishPacket) func() {
return func() {
switch packet.Qos {
case 1:
pa := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket)
pa.MessageID = packet.MessageID
err := cl.WriteP(ctx, pa)
if err != nil {
ERROR.Printf("[Conn:%s] fileWrite publish[%d] ack %v", cl.ID(), pa.MessageID, err)
cl.Close()
}
case 0:
// do nothing, since there is no need to send an ack packet back
}
}
}