MQTT protocol
VuGen's MQTT protocol supports testing for networks using machine-to-machine (M2M) and Internet of Things (IoT) communications.
About MQTT
MQTT is a simple, lightweight, publish/subscribe messaging protocol designed for constrained devices and low-bandwidth, high-latency or unreliable networks.
MQTT is ideal for M2M and IoT communications, as well as for mobile applications where bandwidth and battery power are at a premium. MQTT focuses on minimizing network bandwidth and device resource requirements, while attempting to ensure reliability and some degree of assurance of delivery.
MQTT uses publisher-subscriber operations for communication between clients and the server. The MQTT server is the message broker that controls communication between clients.
Clients, or “things”, can be publishers or subscribers.
- The publisher is the client sending the message. The message goes to the message broker, specifying a topic.
- The subscriber is the client that receives the message. To receive a message on a topic, subscribers have to subscribe to it.
Create an MQTT script
You can use the MQTT Script Wizard to generate attributes for your script, or you can script it manually using the defined MQTT functions.
The client variables for your script are declared in the Extra Files > globals.h file, accessed from the Solution Explorer.
To create an MQTT script:
-
Create a new script by selecting New Script and Solution > MQTT protocol.
A ready-to-use script opens in the Editor, using all of the available MQTT functions. In addition, the Script Wizard is opened automatically in a separate dialog box.
-
Design the script in one of the following ways:
- Use the Script Wizard to generate the script. For details, see MQTT Script Wizard.
- Click Cancel to close the Script Wizard, and modify the ready-to-use script template as needed. For a complete description of the MQTT functions and function calls, see the Function Reference (select the relevant version).
Note: If you are creating a multiple-protocol script, you can integrate MQTT steps into a recorded Web - HTTP/HTML script. For details, see Working with multi-protocol scripts.
-
Configure the runtime settings. These affect the way that a Vuser script runs.
-
In the Solution Explorer, double-click Runtime Settings.
-
In the <test name>:Runtime Settings view, configure the runtime settings as needed. To view descriptions of the individual runtime settings, hold your cursor over a runtime setting field name.
For general details, see Runtime settings and Configure runtime settings.
-
MQTT Script Wizard
The MQTT Script Wizard enables you to define settings that are then generated as code in your MQTT script.
The Script Wizard is displayed automatically (default setting) when you create a new MQTT script. You can also open it by clicking Design Script on the VuGen toolbar. (The Design Script button is available when an MQTT script is open in the Editor.)
UI Element
|
Description
|
---|---|
Connection Settings tab | |
Broker URL |
Address of the broker server in the format: tcp://host:port or ssl://host:port, where the host is the domain name, IPv4 address, or the IPv6 address, in square brackets. Example of IPv6 address: [2001:0db8:85a3:0000:0000:8a2e:0370:7334]. If the port is not specified, the following default ports are used:
|
Client ID |
Define the client ID for the connection. The string is a unique identifier for a client in the network. Leave the field blank to use an automatically generated ID. The client is identified as follows:
|
Authentication settings | If required, define the user name and password to log on to the broker server. |
Enable TLS | Select if secure communication over TLS (SSL) is required, and select the relevant TLS version from the dropdown list. Default uses the version defined in the runtime settings. |
Use client certificate |
Select to use the client certificate, then define the path to the certificate file and private key, and the password for the key (leave the password field empty if the key is not encrypted). |
Check Connection | Click to check that VuGen can connect successfully to the broker using the defined credentials. A green tick is displayed if the connection succeeded, and a red cross if it failed. |
Show wizard for new scripts |
Clear the check box if you do not want the Script Wizard to open automatically when creating new MQTT scripts. Tip: If the Script Wizard does not open automatically, you can open it by clicking Design Script in the VuGen toolbar. |
Clear All | Click to clear all settings in all tabs. |
Generate Code | If the button is enabled, click to add the relevant steps to the code for the script; Or continue to the next tabs to define optional settings. |
Client Settings tab | |
Publisher/Subscriber |
Define values for one of these options. Use the radio buttons to switch between them:
|
Topic to publish | The destination topic for publishing the message, for example: myhome/kitchen/temperature/1 . |
Payload | Set the message to be published, in byte format. |
Retain message |
When checked, this instructs the broker to store the last retained message in the topic together with its QoS. Only one message is stored per topic, so the last retained message always replaces any previously stored message. This is useful for providing the latest status to new subscribers when they subscribe to a topic, so they do not need to wait for the next status update. |
Quality of Service |
The required Quality of Service (QoS). For example, if the connection is lost where QoS = 0, the client will not try to publish again after reconnecting, and a warning is displayed in the script's output. Values are 0 to 2 and Default (as defined in the runtime settings). |
Topic to subscribe |
Use to subscribe the client to a topic, or a set of topics (by using wildcards). The broker automatically sends messages published on these topics. The topic can contain wildcards. Examples:
The default QoS is used, as defined in the runtime settings. |
Last Will and Testament tab | |
Topic | Define the destination topic to notify other clients about an ungracefully disconnected client. |
Payload | Set the message the broker sends to subscribers for the specified topic, when the client disconnects unexpectedly. |
Retain message | When checked, this instructs the broker to store the last retained message in this topic. Only one message is stored per topic, so the last retained message always replaces any previously stored message. |
Additional attributes for clients
You can use the MQTT Script Wizard to define additional attributes for an existing client—a client that already has a connection in the script. The client is defined by the Client ID provided in the wizard.
Possible additional attributes are:
-
Publisher. A client can have multiple publishers. If a publisher is created for an existing client, the new publisher is added in the Actions.c file, for the corresponding client.
-
Subscriber. A client can only subscribe to one topic at a time. If a subscriber is created for an existing client, code generation verifies if the existing client has already subscribed. If it has a subscriber, the one from the wizard is ignored. Otherwise, the subscriber is added to the
client_settings()
function in the vuser_init.c file, and the corresponding unsubscribe is added before the corresponding client’s disconnect in the vuser_end.c file. -
Last Will and Testament. A client can have only one Last Will and Testament (LWT) message. If an LWT message is created for an existing client, the code generation verifies if the existing client already has an LWT. If so, the one from the wizard is ignored. If not, a new LWT function is added to the corresponding client in the
client_settings()
function in the vuser_init.c file.
Working with multi-protocol scripts
You can test scenarios in which your script uses both of the following:
-
MQTT to communicate between the client and the broker
-
Web - HTTP/HTML to communicate between the broker and the web application
You prepare your script by recording the steps on your web application. Then you manually add MQTT steps as needed. The pre-populated MQTT script is not included when working with a multiple protocol script, but you can copy/paste from the Ready-to-use MQTT script template.
To enable support:
-
Create a multiple-protocol script that includes MQTT and Web - HTTP/HTML. For details, see Create a New Script dialog box.
-
Record a web script.
Note: Recording a web script overwrites globals.h, removing the default support for MQTT steps.
-
Restore support for MQTT steps:
-
Open globals.h (located in the Solution Explorer under Extra Files).
-
Add #include "MqttApi.h" to the Include Files section.
-
-
Add MQTT steps to the script.
Sample multi-protocol script
Action() { MQTT client; client = mqtt_create(); mqtt_set_client_id(client, "myclientid"); lr_start_transaction("connect_MQTT"); mqtt_connect(client, "tcp://mymachine:1883"); lr_end_transaction("connect_MQTT", LR_AUTO); lr_start_transaction("navigate_Web"); // your recorded web code here lr_end_transaction("navigate_Web", LR_AUTO); mqtt_publish(client, "topic/subtopic", "payload", MQTT_AUTO, MQTT_DEFAULT, MQTT_NORETAIN); mqtt_disconnect(client); return 0; }
Ready-to-use MQTT script template
The default, single-protocol MQTT script includes actions that are pre-populated with commented out steps (shown below).
When working with multiple-protocol scripts, you first record steps on your web application. Then you add MQTT steps as needed. You can copy/paste the relevant steps from the template below.
For details on any of these functions, see the Function Reference (select the relevant version).
vuser_init
vuser_init() { /* Declared in "globals.h" */ client = mqtt_create(); /* Optional connection settings */ // mqtt_set_client_id(client, "<insert Client ID>"); // mqtt_set_credentials(client, "<username placeholder>", "<password placeholder>"); // mqtt_set_lwt(client, "<topic>", "<sample lwt payload>", MQTT_AUTO, MQTT_DEFAULT, MQTT_RETAIN); /* Optional SSL/TLS settings, applicable for SSL/TLS connections only */ // mqtt_set_tls_certificate(client, "<path to a certificate file, e.g. cert.pem>", "<path to a private key file, e.g. key.pem>", "<password for the private key>"); // mqtt_set_tls_parameters(client, MQTT_TLS_DEFAULT, MQTT_DEFAULT_CIPHERS); /* Connect to an MQTT broker */ mqtt_connect(client, "tcp://<enter an MQTT broker host name>"); /* Uncomment the following if implementing the "subscriber" logic */ // mqtt_subscribe(client, "<topic>"); return 0; }
Action
Action() { /* Uncomment the following if implementing the "subscriber" logic. Make sure to also uncomment subscribe/unsubscribe in vuser_init/end.c */ // /* Option 1: Wait for messages, then handle their contents */ // size_t messageCount = mqtt_await_messages(client, MQTT_DEFAULT); // size_t i = 0; // for ( ; i < messageCount; i++) // { // MQTT_MESSAGE m = mqtt_read_inbox(client); // const char* p = mqtt_get_payload(m); // const char* t = mqtt_get_topic(m); // size_t l = mqtt_get_length(m); // ... do something meaningful with the message // ... for instance, print received message information (assuming its payload is not binary data) // lr_message("received message with size %d from %s", l, t); // lr_message("payload %.*s", l, p); // // mqtt_free_message(m); // } /* Option 2: Wait for messages, then clear Inbox (if their handling is not needed) */ // mqtt_await_messages(client, MQTT_DEFAULT); // mqtt_clear_inbox(client); /* Uncomment the following if implementing the "publisher" logic */ // mqtt_publish(client, "<topic>", "<payload>", MQTT_AUTO, MQTT_DEFAULT, MQTT_RETAIN); return 0; }
vuser_end
vuser_end() { /* Uncomment the following if implementing the "subscriber" logic */ // mqtt_unsubscribe(client, "<topic>"); /* Disconnect from the MQTT broker */ mqtt_disconnect(client); return 0; }