TsgcWSPClient_MQTTMethods › Publish

Publish Method

Publishes a message to a topic using the requested QoS and retain flags.

Overloads

Overload 1

Syntax

function Publish(const aTopic, aText: String; aQoS: TmqttQoS = mtqsAtMostOnce; aRetain: Boolean = False; const aPublishProperties: TsgcWSMQTTPublish_Properties = nil) : Word;

Parameters

NameTypeDescription
aTopicconst StringFully qualified topic name the message is published to (no wildcards).
aTextconst StringUTF-8 payload sent as the PUBLISH packet body.
aQoSTmqttQoSDelivery guarantee: mtqsAtMostOnce (0), mtqsAtLeastOnce (1) or mtqsExactlyOnce (2). Defaults to mtqsAtMostOnce.
aRetainBooleanWhen True the broker stores the message as the retained value for the topic and forwards it to new subscribers.
aPublishPropertiesconst TsgcWSMQTTPublish_PropertiesOptional MQTT 5.0 properties (Content Type, Response Topic, Message Expiry, User Properties). Pass nil to omit.

Return Value

Packet identifier assigned to the PUBLISH packet; non-zero for QoS 1 and 2, zero for QoS 0. Use it to correlate with OnMQTTPubAck, OnMQTTPubRec and OnMQTTPubComp. (Word)

Remarks

Text overload, ideal for JSON documents and other UTF-8 content. The call returns as soon as the packet has been handed to the transport; QoS 1/2 acknowledgements are delivered asynchronously. Requires an active MQTT session established with Connect.

Example

MQTT.Publish('sensors/temp', '{"value":22.5}', mtqsAtLeastOnce, True);

Overload 2

Syntax

function Publish(const aTopic: String; const aStream: TStream; aQoS: TmqttQoS = mtqsAtMostOnce; aRetain: Boolean = False; const aPublishProperties: TsgcWSMQTTPublish_Properties = nil) : Word;

Parameters

NameTypeDescription
aTopicconst StringFully qualified topic name the binary payload is published to.
aStreamconst TStreamSource stream whose full contents are sent verbatim as the PUBLISH payload. Position is saved and restored by the component.
aQoSTmqttQoSDelivery guarantee: mtqsAtMostOnce (0), mtqsAtLeastOnce (1) or mtqsExactlyOnce (2). Defaults to mtqsAtMostOnce.
aRetainBooleanWhen True the broker stores the payload as the retained value for the topic.
aPublishPropertiesconst TsgcWSMQTTPublish_PropertiesOptional MQTT 5.0 properties, typically used to set Content Type (for example image/png) when sending binary data.

Return Value

Packet identifier for the PUBLISH packet; zero for QoS 0. Enables correlation with acknowledgement events. (Word)

Remarks

Binary overload for files, protobuf frames, images and other non-textual payloads. The stream is read in full before serialization, so very large payloads should be chunked at the application layer to avoid large allocations. Behaviour of QoS, Retain and properties is identical to the text overload.

Example

oStream := TFileStream.Create('firmware.bin', fmOpenRead or fmShareDenyWrite);
try
  MQTT.Publish('devices/123/firmware', oStream, mtqsExactlyOnce);
finally
  oStream.Free;
end;

Back to Methods