Demos | Client MQTT

This demo shows how connect to a MQTT broker server. Requires a TsgcWebSocketClient to handle WebSocket / TCP protocols.

 

Configuration

 


  MQTT.Client := WSClient;
  txtParameters.Text := '/';
  chkTLS.Checked := False;
  MQTT.Authentication.Enabled := False;
  MQTT.Authentication.Username := '';
  MQTT.Authentication.Password := '';
  MQTT.MQTTVersion := mqtt311;
  case aItemIndex of
    0: // esegece.com
      begin
        txtHost.Text := 'www.esegece.com';
        txtPort.Text := '15675';
        txtParameters.Text := '/ws';
        MQTT.Authentication.Enabled := True;
        MQTT.Authentication.Username := 'sgc';
        MQTT.Authentication.Password := 'sgc';
      end;
    1: // test.mosquitto.org
      begin
        txtHost.Text := 'test.mosquitto.org';
        txtPort.Text := '1883';
        chkTLS.Checked := False;
        chkOverWebSocket.Checked := False;
      end;
    2: // mqtt.fluux.io
      begin
        txtHost.Text := 'mqtt.fluux.io';
        txtPort.Text := '1883';
        chkTLS.Checked := False;
        chkOverWebSocket.Checked := False;
        MQTT.MQTTVersion := mqtt5;
      end;
    3: // broker.hivemq.com
      begin
        txtHost.Text := 'broker.mqttdashboard.com';
        txtPort.Text := '8000';
        txtParameters.Text := '/mqtt';
        chkTLS.Checked := False;
        chkOverWebSocket.Checked := True;
        MQTT.MQTTVersion := mqtt5;
      end;
  end;

MQTT Events

The connection flow is controlled by MQTT Client component, so you must handle the MQTT events to know when it's connected to broker, when a new message is published, when is disconnected...

 


procedure TfrmWebSocketClient.MQTTMQTTConnect(Connection: TsgcWSConnection;
    const Session: Boolean; const ReasonCode: Integer; const ReasonName:
    string; const ConnectProperties: TsgcWSMQTTCONNACKProperties);
begin
  DoLog('#connected');
  chkTLS.Enabled := False;
  chkCompressed.Enabled := False;
  if FMQTTSubscribeTopic  '' then
  begin
    MQTT.Subscribe(FMQTTSubscribeTopic);
    FMQTTSubscribeTopic := '';
  end;
end;

procedure TfrmWebSocketClient.MQTTMQTTPublish(Connection: TsgcWSConnection;     aTopic, aText: string; PublishProperties: TsgcWSMQTTPublishProperties); begin   DoLog(aTopic + ': ' + aText); end;
procedure TfrmWebSocketClient.MQTTMQTTSubscribe(Connection: TsgcWSConnection;     aPacketIdentifier: Word; aCodes: TsgcWSSUBACKS; SubscribeProperties:     TsgcWSMQTTSUBACKProperties); begin   DoLog('#Subscribe: ' + IntToStr(aPacketIdentifier)); end;
procedure TfrmWebSocketClient.MQTTMQTTDisconnect(Connection: TsgcWSConnection;     ReasonCode: Integer; const ReasonName: string; DisconnectProperties:     TsgcWSMQTTDISCONNECTProperties); begin   DoLog('#disconnected');   chkTLS.Enabled := True;   chkCompressed.Enabled := True; end;