MQTTManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. using LitJson;
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using UnityEngine;
  10. using UnityEngine.Networking;
  11. using uPLibrary.Networking.M2Mqtt.Messages;
  12. using Vuplex.WebView;
  13. public class MQTTManager : MonoBehaviour
  14. {
  15. public PanelController p;
  16. public static MQTTManager Instance;
  17. public string front = "client/";
  18. public string id = "";
  19. public string username = "u@unity3";// 需要根据服务器设置
  20. public string password = null;// 需要根据服务器设置
  21. public string rid = "mqttx_b4c02ddc"; //其他人的ID
  22. public string clientId = "";
  23. public string account;
  24. public string roomId;
  25. public string email;
  26. public string phone;
  27. public string roleId;
  28. // public string resourcePool;
  29. public string resourcePoolId;
  30. public string expertType;
  31. public string _username;
  32. public string room;
  33. public static string certification;
  34. public string topiceNavigation;
  35. public string topiceSync;
  36. public string topiceClose;
  37. public bool isCreateRoom = false;
  38. bool isinitCRoom = true;
  39. private int SignalCount = 0;
  40. private void Awake()
  41. {
  42. Instance = this;
  43. }
  44. private void Update()
  45. {
  46. if(isCreateRoom&& isinitCRoom)
  47. {
  48. isinitCRoom = false;
  49. StartCoroutine(CreateRoom());
  50. }
  51. }
  52. private void Start()
  53. {
  54. Signal();
  55. }
  56. private IEnumerator CreateRoom()
  57. {
  58. yield return new WaitForSeconds(1);
  59. // UICallManager.Instance.EventInvite("", "");
  60. }
  61. /// <summary>
  62. /// 获取信令
  63. /// </summary>
  64. public void Signal()
  65. {
  66. Post("https://api-fat2.ghz-tech.com" + "/cmcc-endustry/v1/signal/certification", "", SignalCallBack);
  67. SignalCount++;
  68. /*
  69. JsonData joindata = new JsonData();
  70. joindata["roomId"] = "734101";
  71. Post("https://api-fat2.ghz-tech.com" + "/cmcc-endustry/v1/rtc/joinRoom", joindata.ToJson(), (string data)=> {
  72. Debug.Log("1111112312312312312"+ data);
  73. });*/
  74. // GameStart.Instance.StartCoroutine(HttpTool.Instance.SendHttp(HttpActionLang.userinfo, "", UserInfoCallBack));
  75. // HttpTool.Instance.PostMqtt(HttpAction.signal_certification, "", SignalCallBack);
  76. }
  77. private Dictionary<string, string> requestHeader = new Dictionary<string, string>();
  78. public Dictionary<string, string> RequestHeader => requestHeader;
  79. public void Post(string methodName, string jsonString, Action<string> CallBack)
  80. {
  81. StartCoroutine(SendHttp(methodName, jsonString, CallBack));
  82. }
  83. public void initHead(string ContentType)
  84. {
  85. requestHeader.Clear();
  86. requestHeader.Add("authorization", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjQ4NzQxMTY1MDIsImlhdCI6MTcyMDUxNjUwMiwidXNlciI6eyJpZCI6MTA5MiwiZW1haWwiOiIiLCJwaG9uZSI6InprZGVtbyIsIm5hbWUiOiJ6a2RlbW8iLCJyb2xlSWQiOjF9fQ.OZ2HDUp9F5S504cmCUh7Ai15sq_nQ5i7ZG_odxhqGGM");
  87. requestHeader.Add("Content-Type", ContentType);
  88. }
  89. public IEnumerator SendHttp(string methodName, string jsonString, Action<string> CallBack, string ContentType = "application/json", bool isPost = true)
  90. {
  91. Debug.Log("Start Queue SendHttp " + methodName);
  92. string text = (!methodName.Contains("http")) ? ("https://api-fat2.ghz-tech.com" + methodName) : methodName;
  93. Debug.Log("URL:" + text + " isPost " + isPost);
  94. UnityWebRequest webRequest = isPost ? new UnityWebRequest(text, "POST") : UnityWebRequest.Get(text);
  95. initHead(ContentType);
  96. using (webRequest)
  97. {
  98. if (!isPost)
  99. {
  100. webRequest.downloadHandler = new DownloadHandlerBuffer();
  101. foreach (KeyValuePair<string, string> item in requestHeader)
  102. {
  103. webRequest.SetRequestHeader(item.Key, item.Value);
  104. }
  105. }
  106. else
  107. {
  108. byte[] bytes = Encoding.UTF8.GetBytes(jsonString);
  109. webRequest.uploadHandler = new UploadHandlerRaw(bytes);
  110. webRequest.downloadHandler = new DownloadHandlerBuffer();
  111. }
  112. foreach (KeyValuePair<string, string> item2 in requestHeader)
  113. {
  114. webRequest.SetRequestHeader(item2.Key, item2.Value);
  115. }
  116. yield return webRequest.SendWebRequest();
  117. Debug.Log("CallBack==>" + webRequest.downloadHandler.text);
  118. if (webRequest.isHttpError || webRequest.isNetworkError)
  119. {
  120. string text2 = webRequest.downloadHandler.text;
  121. CallBack(text2);
  122. }
  123. else
  124. {
  125. string text3 = webRequest.downloadHandler.text;
  126. CallBack(text3);
  127. }
  128. }
  129. }
  130. public void SetAccoutInfo(string account)
  131. {
  132. MQTTManager.Instance.account = account;
  133. }
  134. public static string host;
  135. private void SignalCallBack(string msg)
  136. {
  137. Debug.Log("SignalCallBack " + msg);
  138. JObject obj = JObject.Parse(msg);
  139. if (obj["code"].ToString() == "200")
  140. {
  141. host = obj["data"]["host"].ToString();
  142. // HttpActionLang.Instance.mqttPort = obj["data"]["port"].ToString();
  143. MQTTManager.certification = obj["data"]["certification"].ToString();
  144. MQTTManager.Instance.front = obj["data"]["topicPrefix"].ToString();
  145. MQTTManager.Instance.clientId = obj["data"]["clientId"].ToString();
  146. MQTTManager.Instance.username = obj["data"]["username"].ToString();
  147. p.HandleConnect(host,"", clientId, username, certification, front);
  148. //if (!string.IsNullOrEmpty( obj["data"]["uinoTopics"].ToString()))
  149. //{
  150. // topiceNavigation = obj["data"]["uinoTopics"]["navigation"].ToString();
  151. // topiceSync = obj["data"]["uinoTopics"]["sync"].ToString();
  152. // topiceClose = obj["data"]["uinoTopics"]["close"].ToString();
  153. //}
  154. // ErrorPopup.Instance.UpdateEmqxState(NetState.Connecting);
  155. // MQTTClient.Instance.Connect(host);
  156. SignalCount = 0;
  157. // StartCoroutine(TestCreateRoom());
  158. }
  159. else
  160. {
  161. Debug.LogError("MQTT 获取信令失败 !!!" + obj["code"].ToString());
  162. if(int.Parse(obj["code"].ToString())>= 500)
  163. {
  164. //ErrorPopup.Instance.UpdateEmqxState(NetState.DisConnect);
  165. //ErrorPopup.Instance.ShowEmqxError("服务器连接失败 "+ msg, -1);
  166. }
  167. else
  168. {
  169. // ErrorPopup.Instance.UpdateEmqxState(NetState.StartError);
  170. if (SignalCount > 5)
  171. {
  172. // ErrorPopup.Instance.ShowEmqxError("信令请求失败 " + msg , -1);
  173. }
  174. else
  175. {
  176. Signal();
  177. }
  178. }
  179. }
  180. }
  181. private IEnumerator TestCreateRoom()
  182. {
  183. yield return new WaitForSeconds(5);
  184. }
  185. private void UserInfoCallBack(string msg)
  186. {
  187. Debug.Log(msg);
  188. JObject obj = JObject.Parse(msg);
  189. if (obj["code"].ToString() == "200")
  190. {
  191. MQTTManager.Instance._username = obj["data"]["name"].ToString();
  192. MQTTManager.Instance.roleId = obj["data"]["roleId"].ToString();
  193. MQTTManager.Instance.email = obj["data"]["email"].ToString();
  194. MQTTManager.Instance.phone = obj["data"]["phone"].ToString();
  195. // MQTTManager.Instance.resourcePool = obj["data"]["resourcePool"].ToString();
  196. MQTTManager.Instance.resourcePoolId = obj["data"]["resourcePoolId"].ToString();
  197. MQTTManager.Instance.expertType = obj["data"]["expertType"].ToString();
  198. }
  199. else
  200. {
  201. Debug.LogError("获取用户信息失败 !!!"+ obj["code"].ToString());
  202. }
  203. }
  204. public void SetRoomId(string id)
  205. {
  206. MQTTManager.Instance.roomId = id;
  207. // MQTTClient.Instance.roomId = "9527";
  208. // 订阅房间频道
  209. // MQTTClient.Instance.Subscribe(MQTTManager.Instance.front + "room/" + id);
  210. }
  211. public void UnSubscribe( string id)
  212. {
  213. // MQTTClient.Instance.UnSubscribe(MQTTManager.Instance.front + "room/" + id);
  214. }
  215. /// <summary>
  216. /// 发送消息
  217. /// </summary>
  218. /// <param name="msg"></param>
  219. public void PushMsg(string msg)
  220. {
  221. if (!string.IsNullOrEmpty(msg))
  222. {
  223. JsonData json = new JsonData();
  224. json["account"] = MQTTManager.Instance.account;
  225. json["Sid"] = "sid";//选择的场景id
  226. json["msg"] = msg;
  227. // MQTTClient.Instance.publish(Encoding.UTF8.GetBytes(json.ToJson()));
  228. }
  229. }
  230. /// <summary>
  231. /// 发送消息
  232. /// </summary>
  233. /// <param name="msg"></param>
  234. public void PushMsg(string channelID, string msg)
  235. {
  236. Debug.Log("DGJ ===> MQTT Test "+ msg);
  237. if (!string.IsNullOrEmpty(msg))
  238. {
  239. // MQTTClient.Instance.publish(channelID, Encoding.UTF8.GetBytes(msg));
  240. }
  241. }
  242. /// <summary>
  243. /// 接受消息
  244. /// </summary>
  245. /// <param name="msg"></param>
  246. public void Received(string msg)
  247. {
  248. JObject obj = JObject.Parse(msg);
  249. // Debug.Log("Received ===> " + obj["action"].ToString());
  250. if(obj["action"]!=null)
  251. switch (obj["action"].ToString())
  252. {
  253. case "timeout": // 超时
  254. // UICallManager.Instance.EventTimeOut();
  255. break;
  256. case "invite": // 邀请
  257. break;
  258. case "noExpert": // 无专家
  259. // UICallManager.Instance.EventNoExpert();
  260. break;
  261. case "chat": // 聊天消息
  262. // 拆解用户名 和 聊天内容 显示到聊天框里
  263. string username = obj["from"].ToString();
  264. string chatMsg = obj["chatMessage"].ToString();
  265. break;
  266. case "share": // 接受文件
  267. break;
  268. case "remark": // 空间标注
  269. float Valuex = float.Parse(obj["chatMessage"]["x"].ToString());
  270. float Valuey = float.Parse(obj["chatMessage"]["y"].ToString());
  271. break;
  272. case "clearRemark":
  273. break;
  274. case "leave":
  275. // 退出房间
  276. string roleId = obj["roleId"].ToString();
  277. if (roleId == "2")
  278. {
  279. // RTCRoomManager.Instance.UserOffline(UserEnum.Expert);
  280. }
  281. if (roleId == "1")
  282. {
  283. // RTCRoomManager.Instance.UserOffline(UserEnum.Conterl);
  284. }
  285. break;
  286. case "stop":
  287. // 停止同步位置信息
  288. break;
  289. default:
  290. break;
  291. }
  292. if (obj["image_data"]!=null&&!string.IsNullOrEmpty( obj["image_data"].ToString()))
  293. {
  294. // LangChaoMailManager.Instance.ReceiverMail(obj);
  295. }
  296. }
  297. public void Received(MqttMsgPublishEventArgs MsgData)
  298. {
  299. string msg = Encoding.UTF8.GetString(MsgData.Message);
  300. JObject obj = JObject.Parse(msg);
  301. // Debug.Log("Received ===> " + obj["action"].ToString());
  302. if (obj["action"] != null)
  303. switch (obj["action"].ToString())
  304. {
  305. case "timeout": // 超时
  306. // UICallManager.Instance.EventTimeOut();
  307. break;
  308. case "invite": // 邀请
  309. break;
  310. case "noExpert": // 无专家
  311. // UICallManager.Instance.EventNoExpert();
  312. break;
  313. case "chat": // 聊天消息
  314. // 拆解用户名 和 聊天内容 显示到聊天框里
  315. string username = obj["from"].ToString();
  316. string chatMsg = obj["chatMessage"].ToString();
  317. break;
  318. case "share": // 接受文件
  319. break;
  320. case "remark": // 空间标注
  321. break;
  322. case "clearRemark":
  323. break;
  324. case "leave":
  325. // 退出房间
  326. string roleId = obj["roleId"].ToString();
  327. if (roleId == "2")
  328. {
  329. // RTCRoomManager.Instance.UserOffline(UserEnum.Expert);
  330. }
  331. if (roleId == "1")
  332. {
  333. // RTCRoomManager.Instance.UserOffline(UserEnum.Conterl);
  334. }
  335. break;
  336. default:
  337. break;
  338. }
  339. switch (MsgData.Topic)
  340. {
  341. case "yunyi/coordinate/close":
  342. if (obj["action"] != null&& (obj["action"].ToString()== "stop"))
  343. {
  344. // 停止同步位置信息
  345. // MailUIContent.Instance.CloseSync.SetActive(false);
  346. }
  347. break;
  348. case "yunyi/navigation/diagram":
  349. if (obj["image_data"] != null && !string.IsNullOrEmpty(obj["image_data"].ToString()))
  350. {
  351. // UILogManager.Instance.text2.text = msg;
  352. //MailUIContent.Instance.CloseSync.SetActive(true);
  353. //LangChaoMailManager.Instance.ReceiverMail(obj);
  354. }
  355. break;
  356. default:
  357. break;
  358. }
  359. }
  360. }