AppletStatusCollectionBll.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. using Cksoft.Data;
  2. using Cksoft.Data.Repository;
  3. using DllEapDal;
  4. using DllEapEntity;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.Extensions.Logging;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Net.Sockets;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace DllEapBll
  17. {
  18. public class AppletStatusCollectionBll
  19. {
  20. ILogger<AppletStatusCollectionBll> logger;
  21. public IConfiguration Configuration { get; set; }
  22. List<Machine> CurrMachine = new List<Machine>();
  23. List<Telnet> CurrTelnet = new List<Telnet>();
  24. IDatabase db = null;
  25. public AppletStatusCollectionBll(ILogger<AppletStatusCollectionBll> logger, IConfiguration configuration)
  26. {
  27. Configuration = configuration;
  28. this.logger = logger;
  29. }
  30. public static void AppletCollection(ref string errorinfo)
  31. {
  32. //AppletStatusCollectionBll bll = new AppletStatusCollectionBll(logger);
  33. //bll.DoCollection(ref errorinfo);
  34. }
  35. public void DoCollection(ref string errorinfo)
  36. {
  37. try
  38. {
  39. //LogHelper<EapDataCollectBll>.LogInfo("开始处理机台小程序运行状态---------", "EapAsync", string.Empty);
  40. int timeout = Convert.ToInt32(Configuration["timeout"]);
  41. var interval = Convert.ToInt32(Configuration["CheckStatusInterval"]);
  42. Task.Run(() =>
  43. {
  44. try
  45. {
  46. while (true)
  47. {
  48. StringBuilder stringBuilder = new StringBuilder();
  49. logger.LogError("开始处理机台小程序运行状态---------");
  50. IEnumerable<DllEapEntity.Machine> models = null;
  51. using (IDatabase db = DbFactory.Base("eap"))
  52. {
  53. var dal = new MachineDal(db);
  54. string info = "";
  55. //IEnumerable<DllEapEntity.Machine> models = dal.Get(1, 10000, "ID", "", " and a.id in(2,14,268)", info);
  56. models = dal.Get(1, 10000, "ID", "", "", ref info);
  57. }
  58. List<DllEapEntity.Machine> ttlist = null;
  59. int result = 0;
  60. #region
  61. //foreach (var item in models)
  62. //{
  63. // var telnet = new Telnet("192.168.124.93", 1234, timeout, logger, item);
  64. // string err = string.Empty;
  65. // telnet.ConnectTcp(ref err);
  66. //}
  67. #endregion
  68. #region
  69. List<int> idsOne = new List<int>();
  70. List<int> idsTwo = new List<int>();
  71. var tt = Parallel.ForEach(models,
  72. new ParallelOptions { MaxDegreeOfParallelism = 1000 },
  73. item =>
  74. {
  75. if (CheckIPFormat(item.IPAddress))
  76. {
  77. string error = "";
  78. Telnet p = new Telnet(item.IPAddress, 5888, timeout, logger, item);
  79. if (p.ConnectTcp(ref error))
  80. {
  81. if (item.AppletS != 1)
  82. {
  83. idsOne.Add(item.ID);
  84. }
  85. logger.LogError(item.FCode + "已开启小程序");
  86. }
  87. else
  88. {
  89. if (item.AppletS != -1)
  90. {
  91. idsTwo.Add(item.ID);
  92. }
  93. logger.LogError(item.FCode + "未开启小程序");
  94. }
  95. }
  96. Thread.Sleep(10);
  97. });
  98. if (tt.IsCompleted)
  99. {
  100. if (idsOne.Count >= 1)
  101. {
  102. stringBuilder.AppendLine($" update machine set AppletS=1 where id in ({string.Join(",", idsOne.ConvertAll<string>(new Converter<int, string>(m => m.ToString())).ToArray())}); ");
  103. }
  104. if (idsTwo.Count >= 1)
  105. {
  106. stringBuilder.AppendLine($" update machine set AppletS=-1 where id in ({string.Join(",", idsTwo.ConvertAll<string>(new Converter<int, string>(m => m.ToString())).ToArray())}); ");
  107. }
  108. //LogHelper<EapDataCollectBll>.LogInfo("结束处理机台小程序运行状态---------", "EapAsync", stringBuilder.ToString());
  109. string strsql = stringBuilder.ToString();
  110. if (!string.IsNullOrEmpty(strsql))
  111. {
  112. logger.LogError("修改机台运行状态: " + strsql);
  113. UpdateMachineStatus(strsql);
  114. }
  115. logger.LogError("完成处理机台小程序运行状态---------");
  116. }
  117. #endregion
  118. Thread.Sleep(interval * 1000 * 60);
  119. //Thread.Sleep(10000);
  120. }
  121. }
  122. catch (Exception e)
  123. {
  124. logger.LogError("---------" + e.ToString());
  125. }
  126. });
  127. }
  128. catch (Exception ex)
  129. {
  130. var a = ex.Message; //a的值为:发生一个或多个错误。
  131. var b = ex.GetBaseException(); //b的值为:Task异常测试
  132. Console.WriteLine(a + "|*|" + b);
  133. errorinfo = a;
  134. }
  135. }
  136. private void UpdateMachineStatus(string strsql)
  137. {
  138. try
  139. {
  140. using (IDatabase db = DbFactory.Base("eap"))
  141. {
  142. var count = db.ExecuteBySql(strsql);
  143. }
  144. }
  145. catch (Exception ex)
  146. {
  147. logger.LogError(ex.ToString()); ;
  148. }
  149. }
  150. public int StartSingHsms(Machine row, IDatabase database)
  151. {
  152. List<Telnet> temp = CurrTelnet.Where(c => c.CurrMac.ID == row.ID).ToList();
  153. if (temp.Count > 0)
  154. {
  155. int tempresult = StopSingleHsms(row);
  156. if (tempresult <= 0)
  157. return -1;
  158. }
  159. string errorinfo = "";
  160. Telnet hsms = CreateHsms(row, ref errorinfo);// new Hsms03(row);
  161. int result = hsms.Start(database, ref errorinfo);
  162. if (result <= 0)
  163. {
  164. row.Remark = "启动失败:" + errorinfo;
  165. return -1;
  166. }
  167. row.Remark = "正常";
  168. CurrTelnet.Add(hsms);
  169. return 1;
  170. }
  171. public Telnet CreateHsms(Machine machine, ref string errorinfo)
  172. {
  173. try
  174. {
  175. Telnet telnet = new Telnet(machine.IPAddress, 5888, 1000, logger, machine);
  176. return telnet;
  177. }
  178. catch (Exception ex)
  179. {
  180. errorinfo = ex.ToString();
  181. return null;
  182. }
  183. }
  184. public int StopSingleHsms(Machine row)
  185. {
  186. try
  187. {
  188. string errorinfo = "";
  189. //先在链表里找,是否已经创建该实例
  190. List<Telnet> temp = CurrTelnet.Where(a => a.CurrMac.ID == row.ID).ToList();
  191. if (temp.Count > 0)
  192. {
  193. CurrTelnet.Remove(temp[0]);
  194. }
  195. row.Remark = "停止";
  196. return 1;
  197. }
  198. catch (Exception ex)
  199. {
  200. row.Remark = "启动失败:" + ex.Message.ToString();
  201. return -1;
  202. }
  203. }
  204. public bool CheckIPFormat(string ip)
  205. {
  206. System.Net.IPAddress ipAddress;
  207. if (System.Net.IPAddress.TryParse(ip, out ipAddress))
  208. {
  209. return true;
  210. }
  211. else
  212. {
  213. return false;
  214. }
  215. }
  216. }
  217. public class Telnet
  218. {
  219. private string address;
  220. private int port;
  221. private int timeout;
  222. private static readonly object obj = new object();
  223. ILogger<AppletStatusCollectionBll> logger;
  224. public Machine CurrMac = new Machine();//机台数据
  225. private Thread CheckThread = null;//检查线程
  226. private Socket CurrSocket = null;
  227. public Telnet(string Address, int Port, int CommandTimeout, ILogger<AppletStatusCollectionBll> logger, Machine machine)
  228. {
  229. address = Address;
  230. port = Port;
  231. timeout = CommandTimeout;
  232. this.logger = logger;
  233. CurrMac = machine;
  234. }
  235. /// <summary>
  236. /// 启动socket 进行telnet操作
  237. /// </summary>
  238. public bool Connect(ref string errorinfo)
  239. {
  240. try
  241. {
  242. if (CurrSocket == null)
  243. {
  244. IPAddress ip = IPAddress.Parse(address);//服务端所在IP
  245. IPEndPoint ipEnd = new IPEndPoint(ip, port);//服务端所监听的接口
  246. CurrSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  247. CurrSocket.Connect(ipEnd);
  248. }
  249. else
  250. {
  251. CurrSocket.Shutdown(SocketShutdown.Both);
  252. CurrSocket.Close();//关闭Socket
  253. CurrSocket.Dispose();
  254. CurrSocket = null;
  255. IPAddress ip = IPAddress.Parse(address);//服务端所在IP
  256. IPEndPoint ipEnd = new IPEndPoint(ip, port);//服务端所监听的接口
  257. CurrSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  258. CurrSocket.Connect(ipEnd);
  259. }
  260. return true;
  261. }
  262. catch (Exception e)
  263. {
  264. errorinfo = e.ToString();
  265. logger.LogError(errorinfo);
  266. CurrSocket = null;
  267. return false;
  268. }
  269. }
  270. public bool ConnectTcp(ref string errorinfo)
  271. {
  272. TcpClient tcpClient = null;
  273. try
  274. {
  275. tcpClient = new TcpClient(address, port);
  276. tcpClient.SendTimeout = timeout;
  277. return true;
  278. }
  279. catch (Exception ex)
  280. {
  281. logger.LogError($"TCP检查端口是否连通错误,IP地址:[{address}],错误信息:" + ex.ToString());
  282. return false;
  283. }
  284. finally
  285. {
  286. if (tcpClient != null)
  287. {
  288. tcpClient.Close();
  289. tcpClient.Dispose();
  290. }
  291. }
  292. }
  293. public int Start(IDatabase database, ref string errorinfo)
  294. {
  295. StringBuilder sqlstr = new StringBuilder(100);
  296. int result = StartCheckThread(ref errorinfo);
  297. if (result <= 0)
  298. {
  299. //处理接受失败,写入数据库
  300. sqlstr.Clear();
  301. sqlstr.AppendFormat("{0}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  302. sqlstr.AppendFormat("开始检查线程发生错误\r\n");
  303. sqlstr.AppendFormat("{0}", errorinfo);
  304. logger.LogError(sqlstr.ToString());
  305. return -1;
  306. }
  307. return 1;
  308. }
  309. public int StartCheckThread(ref string errorinfo)
  310. {
  311. try
  312. {
  313. //成功后,启动接受线程
  314. CheckThread = new Thread(CheckThreadFun);
  315. CheckThread.Start();
  316. return 1;
  317. }
  318. catch (Exception ex)
  319. {
  320. errorinfo = ex.Message.ToString();
  321. return -1;
  322. }
  323. }
  324. private void CheckThreadFun()
  325. {
  326. try
  327. {
  328. //while (true)
  329. //{
  330. string errorinfo = "";
  331. using (IDatabase db = DbFactory.Base("eap"))
  332. {
  333. MachineDal machineDal = new MachineDal(db);
  334. CurrMac = machineDal.Get(CurrMac.ID);
  335. var result = Connect(ref errorinfo);
  336. if (result == true)
  337. {
  338. if (CurrMac.AppletS != 1)
  339. {
  340. string sql = $"update machine set AppletS=1 where id={CurrMac.ID};";
  341. logger.LogError(sql);
  342. db.ExecuteBySql(sql);
  343. }
  344. Console.WriteLine(CurrMac.FCode + "已开启小程序");
  345. logger.LogError(CurrMac.FCode + "已开启小程序");
  346. }
  347. else
  348. {
  349. if (CurrMac.AppletS != -1)
  350. {
  351. string sql = $"update machine set AppletS=-1 where id={CurrMac.ID};";
  352. logger.LogError(sql);
  353. db.ExecuteBySql(sql);
  354. }
  355. logger.LogError(CurrMac.FCode + "已关闭小程序");
  356. }
  357. }
  358. Thread.Sleep(1000 * 60 * 5);
  359. //Thread.Sleep(15000);
  360. //}
  361. }
  362. catch (Exception ex)
  363. {
  364. logger.LogError(ex.ToString());
  365. }
  366. }
  367. }
  368. }