THupload-Oss
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

373 lines
17KB

  1. using Newtonsoft.Json;
  2. using System;
  3. using log4net;
  4. using log4net.Config;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using uPLibrary.Networking.M2Mqtt.Messages;
  10. using uPLibrary.Networking.M2Mqtt;
  11. using System.Runtime.InteropServices;
  12. using System.Reflection;
  13. using System.Net.Http;
  14. using System.Web.UI.WebControls;
  15. using System.Threading;
  16. using static THUploadOss.Common;
  17. using System.Net;
  18. using System.IO;
  19. using Newtonsoft.Json.Linq;
  20. namespace THUploadOss
  21. {
  22. public class THMqttClinet
  23. {
  24. public MqttClient mqttClient;
  25. public string m_brokerAddress; // MQTT Broker的地址 106.15.120.154 "192.168.253.130"
  26. public int m_brokerPort; // MQTT Broker的端口号
  27. public string m_clientId; // 客户端的ID,机场编号
  28. public string m_airportCode; // 控制编号
  29. public string m_username; // MQTT Broker的用户名
  30. public string m_password; // MQTT Broker的密码
  31. public string m_uploadSubTopic; // 文件上传订阅 topic
  32. public string m_uploadResTopic; // 文件上传响应 topic
  33. public string m_rtmpSubTic; // rtmp订阅 topic
  34. public string m_rtmpResTopic; // rtmp响应 topic
  35. private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  36. public void MqttClient_MqttMsgPublished(object sender, MqttMsgPublishedEventArgs e)
  37. {
  38. //Console.WriteLine("[" + DateTime.Now.ToString() + "]" + "消息已发布!");
  39. //log.Info("[" + DateTime.Now.ToString() + "]" + "主题:" + msg.Topic + " 收到消息:" + jsonObj.command + " " + jsonObj.requestId);
  40. //发布时会触发:用来记录发布的日志??????????????????????
  41. }
  42. public void MqttClient_MqttMsgReceived(object sender, MqttMsgPublishEventArgs msg)
  43. {
  44. string message = Encoding.UTF8.GetString(msg.Message);
  45. dynamic jsonObj = JsonConvert.DeserializeObject(message);
  46. Logger.WriteInfo("THMqttClinet: MqttClient_MqttMsgReceived-主题:" + msg.Topic + " 收到消息:" + message);
  47. if (msg.Topic == m_uploadSubTopic && jsonObj.command == "start" )//有任务正在执行中,则不能执行此操作需要返回????????????????
  48. {
  49. if (StsrtDownload != -1)
  50. {
  51. Logger.WriteInfo("THMqttClinet: 有任务正在进行中,MqttClient_MqttMsgReceived-主题:" + msg.Topic + " 收到消息:" + message);
  52. return;
  53. }
  54. RequestId = jsonObj.requestId;
  55. DownloadFinsh = 0;
  56. StsrtDownload = 1;
  57. Status = (int)UPLOAD_STATUS.Preparation;
  58. lock (lockFileList)
  59. {
  60. for (int i = FileList.Count - 1; i >= 0; i--)
  61. {
  62. FileList.Remove(FileList[i]);
  63. }
  64. }
  65. }
  66. if (msg.Topic == m_uploadSubTopic && jsonObj.command == "stop")
  67. {
  68. DownloadFinsh = -1;
  69. StsrtDownload = -1;
  70. //Status = (int)UPLOAD_STATUS.Ccancellation;
  71. }
  72. if (msg.Topic == m_rtmpSubTic && jsonObj.command == "start")
  73. {
  74. if (OpenRtmpChannel())
  75. PublishRtmpTopic((int)TRMP.RTMP_OK);
  76. else
  77. PublishRtmpTopic((int)TRMP.RTMP_START_ACTION_FAIL);
  78. }
  79. if (msg.Topic == m_rtmpSubTic && jsonObj.command == "stop")
  80. {
  81. if (CloseRtmpChannel())
  82. PublishRtmpTopic((int)TRMP.RTMP_OK);
  83. else
  84. PublishRtmpTopic((int)TRMP.RTMP_STOP_ACTION_FAIL);
  85. }
  86. }
  87. public bool InitMqttClient()
  88. {
  89. if (!getMqttConfig())
  90. return false;
  91. try
  92. {
  93. mqttClient = new MqttClient(m_brokerAddress, m_brokerPort, false, null, null, MqttSslProtocols.None);
  94. mqttClient.MqttMsgPublished += MqttClient_MqttMsgPublished;
  95. mqttClient.MqttMsgPublishReceived += MqttClient_MqttMsgReceived;
  96. if(MqttConnect())
  97. return true;
  98. else
  99. return false;
  100. }
  101. catch (Exception ex)
  102. {
  103. Logger.WriteError("THMqttClinet: InitMqttClient-MQTT发生错误:" + ex.Message.ToString());
  104. System.Threading.Thread.Sleep(1000);
  105. return false;
  106. }
  107. }
  108. public bool MqttConnect()
  109. {
  110. try
  111. {
  112. mqttClient.Connect(m_clientId, m_username, m_password);
  113. System.Threading.Thread.Sleep(2000);
  114. if (mqttClient.IsConnected)
  115. {
  116. mqttClient.Subscribe(new string[] { m_uploadSubTopic }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
  117. mqttClient.Subscribe(new string[] { m_rtmpSubTic }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
  118. Logger.WriteInfo("THMqttClinet: MqttConnect-连接到MQTT Broker");
  119. return true;
  120. }
  121. else
  122. {
  123. Logger.WriteError("THMqttClinet: MqttConnect-无法连接到MQTT Broker!");
  124. System.Threading.Thread.Sleep(1000);
  125. return false;
  126. }
  127. }
  128. catch (Exception ex)
  129. {
  130. Logger.WriteError("THMqttClinet: MqttConnect-MQTT发生错误:" + ex.Message);
  131. System.Threading.Thread.Sleep(1000);
  132. return false;
  133. }
  134. }
  135. public int PublishUploadTopic()
  136. {
  137. Logger.WriteError("MQTT PublishUploadTopic: StsrtDownload:" + StsrtDownload + "Status:"+ Status);
  138. if (StsrtDownload != -1 || Status != (int)UPLOAD_STATUS.Preparation)
  139. {
  140. JObject data = new JObject
  141. {
  142. { "requestId", RequestId },
  143. { "errorCode", "" },
  144. { "errorMsg", "" },
  145. { "status", Status },// 状态:待执行 5 执行中 10 完成 15 超时 20 失败 25
  146. { "currentTime", DateTime.Now.ToString() }
  147. };
  148. JArray imgjArray = new JArray();
  149. JArray videojArray = new JArray();
  150. lock (lockFileList)
  151. {
  152. foreach (FileStates file in FileList)
  153. {
  154. if (file.fileType == "pic")
  155. {
  156. JObject img = new JObject
  157. {
  158. { "fileName", file.fileName},
  159. { "imageUrl",file.url },
  160. { "status",file.status },
  161. { "progress",file.progress}
  162. };
  163. imgjArray.Add(img);
  164. }
  165. if (file.fileType == "video")
  166. {
  167. JObject video = new JObject
  168. {
  169. { "fileName", file.fileName},
  170. { "videoUrl",file.url },
  171. { "status",file.status },
  172. { "progress",file.progress }
  173. };
  174. videojArray.Add(video);
  175. }
  176. }
  177. }
  178. data.Add("imageList", new JArray(imgjArray));
  179. data.Add("videoList", new JArray(videojArray));
  180. // 将对象序列化为 JSON 字符串
  181. string json = JsonConvert.SerializeObject(data);
  182. Logger.WriteInfo("THMqttClinet: PublishUploadTopic:" + json);
  183. mqttClient.Publish(m_uploadResTopic, Encoding.UTF8.GetBytes(json), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);
  184. if (Status == (int)UPLOAD_STATUS.Complete)
  185. Status = (int)UPLOAD_STATUS.Preparation;
  186. if (Status == (int)UPLOAD_STATUS.Fail)
  187. Status = (int)UPLOAD_STATUS.Preparation;
  188. if (Status == (int)UPLOAD_STATUS.Ccancellation)
  189. Status = (int)UPLOAD_STATUS.Preparation;
  190. }
  191. System.Threading.Thread.Sleep(5000);
  192. return 0;
  193. }
  194. public int PublishRtmpTopic(int ret)
  195. {
  196. var data = new { code = ret , msg = RTMP_RESULT[ret], data = "null" };
  197. string json = JsonConvert.SerializeObject(data);
  198. Logger.WriteInfo("THMqttClinet: PublishRtmpTopic:" + json);
  199. mqttClient.Publish(m_rtmpResTopic, Encoding.UTF8.GetBytes(json), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);
  200. return 0;
  201. }
  202. public bool CloseRtmpChannel()
  203. {
  204. // 创建HttpClient实例
  205. HttpClient client = new HttpClient();
  206. try
  207. {
  208. // 发送GET请求并获取响应
  209. HttpResponseMessage response = client.GetAsync("http://localhost:19610/api/v1/getChannelList?offset=0&row=50").Result;
  210. // 检查响应是否成功
  211. if (response.IsSuccessStatusCode)
  212. {
  213. // 读取响应内容
  214. string content = response.Content.ReadAsStringAsync().Result;
  215. Logger.WriteInfo("CloseRtmpChannel: "+content);
  216. dynamic jsonObj = JsonConvert.DeserializeObject(content);
  217. string srcURL = jsonObj.ChannelList[0].srcURL;
  218. srcURL = WebUtility.UrlEncode(srcURL).Replace("%3A", ":");
  219. string dstURL = jsonObj.ChannelList[0].dstURL;
  220. dstURL = WebUtility.UrlEncode(dstURL).Replace("%3A", ":");
  221. string closeUrl = "http://127.0.0.1:19610/api/v1/updateChannel?indexCode=" + jsonObj.ChannelList[0].indexcode + "&name=" + jsonObj.ChannelList[0].name + "&srcURL=%22" + srcURL + "%22&connectType=" + jsonObj.ChannelList[0].connectType + "&timeout=" + jsonObj.ChannelList[0].connectTimeout + "&mediaType=video" + "&dstURL=" + dstURL + "&dstFormat=rtmp&enable=false";
  222. // 输出响应内容
  223. HttpResponseMessage closeResponse = client.GetAsync(closeUrl).Result;
  224. if (closeResponse.IsSuccessStatusCode)
  225. {
  226. string closeContent = closeResponse.Content.ReadAsStringAsync().Result;
  227. Logger.WriteInfo("CloseRtmpChannel: "+closeContent);
  228. if (closeContent == "OK")
  229. return true;
  230. else
  231. return false;
  232. }
  233. }
  234. else
  235. {
  236. Logger.WriteError("THMqttClinet: CloseRtmpChannel-请求失败,状态码:" + response.StatusCode);
  237. return false;
  238. }
  239. }
  240. catch (Exception e)
  241. {
  242. Logger.WriteError($"THMqttClinet: CloseRtmpChannel-其他错误发生: {e.Message}");
  243. return false;
  244. }
  245. return false;
  246. }
  247. public bool OpenRtmpChannel()
  248. {
  249. // 创建HttpClient实例
  250. HttpClient client = new HttpClient();
  251. try
  252. {
  253. // 发送GET请求并获取响应
  254. HttpResponseMessage response = client.GetAsync("http://localhost:19610/api/v1/getChannelList?offset=0&row=50").Result;
  255. // 检查响应是否成功
  256. if (response.IsSuccessStatusCode)
  257. {
  258. // 读取响应内容
  259. string content = response.Content.ReadAsStringAsync().Result;
  260. // 输出响应内容
  261. Logger.WriteInfo("OpenRtmpChannel: "+content);
  262. dynamic jsonObj = JsonConvert.DeserializeObject(content);
  263. string srcURL = jsonObj.ChannelList[0].srcURL;
  264. srcURL = WebUtility.UrlEncode(srcURL).Replace("%3A", ":");
  265. string dstURL = jsonObj.ChannelList[0].dstURL;
  266. dstURL = WebUtility.UrlEncode(dstURL).Replace("%3A", ":");
  267. string openUrl = "http://127.0.0.1:19610/api/v1/updateChannel?indexCode=" + jsonObj.ChannelList[0].indexcode + "&name=" + jsonObj.ChannelList[0].name + "&srcURL=%22" + srcURL + "%22&connectType=" + jsonObj.ChannelList[0].connectType + "&timeout=" + jsonObj.ChannelList[0].connectTimeout + "&mediaType=video" + "&dstURL=" + dstURL + "&dstFormat=rtmp&enable=true";
  268. // 输出响应内容
  269. HttpResponseMessage openResponse = client.GetAsync(openUrl).Result;
  270. if (openResponse.IsSuccessStatusCode)
  271. {
  272. string closeContent = openResponse.Content.ReadAsStringAsync().Result;
  273. Logger.WriteInfo("OpenRtmpChannel: "+closeContent);
  274. if (closeContent == "OK")
  275. return true;
  276. else
  277. return false;
  278. }
  279. }
  280. else
  281. {
  282. Logger.WriteError("THMqttClinet: OpenRtmpChannel-请求失败,状态码:" + response.StatusCode);
  283. return false;
  284. }
  285. }
  286. catch (Exception e)
  287. {
  288. Logger.WriteError($"THMqttClinet: OpenRtmpChannel-其他错误发生: {e.Message}");
  289. return false;
  290. }
  291. return false;
  292. }
  293. public bool getMqttConfig()
  294. {
  295. if (System.IO.File.Exists(ConfigPath))
  296. {
  297. try {
  298. StringBuilder brokerAddress = new StringBuilder(20);
  299. GetPrivateProfileString("MQTT", "brokerAddress", "配置文件存在,读取未成功!", brokerAddress, 255, ConfigPath);
  300. m_brokerAddress = brokerAddress.ToString();
  301. StringBuilder brokerPort = new StringBuilder(20);
  302. GetPrivateProfileString("MQTT", "brokerPort", "配置文件存在,读取未成功!", brokerPort, 255, ConfigPath);
  303. m_brokerPort = int.Parse(brokerPort.ToString());
  304. StringBuilder airportCode = new StringBuilder(100);
  305. GetPrivateProfileString("MQTT", "airportCode", "配置文件存在,读取未成功!", airportCode, 255, ConfigPath);
  306. m_airportCode = airportCode.ToString();
  307. StringBuilder clientId = new StringBuilder(100);
  308. GetPrivateProfileString("MQTT", "clientId", "配置文件存在,读取未成功!", clientId, 255, ConfigPath);
  309. m_clientId = clientId.ToString();
  310. StringBuilder username = new StringBuilder(100);
  311. GetPrivateProfileString("MQTT", "username", "配置文件存在,读取未成功!", username, 255, ConfigPath);
  312. m_username = username.ToString();
  313. StringBuilder password = new StringBuilder(100);
  314. GetPrivateProfileString("MQTT", "password", "配置文件存在,读取未成功!", password, 255, ConfigPath);
  315. m_password = password.ToString();
  316. StringBuilder uploadSubTopic = new StringBuilder(100);
  317. GetPrivateProfileString("MQTT", "uploadSubTopic", "配置文件存在,读取未成功!", uploadSubTopic, 255, ConfigPath);
  318. m_uploadSubTopic = uploadSubTopic.ToString();
  319. m_uploadSubTopic = m_uploadSubTopic.Replace("&", m_airportCode);
  320. StringBuilder uploadResTopic = new StringBuilder(100);
  321. GetPrivateProfileString("MQTT", "uploadResTopic", "配置文件存在,读取未成功!", uploadResTopic, 255, ConfigPath);
  322. m_uploadResTopic = uploadResTopic.ToString();
  323. m_uploadResTopic = m_uploadResTopic.Replace("&", m_airportCode);
  324. StringBuilder rtmpSubTic = new StringBuilder(100);
  325. GetPrivateProfileString("MQTT", "rtmpSubTic", "配置文件存在,读取未成功!", rtmpSubTic, 255, ConfigPath);
  326. m_rtmpSubTic = rtmpSubTic.ToString();
  327. m_rtmpSubTic = m_rtmpSubTic.Replace("&", m_airportCode);
  328. StringBuilder rtmpResTopic = new StringBuilder(100);
  329. GetPrivateProfileString("MQTT", "rtmpResTopic", "配置文件存在,读取未成功!", rtmpResTopic, 255, ConfigPath);
  330. m_rtmpResTopic = rtmpResTopic.ToString();
  331. m_rtmpResTopic = m_rtmpResTopic.Replace("&", m_airportCode);
  332. return true;
  333. }
  334. catch (Exception ex)
  335. {
  336. Logger.WriteError("THMqttClinet: getMqttConfig" + ex.Message.ToString());
  337. return false;
  338. }
  339. }
  340. return false;
  341. }
  342. }
  343. }