Line data Source code
1 : /*
2 : * Package : mqtt_client
3 : * Author : S. Hamblett <steve.hamblett@linux.com>
4 : * Date : 19/06/2017
5 : * Copyright : S.Hamblett
6 : */
7 :
8 : part of mqtt_client;
9 :
10 : /// Class that contains details related to an MQTT Connect messages payload
11 : class MqttPublishPayload extends MqttPayload {
12 : MqttHeader header;
13 : MqttPublishVariableHeader variableHeader;
14 :
15 : /// The message that forms the payload of the publish message.
16 : typed.Uint8Buffer message;
17 :
18 : /// Initializes a new instance of the MqttPublishPayload class.
19 4 : MqttPublishPayload() {
20 8 : this.message = new typed.Uint8Buffer();
21 : }
22 :
23 : /// Initializes a new instance of the MqttPublishPayload class.
24 : MqttPublishPayload.fromByteBuffer(MqttHeader header,
25 2 : MqttPublishVariableHeader variableHeader, MqttByteBuffer payloadStream) {
26 2 : this.header = header;
27 2 : this.variableHeader = variableHeader;
28 2 : readFrom(payloadStream);
29 : }
30 :
31 : /// Creates a payload from the specified header stream.
32 : void readFrom(MqttByteBuffer payloadStream) {
33 : // The payload of the publish message is not a string, just a binary chunk of bytes.
34 : // The length of the bytes is the length specified in the header, minus any bytes
35 : // spent in the variable header.
36 10 : final int messageBytes = header.messageSize - variableHeader.length;
37 4 : message = payloadStream.read(messageBytes);
38 : }
39 :
40 : /// Writes the payload to the supplied stream.
41 : void writeTo(MqttByteBuffer payloadStream) {
42 4 : payloadStream.write(message);
43 : }
44 :
45 : /// Gets the length of the payload in bytes when written to a stream.
46 : int getWriteLength() {
47 4 : return message.length;
48 : }
49 :
50 : /// Returns a string representation of the payload.
51 : String toString() {
52 15 : return "Payload: {${message.length} bytes={${bytesToString(message)}";
53 : }
54 :
55 : /// Converts an array of bytes to a byte string.
56 : static String bytesToString(typed.Uint8Buffer message) {
57 3 : final StringBuffer sb = new StringBuffer();
58 6 : for (int b in message) {
59 3 : sb.write('<');
60 3 : sb.write(b);
61 3 : sb.write('>');
62 : }
63 3 : return sb.toString();
64 : }
65 :
66 : /// Converts an array of bytes to a character string.
67 : static String bytesToStringAsString(typed.Uint8Buffer message) {
68 1 : final StringBuffer sb = new StringBuffer();
69 2 : for (int b in message) {
70 1 : sb.writeCharCode(b);
71 : }
72 1 : return sb.toString();
73 : }
74 : }
|