In order to connect to a MQTT Server, you must create first a TsgcWebSocketClient and a TsgcWSPClient_MQTT. Then you must attach MQTT Component to WebSocket Client.
Connect to Mosquitto MQTT server using websocket protocol. Subscribe to topic: "topic1" after connect.
oClient := TsgcWebSocketClient.Create(nil);
oClient.Host := 'test.mosquitto.org';
oClient.Port := 8080;
oMQTT := TsgcWSPClient_MQTT.Create(nil);
oMQTT.Client := oClient;
oClient.Active := True;
procedure OnMQTTConnect(Connection: TsgcWSConnection; const Session: Boolean; const ReasonCode: Integer;
const ReasonName: string; const ConnectProperties: TsgcWSMQTTCONNACKProperties);
begin
oMQTT.Subscribe('topic1');
end;
MQTT requires a Client Identifier to identify client connection. Component sets a random value automatically but you can set your own Client Identifier if required, to do this, just handle OnBeforeConnect event and set your value on aClientIdentifier parameter.
procedure OnMQTTBeforeConnect(Connection: TsgcWSConnection; var aCleanSession: Boolean;
var aClientIdentifier: string);
begin
aClientIdentifier := 'your client id';
end;
Somes servers require an user and password to authorize MQTT connections. Use Authentication property to set the value for username and password before connect to server.
oMQTT := TsgcWSPClient_MQTT.Create(nil);
oMQTT.Authentication.Enabled := True;
oMQTT.Authentication.UserName := 'your user';
oMQTT.Authentication.Password := 'your password';