MQTTClient.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. using LitJson;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using UnityEngine;
  7. using UnityEngine.Android;
  8. using uPLibrary.Networking.M2Mqtt.Messages;
  9. using static QTTManager;
  10. public class MQTTClient : MonoSingleton<MQTTClient>
  11. {
  12. public string OnlineType = "online/";
  13. string password = null;// 需要根据服务器设置
  14. // public static byte[] bytes;
  15. // public static byt ta;
  16. QTTManager qt;
  17. // Start is called before the first frame update
  18. void Start()
  19. {
  20. // 请求文件读取和写入权限
  21. if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead) ||
  22. !Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
  23. {
  24. Permission.RequestUserPermission(Permission.ExternalStorageRead);
  25. Permission.RequestUserPermission(Permission.ExternalStorageWrite);
  26. }
  27. //bytes = (Resources.Load("emqxsl-ca") as TextAsset).bytes;
  28. //Debug.Log(" DGJ ===> emqxsl-ca.bytes "+ bytes.Length);
  29. }
  30. Queue<MqttMsgPublishEventArgs> rlist = new Queue<MqttMsgPublishEventArgs>();
  31. private void OnReceived(MqttMsgPublishEventArgs obj)
  32. {
  33. rlist.Enqueue(obj);
  34. }
  35. private void OnConnecting()
  36. {
  37. Debug.Log("MQtt 连接中");
  38. }
  39. private void onSucceed()
  40. {
  41. Subscribe();
  42. }
  43. private void onFaild()
  44. {
  45. Debug.Log("MQtt 连接失败");
  46. }
  47. // Update is called once per frame
  48. void Update()
  49. {
  50. if (rlist.Count > 0)
  51. {
  52. for (int i = 0; i < rlist.Count; i++)
  53. {
  54. OnUnityReceived(rlist.Dequeue());
  55. }
  56. }
  57. }
  58. //MQTT接收到的数据
  59. public void OnUnityReceived(MqttMsgPublishEventArgs obj)
  60. {
  61. string msg = Encoding.UTF8.GetString(obj.Message);
  62. Debug.Log("uid => " + obj.Topic + ":\n" + msg);
  63. try
  64. {
  65. JsonData data = JsonMapper.ToObject(msg);
  66. Debug.Log(" DGJ === > " + data["type"].ToString());
  67. switch (data["type"].ToString())
  68. {
  69. case "CamPos":
  70. Debug.Log("DGJ ===> CamPos");
  71. // 根据 uid 同步Player 位置 如果没有就创建
  72. MultiPlayerManager.Instance.ReceivedCamPos(obj.Topic, data);
  73. break;
  74. case "ActiveSp":
  75. // 同步对应景点的开关
  76. MultiPlayerManager.Instance.ReceivedActiveSp( data);
  77. break;
  78. case "ActiveVideo":
  79. // 同步播放器的对应状态
  80. MultiPlayerManager.Instance.ReceivedActiveVideo(data);
  81. break;
  82. default:
  83. break;
  84. }
  85. }
  86. catch
  87. {
  88. return;
  89. }
  90. }
  91. private void OnDestroy()
  92. {
  93. DisConnect();
  94. }
  95. public string auth;
  96. public string topicPrefix;
  97. public string clientIdPrefix;
  98. public void setData(JsonData data)
  99. {
  100. //MQTTClinet 连接
  101. MQTTClient.Instance.SetUserName(data["auth"].ToString());
  102. MQTTClient.Instance.SetFront(data["topicPrefix"].ToString());
  103. clientIdPrefix = data["clientIdPrefix"].ToString();
  104. }
  105. public void PublicPosScene(string sid,string pos)
  106. {
  107. ;
  108. if (qt != null && qt.IsConnect())
  109. {
  110. // Debug.Log("发送===》"+ "10001/realtime/project/" + sid+"_"+ pos);
  111. publish("10001/realtime/project/" + sid,Encoding.UTF8.GetBytes(pos));
  112. }
  113. }
  114. public void SubscribeScene(string sid)
  115. {
  116. Debug.Log(" DGJ =====> 订阅 " + topicPrefix + sid);
  117. Debug.Log(" DGJ =====> 订阅 " + topicPrefix + OnlineType + sid);
  118. ushort s = qt.Subscribe(
  119. new string[]
  120. {
  121. topicPrefix+sid,
  122. topicPrefix+OnlineType+sid
  123. },
  124. new byte[]
  125. {
  126. MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE,
  127. MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE
  128. });
  129. }
  130. public void SetUserName(string username)
  131. {
  132. if (auth != null)
  133. this.auth = username;
  134. }
  135. public void SetFront(string front)
  136. {
  137. if (topicPrefix != null)
  138. this.topicPrefix = front;
  139. }
  140. public string id;
  141. public string rid;
  142. //连接
  143. public void Connect()
  144. {
  145. Debug.Log("DGJ ===> MQTT ");
  146. if (DeviceType.type == "Phone")
  147. {
  148. id = UserInfo.Instance.Account + "_Phone";
  149. rid = clientIdPrefix+UserInfo.Instance.Account + "_Glasses";
  150. }
  151. else
  152. {
  153. id = UserInfo.Instance.Account + "_Glasses";
  154. rid = clientIdPrefix + UserInfo.Instance.Account + "_Phone";
  155. }
  156. DisConnect();
  157. Debug.Log("mqtturl=====》" + HttpAction.Instance.mqtturl+"_"+ HttpAction.Instance.officeport+ (Resources.Load("emqxsl-ca") as TextAsset).bytes.Length);
  158. qt = new QTTManager(topicPrefix+id, auth, password, HttpAction.Instance.mqtturl, HttpAction.Instance.officeport);
  159. qt.Connect();
  160. StartCoroutine(Reconnection());
  161. qt.ConnectionFailed -= onFaild;
  162. qt.ConnectionSucceeded -= onSucceed;
  163. qt.OnConnecting -= OnConnecting;
  164. qt.OnReceived -= OnReceived;
  165. qt.OnClose -= OnClose;
  166. qt.ConnectionFailed += onFaild;
  167. qt.ConnectionSucceeded += onSucceed;
  168. qt.OnConnecting += OnConnecting;
  169. qt.OnReceived += OnReceived;
  170. qt.OnClose += OnClose;
  171. }
  172. private void OnClose(EventArgs obj)
  173. {
  174. Debug.Log("断开连接");
  175. }
  176. private IEnumerator Reconnection()
  177. {
  178. while (true)
  179. {
  180. yield return new WaitForSeconds(5);
  181. if(qt!=null&&!qt.IsConnect())
  182. {
  183. Debug.Log(" DGJ ===> Reconnection ");
  184. Connect();
  185. }
  186. }
  187. }
  188. //断开连接
  189. public void DisConnect()
  190. {
  191. if (qt != null && qt.IsConnect())
  192. qt.DisConnect();
  193. }
  194. //订阅
  195. public void Subscribe()
  196. {
  197. Debug.Log(" DGJ =====> Subscribe "+ id);
  198. ushort s = qt.Subscribe(
  199. new string[]
  200. {
  201. topicPrefix+id
  202. },
  203. new byte[]
  204. {
  205. MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE
  206. });
  207. Debug.Log(" DGJ =====> Subscribe2");
  208. }
  209. public void StartSendCameraPos()
  210. {
  211. StartCoroutine(sendCameraPos());
  212. }
  213. //眼镜端像手机端发送实时位置
  214. IEnumerator sendCameraPos()
  215. {
  216. Debug.Log("DGJ =====> sendCameraPos" + qt.IsConnect());
  217. while (true)
  218. {
  219. if(qt!=null&& qt.IsConnect())
  220. {
  221. JsonData json = new JsonData();
  222. json["type"] = "CamPos";
  223. // json["x"] = OpenXRCamera.Instance.head.position.x;
  224. //json["y"] = OpenXRCamera.Instance.head.position.y;
  225. //json["z"] = OpenXRCamera.Instance.head.position.z;
  226. json["x"] = GameManager.Instance.Player.transform.localPosition.x;
  227. json["y"] = GameManager.Instance.Player.transform.localPosition.y;
  228. json["z"] = GameManager.Instance.Player.transform.localPosition.z;
  229. json["Sid"] = "sid";//选择的场景id
  230. publish(rid,Encoding.UTF8.GetBytes(json.ToJson()));
  231. }
  232. yield return new WaitForSeconds(0.1f);
  233. }
  234. }
  235. //眼镜发送触发的景点
  236. public void sendActiveSp(string spid,bool isOpen)
  237. {
  238. JsonData json = new JsonData();
  239. json["type"] = "ActiveSp";
  240. json["Sid"] = "sid";//选择的场景id
  241. json["spid"] = spid;//景点id
  242. json["isOpen"] = isOpen;//是否打开
  243. publish(rid,Encoding.UTF8.GetBytes(json.ToJson()));
  244. Debug.Log("MQtt 发送manage");
  245. }
  246. //眼镜发送触发的视频
  247. public void sendActiveVideo(string spid,string videoId, bool isplay,float jindu)
  248. {
  249. JsonData json = new JsonData();
  250. json["type"] = "ActiveVideo";
  251. json["Sid"] = "sid";//选择的场景id
  252. json["spid"] = spid;//景点id
  253. json["videoId"] = videoId;//视频id
  254. json["isplay"] = isplay;//是否播放
  255. json["jindu"] = jindu;//视频进度
  256. publish(rid,Encoding.UTF8.GetBytes(json.ToJson()));
  257. Debug.Log("MQtt 发送manage");
  258. }
  259. void publish(string str,byte[] bs)
  260. {
  261. if(qt!=null&& qt.IsConnect())
  262. {
  263. // Debug.Log(id + " DGJ publish =====> " + front+rid + " " + bs.Length);
  264. qt.Publish(str, bs, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
  265. }
  266. else
  267. {
  268. Debug.LogError(" MQTT 未连接 ");
  269. }
  270. }
  271. }