MQTT - Unity interface
[!WARNING] This documentation is set to be partialy merged with the API documentation for Unity.
[!WARNING] This package does not allow for certificate validation.
Project owner: Yann van Eijk
Project description
This repository contains the scripts needed within Unity to create an interface between MQTT and Unity. Its main functionality is to receive and sent real-time messages
from topics
on the MQTT Broker. These messages
are processed within Unity as strings
, for other types use TryParse
.
Installation
The MQTT package is part of the 'DT lab Unity interface package'. For a full installation guide, please refer to...
MQTT broker connections
AEstablishing a connection to the MQTT broker canis befacilitated established usingthrough the MQTT editor window.window, Thisaccessible window can be found under the headervia Tools -> EAISI Digital Twin Lab -> MQTT editor
. AUpon opening, a new window shouldwill pop upappear next to the Inspector
window.
InTo thisconfigure window,the connection, the following parameters need tomust be set:configured:
Variable | Type | Description | Optional/ Required |
---|---|---|---|
Server adress | String | Hostname or IP adress of MQTT Broker. | Required |
Port | String | Port number of MQTT on broker. | Required |
Use Credentials | Boolean | Some MQTT brokers require user credentials for connections. If this is the case for the broker you want to connect to, tick this box. | Optional (Check broker) |
Use Encryption | Boolean | Some MQTT brokers require an encrypted connection. If this is the case for the broker you want to connect to, tick this box. | Optional (Check broker) |
Username | String | Username of account set at MQTT broker. | Optional (see Use Credentials ) |
Password | String | Password of account set at MQTT broker. | Optional (see Use Credentials ) |
Topics | List<String> | List of topics to subscribe to. All subscription topics used in the Unity project should be declared here. | Optional (Required for subscription functionality) |
Connect to MQTT broker at runtime | Boolean | Disables editor time connection and enables connection upon entering runtime. Only enable this setting after testing the connection in editor time. | Optional |
Upon the initial opening of the editor window,window initially, the Server
and adressAddressPort
variables are already set.pre-configured. This allows thequick usertesting to quickly check ifof a connection to test.mosquitto.org
can be established.. To test this,verify, click the gray connect button onat the bottom of the MQTT editor window. In the console, aA debugging message should popappear upin the console stating Connected to: test.mosquitto.org:1883
., Thisindicating indicatessuccessful that the package is working as intended.functionality.
Workflow
- Setup MQTT broker. If you already have an account and password provided by the Digital Twin Lab or if you already setup your own broker, go to step 2. For certain projects it is possible to make use of the MQTT broker of the Digital Twin Lab. If you want to make use of the MQTT broker of the Digital Twin Lab, but dont have credentials yet, please contact us via e-mail.
- Open the
MQTT Editor Window
viaTools -> EAISI Digital Twin Lab -> MQTT editor
in the Unity Editor. A new windowshouldwillpopopenup next toalongside theInspector
window. You canTo test thelibrarylibrary,by clickingclick theConnect
button on the bottom of the MQTT editor window withoutchangingaltering anyof the windowsparameters. Thisonlysolely tests if the interface can connect toaan MQTTbroker,broker; no messages are relayed. A message statingConnected to: test.mosquitto.org:1883
should pop up in theConsole
window within Unity. ClickingDisconnect
disconnects the Unity client from the MQTT broker, indicated but the messageDisconnected from: test.mosquitto.org:1883
.Now,Establish the connection to the desired MQTTbroker can be established.broker.Make sureEnsure toexecutecomplete step 1 of this workflow.- Fill in the parameters in the MQTT editor window as described in MQTT broker connections
accordingbasedto the settings ofon your MQTTbroker.broker settings. ClickConnect
, if no connection is established, an error message will pop up in the Console. I.e.SocketException: Could not resolve host 'test.mosquittofalse.org'
, indicating the wrong server adress. Any error concerning aMqttCommunicationTimedOutException
indicates a wrong port. If a connections is established, clickDisconnect
. - If applicable,
you cantest receiving messages from the MQTT broker by addingthe subsciptionsubscription topics in theTopics
list.You can do so by clickingClick the+
button andenteringenter the full path to the variableyouintendedwantforto receivereception in Unity. AfterhittingclickingConnect
, the topic and value shouldbe displayeddisplay in theReceived
header at the bottom of the MQTT editor. ClickDisconnect
. - If applicable,
you cantest sending messages to the MQTT broker from Unity. After clickingConnect
, aPublish
header shouldbeappearvisible right underbelow the
t button.DisconnectDisconnecForEnter the topic's path in theTopic
value,fieldenterand thepath of the topic you wantmessage to publishto. Forin theMessage
valuefield.enterTotheverify messageyou want to publish. To check if the messages is received,reception, check the MQTT broker or any MQTT client subscribed to the publishing topic. ClickDisconnect
. ForToreceivingreceive messagesinat runtime,make sure to fill inpopulate all topicsyou want to subscribe tointended foryoursubscription dor the Unity project in theTopics
headersection and check theConnect to MQTT broker upon entering runtime box
box.. Oncethis box has been ticked,checked, no changes can be made to the MQTT editor window. Unity will automatically connect to the MQTT broker and subscribe to thesubscriptionspecified topics.InToorder to read theseaccess received messagesinat runtime,you could doutilize something like theDataManager
script attached to theData
t prefabObjectObjecwhich can befound under the folder.../DT lab/MQTT
. This script subscribes to all topicspresentlisted in the subscription topic list of the editor windowvaivia theMessageManager
. It stores these values in a public string each time the valuechanges,changes and uses theUpdate()
functionality to display them in theInspector
window. Inshort,summary, to receive data from a topicinat runtime, yourMonoBehaviour
script should call:
WhereMessageManager.Instance.SubscribeToTopic(topic, HandleFunction);
topic
is the subscription topic, andHandleFunction
is the function that gets called when the value on the topic gets updated. An example of this is shown below.
This function stores the received message of the topic in the dictionaryprivate void HandleFunction(string topic, string message) { SubscribedTopics[topic] = message; }
SubscribedTopics
.,Butthoughyouself-defined function candefinebeyourusedownasfunction if desired.well.PublisihingPublishing in run time can bedoneachieved by calling the function below.MQTT_lib.PublishToTopic(TopicToPublish, message.ToString());
TopicToPublish
is a string of the full path of the topic you want to pulbisch to.message
is the messageyou wantto publish. Make sure this message is converted to either a string or JSON format.You can reiterate stepsSteps 6 to 9 can beiteralyiteratedrepeatedas needed togetattain the desired data interface between Unity and theMWTTMQTT broker.
Development
- Code needs to be reviewed.
- Build needs to be checked.