Completed
Push — master ( 639ef0...066714 )
by Camilo
02:30
created

Publish::getMessage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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