using LitJson; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using UnityEngine; using UnityEngine.Networking; using uPLibrary.Networking.M2Mqtt.Messages; using Vuplex.WebView; public class MQTTManager : MonoBehaviour { public PanelController p; public static MQTTManager Instance; public string front = "client/"; public string id = ""; public string username = "u@unity3";// 需要根据服务器设置 public string password = null;// 需要根据服务器设置 public string rid = "mqttx_b4c02ddc"; //其他人的ID public string clientId = ""; public string account; public string roomId; public string email; public string phone; public string roleId; // public string resourcePool; public string resourcePoolId; public string expertType; public string _username; public string room; public static string certification; public string topiceNavigation; public string topiceSync; public string topiceClose; public bool isCreateRoom = false; bool isinitCRoom = true; private int SignalCount = 0; private void Awake() { Instance = this; } private void Update() { if(isCreateRoom&& isinitCRoom) { isinitCRoom = false; StartCoroutine(CreateRoom()); } } private void Start() { Signal(); } private IEnumerator CreateRoom() { yield return new WaitForSeconds(1); // UICallManager.Instance.EventInvite("", ""); } /// /// 获取信令 /// public void Signal() { Post("https://api-fat2.ghz-tech.com" + "/cmcc-endustry/v1/signal/certification", "", SignalCallBack); SignalCount++; /* JsonData joindata = new JsonData(); joindata["roomId"] = "734101"; Post("https://api-fat2.ghz-tech.com" + "/cmcc-endustry/v1/rtc/joinRoom", joindata.ToJson(), (string data)=> { Debug.Log("1111112312312312312"+ data); });*/ // GameStart.Instance.StartCoroutine(HttpTool.Instance.SendHttp(HttpActionLang.userinfo, "", UserInfoCallBack)); // HttpTool.Instance.PostMqtt(HttpAction.signal_certification, "", SignalCallBack); } private Dictionary requestHeader = new Dictionary(); public Dictionary RequestHeader => requestHeader; public void Post(string methodName, string jsonString, Action CallBack) { StartCoroutine(SendHttp(methodName, jsonString, CallBack)); } public void initHead(string ContentType) { requestHeader.Clear(); requestHeader.Add("authorization", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjQ4NzQxMTY1MDIsImlhdCI6MTcyMDUxNjUwMiwidXNlciI6eyJpZCI6MTA5MiwiZW1haWwiOiIiLCJwaG9uZSI6InprZGVtbyIsIm5hbWUiOiJ6a2RlbW8iLCJyb2xlSWQiOjF9fQ.OZ2HDUp9F5S504cmCUh7Ai15sq_nQ5i7ZG_odxhqGGM"); requestHeader.Add("Content-Type", ContentType); } public IEnumerator SendHttp(string methodName, string jsonString, Action CallBack, string ContentType = "application/json", bool isPost = true) { Debug.Log("Start Queue SendHttp " + methodName); string text = (!methodName.Contains("http")) ? ("https://api-fat2.ghz-tech.com" + methodName) : methodName; Debug.Log("URL:" + text + " isPost " + isPost); UnityWebRequest webRequest = isPost ? new UnityWebRequest(text, "POST") : UnityWebRequest.Get(text); initHead(ContentType); using (webRequest) { if (!isPost) { webRequest.downloadHandler = new DownloadHandlerBuffer(); foreach (KeyValuePair item in requestHeader) { webRequest.SetRequestHeader(item.Key, item.Value); } } else { byte[] bytes = Encoding.UTF8.GetBytes(jsonString); webRequest.uploadHandler = new UploadHandlerRaw(bytes); webRequest.downloadHandler = new DownloadHandlerBuffer(); } foreach (KeyValuePair item2 in requestHeader) { webRequest.SetRequestHeader(item2.Key, item2.Value); } yield return webRequest.SendWebRequest(); Debug.Log("CallBack==>" + webRequest.downloadHandler.text); if (webRequest.isHttpError || webRequest.isNetworkError) { string text2 = webRequest.downloadHandler.text; CallBack(text2); } else { string text3 = webRequest.downloadHandler.text; CallBack(text3); } } } public void SetAccoutInfo(string account) { MQTTManager.Instance.account = account; } public static string host; private void SignalCallBack(string msg) { Debug.Log("SignalCallBack " + msg); JObject obj = JObject.Parse(msg); if (obj["code"].ToString() == "200") { host = obj["data"]["host"].ToString(); // HttpActionLang.Instance.mqttPort = obj["data"]["port"].ToString(); MQTTManager.certification = obj["data"]["certification"].ToString(); MQTTManager.Instance.front = obj["data"]["topicPrefix"].ToString(); MQTTManager.Instance.clientId = obj["data"]["clientId"].ToString(); MQTTManager.Instance.username = obj["data"]["username"].ToString(); p.HandleConnect(host,"", clientId, username, certification, front); //if (!string.IsNullOrEmpty( obj["data"]["uinoTopics"].ToString())) //{ // topiceNavigation = obj["data"]["uinoTopics"]["navigation"].ToString(); // topiceSync = obj["data"]["uinoTopics"]["sync"].ToString(); // topiceClose = obj["data"]["uinoTopics"]["close"].ToString(); //} // ErrorPopup.Instance.UpdateEmqxState(NetState.Connecting); // MQTTClient.Instance.Connect(host); SignalCount = 0; // StartCoroutine(TestCreateRoom()); } else { Debug.LogError("MQTT 获取信令失败 !!!" + obj["code"].ToString()); if(int.Parse(obj["code"].ToString())>= 500) { //ErrorPopup.Instance.UpdateEmqxState(NetState.DisConnect); //ErrorPopup.Instance.ShowEmqxError("服务器连接失败 "+ msg, -1); } else { // ErrorPopup.Instance.UpdateEmqxState(NetState.StartError); if (SignalCount > 5) { // ErrorPopup.Instance.ShowEmqxError("信令请求失败 " + msg , -1); } else { Signal(); } } } } private IEnumerator TestCreateRoom() { yield return new WaitForSeconds(5); } private void UserInfoCallBack(string msg) { Debug.Log(msg); JObject obj = JObject.Parse(msg); if (obj["code"].ToString() == "200") { MQTTManager.Instance._username = obj["data"]["name"].ToString(); MQTTManager.Instance.roleId = obj["data"]["roleId"].ToString(); MQTTManager.Instance.email = obj["data"]["email"].ToString(); MQTTManager.Instance.phone = obj["data"]["phone"].ToString(); // MQTTManager.Instance.resourcePool = obj["data"]["resourcePool"].ToString(); MQTTManager.Instance.resourcePoolId = obj["data"]["resourcePoolId"].ToString(); MQTTManager.Instance.expertType = obj["data"]["expertType"].ToString(); } else { Debug.LogError("获取用户信息失败 !!!"+ obj["code"].ToString()); } } public void SetRoomId(string id) { MQTTManager.Instance.roomId = id; // MQTTClient.Instance.roomId = "9527"; // 订阅房间频道 // MQTTClient.Instance.Subscribe(MQTTManager.Instance.front + "room/" + id); } public void UnSubscribe( string id) { // MQTTClient.Instance.UnSubscribe(MQTTManager.Instance.front + "room/" + id); } /// /// 发送消息 /// /// public void PushMsg(string msg) { if (!string.IsNullOrEmpty(msg)) { JsonData json = new JsonData(); json["account"] = MQTTManager.Instance.account; json["Sid"] = "sid";//选择的场景id json["msg"] = msg; // MQTTClient.Instance.publish(Encoding.UTF8.GetBytes(json.ToJson())); } } /// /// 发送消息 /// /// public void PushMsg(string channelID, string msg) { Debug.Log("DGJ ===> MQTT Test "+ msg); if (!string.IsNullOrEmpty(msg)) { // MQTTClient.Instance.publish(channelID, Encoding.UTF8.GetBytes(msg)); } } /// /// 接受消息 /// /// public void Received(string msg) { JObject obj = JObject.Parse(msg); // Debug.Log("Received ===> " + obj["action"].ToString()); if(obj["action"]!=null) switch (obj["action"].ToString()) { case "timeout": // 超时 // UICallManager.Instance.EventTimeOut(); break; case "invite": // 邀请 break; case "noExpert": // 无专家 // UICallManager.Instance.EventNoExpert(); break; case "chat": // 聊天消息 // 拆解用户名 和 聊天内容 显示到聊天框里 string username = obj["from"].ToString(); string chatMsg = obj["chatMessage"].ToString(); break; case "share": // 接受文件 break; case "remark": // 空间标注 float Valuex = float.Parse(obj["chatMessage"]["x"].ToString()); float Valuey = float.Parse(obj["chatMessage"]["y"].ToString()); break; case "clearRemark": break; case "leave": // 退出房间 string roleId = obj["roleId"].ToString(); if (roleId == "2") { // RTCRoomManager.Instance.UserOffline(UserEnum.Expert); } if (roleId == "1") { // RTCRoomManager.Instance.UserOffline(UserEnum.Conterl); } break; case "stop": // 停止同步位置信息 break; default: break; } if (obj["image_data"]!=null&&!string.IsNullOrEmpty( obj["image_data"].ToString())) { // LangChaoMailManager.Instance.ReceiverMail(obj); } } public void Received(MqttMsgPublishEventArgs MsgData) { string msg = Encoding.UTF8.GetString(MsgData.Message); JObject obj = JObject.Parse(msg); // Debug.Log("Received ===> " + obj["action"].ToString()); if (obj["action"] != null) switch (obj["action"].ToString()) { case "timeout": // 超时 // UICallManager.Instance.EventTimeOut(); break; case "invite": // 邀请 break; case "noExpert": // 无专家 // UICallManager.Instance.EventNoExpert(); break; case "chat": // 聊天消息 // 拆解用户名 和 聊天内容 显示到聊天框里 string username = obj["from"].ToString(); string chatMsg = obj["chatMessage"].ToString(); break; case "share": // 接受文件 break; case "remark": // 空间标注 break; case "clearRemark": break; case "leave": // 退出房间 string roleId = obj["roleId"].ToString(); if (roleId == "2") { // RTCRoomManager.Instance.UserOffline(UserEnum.Expert); } if (roleId == "1") { // RTCRoomManager.Instance.UserOffline(UserEnum.Conterl); } break; default: break; } switch (MsgData.Topic) { case "yunyi/coordinate/close": if (obj["action"] != null&& (obj["action"].ToString()== "stop")) { // 停止同步位置信息 // MailUIContent.Instance.CloseSync.SetActive(false); } break; case "yunyi/navigation/diagram": if (obj["image_data"] != null && !string.IsNullOrEmpty(obj["image_data"].ToString())) { // UILogManager.Instance.text2.text = msg; //MailUIContent.Instance.CloseSync.SetActive(true); //LangChaoMailManager.Instance.ReceiverMail(obj); } break; default: break; } } }