Skip to main content

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 adressAddress and Port 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

  1. 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.
  2. Open the MQTT Editor Window via Tools -> EAISI Digital Twin Lab -> MQTT editor in the Unity Editor. A new window shouldwill popopen up next toalongside the Inspector window.
  3. You canTo test the librarylibrary, by clickingclick the Connect button on the bottom of the MQTT editor window without changingaltering any of the windows parameters. This onlysolely tests if the interface can connect to aan MQTT broker,broker; no messages are relayed. A message stating Connected to: test.mosquitto.org:1883 should pop up in the Console window within Unity. Clicking Disconnect disconnects the Unity client from the MQTT broker, indicated but the message Disconnected from: test.mosquitto.org:1883.
  4. Now,Establish the connection to the desired MQTT broker can be established.broker. Make sureEnsure to executecomplete step 1 of this workflow.
  5. Fill in the parameters in the MQTT editor window as described in MQTT broker connections accordingbased to the settings ofon your MQTT broker.broker settings. Click Connect, 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 a MqttCommunicationTimedOutException indicates a wrong port. If a connections is established, click Disconnect.
  6. If applicable, you can test receiving messages from the MQTT broker by adding the subsciptionsubscription topics in the Topics list. You can do so by clickingClick the + button and enteringenter the full path to the variable youintended wantfor to receivereception in Unity. After hittingclicking Connect, the topic and value should be displayeddisplay in the Received header at the bottom of the MQTT editor. Click Disconnect.
  7. If applicable, you can test sending messages to the MQTT broker from Unity. After clicking Connect, a Publish header should beappear visible right underbelow the DisconnectDisconnect button. ForEnter the topic's path in the Topic value,field enterand the path of the topic you wantmessage to publish to. Forin the Message valuefield. enterTo theverify message you want to publish. To check if the messages is received,reception, check the MQTT broker or any MQTT client subscribed to the publishing topic. Click Disconnect.
  8. ForTo receivingreceive messages inat runtime, make sure to fill inpopulate all topics you want to subscribe tointended for yoursubscription dor the Unity project in the Topics headersection and check the Connect to MQTT broker upon entering runtime box box.. Once this 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 the subscriptionspecified topics. InTo order to read theseaccess received messages inat runtime, you could doutilize something like the DataManager script attached to the Data ObjectObject prefab which can be found under the folder .../DT lab/MQTT. This script subscribes to all topics presentlisted in the subscription topic list of the editor window vaivia the MessageManager. It stores these values in a public string each time the value changes,changes and uses the Update() functionality to display them in the Inspector window. In short,summary, to receive data from a topic inat runtime, your MonoBehaviour script should call:
    
     MessageManager.Instance.SubscribeToTopic(topic, HandleFunction);
     
    Where topic is the subscription topic, and HandleFunction is the function that gets called when the value on the topic gets updated. An example of this is shown below.
    
     private void HandleFunction(string topic, string message)
     {
         SubscribedTopics[topic] = message;
     }
     
    This function stores the received message of the topic in the dictionary SubscribedTopics., Butthough youself-defined function can definebe yourused ownas function if desired.well.
  9. PublisihingPublishing in run time can be doneachieved 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 message you want to publish. Make sure this message is converted to either a string or JSON format.
  10. You can reiterate stepsSteps 6 to 9 can be iteralyiterated repeatedas needed to getattain the desired data interface between Unity and the MWTTMQTT broker.

Development

  1. Code needs to be reviewed.
  2. Build needs to be checked.