Application of MQTT communication protocol in Unity -- JS implementation

Posted by rhyspaterson on Thu, 09 Apr 2020 16:34:19 +0200

It has been studied in the industrial field for a long time. According to the requirements of digital twin, it is necessary to get through the network, from CLP to IOT to Dass to virtual factory (3D visualization). In order to get through the state of control and anti control, it is necessary to get through the network communication. For Unity, the first thought must be Socket communication, which is also a familiar method for many developers. However, MQTT communication protocol is used in industrial communication It is widely used in, so today I will introduce the use of MQTT communication protocol in Unity
Because I want to go to the cloud, so I tested two schemes
1. MQTT communication is realized through JS, and then communication is realized through Unity and JS interaction
First of all, we need two scripts: paho-mqtt.js and jquery.min.js. There are many scripts on the Internet. If you are proficient in JS, you can also write them yourself. You all know what they are used for.
Here is the code to realize connection and information communication

    <script src="./jquery.min.js"></script>
    <script src="./paho-mqtt.js"></script>
        <scrpt>
           //MQTT connection
    //Select a subscription topic
    var selectedTopics = [];
    //Select publish theme
    var currentTopic;
      //Client options
    var option = {
        "ServerUri": "127.0.0.1",
        "ServerPort": 61623,
        "UserName": "admin",
        "Password": "password",
        "ClientId": "",
        "TimeOut": 5,
        "KeepAlive": 100,
        "CleanSession": false,
        "SSL":false
    }

      //Client
    var client;

      //Connect
    function connectFun(){
        option .ClientId = guid();
        client = new Paho.Client(option.ServerUri, option.ServerPort, option.ClientId);
        client.onConnectionLost = onConnectionLost;
        client.onMessageArrived = onMessageArrived;
        client.connect({
            invocationContext: {
                host: option.ServerUri,//IP address
                port: option.ServerPort,//Port number
               path: client.path,
                clientId: option.ClientId//Identification
            },
            timeout: option.TimeOut,//Connection timeout
            keepAliveInterval: option.KeepAlive,//heartbeat interval
            cleanSession: option.CleanSession,//Clear Session or not
            useSSL: option.SSL,//Enable SSL or not
            userName: option.UserName,  //User name
            password: option.Password,  //Password
            onSuccess: onConnect,//Connection success callback event
            onFailure: onError//Connection failure callback event
        }); 
    }

    //Disconnect
    function disConnect(){
        //client.disconnect();
    }

    //Subscribe
    function onSubscrip(sub)
    {
        if (!client) {
            gameInstance.SendMessage("GameAPP","OnException","Please connect to the service");
            //alert("failure");
            return; 
        }

        selectedTopics.push(sub);
        client.subscribe(selectedTopics,0x02);
        //alert("subscription:" + sub);
        gameInstance.SendMessage("GameAPP","OnException","Subscription channel:" + sub);
    }

            //Release
    function onRele(sub,info)
    {
        if (!client) {
            gameInstance.SendMessage("GameAPP","OnException","Please connect to the service");
            return;
        }

        var message = new Paho.Message(info);
        currentTopic = sub;
        message.destinationName = currentTopic;
        //client.send(message)
        client.publish(currentTopic,info,0x02,false);

        gameInstance.SendMessage("GameAPP","OnException","Publish message:" + info);

    }

         //Receive message event
    function onMessageArrived(data) {
        gameInstance.SendMessage("GameAPP","OnGetInfo","Receive message:" + data.payloadString);
        //alert("message:" + data.payloadString);
    } 

    //Disconnect event
    function onConnectionLost(e) {
        if (e.errorCode !== 0) {
           gameInstance.SendMessage("GameAPP","OnException","Publish message:" + e.errorCode);
        }
    }

    //Connection success callback event
    function onConnect()
    {
        gameInstance.SendMessage("GameAPP","OnException","Connection succeeded!");
    }

    function onError(e){
        gameInstance.SendMessage("GameAPP","OnException","Connection failed. Please reconnect,");
    }

    //Generate GUID
    function guid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

        </script>

Just send the received information to Unity, or the information obtained from Unity.

Topics: Javascript Unity SSL network JQuery