1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace unreal4u\MQTT\Protocol; |
6
|
|
|
|
7
|
|
|
use unreal4u\MQTT\Application\EmptyReadableResponse; |
8
|
|
|
use unreal4u\MQTT\Application\Message; |
9
|
|
|
use unreal4u\MQTT\Exceptions\InvalidQoSLevel; |
10
|
|
|
use unreal4u\MQTT\Internals\ClientInterface; |
11
|
|
|
use unreal4u\MQTT\Internals\ProtocolBase; |
12
|
|
|
use unreal4u\MQTT\Internals\ReadableContent; |
13
|
|
|
use unreal4u\MQTT\Internals\ReadableContentInterface; |
14
|
|
|
use unreal4u\MQTT\Internals\WritableContent; |
15
|
|
|
use unreal4u\MQTT\Internals\WritableContentInterface; |
16
|
|
|
use unreal4u\MQTT\Utilities; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* A PUBLISH Control Packet is sent from a Client to a Server or vice-versa to transport an Application Message. |
20
|
|
|
* |
21
|
|
|
* @see http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718037 |
22
|
|
|
*/ |
23
|
|
|
final class Publish extends ProtocolBase implements ReadableContentInterface, WritableContentInterface |
24
|
|
|
{ |
25
|
|
|
use ReadableContent; |
26
|
|
|
use WritableContent; |
27
|
|
|
|
28
|
|
|
const CONTROL_PACKET_VALUE = 3; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Contains the message to be sent |
32
|
|
|
* @var Message |
33
|
|
|
*/ |
34
|
|
|
private $message; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Some interchanges with the broker will send or receive a packet identifier |
38
|
|
|
* @var int |
39
|
|
|
*/ |
40
|
|
|
public $packetIdentifier = 0; |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Flag to check whether a message is a redelivery (DUP flag) |
44
|
|
|
* @see http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718038 |
45
|
|
|
* @var bool |
46
|
|
|
*/ |
47
|
|
|
public $isRedelivery = false; |
48
|
|
|
|
49
|
4 |
|
public function createVariableHeader(): string |
50
|
|
|
{ |
51
|
4 |
|
if ($this->message === null) { |
52
|
1 |
|
throw new \InvalidArgumentException('You must at least provide a message object with a topic name'); |
53
|
|
|
} |
54
|
|
|
|
55
|
3 |
|
$bitString = $this->createUTF8String($this->message->getTopicName()); |
56
|
|
|
// Reset the special flags should the object be reused with another message |
57
|
3 |
|
$this->specialFlags = 0; |
58
|
|
|
|
59
|
3 |
|
if ($this->isRedelivery) { |
60
|
|
|
$this->logger->debug('Activating redelivery bit'); |
61
|
|
|
// DUP flag: if the message is a re-delivery, mark it as such |
62
|
|
|
$this->specialFlags |= 8; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
// Check QoS level and perform the corresponding actions |
66
|
3 |
|
if ($this->message->getQoSLevel() !== 0) { |
67
|
|
|
// 2 for QoS lvl1 and 4 for QoS lvl2 |
68
|
2 |
|
$this->specialFlags |= ($this->message->getQoSLevel() * 2); |
69
|
2 |
|
$this->packetIdentifier++; |
70
|
2 |
|
$bitString .= Utilities::convertNumberToBinaryString($this->packetIdentifier); |
71
|
2 |
|
$this->logger->debug(sprintf('Activating QoS level %d bit', $this->message->getQoSLevel()), [ |
72
|
2 |
|
'specialFlags' => $this->specialFlags, |
73
|
|
|
]); |
74
|
|
|
} |
75
|
|
|
|
76
|
3 |
|
if ($this->message->isRetained()) { |
77
|
|
|
// RETAIN flag: should the server retain the message? |
78
|
1 |
|
$this->specialFlags |= 1; |
79
|
1 |
|
$this->logger->debug('Activating retain flag', ['specialFlags' => $this->specialFlags]); |
80
|
|
|
} |
81
|
|
|
|
82
|
3 |
|
$this->logger->info('Variable header created', ['specialFlags' => $this->specialFlags]); |
83
|
|
|
|
84
|
3 |
|
return $bitString; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
public function createPayload(): string |
88
|
|
|
{ |
89
|
|
|
if (!$this->message->validateMessage()) { |
90
|
|
|
throw new \InvalidArgumentException('Invalid message'); |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
return $this->message->getPayload(); |
94
|
|
|
} |
95
|
|
|
|
96
|
|
|
/** |
97
|
|
|
* QoS level 0 does not have to wait for a answer, so return false. Any other QoS level returns true |
98
|
|
|
* @return bool |
99
|
|
|
*/ |
100
|
4 |
|
public function shouldExpectAnswer(): bool |
101
|
|
|
{ |
102
|
4 |
|
$shouldExpectAnswer = !($this->message->getQoSLevel() === 0); |
103
|
4 |
|
$this->logger->debug('Checking whether we should expect an answer or not', [ |
104
|
4 |
|
'shouldExpectAnswer' => $shouldExpectAnswer, |
105
|
|
|
]); |
106
|
4 |
|
return $shouldExpectAnswer; |
107
|
|
|
} |
108
|
|
|
|
109
|
2 |
|
public function expectAnswer(string $data, ClientInterface $client): ReadableContentInterface |
110
|
|
|
{ |
111
|
2 |
|
if ($this->shouldExpectAnswer() === false) { |
112
|
1 |
|
return new EmptyReadableResponse($this->logger); |
113
|
|
|
} |
114
|
|
|
|
115
|
1 |
|
$pubAck = new PubAck($this->logger); |
116
|
1 |
|
$pubAck->instantiateObject($data, $client); |
117
|
1 |
|
return $pubAck; |
118
|
|
|
} |
119
|
|
|
|
120
|
|
|
/** |
121
|
|
|
* Sets the to be sent message |
122
|
|
|
* |
123
|
|
|
* @param Message $message |
124
|
|
|
* @return WritableContentInterface |
125
|
|
|
*/ |
126
|
6 |
|
public function setMessage(Message $message): WritableContentInterface |
127
|
|
|
{ |
128
|
6 |
|
$this->message = $message; |
129
|
6 |
|
return $this; |
130
|
|
|
} |
131
|
|
|
|
132
|
|
|
/** |
133
|
|
|
* Gets the set message |
134
|
|
|
* |
135
|
|
|
* @return Message |
136
|
|
|
*/ |
137
|
|
|
public function getMessage(): Message |
138
|
|
|
{ |
139
|
|
|
return $this->message; |
140
|
|
|
} |
141
|
|
|
|
142
|
|
|
/** |
143
|
|
|
* Sets several bits and pieces from the first byte of the fixed header for the Publish packet |
144
|
|
|
* |
145
|
|
|
* @param int $firstByte |
146
|
|
|
* @return Publish |
147
|
|
|
* @throws \unreal4u\MQTT\Exceptions\InvalidQoSLevel |
148
|
|
|
*/ |
149
|
|
|
private function analyzeFirstByte(int $firstByte): Publish |
150
|
|
|
{ |
151
|
|
|
$this->logger->debug('Analyzing first byte', [sprintf('%08d', decbin($firstByte))]); |
152
|
|
|
// Retained bit is bit 0 of first byte |
153
|
|
|
$this->message->setRetainFlag(false); |
154
|
|
|
if ($firstByte & 1) { |
155
|
|
|
$this->message->setRetainFlag(true); |
156
|
|
|
} |
157
|
|
|
// QoS level are the last bits 2 & 1 of the first byte |
158
|
|
|
$this->message->setQoSLevel($this->determineIncomingQoSLevel($firstByte)); |
159
|
|
|
|
160
|
|
|
// Duplicate message must be checked only on QoS > 0, else set it to false |
161
|
|
|
$this->isRedelivery = false; |
162
|
|
|
if ($firstByte & 8 && $this->message->getQoSLevel() !== 0) { |
163
|
|
|
// Is a duplicate is always bit 3 of first byte |
164
|
|
|
$this->isRedelivery = true; |
165
|
|
|
} |
166
|
|
|
|
167
|
|
|
return $this; |
168
|
|
|
} |
169
|
|
|
|
170
|
|
|
/** |
171
|
|
|
* Finds out the QoS level in a fixed header for the Publish object |
172
|
|
|
* |
173
|
|
|
* @param int $bitString |
174
|
|
|
* @return int |
175
|
|
|
* @throws \unreal4u\MQTT\Exceptions\InvalidQoSLevel |
176
|
|
|
*/ |
177
|
|
|
private function determineIncomingQoSLevel(int $bitString): int |
178
|
|
|
{ |
179
|
|
|
// QoS lvl 6 does not exist, throw exception |
180
|
|
|
if (($bitString & 6) >= 6) { |
181
|
|
|
throw new InvalidQoSLevel('Invalid QoS level "' . $bitString . '" found (both bits set?)'); |
182
|
|
|
} |
183
|
|
|
|
184
|
|
|
// Strange operation, why? Because 4 == QoS lvl2; 2 == QoS lvl1, 0 == QoS lvl0 |
185
|
|
|
return $bitString & 4 / 2; |
186
|
|
|
} |
187
|
|
|
|
188
|
|
|
/** |
189
|
|
|
* Will perform sanity checks and fill in the Readable object with data |
190
|
|
|
* @param string $rawMQTTHeaders |
191
|
|
|
* @param ClientInterface $client |
192
|
|
|
* @return ReadableContentInterface |
193
|
|
|
* @throws \OutOfRangeException |
194
|
|
|
*/ |
195
|
|
|
public function fillObject(string $rawMQTTHeaders, ClientInterface $client): ReadableContentInterface |
196
|
|
|
{ |
197
|
|
|
if (\strlen($rawMQTTHeaders) === 1) { |
198
|
|
|
$this->logger->debug('Fast check, read rest of data from socket'); |
199
|
|
|
$restOfBytes = $client->readSocketData(1); |
200
|
|
|
$payload = $client->readSocketData(\ord($restOfBytes)); |
201
|
|
|
} else { |
202
|
|
|
$this->logger->debug('Slow form, retransform data and read rest of data'); |
203
|
|
|
$restOfBytes = $rawMQTTHeaders{1}; |
204
|
|
|
$payload = substr($rawMQTTHeaders, 2); |
205
|
|
|
$exactRest = \ord($restOfBytes) - \strlen($payload); |
206
|
|
|
$payload .= $client->readSocketData($exactRest); |
207
|
|
|
$rawMQTTHeaders = $rawMQTTHeaders{0}; |
208
|
|
|
} |
209
|
|
|
|
210
|
|
|
// At this point, $rawMQTTHeaders will be always 1 byte long |
211
|
|
|
$this->message = new Message(); |
212
|
|
|
$this->analyzeFirstByte(\ord($rawMQTTHeaders)); |
213
|
|
|
// $rawMQTTHeaders may be redefined |
214
|
|
|
$rawMQTTHeaders = $rawMQTTHeaders . $restOfBytes . $payload; |
215
|
|
|
|
216
|
|
|
// Topic size is always the 3rd byte |
217
|
|
|
$topicSize = \ord($rawMQTTHeaders{3}); |
218
|
|
|
|
219
|
|
|
$messageStartPosition = 4; |
220
|
|
|
if ($this->message->getQoSLevel() > 0) { |
221
|
|
|
// [2 (fixed header) + 2 (topic size) + $topicSize] marks the beginning of the 2 packet identifier bytes |
222
|
|
|
$this->packetIdentifier = Utilities::convertBinaryStringToNumber( |
223
|
|
|
$rawMQTTHeaders{5 + $topicSize} . $rawMQTTHeaders{4 + $topicSize} |
224
|
|
|
); |
225
|
|
|
$messageStartPosition += 2; |
226
|
|
|
} |
227
|
|
|
|
228
|
|
|
$this->logger->debug('Determined headers', [ |
229
|
|
|
'topicSize' => $topicSize, |
230
|
|
|
'QoSLevel' => $this->message->getQoSLevel(), |
231
|
|
|
'isDuplicate' => $this->isRedelivery, |
232
|
|
|
'isRetained' => $this->message->isRetained(), |
233
|
|
|
'packetIdentifier' => $this->packetIdentifier, |
234
|
|
|
]); |
235
|
|
|
|
236
|
|
|
$this->message->setPayload(substr($rawMQTTHeaders, $messageStartPosition + $topicSize)); |
237
|
|
|
$this->message->setTopicName(substr($rawMQTTHeaders, $messageStartPosition, $topicSize)); |
238
|
|
|
|
239
|
|
|
return $this; |
240
|
|
|
} |
241
|
|
|
|
242
|
|
|
/** |
243
|
|
|
* @inheritdoc |
244
|
|
|
* @throws \unreal4u\MQTT\Exceptions\ServerClosedConnection |
245
|
|
|
* @throws \unreal4u\MQTT\Exceptions\NotConnected |
246
|
|
|
* @throws \unreal4u\MQTT\Exceptions\Connect\NoConnectionParametersDefined |
247
|
|
|
*/ |
248
|
|
|
public function performSpecialActions(ClientInterface $client, WritableContentInterface $originalRequest): bool |
249
|
|
|
{ |
250
|
|
|
if ($this->message->getQoSLevel() === 0) { |
251
|
|
|
$this->logger->debug('No response needed', ['qosLevel', $this->message->getQoSLevel()]); |
252
|
|
|
} else { |
253
|
|
|
if ($this->message->getQoSLevel() === 1) { |
254
|
|
|
$this->logger->debug('Responding with PubAck', ['qosLevel' => $this->message->getQoSLevel()]); |
255
|
|
|
$client->sendData($this->composePubAckAnswer()); |
256
|
|
|
} elseif ($this->message->getQoSLevel() === 2) { |
257
|
|
|
$this->logger->debug('Responding with PubRec', ['qosLevel' => $this->message->getQoSLevel()]); |
258
|
|
|
$client->sendData(new PubRec($this->logger)); |
259
|
|
|
} |
260
|
|
|
} |
261
|
|
|
|
262
|
|
|
return true; |
263
|
|
|
} |
264
|
|
|
|
265
|
|
|
/** |
266
|
|
|
* Composes a PubAck answer with the same packetIdentifier as what we received |
267
|
|
|
* @return PubAck |
268
|
|
|
*/ |
269
|
|
|
private function composePubAckAnswer(): PubAck |
270
|
|
|
{ |
271
|
|
|
$pubAck = new PubAck($this->logger); |
272
|
|
|
$pubAck->packetIdentifier = $this->packetIdentifier; |
273
|
|
|
return $pubAck; |
274
|
|
|
} |
275
|
|
|
} |
276
|
|
|
|