MQTTClient.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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);
  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. }
  167. private void OnClose(EventArgs obj)
  168. {
  169. Debug.Log("断开连接");
  170. }
  171. private IEnumerator Reconnection()
  172. {
  173. while (true)
  174. {
  175. yield return new WaitForSeconds(5);
  176. if(qt!=null&&!qt.IsConnect())
  177. {
  178. Debug.Log(" DGJ ===> Reconnection ");
  179. Connect();
  180. }
  181. }
  182. }
  183. //断开连接
  184. public void DisConnect()
  185. {
  186. if (qt != null && qt.IsConnect())
  187. qt.DisConnect();
  188. }
  189. //订阅
  190. public void Subscribe()
  191. {
  192. Debug.Log(" DGJ =====> Subscribe "+ id);
  193. ushort s = qt.Subscribe(
  194. new string[]
  195. {
  196. topicPrefix+id
  197. },
  198. new byte[]
  199. {
  200. MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE
  201. });
  202. Debug.Log(" DGJ =====> Subscribe2");
  203. }
  204. public void StartSendCameraPos()
  205. {
  206. StartCoroutine(sendCameraPos());
  207. }
  208. //眼镜端像手机端发送实时位置
  209. IEnumerator sendCameraPos()
  210. {
  211. Debug.Log("DGJ =====> sendCameraPos" + qt.IsConnect());
  212. while (true)
  213. {
  214. if(qt!=null&& qt.IsConnect())
  215. {
  216. JsonData json = new JsonData();
  217. json["type"] = "CamPos";
  218. // json["x"] = OpenXRCamera.Instance.head.position.x;
  219. //json["y"] = OpenXRCamera.Instance.head.position.y;
  220. //json["z"] = OpenXRCamera.Instance.head.position.z;
  221. json["x"] = GameManager.Instance.Player.transform.localPosition.x;
  222. json["y"] = GameManager.Instance.Player.transform.localPosition.y;
  223. json["z"] = GameManager.Instance.Player.transform.localPosition.z;
  224. json["Sid"] = "sid";//选择的场景id
  225. publish(rid,Encoding.UTF8.GetBytes(json.ToJson()));
  226. }
  227. yield return new WaitForSeconds(0.1f);
  228. }
  229. }
  230. //眼镜发送触发的景点
  231. public void sendActiveSp(string spid,bool isOpen)
  232. {
  233. JsonData json = new JsonData();
  234. json["type"] = "ActiveSp";
  235. json["Sid"] = "sid";//选择的场景id
  236. json["spid"] = spid;//景点id
  237. json["isOpen"] = isOpen;//是否打开
  238. publish(rid,Encoding.UTF8.GetBytes(json.ToJson()));
  239. Debug.Log("MQtt 发送manage");
  240. }
  241. //眼镜发送触发的视频
  242. public void sendActiveVideo(string spid,string videoId, bool isplay,float jindu)
  243. {
  244. JsonData json = new JsonData();
  245. json["type"] = "ActiveVideo";
  246. json["Sid"] = "sid";//选择的场景id
  247. json["spid"] = spid;//景点id
  248. json["videoId"] = videoId;//视频id
  249. json["isplay"] = isplay;//是否播放
  250. json["jindu"] = jindu;//视频进度
  251. publish(rid,Encoding.UTF8.GetBytes(json.ToJson()));
  252. Debug.Log("MQtt 发送manage");
  253. }
  254. void publish(string str,byte[] bs)
  255. {
  256. if(qt!=null&& qt.IsConnect())
  257. {
  258. // Debug.Log(id + " DGJ publish =====> " + front+rid + " " + bs.Length);
  259. qt.Publish(str, bs, MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
  260. }
  261. else
  262. {
  263. Debug.LogError(" MQTT 未连接 ");
  264. }
  265. }
  266. }