TsgcWSPClient_MQTT | クライアント MQTT 接続

MQTT Serverに接続するには、まずTsgcWebSocketClientTsgcWSPClient_MQTTを作成する必要があります。次に、MQTTコンポーネントをWebSocketクライアントにアタッチする必要があります。

 

基本的な使い方

WebSocket プロトコルを使用して Mosquitto MQTT サーバーに接続します。接続後にトピック "topic1" にサブスクライブします。

 


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 はクライアント接続を識別するためにクライアント識別子が必要です。コンポーネントは自動的にランダムな値を設定しますが、必要に応じて独自のクライアント識別子を設定できます。設定するには、OnBeforeConnect イベントを処理し、aClientIdentifier パラメータに値を設定します。

 


procedure OnMQTTBeforeConnect(Connection: TsgcWSConnection; var aCleanSession: Boolean; 
  var aClientIdentifier: string);
begin
  aClientIdentifier := 'your client id';
end;

認証

一部のサーバーでは MQTT 接続を認証するためにユーザー名とパスワードが必要です。サーバーに接続する前に Authentication プロパティを使用してユーザー名とパスワードの値を設定してください。

 


oMQTT := TsgcWSPClient_MQTT.Create(nil);
oMQTT.Authentication.Enabled := True;
oMQTT.Authentication.UserName := 'your user';
oMQTT.Authentication.Password := 'your password';