一直以来在工业领域研究,根据数字孪生的要求,需要打通网络,从CLP到IOT到Dass到虚拟工厂(三维可视化),为了打通控制与反控制的状态,需要打通网络通信,对于Unity首先想到的肯定是Socket通信,这也是很多开发人员所熟悉的方法,但是MQTT通信协议在工业通信中使用很普遍,所以今天我就对MQTT通信协议在Unity使用做介绍
我这边因为要上云端,所以,我测试了两套方案
1.通过JS实现MQTT通信,再通过Unity与JS交互,实现通信
首先需要paho-mqtt.js,jquery.min.js两个脚本,网上有很多,如果是精通JS的也可以自己写,大家都知道用来干嘛的。
下面是实现连接和信息通信的代码
<script src="./jquery.min.js"></script>
<script src="./paho-mqtt.js"></script>
<scrpt>
//MQTT连接
//选中订阅主题
var selectedTopics = [];
//选中发布主题
var currentTopic;
//客户端选项
var option = {
"ServerUri": "127.0.0.1",
"ServerPort": 61623,
"UserName": "admin",
"Password": "password",
"ClientId": "",
"TimeOut": 5,
"KeepAlive": 100,
"CleanSession": false,
"SSL":false
}
//客户端
var client;
//连接
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地址
port: option.ServerPort,//端口号
path: client.path,
clientId: option.ClientId//标识
},
timeout: option.TimeOut,//连接超时时间
keepAliveInterval: option.KeepAlive,//心跳间隔
cleanSession: option.CleanSession,//是否清理Session
useSSL: option.SSL,//是否启用SSL
userName: option.UserName, //用户名
password: option.Password, //密码
onSuccess: onConnect,//连接成功回调事件
onFailure: onError//连接失败回调事件
});
}
//断开连接
function disConnect(){
//client.disconnect();
}
//订阅
function onSubscrip(sub)
{
if (!client) {
gameInstance.SendMessage("GameAPP","OnException","请连接服务");
//alert("失败");
return;
}
selectedTopics.push(sub);
client.subscribe(selectedTopics,0x02);
//alert("订阅:" + sub);
gameInstance.SendMessage("GameAPP","OnException","订阅频道:" + sub);
}
//发布
function onRele(sub,info)
{
if (!client) {
gameInstance.SendMessage("GameAPP","OnException","请连接服务");
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","发布消息:" + info);
}
//接收消息事件
function onMessageArrived(data) {
gameInstance.SendMessage("GameAPP","OnGetInfo","接收消息:" + data.payloadString);
//alert("消息:" + data.payloadString);
}
//连接断开事件
function onConnectionLost(e) {
if (e.errorCode !== 0) {
gameInstance.SendMessage("GameAPP","OnException","发布消息:" + e.errorCode);
}
}
//连接成功回调事件
function onConnect()
{
gameInstance.SendMessage("GameAPP","OnException","连接成功!");
}
function onError(e){
gameInstance.SendMessage("GameAPP","OnException","连接失败,请重新连接,");
}
//生成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>
只需要将接受的信息发给Unity,或者从Unity获取的信息发出。
原文地址:https://blog.51cto.com/myselfdream/2486066
时间: 2024-11-08 08:55:24