QuickStart
Connect, subscribe, publish
Wire the protocol to a client, open the connection, subscribe to a topic and publish to it. The message comes back on OnMQTTPublish.
uses
Classes, SysUtils,
sgcWebSocket, sgcWebSocket_Classes, sgcWebSocket_Protocols,
sgcWebSocket_Types, sgcWebSocket_Protocol_MQTT_Client,
sgcWebSocket_Protocol_MQTT_Message;
procedure TfrmClientPROTOCOL.FormCreate(Sender: TObject);
begin
WSClient := TsgcWebSocketClient.Create(Self);
WSClient.Host := 'www.esegece.com';
WSClient.Port := 15675;
WSClient.TLS := False;
MQTT.Client := WSClient;
WSClient.Active := True;
end;
For plain MQTT over TCP rather than over WebSockets, create a TsgcTCPClient from sgcTCP_Client_WS instead and point MQTT.Client at that. Nothing else changes, which is the reason the two components are separate.
procedure TfrmClientPROTOCOL.btnSubscribeClick(Sender: TObject);
begin
MQTT.Subscribe('sgc/quickstart');
end;
procedure TfrmClientPROTOCOL.btnPublishClick(Sender: TObject);
begin
MQTT.Publish('sgc/quickstart', 'hello from Delphi',
mtqsAtLeastOnce, False);
end;
procedure TfrmClientPROTOCOL.btnUnsubscribeClick(Sender: TObject);
begin
MQTT.UnSubscribe('sgc/quickstart');
end;
Publish returns a Word, the packet identifier, and does not wait. PublishAndWait returns a Boolean and blocks until the broker confirms, with a timeout that defaults to ten seconds. TmqttQoS comes from sgcWebSocket_Types.
procedure TfrmClientPROTOCOL.MQTTMQTTConnect(Connection: TsgcWSConnection;
const Session: Boolean; const ReasonCode: Integer;
const ReasonName: String;
const ConnectProperties: TsgcWSMQTTCONNACKProperties);
begin
memoLog.Lines.Add('#connected: ' + ReasonName);
end;
procedure TfrmClientPROTOCOL.MQTTMQTTSubscribe(Connection: TsgcWSConnection;
aPacketIdentifier: Word; aCodes: TsgcWSSUBACKS;
SubscribeProperties: TsgcWSMQTTSUBACKProperties);
begin
memoLog.Lines.Add('#subscribed: ' + IntToStr(aPacketIdentifier));
end;
procedure TfrmClientPROTOCOL.MQTTMQTTPublish(Connection: TsgcWSConnection;
aTopic, aText: string;
PublishProperties: TsgcWSMQTTPUBLISHProperties);
begin
memoLog.Lines.Add(aTopic + ': ' + aText);
end;
These are the three that matter first. Nine more exist for the acknowledgement flow, disconnection and MQTT 5.0 authentication. Let the IDE generate the handlers, because the parameter lists are long and the properties objects differ per event.