IoT Hub is a managed service, hosted in the cloud, that acts as a central message hub for bi-directional communication between your IoT application and the devices it manages. You can use Azure IoT Hub to build IoT solutions with reliable and secure communications between millions of IoT devices and a cloud-hosted solution backend. You can connect virtually any device to IoT Hub.
IoT Hub supports communications both from the device to the cloud and from the cloud to the device. IoT Hub supports multiple messaging patterns such as device-to-cloud telemetry, file upload from devices, and request-reply methods to control your devices from the cloud. IoT Hub monitoring helps you maintain the health of your solution by tracking events such as device creation, device failures, and device connections.
IoT Hub's capabilities help you build scalable, full-featured IoT solutions such as managing industrial equipment used in manufacturing, tracking valuable assets in healthcare, and monitoring office building usage.
IoT Hub gives you a secure communication channel for your devices to send data. IoT Hub and the device SDKs support the following protocols for connecting devices:
MQTT
MQTT over WebSockets
Multiple authentication types support a variety of device capabilities:
SAS token-based authentication to quickly get started with your IoT solution.
Individual X.509 certificate authentication for secure, standards-based authentication.
TsgcIoTAzure_MQTT_Client is the component used for connect to Azure IoT, one client can connect to only one device. Client connects using plain MQTT protocol and authenticates using SAS / X.509 Client Certificate.
In order to connect to Azure IoT Hub, client needs the following properties:
Azure.IoTHub: server name where MQTT client will connect.
Azure.DeviceId: name of device in azure IoT Hub.
Azure allows multiple authentication types, by default uses SAS tokens.
SAS Authentication
SAS.Enabled: enable if authentication uses SAS.
SAS.SecretKey: the SAS Token from your Azure IoT Account.
SAS.KeyName: the Shared Access Key Name.
SAS.Expiry: set the number of minutes before SAS Token expires. Default value is 1440 (24 hours).
If you have a connection string, you can read the connection string values automatically using the method ReadConnectionString. Example:
ReadConnectionString('HostName=yourhub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=Yj7RRPnkSDTv+UCFLgwIP/FrbDymZv4qVAIoTLHUFR8=');
X509 Certificates
Using OpenSSL as IOHandler
Certificate.Enabled: enable if authentication uses certificates.
Certificate.CertFile: path to X.509 client certificate.
Certificate.KeyFile: path to X.509 client key file.
Certificate.Password: if certificate has a password set here.
Version: TLS version, by default uses TLS 1.0
Using SChannel as IOHandler
Certificate.Enabled: enable if authentication uses certificates.
Certificate.CertFile: path to PFX certificate (first the certificate must be converted to PFX). Read More.
Certificate.Password: if certificate has a password set here.
Version: TLS version, by default uses TLS 1.0
Other properties:
MQTTHeartBeat: if enabled attempts to keep alive MQTT connection sending a ping every x seconds.
Interval: number of seconds between each ping.
WatchDog: if enabled, when an unexpected disconnection is detected, tries to reconnect to the server automatically.
Interval: seconds before reconnection attempts.
Attempts: maximum number of reconnection attempts; zero means unlimited.
LogFile: if enabled, saves socket messages to a log file (useful for debugging). The access to log file is not thread safe if it's accessed from several threads.
Enabled: if enabled every time a message is received and sent by socket it will be saved on a file.
FileName: full path to the filename.
Azure MQTT implementation is based on MQTT version 3.1.1 but it deviates from the specification as follows:
IoT Hub does not support QoS 2 messages. If a device app publishes a message with QoS 2, IoT Hub closes the network connection.
IoT Hub does not persist Retain messages. If a device sends a message with the RETAIN flag set to 1, IoT Hub adds the x-opt-retain application property to the message. In this case, instead of persisting the retain message, IoT Hub passes it to the backend app.
IoT Hub only supports one active MQTT connection per device. Any new MQTT connection on behalf of the same device ID causes IoT Hub to drop the existing connection.
First, you must sign in your Azure account, register a new device and create an authentication method for this device. Once is done, you can create create a new TsgcIoTAzure_MQTT_Client and connect to Azure IoT Hub.
For example:
oClient := TsgcIoTAzure_MQTT_Client.Create(nil);
oClient.Azure.IoTHub := 'youriothub.azure-devices.net';
oClient.Azure.DeviceId := 'YourDeviceId';
oClient.SAS.Enabled := True;
oClient.SAS.SecretKey := 'YourSecretKey';
oClient.OnMQTTConnect := OnMQTTConnectEvent;
oClient.Active := True;
procedure OnMQTTConnect(Connection: TsgcWSConnection; const Session: Boolean; const
ReturnCode: TmqttConnReturnCode);
begin
ShowMessage('Connected to Azure IoT Hub');
end;
When sending information from the device app to the solution back end, IoT Hub exposes following options:
1. Device-to-cloud messages for time series telemetry and alerts.
oClient.Send_DeviceToCloud('{"temp": 10}', azuIoTQoS1);
You can send key-value properties using a TStringList, just fill the TStringList with the desired message properties and pass these as argument.
oProperties := TStringList.Create;
Try
oProperties.AddPair('prop_name1', 'prop_value1');
oProperties.AddPair('prop_name2', 'prop_value2');
oClient.Send_DeviceToCloud('{"temp": 10}', oProperties, azuIoTQoS1);
Finally
oProperties.Free;
End;
If you need to set the ContentType and ContentEncoding of the message, you must add the these values to the Properties List, the name of these properties are defined by Azure.
Name | Value |
$.ct | application/json |
$.ce | utf-8 |
oProperties := TStringList.Create;
Try
oProperties.AddPair('$.ct', 'application/json');
oProperties.AddPair('$.ce', 'utf-8');
oClient.Send_DeviceToCloud('{"temp": 10}', oProperties, azuIoTQoS1);
Finally
oProperties.Free;
End;
2. Device twin's reported properties for reporting device state information such as available capabilities, conditions, or the state of long-running workflows. For example, configuration and software updates.
oClient.Set_DeviceTwinsProperties('1', '{"sgc":1}');
IoT Hub provides three options for device apps to expose functionality to a back-end app:
1. Direct methods for communications that require immediate confirmation of the result. Direct methods are often used for interactive control of devices such as turning on a fan.
oClient.Subscribe_DirectMethod;
You can respond to public methods, using following method.
oClient.RespondPublicMethod(RequestId, Status, 'Your Response', azuIoTQoS1);
2. Twin's desired properties for long-running commands intended to put the device into a certain desired state. For example, set the telemetry send interval to 30 minutes. You can get Properties using following method.
oClient.Get_DeviceTwinsProperties('1');
3. Cloud-to-device messages for one-way notifications to the device app. To get messages, first you must subscribe.
oClient.Subscribe_CloudToDevice;
Messages are received OnMQTTPublish event.
procedure TFRMSGCClientIoT.AzureIoTMQTTPublish(Connection: TsgcWSConnection; aTopic, aText: string);
begin
DoLog('Received Message: ' + aTopic + ' ' + aText);
end;
IoT hub facilitates file uploads from connected devices by providing them with shared access signature (SAS) URIs or X509 certificates.
If you select SAS, you must set the following properties:
If you select X509 certificates, you must set the following properties:
Use the method UploadFile to upload a file to the Azure Servers. If the Overwrite parameter is set to true, it will replace the existing file. If the Overwrite parameter is set to false, it will only upload if the file doesn't exist and will raise an error if it exists (this is the option by default).
procedure UploadFileToAzure;
begin
oDialog := TOpenDialog.Create(nil);
Try
if oDialog.Execute then
AzureIoT.UploadFile(oDialog.FileName);
Finally
oDialog.Free;
End;
end;
Azure IoT allows to register devices from code using DPS. Currently, the library supports registering a device passing the Scope Id and Registration Id as parameters.
oClient := TsgcIoTAzure_MQTT_Client.Create(nil);
Try
oClient.Certificate.CertFile := 'cert.pem';
oClient.Certificate.KeyFile := 'key.pem';
oClient.Certificate.Enabled := True;
oResponse := TsgcIoT_Azure_OperationRegistrationState.Create;
Try
if oClient.ProvisioningDeviceClient_Register('scope_id', 'registration_id', oResponse) then
ShowMessage('#Provisioning Register OK: ' + oResponse.Status)
else
ShowMessage('#Provisioning Register Error: ' + oResponse.Status);
Finally
FreeAndNil(oResponse);
End;
Finally
FreeAndNil(oClient);
End;
You can use the application Azure IoT Explorer to interact with devices connected to your IoT Hub, you can see the telemetry messages received, the devices registered... the application is free and can be downloaded from:
https://github.com/Azure/azure-iot-explorer/releases