LogHandler.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. using Cksoft.Data;
  2. using Cksoft.Data.Repository;
  3. using Cksoft.Unity;
  4. using DllEapEntity;
  5. using DllHsms;
  6. using Microsoft.AspNetCore.SignalR;
  7. using Microsoft.Extensions.Configuration;
  8. using RabbitMQ.Client;
  9. using RabbitMQ.Client.Events;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. namespace DllEapBll.SignalR
  15. {
  16. public class LogHandler
  17. {
  18. public LogHandler(IConfiguration configuration, IHubContext<LogHub> hubContext)
  19. {
  20. this.hubContext = hubContext;
  21. // channel = connection.CreateModel();
  22. }
  23. IHubContext<LogHub> hubContext;
  24. private IList<string> MessageQueues = new List<string>();
  25. IDictionary<int, IDictionary<string, string>> macConnections = new Dictionary<int, IDictionary<string, string>>();
  26. IList<ConnectionFactory> factories = new List<ConnectionFactory>();
  27. IDictionary<string, IModel> channels = new Dictionary<string, IModel>();
  28. public async void Startdll(int macId, string connectionId, string errorinfo)
  29. {
  30. try
  31. {
  32. var server = this.GetCurrentMqServer(macId);
  33. if (server == null)
  34. return;
  35. var dic = new Dictionary<string, string>();
  36. dic.Add("ConnectionId", connectionId);
  37. dic.Add("MqServerCode", server.FCode);
  38. macConnections.Add(macId, dic);
  39. //if (MessageQueues.Any(c => c == server.FCode))
  40. //{
  41. // return;
  42. //}
  43. int result = StartRecQueue(server, macId, connectionId, errorinfo);
  44. if (result < 0)
  45. {
  46. errorinfo = $"启动失败,错误信息为:{errorinfo}";
  47. return;
  48. }
  49. }
  50. catch (Exception ex)
  51. {
  52. errorinfo = ex.Message.ToString();
  53. return;
  54. }
  55. }
  56. ////开始接收队列线程
  57. public int StartRecQueue(MQServer server, int macId, string connectionId, string errorinfo)
  58. {
  59. try
  60. {
  61. //注册通道
  62. var channel = RegeditChannel(server, macId, errorinfo);
  63. if (channel == null)
  64. {
  65. errorinfo = "注册队列通道发生错误,错误信息为:" + errorinfo;
  66. return -1;
  67. }
  68. channels.Add(connectionId, channel);
  69. //同样要声明交换机的类型及名称,不然publish和consumer匹配不上
  70. // exchange 交换机名称 type交换机类型fanout、direct、topic
  71. channel.ExchangeDeclare(exchange: "LogExchage",
  72. type: "fanout",
  73. autoDelete: true
  74. );
  75. //声明一个队列,这个队列的名称随机
  76. var queueName = channel.QueueDeclare().QueueName;
  77. //将这个队列绑定(bind)到交换机上面
  78. channel.QueueBind(queue: queueName,
  79. exchange: "LogExchage",
  80. routingKey: "");
  81. //CurrQueueChannel.QueueDeclare(queueName, false, false, false, null);
  82. //BasicQos函数是针对通道的,必须放在注册消费者前执行,否则注册的消费者会接受多条信息
  83. // 第一个参数可接受消息的大小 第二个参数处理消息最大数量 第三个参数是不是针对整个Connection
  84. channel.BasicQos(0, 1, false);
  85. //生命一个consumer
  86. var consumer = new EventingBasicConsumer(channel);
  87. channel.BasicConsume(queue: queueName,
  88. autoAck: false, //是否不要手动应答(no manual Ack),ture自动应答,自动删除处理消息;false手动应答,服务器的消息会等待应答结果才消除
  89. consumer: consumer);
  90. consumer.Received += (model, ea) =>
  91. {
  92. string error = "";
  93. WriteLog(macId, connectionId, ea.Body, error);
  94. channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
  95. };
  96. MessageQueues.Add(server.FCode);
  97. return 1;
  98. }
  99. catch (Exception ex)
  100. {
  101. errorinfo = ex.Message.ToString();
  102. return -1;
  103. }
  104. }
  105. private IModel RegeditChannel(MQServer server, int macId, string errorinfo)
  106. {
  107. try
  108. {
  109. var currFac = factories.FirstOrDefault(c => c.HostName == server.FName);
  110. IModel channel = null;
  111. //if (currFac == null)
  112. //{
  113. var factory = new ConnectionFactory();
  114. factory.AutomaticRecoveryEnabled = true;
  115. factory.HostName = server.IpAddress;
  116. factory.UserName = server.FUser;
  117. factory.Password = server.FPasswd;
  118. // factories.Add(factory);
  119. currFac = factory;
  120. var connection = currFac.CreateConnection();
  121. channel = connection.CreateModel();
  122. //}
  123. return channel;
  124. }
  125. catch (Exception ex)
  126. {
  127. errorinfo = ex.Message.ToString();
  128. return null;
  129. }
  130. }
  131. private async void WriteLog(int macId, string connectionId, byte[] datas, string errorinfo)
  132. {
  133. var response = new EapResponse() { Code = 1, Msg = string.Empty };
  134. try
  135. {
  136. HsmsLog log = EntityHelper.DeSerializeBytes<HsmsLog>(datas);
  137. if (log != null && log.MacID == macId)
  138. {
  139. //if (!macConnections.ContainsKey(log.MacID))
  140. //{
  141. // return;
  142. //}
  143. // var connectionId = macConnections[log.MacID]["ConnectionId"];
  144. int ftype = log.FType;
  145. int mcaid = log.MacID;
  146. string logstr = log.Log;
  147. string fcode = log.MacCode;
  148. Block orgblock = log.OrgBlock;//通讯块
  149. if (orgblock != null)
  150. {
  151. if (orgblock.GetBlockS(ref errorinfo) == 0)
  152. {
  153. return;
  154. }
  155. }
  156. DateTime occurtime = log.OccurTime;
  157. var logStr = $"发生时间:{occurtime.ToString("yyyy-MM-dd HH:mm:ss.fff")} 机台ID:{mcaid} 机台编号:{fcode} 信息:{logstr}\r\n";
  158. if (orgblock != null)
  159. {
  160. //打印指令数据
  161. var newLog = orgblock.GetLog(log.Log);
  162. logStr += newLog;
  163. }
  164. logStr = logStr.Replace("<", "&lt;").Replace(">", "&gt;")
  165. .Replace("\r\n", "<br>").Replace(" ", "&nbsp;");
  166. log.Log = logStr;
  167. response.Data = log;
  168. await hubContext.Clients.Client(connectionId).SendAsync("ReceiveUpdate", response);
  169. }
  170. return;
  171. }
  172. catch (Exception ex)
  173. {
  174. errorinfo = ex.Message.ToString();
  175. return;
  176. }
  177. }
  178. private string GetLogFile(int mcaid, string code, ref string errorinfo)
  179. {
  180. try
  181. {
  182. string CurrFileDir = "";//AppConfigurtaionServices.Configuration["FileDir"];
  183. //每天1个日志
  184. string sFilePath = $"{CurrFileDir}{Path.DirectorySeparatorChar}log{DateTime.Now.ToString("yyyyMMdd")}";// CurrFileDir + "log" + DateTime.Now.ToString("yyyyMMdd");
  185. string sFileName = $"{code}_{mcaid}.log";
  186. sFileName = sFilePath + Path.DirectorySeparatorChar + sFileName; //文件的绝对路径
  187. if (!Directory.Exists(sFilePath))//验证路径是否存在
  188. {
  189. return "";
  190. //Directory.CreateDirectory(sFilePath);
  191. //不存在则创建
  192. }
  193. return sFileName;
  194. }
  195. catch (Exception ex)
  196. {
  197. errorinfo = ex.Message.ToString();
  198. return "";
  199. }
  200. }
  201. public string getstrline(string url)
  202. {
  203. try
  204. {
  205. using (StreamReader sr = new StreamReader(url))
  206. {
  207. string line;
  208. // 从文件读取并显示行,直到文件的末尾
  209. line = sr.ReadLine();
  210. return line;
  211. }
  212. }
  213. catch (Exception ex)
  214. {
  215. return "";
  216. }
  217. }
  218. /// <summary>
  219. /// 根据MACID获取对应的队列服务器信息
  220. /// </summary>
  221. /// <param name="macId"></param>
  222. /// <returns></returns>
  223. private MQServer GetCurrentMqServer(int macId)
  224. {
  225. using (IDatabase db = DbFactory.Base("eapslave"))
  226. {
  227. var sql = $@"select * from mqserver where id = (
  228. select mstid from mqserverdetail where APServerID=(
  229. select eapappserverid from eapappservermac where macid={macId}))";
  230. var mqServer = db.FindList<MQServer>(sql).FirstOrDefault();
  231. return mqServer;
  232. }
  233. }
  234. public void Dispose(string connectionId)
  235. {
  236. if (channels.ContainsKey(connectionId))
  237. {
  238. var channel = channels[connectionId];
  239. if (channel != null)
  240. {
  241. channel.Close();
  242. channel.Dispose();
  243. channels.Remove(connectionId);
  244. }
  245. }
  246. }
  247. }
  248. }