1 TMS SOFTWARE TMS MQTT DEVELOPERS GUIDE TMS MQTT DEVELOPERS GUIDE Feb 2017 Cop
1 TMS SOFTWARE TMS MQTT DEVELOPERS GUIDE TMS MQTT DEVELOPERS GUIDE Feb 2017 Copyright © 2017 by tmssoftware.com bvba Web: http://www.tmssoftware.com Email: info@tmssoftware.com 2 TMS SOFTWARE TMS MQTT DEVELOPERS GUIDE Index Introduction ................................................................................................. 4 Usage ......................................................................................................... 4 Installation ................................................................................................ 4 Prerequisites ........................................................................................... 4 Installation in Delphi ................................................................................. 4 Installation in Lazarus/FPC .......................................................................... 4 Getting started ........................................................................................... 5 At Design Time ........................................................................................ 5 At Runtime ............................................................................................. 5 Free Brokers ........................................................................................... 5 Connecting ................................................................................................ 6 Connection settings ................................................................................... 6 Username and Password ............................................................................. 7 Code example ....................................................................................... 8 Keeping a connection alive .......................................................................... 9 Code example ....................................................................................... 9 Automatic reconnecting .............................................................................. 9 Code example ...................................................................................... 10 Last Will Testament (LWT) ......................................................................... 10 The following parameters can be provided: ................................................... 10 Code example ...................................................................................... 11 Publishing ................................................................................................ 11 Topic Name ........................................................................................... 11 Packet Payload ....................................................................................... 11 Quality of Service (QoS) ............................................................................. 11 Retain-flag ............................................................................................ 12 Code example ........................................................................................ 12 Subscribing ............................................................................................... 13 Topic Filter ........................................................................................... 13 Single-level wildcard + ........................................................................... 13 Multi-level wildcard #............................................................................. 13 Subscription Quality of Service .................................................................... 13 Code example ........................................................................................ 14 Ensure a subscription was successful .............................................................. 14 3 TMS SOFTWARE TMS MQTT DEVELOPERS GUIDE Unsubscribing ............................................................................................ 15 Receiving published messages ........................................................................ 16 Pinging ................................................................................................... 16 Monitoring in- and outgoing packets ................................................................. 17 Logging ................................................................................................... 17 Demo ........................................................................................................ 18 4 TMS SOFTWARE TMS MQTT DEVELOPERS GUIDE Introduction The TMS MQTT component as a full-featured Delphi MQTT Client that implements the 3.1.1 version of the MQTT protocol. http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html The component is developed to work on all major operating systems (Windows, Mac, Linux, iOS and Android) and it supports the VCL, FMX and FPC frameworks. It has the following Key feaures: - Quality of Service 0, 1 and 2 - Automatic pinging - Automatic reconnect - Last Will and Testament (LWT) - SSL connections - Authentication Usage Installation Prerequisites The TMS MQTT Library has a dependency on Indy so make sure you have a working version of Indy installed. Installation in Delphi To install TMS MQTT in RAD studio, download and install the appropriate installer for your version of the IDE. Installation in Lazarus/FPC To install TMS MQTT in lazarus, download and open the TMS.MQTT.lpi package and install it manually into the IDE. 5 TMS SOFTWARE TMS MQTT DEVELOPERS GUIDE Getting started At Design Time The TTMSMQTTClient comes as a non-visual component that, after successful installation, can be found in the tool palette under TMS MQTT. Just add an instance of the client to your form to get started. All necessary settings to connect the client will be available through the Object Inspector. At Runtime The TTMSMQTTClient can also be created at runtime. See below for an example on how to do that. procedure TMQTTExampleForm.FormCreate(Sender: TObject); begin MQTTClient := TTMSMQTTClient.Create(Self); end; Free Brokers Instead of having to install your own broker first, note that to get started with MQTT, you can use one of the public free brokers listed on the following page: http://moxd.io/2015/10/public-mqtt-brokers/ 6 TMS SOFTWARE TMS MQTT DEVELOPERS GUIDE Connecting Connection settings Before connecting the client to a broker the following parameters can be set. Property Type Description Default value Mandatory ClientID string This is the unique ID for the Client random string no BrokerHostName string Hostname of the broker you want to connect to yes BrokerPort integer The port to use when connecting to the broker 1883 no UseSSL boolean Whether or not to connect through SSL false no Credentials TMQTTCredentials The credentials to use when connecting (more info below) no KeepAliveSettings TMQTTKeepAliveSettings Setting to keep the connection alive (more info below) no LastWillSettings TMQTTLastWillSettings The LWT settings (more info below) no Connecting the client is done using the Connect prodecure on the TTMSMQTTClient instance. This procedure takes one optional parameter to state if it should start a new session or continue with a previous session. Connecting the client is an asynchronous process. That means that you will have to subscribe to the OnConnectedStatusChanged event to know when the connection was successful. See below for a typical example on how to connect the client from code, the same thing can of course be achieved by using the Object Inspector in design-time. 7 TMS SOFTWARE TMS MQTT DEVELOPERS GUIDE procedure TMQTTExampleForm.ConnectButtonOnClick(Sender: TObject); begin MQTTClient.ClientID := 'MyUniqueClientID'; MQTTClient.BrokerHostName := 'broker.mydomain.com'; MQTTClient.OnConnectedStatusChanged := ClientOnConnectedStatusChanged; MQTTClient.Connect; end; procedure TMQTTExampleForm.ClientOnConnectedStatusChanged(ASender: TObject; const AConnected: Boolean; AStatus: TTMSMQTTConnectionStatus); begin if (AConnected) then begin // The client is now connected and you can now start interacting with the broker. ShowMessage('We are connected!'); end else begin // The client is NOT connected and any interaction with the broker will result in an exception. case AStatus of csConnectionRejected_InvalidProtocolVersion, csConnectionRejected_InvalidIdentifier, csConnectionRejected_ServerUnavailable, csConnectionRejected_InvalidCredentials, csConnectionRejected_ClientNotAuthorized: ; // the connection is rejected by broker csConnectionLost: ; // the connection with the broker is lost csConnecting: ; // The client is trying to connect to the broker csReconnecting: ; // The client is trying to reconnect to the broker end; end; end; Username and Password Some broker connections require a client to provide a username and password when connecting. This can be achieved by editing the Credentials property on the TTMSMQTTClient instance. Property Type Description Default value Mandatory Username string The username no Password string The password no 8 TMS SOFTWARE TMS MQTT DEVELOPERS GUIDE Code example procedure TMQTTExampleForm.ConnectCredentialsButtonClick(Sender: TObject); begin MQTTClient.ClientID := 'MyUniqueClientID'; MQTTClient.BrokerHostName := 'broker.mydomain.com'; MQTTClient.Credentials.Username := 'myUsername'; MQTTClient.Credentials.Password := 'myPassword'; MQTTClient.Connect; end; 9 TMS SOFTWARE TMS MQTT DEVELOPERS GUIDE Keeping a connection alive The MQTT protocol requires an open connection between the client and the broker at all times. When connecting to the broker a client must provide a keep alive interval, this is the maximum allowed timespan in which no messages can be exchanged between the client and the broker. If this period is exceeded, the broker must disconnect the client. To maintain an open connection, the client must thus send a PINGREQ packet to the broker if no other packets has been exchanged within the keep alive timespan. The Keep Alive Settings can be configured using the KeepAliveSettings property on the TTMSMQTTClient instance before connecting. Property Type Description Default value Mandatory KeepConnectionAlive boolean Whether or not the client should keep the connection alive true no KeepAliveInterval word The keep alive interval in seconds 120 no Code example procedure TMQTTExampleForm.ConnectKeepAliveButtonClick(Sender: TObject); begin MQTTClient.ClientID := 'MyUniqueClientID'; MQTTClient.BrokerHostName := 'broker.mydomain.com'; MQTTClient.KeepAliveSettings.KeepConnectionAlive := true; // Enable Keep Alive MQTTClient.KeepAliveSettings.KeepAliveInterval := 60; // 1 minute interval MQTTClient.Connect; end; Automatic reconnecting The TMS MQTT Client features a way to automatically reconnect to the broker if the connection gets lost unexpectedly. This feature is disabled by default. Enabling automatic reconnecting can be done by editing the KeepAliveSettings property on the TTMSMQTTClient instance before connecting. 10 TMS SOFTWARE TMS MQTT DEVELOPERS GUIDE Property Type Description Default value Mandatory AutoReconnect boolean Whether or not the client should try to restore a broken connection false no AutoReconnectInterval word The interval to try reconnecting in seconds 30 no Code example procedure TMQTTExampleForm.ConnectAutoReconnectButtonClick(Sender: TObject); begin MQTTClient.ClientID := 'MyUniqueClientID'; MQTTClient.BrokerHostName := 'broker.mydomain.com'; MQTTClient.KeepAliveSettings.AutoReconnect := true; // Enable Auto-Reconnect MQTTClient.KeepAliveSettings.AutoReconnectInterval := 10; // Try reconnecting every 10 seconds MQTTClient.Connect; end; Last Will Testament (LWT) The MQTT protocol allows a client to provide an optional Last Will Testament (LWT) when connecting to a broker. When provided, the broker will publish a message to the given topic as soon as it lost the connection with the client and didnt recieved a proper disconnect message. The last will is a way to notify other clients that a client has lost it’s connection. The LWT can be configured using the LastWillSettings property on the TTMSMQTTClient instance before connecting. The following parameters can be provided: Property Type Description Default value Mandatory Topic string The topic that should be used to publish the LWT message yes WillMessage string The actual message no Retain boolean Whether or not the message should be retained on the broker false no QoS TMQTTQoS the Quality of Service that should be used to send the LWT qosAtMostOnce no 11 TMS SOFTWARE TMS MQTT DEVELOPERS GUIDE Property Type Description Default value Mandatory message Code example procedure TMQTTExampleForm.ConnectLWTClick(Sender: TObject); begin MQTTClient.ClientID := 'MyUniqueClientID'; MQTTClient.BrokerHostName := 'broker.mydomain.com'; MQTTClient.LastWillSettings.Topic := 'clients/disconnected'; MQTTClient.LastWillSettings.WillMessage := 'MyUniqueClientID'; MQTTClient.Connect; end; Publishing After a connection has been established you can start publishing messages to a specific topic. This can be done by calling the Publish method on the TTMSMQTTClient instance. The method takes 4 parameters of which only the first is mandatory. Topic Name The topic to where you publish should be a valid UTF8 string and should be at least 1 character long. The topic name can consist of one or more levels separated by a forward slash (/) and cannot contain any wildcard characters (+ OR #). Here are some examples of valid topics to publish to: - myapp/heatsensor - myapp/garage/temperature - m/g/t - humidity Please note that the topics are case-sensitive. Packet Payload The payload of a packet can be sent as a string or as an array of bytes (TBytes). This parameter is optional, by default a nil value will be sent. Quality of Service (QoS) This parameter uploads/s3/ tms-software-tms-mqtt-developers-guide.pdf
Documents similaires










-
28
-
0
-
0
Licence et utilisation
Gratuit pour un usage personnel Attribution requise- Détails
- Publié le Jui 25, 2022
- Catégorie Creative Arts / Ar...
- Langue French
- Taille du fichier 0.5581MB