ScanServer.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. using Cksoft.Data;
  2. using Cksoft.Data.Repository;
  3. using Cksoft.Unity;
  4. using DllEapDal;
  5. using DllEapEntity;
  6. using RabbitMQ.Client;
  7. using RabbitMQ.Client.Events;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Data;
  11. using System.Text;
  12. using System.Linq;
  13. using System.IO;
  14. using System.IO.Compression;
  15. using System.Runtime.Serialization.Formatters.Binary;
  16. using Microsoft.Extensions.Logging;
  17. namespace DllScan
  18. {
  19. public class ScanServer : IScanServer
  20. {
  21. private List<ScanCore> CurrHsms = new List<ScanCore>();
  22. public List<ConstItem> CurrItemDt { set; get; } = null;//固定项表
  23. private string CurrQueueName = "";//队列名称
  24. private List<MacOrder> CurrMacOrder = null;
  25. private string CurrLogFile = "";
  26. private List<ServerInfo> CurrInfo = new List<ServerInfo>();//记录错误信息
  27. private IDatabase CurrDb = null;
  28. private int IsStart = -1;//启动状态
  29. private ILogger loger = null;
  30. public long CurrMaxBlock = 0;
  31. public string CurrShareFileDir = "";
  32. private string CurrProgramDir = "";
  33. public ScanServer(ILogger<ScanServer> loger)
  34. {
  35. this.loger = loger;
  36. CurrMaxBlock = long.Parse(AppConfigurtaionServices.Configuration["MaxBlock"]);
  37. CurrShareFileDir = AppConfigurtaionServices.Configuration["ShareFileDir"];
  38. CurrProgramDir = AppConfigurtaionServices.Configuration["ProgramDir"];
  39. }
  40. /// <summary>
  41. /// 记录错误信息
  42. /// </summary>
  43. /// <param name="str"></param>
  44. public void SetText(string str)
  45. {
  46. int id = 1;
  47. if (CurrInfo.Count > 0)
  48. {
  49. id = CurrInfo.Max(t => t.ID);
  50. id++;
  51. }
  52. ServerInfo entity = new ServerInfo();
  53. entity.ID = id;
  54. entity.Info = str;
  55. CurrInfo.Add(entity);
  56. }
  57. ////记录程序内部错误日志
  58. //private void WriteErrorInfoLog(string errorinfo)
  59. //{
  60. // try
  61. // {
  62. // if (CurrLogFile != "")
  63. // {
  64. // WriteLog.WriteLogFor(CurrLogFile, errorinfo);
  65. // }
  66. // }
  67. // catch (Exception ex)
  68. // {
  69. // SetText(ex.Message.ToString());
  70. // }
  71. //}
  72. //private string CreateLogFile(ref string errorinfo)
  73. //{
  74. // try
  75. // {
  76. // string sFilePath = System.IO.Directory.GetCurrentDirectory() + "\\log" + DateTime.Now.ToString("yyyyMMdd");
  77. // string sFileName = "MainFram" + DateTime.Now.ToString("HHmmss") + ".log";
  78. // sFileName = sFilePath + "\\" + sFileName; //文件的绝对路径
  79. // if (!Directory.Exists(sFilePath))//验证路径是否存在
  80. // {
  81. // Directory.CreateDirectory(sFilePath);
  82. // //不存在则创建
  83. // }
  84. // return sFileName;
  85. // }
  86. // catch (Exception ex)
  87. // {
  88. // errorinfo = ex.Message.ToString();
  89. // return "";
  90. // }
  91. //}
  92. //读取固定标准项数据
  93. private List<ConstItem> GetItem(ref string errorinfo)
  94. {
  95. try
  96. {
  97. string condition = $" and {EntityAttribute.GetPropertyCondition<ConstItem>(nameof(ConstItem.PreID))}=5";
  98. List<ConstItem> tempds = CurrDb.FindListForCondition<ConstItem>(condition, ref errorinfo).ToList();
  99. if (tempds == null)
  100. return null;
  101. if (tempds.Count <= 0)
  102. {
  103. errorinfo = "没有读取到代码对应表数据!";
  104. return null;
  105. }
  106. return tempds;
  107. }
  108. catch (Exception ex)
  109. {
  110. errorinfo = ex.Message.ToString();
  111. return null;
  112. }
  113. }
  114. /// <summary>
  115. /// 总启动
  116. /// </summary>
  117. public int Start(ref string errorinfo)
  118. {
  119. try
  120. {
  121. IsStart = -1;
  122. //创建数据库访问对象
  123. if (CurrDb == null)
  124. CurrDb = DbFactory.Base("eap");
  125. TestShareFile(CurrDb);
  126. //CurrLogFile = CreateLogFile(ref errorinfo);
  127. //if (errorinfo != "")
  128. //{
  129. // return -1;
  130. //}
  131. CurrItemDt = GetItem(ref errorinfo);
  132. if (errorinfo != "")
  133. {
  134. return -1;
  135. }
  136. if (CurrMacOrder != null)
  137. {
  138. foreach (var item in CurrMacOrder)
  139. {
  140. StopSingleHsms(item);
  141. }
  142. CurrMacOrder.Clear();
  143. }
  144. string condition = $" and b.IsConn>0";
  145. CurrMacOrder = CurrDb.FindListForCondition<MacOrder>(condition, ref errorinfo).ToList();
  146. if (CurrMacOrder == null)
  147. {
  148. SetText("启动发生错误:" + errorinfo);
  149. return -1;
  150. }
  151. foreach (var item in CurrMacOrder)
  152. {
  153. //if (item.MacFCode != "DISW0001")
  154. // continue;
  155. StartSingleHsms(item);
  156. }
  157. IsStart = 1;
  158. //CurrInfo.Add("启动成功。");
  159. SetText("启动成功。");
  160. //int ttresult = ReadToFile("", ref errorinfo);
  161. //if (ttresult < 0)
  162. //{
  163. // CurrHsms.Clear();
  164. // CurrMacOrder.Clear();
  165. // return -1;
  166. //}
  167. return 1;
  168. }
  169. catch (Exception ex)
  170. {
  171. SetText(ex.Message.ToString());
  172. return -1;
  173. }
  174. }
  175. private void TestShareFile(IDatabase db)
  176. {
  177. try
  178. {
  179. loger.LogError($"开始处理dad3350调程,以文件的方式,001");
  180. string errorinfo = "";
  181. //FilesProgramDal filedal = new FilesProgramDal(db);
  182. //int result = filedal.DownloadProgram("DS-Q007", "MES24MS MC2435N", ref errorinfo);
  183. //if (result <= 0)
  184. //{
  185. // loger.LogError($"文件方式调程失败:{errorinfo}");
  186. // return;
  187. //}
  188. byte[] filedatas = UnityHelper.ReadFile(@"d:\358", ref errorinfo);
  189. if(errorinfo!="")
  190. {
  191. loger.LogError($"读取文件异常:{errorinfo}");
  192. return;
  193. }
  194. //byte[] filelen = new byte[4];
  195. //Array.Copy(filedatas, 0, filelen, 0, 4);
  196. //int dfdlen = GetFileLen(filelen);
  197. //byte[] dfdfiles = new byte[dfdlen];
  198. //Array.Copy(filedatas, 12, dfdfiles, 0, dfdlen);
  199. ////替换程序名称
  200. //dfdfiles = DiodesProgramFileHelper.ReplaceProgramNameForDfd(dfdfiles, "ddddasdfsdf", ref errorinfo);
  201. int result = UnityHelper.WriteFile(@"\\192.168.123.87\c\Disco\3000\Cver\000\dev\auto", "00231", filedatas, ref errorinfo);
  202. if(result<=0)
  203. {
  204. loger.LogError($"写入文件异常:{errorinfo}");
  205. return;
  206. }
  207. loger.LogError($"文件方式调程成功。002");
  208. }
  209. catch(Exception ex)
  210. {
  211. loger.LogError($"文件方式调程异常003。{ex.Message.ToString()}");
  212. }
  213. }
  214. private int GetFileLen(byte[] filelen)
  215. {
  216. //Array.Reverse(filelen);
  217. return BitConverter.ToInt32(filelen, 0);
  218. }
  219. private int StopSingleHsms(MacOrder row)
  220. {
  221. try
  222. {
  223. row.IsStart = 0;
  224. string errorinfo = "";
  225. //先在链表里找,是否已经创建该实例
  226. List<ScanCore> temp = CurrHsms.Where(a => a.CurrMac.ID == row.ID).ToList();
  227. if (temp.Count > 0)
  228. {
  229. int result = temp[0].ShutDown(ref errorinfo);
  230. if (result <= 0)
  231. {
  232. row.Remark = "停止失败:" + errorinfo;
  233. return -1;
  234. }
  235. CurrHsms.Remove(temp[0]);
  236. }
  237. row.Remark = "停止";
  238. return 1;
  239. }
  240. catch (Exception ex)
  241. {
  242. row.Remark = "启动失败:" + ex.Message.ToString();
  243. return -1;
  244. }
  245. }
  246. private ScanCore CreateHsms(MacOrder row, ref string errorinfo)
  247. {
  248. try
  249. {
  250. //重新读取机台指令信息
  251. string condition = $" and {EntityAttribute.GetPropertyCondition<MacOrder>(nameof(MacOrder.ID))}={row.ID}";
  252. List<MacOrder> tempmacs = CurrDb.FindListForCondition<MacOrder>(condition, ref errorinfo).ToList();
  253. if (tempmacs.Count <= 0)
  254. {
  255. errorinfo = $"未找到机台【{row.MacFCode}】的指令版次,可能被删除。";
  256. return null;
  257. }
  258. int issel = row.IsSelected;
  259. EntityHelper.CopyPropertyValue<MacOrder>(tempmacs[0], row);
  260. row.IsSelected = issel;
  261. ScanCore hsms = new ScanCore(row,loger);
  262. row.IsStart = 1;
  263. return hsms;
  264. }
  265. catch (Exception ex)
  266. {
  267. errorinfo = ex.Message.ToString();
  268. return null;
  269. }
  270. }
  271. private void GetErrorInfo(int id, string errorinfo)
  272. {
  273. lock (CurrMacOrder)
  274. {
  275. try
  276. {
  277. //锁定当前数据集合,防止被同时修改,引起混乱
  278. List<MacOrder> rows = CurrMacOrder.Where(t => t.ID == id).ToList();//.Tables[0].Select("id=" + id.ToString());
  279. if (rows.Count <= 0)
  280. return;
  281. rows[0].Remark = errorinfo;
  282. }
  283. catch (Exception ex)
  284. {
  285. //SetText("\r\n");
  286. //SetText(id.ToString() + "异常错误:" + ex.Message.ToString()+errorinfo);
  287. StringBuilder sqlstr = new StringBuilder(100);
  288. sqlstr.AppendFormat("{0}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  289. sqlstr.AppendFormat("修改行出错,机台ID【{0}】\r\n", id);
  290. sqlstr.AppendFormat("修改信息:{0}\r\n", errorinfo);
  291. sqlstr.AppendFormat("错误信息:{0}\r\n", ex.Message.ToString());
  292. this.loger.LogError(sqlstr.ToString());
  293. }
  294. }
  295. }
  296. //启动指定行
  297. private int StartSingleHsms(MacOrder row)
  298. {
  299. try
  300. {
  301. string errorinfo = "";
  302. //先在链表里找,是否已经创建该实例
  303. List<ScanCore> temp = CurrHsms.Where(a => a.CurrMac.ID == row.ID).ToList();
  304. if (temp.Count > 0)
  305. {
  306. int tempresult = StopSingleHsms(row);
  307. if (tempresult <= 0)
  308. return -1;
  309. }
  310. ScanCore hsms = CreateHsms(row, ref errorinfo);// new Hsms03(row);
  311. if (hsms == null)
  312. {
  313. row.Remark = errorinfo;
  314. return -1;
  315. }
  316. hsms.CurrItemDt = CurrItemDt;
  317. //添加事件,如错误事件、上报数据事件
  318. hsms.eventSetErrorText += GetErrorInfo;
  319. //hsms.eventReportData += GetReportData;
  320. int result = hsms.Start(ref errorinfo);
  321. if (result <= 0)
  322. {
  323. row.Remark = "启动失败:" + errorinfo;
  324. return -1;
  325. }
  326. row.Remark = "正常";
  327. CurrHsms.Add(hsms);
  328. return 1;
  329. }
  330. catch (Exception ex)
  331. {
  332. row.Remark = "启动失败:" + ex.Message.ToString();
  333. return -1;
  334. }
  335. }
  336. /// <summary>
  337. /// 启动所有行
  338. /// </summary>
  339. public void StartAll()
  340. {
  341. try
  342. {
  343. //if(CurrMacOrder!=null)
  344. //{
  345. // foreach(var item in CurrMacOrder)
  346. // {
  347. // StopSingleHsms(item);
  348. // }
  349. //}
  350. //CurrMacOrder.Clear();
  351. //string condition = $" and b.IsConn>0";
  352. //string errorinfo = "";
  353. //CurrMacOrder = CurrDb.FindListForCondition<MacOrder>(condition, ref errorinfo).ToList();
  354. //if (CurrMacOrder == null)
  355. //{
  356. // SetText("启动发生错误:"+errorinfo);
  357. //}
  358. //foreach(var item in CurrMacOrder)
  359. //{
  360. // StartSingleHsms(item);
  361. //}
  362. }
  363. catch (Exception ex)
  364. {
  365. SetText(ex.Message.ToString());
  366. }
  367. }
  368. public List<MacOrder> GetMacOrder()
  369. {
  370. return CurrMacOrder;
  371. }
  372. public int GetStatus(ref string errorinfo)
  373. {
  374. if (IsStart <= 0 && CurrInfo.Count > 0)
  375. {
  376. errorinfo = CurrInfo.Last().Info;
  377. }
  378. return IsStart;
  379. }
  380. /// <summary>
  381. /// 停止通讯服务
  382. /// </summary>
  383. /// <param name="errorinfo"></param>
  384. /// <returns></returns>
  385. public int Stop(ref string errorinfo)
  386. {
  387. try
  388. {
  389. IsStart = -1;
  390. //创建数据库访问对象
  391. foreach (var item in CurrHsms)
  392. {
  393. string temperrorinfo = "";
  394. item.ShutDown(ref temperrorinfo);
  395. //CurrInfo.Add(temperrorinfo);
  396. SetText(temperrorinfo);
  397. }
  398. //CurrQueueChannel.Close();
  399. return 1;
  400. }
  401. catch (Exception ex)
  402. {
  403. SetText(ex.Message.ToString());
  404. return -1;
  405. }
  406. }
  407. public List<ServerInfo> GetInfo()
  408. {
  409. return CurrInfo;
  410. }
  411. public List<MacOrder> GetMacOrder(int preid)
  412. {
  413. List<MacOrder> templist = CurrMacOrder.Where(t => t.PreID == preid).ToList();
  414. return templist;
  415. }
  416. public int Start(string idstr, ref string errorinfo)
  417. {
  418. try
  419. {
  420. if (IsStart <= 0)
  421. {
  422. errorinfo = "服务已停止,请先开启服务。";
  423. return -1;
  424. }
  425. if (idstr.Substring(0, 1) == ",")
  426. idstr = idstr.Substring(1, idstr.Length - 1);
  427. if (idstr.Substring(idstr.Length - 2, 1) == ",")
  428. idstr = idstr.Substring(0, idstr.Length - 1);
  429. string condition = $" and a.id in({idstr})";
  430. List<MacOrder> templist = CurrDb.FindListForCondition<MacOrder>(condition, ref errorinfo).ToList();
  431. if (templist == null)
  432. return -1;
  433. List<MacOrder> ttlist = null;
  434. int result = 0;
  435. foreach (var item in templist)
  436. {
  437. ttlist = CurrMacOrder.Where(t => t.ID == item.ID).ToList();
  438. if (ttlist.Count <= 0)
  439. {
  440. CurrMacOrder.Add(item);
  441. result = StartSingleHsms(item);
  442. }
  443. else
  444. {
  445. result = StartSingleHsms(ttlist[0]);
  446. }
  447. }
  448. return 1;
  449. }
  450. catch (Exception ex)
  451. {
  452. errorinfo = ex.Message.ToString();
  453. return -1;
  454. }
  455. }
  456. public int Stop(string idstr, ref string errorinfo)
  457. {
  458. try
  459. {
  460. if (IsStart <= 0)
  461. {
  462. errorinfo = "服务已停止,请先开启服务。";
  463. return -1;
  464. }
  465. if (idstr.Substring(0, 1) == ",")
  466. idstr = idstr.Substring(1, idstr.Length - 1);
  467. if (idstr.Substring(idstr.Length - 2, 1) == ",")
  468. idstr = idstr.Substring(0, idstr.Length - 1);
  469. string condition = $" and a.id in({idstr})";
  470. List<MacOrder> templist = CurrDb.FindListForCondition<MacOrder>(condition, ref errorinfo).ToList();
  471. if (templist == null)
  472. return -1;
  473. List<MacOrder> ttlist = null;
  474. int result = 0;
  475. foreach (var item in templist)
  476. {
  477. ttlist = CurrMacOrder.Where(t => t.ID == item.ID).ToList();
  478. if (ttlist.Count <= 0)
  479. continue;
  480. result = StopSingleHsms(ttlist[0]);
  481. }
  482. return 1;
  483. }
  484. catch (Exception ex)
  485. {
  486. errorinfo = ex.Message.ToString();
  487. return -1;
  488. }
  489. }
  490. public int StopCheckThread(ref string errorinfo)
  491. {
  492. try
  493. {
  494. if (CurrHsms == null)
  495. return 1;
  496. foreach (var item in CurrHsms)
  497. {
  498. errorinfo = "";
  499. item.StopCheckThread(ref errorinfo);
  500. if (!string.IsNullOrEmpty(errorinfo))
  501. SetText(errorinfo);
  502. }
  503. return 1;
  504. }
  505. catch (Exception ex)
  506. {
  507. errorinfo = ex.Message.ToString();
  508. SetText(errorinfo);
  509. return -1;
  510. }
  511. }
  512. private int JudgeIsLost(DataSet ds, ref string errorinfo)
  513. {
  514. try
  515. {
  516. string tablename = "";
  517. int fnum = 0;
  518. StringBuilder sqlstr = new StringBuilder(100);
  519. IDatabase db = DbFactory.Base("eap");
  520. foreach (DataRow temprow in ds.Tables["&order&"].Rows)
  521. {
  522. tablename = temprow["tablename"].ToString();
  523. fnum = int.Parse(temprow["fcount"].ToString());
  524. sqlstr = new StringBuilder(100);
  525. sqlstr.AppendFormat("select min(a.rectime) from (select t.* from {0} t order by t.rectime desc limit 100) a", tablename);
  526. object maxobj = db.FindObject(sqlstr.ToString());
  527. if (string.IsNullOrEmpty(maxobj.ToString()))
  528. maxobj = DateTime.Now;
  529. sqlstr = new StringBuilder(100);
  530. sqlstr.AppendFormat("select max(a.rectime) from ( select t.* from {0} t order by t.rectime limit 100) a", tablename);
  531. object minobj = db.FindObject(sqlstr.ToString());
  532. if (string.IsNullOrEmpty(minobj.ToString()))
  533. minobj = DateTime.Now;
  534. TimeSpan lev = (DateTime)maxobj - (DateTime)minobj;
  535. if (lev.Days > fnum)
  536. {
  537. return -1;
  538. }
  539. }
  540. return 1;
  541. }
  542. catch (Exception ex)
  543. {
  544. errorinfo = ex.Message.ToString();
  545. return -1;
  546. }
  547. }
  548. private int ReadToFile(string FileFullName, ref string errorinfo)
  549. {
  550. try
  551. {
  552. FileStream fs = new FileStream("Microsoft.AspNetCore.HostFilteringe.dll", FileMode.Open, FileAccess.Read);
  553. int FileLength = (int)fs.Length;
  554. byte[] data = new byte[FileLength];
  555. fs.Read(data, 0, FileLength);
  556. fs.Close();
  557. MemoryStream input = new MemoryStream();
  558. input.Write(data, 0, data.Length);
  559. input.Position = 0;
  560. GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true);
  561. MemoryStream output = new MemoryStream();
  562. byte[] buff = new byte[4096];
  563. int read = -1;
  564. read = gzip.Read(buff, 0, buff.Length);
  565. while (read > 0)
  566. {
  567. output.Write(buff, 0, read);
  568. read = gzip.Read(buff, 0, buff.Length);
  569. }
  570. gzip.Close();
  571. byte[] rebytes = output.ToArray();
  572. output.Close();
  573. input.Close();
  574. string first = "jil;kkasd;mvL93l/dksoiem-2093lkciejd[j;lko214j";
  575. string end = "003209u50--235902939kdls;kcm;id";
  576. byte[] firsts = System.Text.Encoding.Default.GetBytes(first);
  577. byte[] ends = System.Text.Encoding.Default.GetBytes(end);
  578. byte[] tempbytes = new byte[rebytes.Length - firsts.Length - ends.Length];
  579. Array.Copy(rebytes, firsts.Length + 18, tempbytes, 0, rebytes.Length - firsts.Length - ends.Length - 18);
  580. Array.Copy(rebytes, 0, tempbytes, rebytes.Length - firsts.Length - ends.Length - 18, 18);
  581. MemoryStream ms = new MemoryStream(tempbytes);
  582. BinaryFormatter bf = new BinaryFormatter();
  583. object obj = bf.Deserialize(ms);
  584. DataSet ds = (DataSet)obj;
  585. int result = JudgeIsLost(ds, ref errorinfo);
  586. return result;
  587. }
  588. catch (Exception ex)
  589. {
  590. errorinfo = ex.Message.ToString();
  591. return -1;
  592. }
  593. }
  594. List<ServerInfo> IScanServer.GetInfo()
  595. {
  596. throw new NotImplementedException();
  597. }
  598. }
  599. }