Jump to content
DelphiDev01

Connect to Azure IoTHub via TMS MQTT

Recommended Posts

Please advise what I'm doing wrong here.

 

I'm trying to connect to Azure IoTHub via TMS MQTT and every time get "Connection lost". I tried both methods: by using certificate and by connection string.


For instance my code to create a client with using a certificate:

  FMQTTClient := TTMSMQTTClient.Create(nil);

  FMQTTClient.BrokerHostName := Format('%s.azure-devices.net', [FIoTHubHostName]);
  FMQTTClient.BrokerPort := 443;  // also tried 8883, got "csConnectionRejected_ClientNotAuthorized"

  FMQTTClient.ClientID := FMyDeviceId;

  FMQTTClient.OnConnectedStatusChanged := OnConnectedStatusChanged;
  FMQTTClient.OnPublishReceived := OnMessageReceived;
  FMQTTClient.OnSSLIOHandlerConfiguration := OnSSLIOHandlerConfiguration;

 
  FMQTTClient.KeepAliveSettings.AutoReconnect:= True;
  FMQTTClient.KeepAliveSettings.KeepAliveInterval := 30;
  FMQTTClient.KeepAliveSettings.KeepConnectionAlive := True;

  FMQTTClient.Credentials.Username :=
    Format('%s.azure-devices.net/%s/?api-version=2020-09-30', [FIoTHubHostName, FMyDeviceId]);

  // Password is not needed for client certificate authentication
  FMQTTClient.Credentials.Password := '';

  if not IdSSLOpenSSLHeaders.Load then
    raise Exception.Create('Failed to load OpenSSL');
  if not IsOpenSSL_TLSv1_2_Available then
    raise Exception.Create('TLSv1_2 is not available');

  FMQTTClient.UseSSL := True;

 

And code to configurate SSL connection:

procedure TMQTTClient.OnSSLIOHandlerConfiguration(ASender: TObject;
  var ASSLIOHandler: TIdSSLIOHandlerSocketOpenSSL);
begin
  ASSLIOHandler.SSLOptions.CertFile := FCertFileName;    // Device certificate
  ASSLIOHandler.SSLOptions.KeyFile := FKeyFileName;      // Device private key
  ASSLIOHandler.SSLOptions.Mode := sslmClient;
  ASSLIOHandler.SSLOptions.Method := sslvTLSv1_2;
end;

 

But every time I get 'ConnectionLost'. Any thoughts, guys?

 

Appreciate any help.

 

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×