BICollectDal.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. using Cksoft.Data;
  2. using Cksoft.Data.Repository;
  3. using Cksoft.Unity;
  4. using Cksoft.Unity.Log4NetConfig;
  5. using DllEapCommon.Notice;
  6. using DllEapEntity;
  7. using DllEapEntity.Dtos;
  8. using DllEapEntity.OFILM;
  9. using Microsoft.Extensions.Logging;
  10. using Newtonsoft.Json;
  11. using Newtonsoft.Json.Schema;
  12. using SharpCifs.Util.Sharpen;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Data;
  16. using System.Diagnostics;
  17. using System.Linq;
  18. using System.Text;
  19. using System.Threading.Tasks;
  20. namespace DllEapDal.OFILM
  21. {
  22. /// <summary>
  23. /// BI系统数据推送
  24. /// </summary>
  25. public class BICollectDal
  26. {
  27. private IDatabase CurrDb = null;
  28. public BICollectDal(IDatabase db)
  29. {
  30. CurrDb = db;
  31. }
  32. public BICollectDal()
  33. {
  34. }
  35. /// <summary>
  36. /// 获取未推送到BI的报警数据
  37. /// </summary>
  38. /// <returns></returns>
  39. private IEnumerable<McaEventStatisticByDay> GetAlarms()
  40. {
  41. string sql = $@"select a.Id,f.FCode as Manufacturer,a.EventCode,
  42. b.RegionId,b.FactoryId,g.Factory,
  43. a.AlarmCode,a.AlarmDesc,a.McaCode,b.FName as McaName,
  44. e.FName as MacModelName,a.StartTime,a.EndTime,a.TimeSpan,a.IsInProducing,a.IsHandled,
  45. e.FCode as MacModel,e.SoftVersion,c.PCode,d.FName as PName,b.IpAddress
  46. from McaEventStatisticByDay a
  47. left join Machine b on a.McaCode=b.FCode
  48. left join MacTProcess c on b.id=c.MacID
  49. left join TProcess d on c.PCode=d.FCode
  50. left join MacModel e on b.MModeId=e.id
  51. left join Supplier f on e.SupplierId=f.id
  52. left join FactoryRegion g on b.FactoryId=g.id "
  53. + $" where 1=1 and a.EventCode='C00007' and a.IsBICollect=0 ";
  54. return CurrDb.FindList<McaEventStatisticByDay>(sql);
  55. }
  56. /// <summary>
  57. /// 获取当前关机的机台
  58. /// </summary>
  59. /// <returns></returns>
  60. private IEnumerable<MacStatus> GetShutdownConnMacs(IDatabase db)
  61. {
  62. var sql = "select * from macstatus where statusid=204906";
  63. return db.FindList<MacStatus>(sql);
  64. }
  65. /// <summary>
  66. /// 获取机台状态
  67. /// </summary>
  68. /// <returns></returns>
  69. private IEnumerable<MacStatus> GetMacStatuses(DateTime dateStart, ref string errorinfo)
  70. {
  71. string sql = $@"select a.*,d.FName as Supplier,b.IpAddress,b.RegionId,
  72. g.FName as Factory,c.SoftVersion,f.FCode as ProcessCode,h.Project,
  73. c.FCode as MacModel,c.FName as MacModelName
  74. from macstatus a
  75. left join machine b on a.maccode=b.fcode
  76. left join macmodel c on b.mmodeid=c.id
  77. left join supplier d on c.supplierid =d.id
  78. left join MacTProcess e on b.id=e.MacID
  79. left join TProcess f on e.PCode=f.FCode
  80. left join FactoryRegion g on b.factoryId=g.Id
  81. left join projectandprogram h on {OfilmRecipeProvider.GenRecipeString("a")} = h.Recipe
  82. where (a.etime>='{dateStart}' or
  83. a.etime='0001-01-01 00:00:00') ";
  84. return CurrDb.FindList<MacStatus>(sql);
  85. }
  86. /// <summary>
  87. /// 获取产量数据
  88. /// </summary>
  89. /// <returns></returns>
  90. private IEnumerable<OutputDto> GetOutputDatas(DateTime start, DateTime end, IDatabase db)
  91. {
  92. string sql = $@"select a.fcount as count,e.fcode as pcode,e.fname as pname,f.fcode as macmodel,
  93. f.fname as macmodelname,c.fcode as code,c.fname as name,
  94. b.timelen as TimeLen,a.Id as DetailId,b.EDate as Fdate,
  95. {OfilmRecipeProvider.GenRecipeString("b", "pName")} programName,
  96. g.fName as factory,h.FName as line,i.FName as floor,k.FName Plant,
  97. e.fCode Work_Process,f.FCode Dev_Type,j.Project
  98. from maccountdetail a
  99. left join maccountmst b on a.mstid=b.id
  100. left join machine c on b.macid=c.id
  101. left join mactprocess d on c.id=d.macid
  102. left join tprocess e on d.pcode=e.fcode
  103. left join macmodel f on c.mmodeid=f.id
  104. left join factoryregion g on c.FactoryId = g.id
  105. left join factoryregion h on c.RegionId=h.id
  106. left join factoryregion i on h.ParentId=i.id
  107. left join factoryregion k on i.ParentId=k.id
  108. left join projectandprogram j on j.Recipe = {OfilmRecipeProvider.GenRecipeString("b", "PName")}
  109. where a.typeid=0 and b.EDate>'{start.ToString("yyyy-MM-dd HH:mm:ss")}' and b.EDate<='{end.ToString("yyyy-MM-dd HH:mm:ss")}'
  110. and a.paramcode='{DllHsms.StandardCode.SVID_FinishUnit}' ";
  111. return db.FindList<OutputDto>(sql);
  112. }
  113. /// <summary>
  114. /// 推送机台状态信息
  115. /// </summary>
  116. /// <param name="errorinfo"></param>
  117. /// <returns></returns>
  118. public int CollectMacStatus(ref string errorinfo)
  119. {
  120. var lastHistory = CurrDb.FindListForCondition<BIHistory>($" " +
  121. $"and a.Type=1 and a.Status=1 order by fdate desc", ref errorinfo).FirstOrDefault();
  122. DateTime dateStart;
  123. if (lastHistory == null)
  124. {
  125. dateStart = Convert.ToDateTime("2020-08-25 17:00:00");
  126. }
  127. else
  128. {
  129. dateStart = lastHistory.FDate;
  130. }
  131. Stopwatch watch = new Stopwatch();
  132. watch.Start();
  133. var statuses = this.GetMacStatuses(dateStart, ref errorinfo).OrderBy(c => c.RecTime);
  134. long ticks = watch.ElapsedMilliseconds;
  135. watch.Reset();
  136. watch.Restart();
  137. DateTime now = DateTime.Now;
  138. var biStatuses = new List<BIMachineStatus>();
  139. var regionDal = new FactoryRegionDal(CurrDb);
  140. var ids = new List<int>();
  141. var machines = CurrDb.FindListForCondition<Machine>(string.Empty, ref errorinfo);
  142. var allRegions = regionDal.Get(1, 10000, "ID", "asc", string.Empty, errorinfo);
  143. foreach (var item in machines)
  144. {
  145. var floor = string.Empty;
  146. var line = string.Empty;
  147. // 获取楼层及产线
  148. if (item.RegionId != 0)
  149. {
  150. var fullRegionName = regionDal.GetFullRegionName(item.RegionId, allRegions);
  151. var arr = fullRegionName.Split('/');
  152. if (arr.Count() == 2)
  153. {
  154. floor = arr[1];
  155. }
  156. else if (arr.Count() == 3)
  157. {
  158. floor = arr[1];
  159. line = arr[2];
  160. }
  161. item.Floor = floor;
  162. item.Line = line;
  163. }
  164. }
  165. if (statuses != null && statuses.Count() > 0)
  166. {
  167. foreach (var item in statuses)
  168. {
  169. var mac = machines.FirstOrDefault(c => c.FCode.ToUpper() == item.MacCode.ToUpper());
  170. if (mac == null)
  171. {
  172. continue;
  173. }
  174. var recipe = "";
  175. if (item.Remark != null)
  176. {
  177. recipe = item.Remark.Split(new char[] { '-', '_', ' ' },
  178. StringSplitOptions.RemoveEmptyEntries)[0];
  179. }
  180. var status = 5;
  181. #region 将EAP的状态码转换为BI大数据通用状态码
  182. if (item.StatusID == 1) // 未连接
  183. {
  184. status = 1;
  185. }
  186. else if (item.StatusID == 2) // 准备
  187. {
  188. status = 33;
  189. }
  190. else if (item.StatusID == 3) // 空闲
  191. {
  192. status = 2049;
  193. }
  194. else if (item.StatusID == 4) // 运行
  195. {
  196. status = 3;
  197. }
  198. else if (item.StatusID == 6)
  199. {
  200. status = 5;
  201. }
  202. else if (item.StatusID == 204906)
  203. {
  204. status = 2;
  205. }
  206. else
  207. {
  208. status = item.StatusID;
  209. }
  210. #endregion
  211. var fdate = now;
  212. if (item.ETime.ToString("yyyy-MM-dd HH:mm:ss") == "0001-01-01 00:00:00")
  213. {
  214. if (item.STime >= dateStart)
  215. {
  216. fdate = item.STime;
  217. }
  218. else
  219. {
  220. fdate = dateStart;
  221. }
  222. }
  223. else
  224. {
  225. if (item.STime >= dateStart)
  226. {
  227. fdate = item.STime;
  228. }
  229. else
  230. {
  231. fdate = dateStart;
  232. }
  233. }
  234. var entity = new BIMachineStatus
  235. {
  236. Description = item.AlarmDescribe == "报警解除" ? "" : item.AlarmDescribe,
  237. Device_Code = item.MacCode,
  238. Dev_IP = item.IpAddress,
  239. Dev_Type = item.MacModelName,
  240. Status_Code = item.AlarmCode,
  241. Factory = item.Factory,
  242. FDate = fdate,
  243. Floor = mac.Floor,
  244. Line = mac.Line,
  245. Recipe = recipe,
  246. Status = status,
  247. Version = item.SoftVersion,
  248. Work_Process = item.ProcessCode,
  249. Project = item.Project ?? "异常"
  250. };
  251. biStatuses.Add(entity);
  252. ids.Add(item.ID);
  253. }
  254. watch.Stop();
  255. long t2 = watch.ElapsedMilliseconds;
  256. long count = statuses.Count();
  257. watch.Reset();
  258. watch.Restart();
  259. var sb = new StringBuilder("insert into BIMachineStatus (Device_Code,FDate,Status,Status_Code,Description," +
  260. "Factory,Floor,Project,Recipe,Work_Process,Dev_Type,Line,Version," +
  261. "Dev_IP) Values");
  262. foreach (var item in biStatuses)
  263. {
  264. sb.Append($@"('{item.Device_Code}','{item.FDate}','{item.Status}','{item.Status_Code}',
  265. '{item.Description}','{item.Factory}','{item.Floor}','{item.Project}','{item.Recipe}',
  266. '{item.Work_Process}','{item.Dev_Type}','{item.Line}','{item.Version}','{item.Dev_IP}'),");
  267. }
  268. sb.Remove(sb.Length - 1, 1);
  269. sb.Append(";");
  270. if (CurrDb.ExecuteBySql(sb.ToString()) < 0)
  271. {
  272. errorinfo = "数据汇总失败";
  273. return -1;
  274. }
  275. watch.Stop();
  276. long t3 = watch.ElapsedMilliseconds;
  277. var history = new BIHistory
  278. {
  279. FDate = now,
  280. Status = 1,
  281. Type = 1
  282. };
  283. CurrDb.InsertFor(history, string.Empty);
  284. }
  285. return 1;
  286. }
  287. /// <summary>
  288. /// 推送机台
  289. /// </summary>
  290. /// <param name="errorinfo"></param>
  291. /// <returns></returns>
  292. public int CollectOutput(int delay, ref string errorinfo)
  293. {
  294. var now = DateTime.Now.AddMinutes(-delay);
  295. var lastPushDate = CurrDb.FindListForCondition<BIHistory>(" and 1=1 order by id desc limit 0,1",
  296. ref errorinfo).FirstOrDefault();
  297. var lastTime = now.AddMinutes(-10);
  298. if (lastPushDate != null && lastPushDate.FDate > now.AddHours(-5))
  299. {
  300. lastTime = lastPushDate.FDate;
  301. }
  302. //lastTime = now.AddMinutes(-30);
  303. var times = Math.Floor((now - lastTime).TotalMinutes / 10);
  304. for (int i = 0; i < times; i++)
  305. {
  306. var start = lastTime.AddMinutes(i * 10);
  307. var end = start.AddMinutes(10);
  308. using (IDatabase db = DbFactory.Base("eap"))
  309. {
  310. var shutdownMacs = this.GetShutdownConnMacs(db);
  311. var datas = this.GetOutputDatas(start, end, db);
  312. if (datas != null && datas.Count() > 0)
  313. {
  314. var macRecipeGroups = datas.GroupBy(c => new { c.Code, c.ProgramName });
  315. var list = new List<BIOutput>();
  316. foreach (var item in macRecipeGroups)
  317. {
  318. var entity = new BIOutput
  319. {
  320. All_Product = item.Sum(c => c.Count),
  321. Device_Code = item.Key.Code,
  322. FDate = end,
  323. Goods = item.Sum(c => c.Count),
  324. Recipe = item.Key.ProgramName,
  325. Factory = item.FirstOrDefault().Factory,
  326. Plant = item.FirstOrDefault()?.Plant,
  327. Floor = item.FirstOrDefault().Floor,
  328. Line = item.FirstOrDefault().Line,
  329. Project = item.FirstOrDefault().Project,
  330. Dev_Type = item.FirstOrDefault().Dev_Type,
  331. Work_Process = item.FirstOrDefault().Work_Process
  332. };
  333. list.Add(entity);
  334. }
  335. if (list != null && list.Count > 0)
  336. {
  337. foreach (var item in list)
  338. {
  339. if (string.IsNullOrEmpty(item.Device_Code) || item.Device_Code.Length != 7)
  340. {
  341. continue;
  342. }
  343. var status = db.FindListForCondition<MacStatus01>($" and a.maccode='{item.Device_Code}' order by id desc",
  344. ref errorinfo).FirstOrDefault();
  345. if (status != null && (status.StatusID == 1 || status.StatusID == 204906) && item.Goods == 0)
  346. {
  347. continue;
  348. }
  349. CallEESServiceOutput(item);
  350. }
  351. }
  352. var pushHistory = new BIHistory
  353. {
  354. FDate = end,
  355. Type = 1
  356. };
  357. if (db.InsertFor(pushHistory, string.Empty) < 0)
  358. {
  359. errorinfo = "新增推送历史失败";
  360. continue;
  361. }
  362. //}
  363. }
  364. }
  365. }
  366. return 1;
  367. }
  368. /// <summary>
  369. /// 推送产量数据到BI接口
  370. /// </summary>
  371. /// <param name="bIOutput"></param>
  372. private void CallEESServiceOutput(BIOutput bIOutput)
  373. {
  374. string errorinfo = string.Empty;
  375. EES.EESDeviceReportServiceClient client = null;
  376. try
  377. {
  378. client = new EES.EESDeviceReportServiceClient();
  379. var str = JsonConvert.SerializeObject(bIOutput, new JsonSerializerSettings
  380. {
  381. DateFormatString = "yyyy-MM-dd HH:mm:ss"
  382. });
  383. var res = client.eesProductSumReport(str);
  384. if (!string.IsNullOrEmpty(res))
  385. {
  386. var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(res);
  387. if (dictionary != null && dictionary.ContainsKey("resultCode") && dictionary["resultCode"] == "OK")
  388. {
  389. LogHelper<BIMachineStatus>.LogError($"推送产量BI数据成功-->{JsonConvert.SerializeObject(bIOutput)}", "BI大数据", string.Empty);
  390. }
  391. else
  392. {
  393. var msg = dictionary.ContainsKey("msg") ? dictionary["msg"] : "推送失败";
  394. var content = $"推送BI数据失败[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}],异常为:{msg}";
  395. ServiceErrorNoticeHelper.Notice(content, ref errorinfo);
  396. LogHelper<BIMachineStatus>.LogError($"推送BI产量数据成功-->{JsonConvert.SerializeObject(bIOutput)}", "BI大数据", string.Empty);
  397. }
  398. }
  399. }
  400. catch (Exception ex)
  401. {
  402. var content = $"推送BI数据失败[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}],异常为:{ex.Message}";
  403. ServiceErrorNoticeHelper.Notice(content, ref errorinfo);
  404. LogHelper<BIMachineStatus>.LogError($"推送BI产量数据失败-->{ex.ToString()}", "BI大数据", string.Empty);
  405. }
  406. finally
  407. {
  408. client.CloseAsync();
  409. }
  410. }
  411. /// <summary>
  412. /// 将机台状态转换成BI接口接收的实体并调用接口推送
  413. /// </summary>
  414. /// <param name="macStatus"></param>
  415. /// <param name="errorinfo"></param>
  416. public void PushStatusToBI(IEnumerable<MacStatus> macStatuses, string errorinfo)
  417. {
  418. Task.Run(() =>
  419. {
  420. if (macStatuses != null && macStatuses.Count() > 0)
  421. {
  422. var list = new List<BIMachineStatus>();
  423. foreach (var macStatus in macStatuses)
  424. {
  425. var recipe = string.Empty;
  426. if (!string.IsNullOrEmpty(macStatus.Remark))
  427. {
  428. recipe = macStatus.Remark.Replace(".", "-").Replace("_", "-").Replace(" ", "-").Split("-")?[0];
  429. }
  430. var sql = $@"select a.FCode Device_Code,a.IpAddress Dev_IP,b.FCode Dev_Type,b.SoftVersion Version,
  431. c.FCode Work_Process,d.FName Factory,e.FName Floor,f.FName Line,h.FName Plant
  432. from Machine a
  433. left join MacModel b on a.MModeID=b.Id
  434. left join MacTProcess g on a.id=g.macid
  435. left join TProcess c on g.PCode=c.FCode
  436. left join FactoryRegion d on a.FactoryId=d.id
  437. left join FactoryRegion f on a.RegionId=f.id
  438. left join FactoryRegion e on f.ParentId=e.id
  439. left join FactoryRegion h on e.ParentId=h.id
  440. where a.FCode='{macStatus.MacCode}'";
  441. var biStatus = CurrDb.FindList<BIMachineStatus>(sql).FirstOrDefault();
  442. var project = "未维护";
  443. if (!string.IsNullOrEmpty(recipe))
  444. {
  445. sql = $"select project from projectandprogram where recipe='{recipe}'";
  446. project = CurrDb.FindList<string>(sql).FirstOrDefault() ?? "未维护";
  447. }
  448. biStatus.Recipe = recipe;
  449. // biStatus.Status = macStatus.StatusID;
  450. biStatus.Status_Code = macStatus.AlarmCode;
  451. biStatus.Description = macStatus.AlarmDescribe;
  452. biStatus.Project = project;
  453. var standard = CurrDb.FindListForCondition<StandardStatus>($" and a.StatusVal={macStatus.StatusID}", ref errorinfo)
  454. .FirstOrDefault();
  455. var status = 1;
  456. #region 将EAP的状态码转换为BI大数据通用状态码
  457. if (macStatus.StatusID == 1) // 未连接
  458. {
  459. status = 1;
  460. }
  461. else if (macStatus.StatusID == 4) // 运行
  462. {
  463. status = 3;
  464. }
  465. else if (macStatus.StatusID == 6)
  466. {
  467. if (string.IsNullOrEmpty(macStatus.AlarmDescribe))
  468. {
  469. biStatus.Description = "故障";
  470. biStatus.Status_Code = "0";
  471. }
  472. status = 5;
  473. }
  474. else if (macStatus.StatusID == 204906)
  475. {
  476. status = 2;
  477. }
  478. else if (macStatus.StatusID == 3 || macStatus.StatusID == 10 || (macStatus.StatusID > 200000
  479. && macStatus.StatusID != 204906)) // 空闲
  480. {
  481. status = 2049;
  482. biStatus.Status_Code = macStatus.StatusID.ToString();
  483. if (macStatus.StatusID == 204907)
  484. {
  485. biStatus.Status_Code = "204906";
  486. }
  487. else if (macStatus.StatusID == 204908)
  488. {
  489. biStatus.Status_Code = "204907";
  490. }
  491. else if (macStatus.StatusID == 204999)
  492. {
  493. biStatus.Status_Code = "204908";
  494. }
  495. biStatus.Description = standard.FName;
  496. if (macStatus.StatusID == 3)
  497. {
  498. biStatus.Status_Code = "0";
  499. }
  500. }
  501. else
  502. {
  503. status = 2049;
  504. biStatus.Status_Code = "204908";
  505. biStatus.Description = "其他";
  506. }
  507. #endregion
  508. biStatus.Status = status;
  509. biStatus.FDate = macStatus.STime;
  510. if (biStatus.Status != 2049 && biStatus.Status != 5)
  511. {
  512. biStatus.Status_Code = "0";
  513. biStatus.Description = standard.FName;
  514. }
  515. if (biStatus.Description == "运行")
  516. biStatus.Description = "稼动";
  517. if (biStatus.Description == "空闲")
  518. biStatus.Description = "待机";
  519. list.Add(biStatus);
  520. }
  521. CallEESServiceMacStatus(list);
  522. }
  523. });
  524. }
  525. public async Task PushStatusToBIBatch(IEnumerable<MacStatus> macStatuses, string errorinfo)
  526. {
  527. if (macStatuses != null && macStatuses.Count() > 0)
  528. {
  529. var list = new List<BIMachineStatus>();
  530. foreach (var macStatus in macStatuses)
  531. {
  532. var recipe = string.Empty;
  533. if (!string.IsNullOrEmpty(macStatus.Remark))
  534. {
  535. recipe = macStatus.Remark.Replace(".", "-").Replace("_", "-").Replace(" ", "-").Split("-")?[0];
  536. }
  537. var sql = $@"select a.FCode Device_Code,a.IpAddress Dev_IP,b.FCode Dev_Type,b.SoftVersion Version,
  538. c.FCode Work_Process,d.FName Factory,e.FName Floor,f.FName Line,h.FName Plant
  539. from Machine a
  540. left join MacModel b on a.MModeID=b.Id
  541. left join MacTProcess g on a.id=g.macid
  542. left join TProcess c on g.PCode=c.FCode
  543. left join FactoryRegion d on a.FactoryId=d.id
  544. left join FactoryRegion f on a.RegionId=f.id
  545. left join FactoryRegion e on f.ParentId=e.id
  546. left join FactoryRegion h on e.ParentId=h.id
  547. where a.FCode='{macStatus.MacCode}'";
  548. var biStatus = CurrDb.FindList<BIMachineStatus>(sql).FirstOrDefault();
  549. if (biStatus == null)
  550. continue;
  551. var project = "未维护";
  552. if (!string.IsNullOrEmpty(recipe))
  553. {
  554. sql = $"select project from projectandprogram where recipe='{recipe}'";
  555. project = CurrDb.FindList<string>(sql).FirstOrDefault() ?? "未维护";
  556. }
  557. biStatus.Recipe = recipe;
  558. // biStatus.Status = macStatus.StatusID;
  559. biStatus.Status_Code = macStatus.AlarmCode;
  560. biStatus.Description = macStatus.AlarmDescribe;
  561. biStatus.Project = project;
  562. var standard = CurrDb.FindListForCondition<StandardStatus>($" and a.StatusVal={macStatus.StatusID}", ref errorinfo)
  563. .FirstOrDefault();
  564. var status = 1;
  565. #region 将EAP的状态码转换为BI大数据通用状态码
  566. if (macStatus.StatusID == 1) // 未连接
  567. {
  568. status = 1;
  569. }
  570. else if (macStatus.StatusID == 4) // 运行
  571. {
  572. status = 3;
  573. }
  574. else if (macStatus.StatusID == 6)
  575. {
  576. if (string.IsNullOrEmpty(macStatus.AlarmDescribe))
  577. {
  578. biStatus.Description = "故障";
  579. biStatus.Status_Code = "0";
  580. }
  581. status = 5;
  582. if (macStatus.AlarmCode == "SVID")
  583. {
  584. status = 2049;
  585. biStatus.Status_Code = "0";
  586. biStatus.Description = "空闲";
  587. }
  588. }
  589. else if (macStatus.StatusID == 204906)
  590. {
  591. status = 2;
  592. }
  593. else if (macStatus.StatusID == 3 || macStatus.StatusID == 10 || (macStatus.StatusID > 200000
  594. && macStatus.StatusID != 204906)) // 空闲
  595. {
  596. status = 2049;
  597. biStatus.Status_Code = macStatus.StatusID.ToString();
  598. if (macStatus.StatusID == 204907)
  599. {
  600. biStatus.Status_Code = "204906";
  601. }
  602. else if (macStatus.StatusID == 204908)
  603. {
  604. biStatus.Status_Code = "204907";
  605. }
  606. else if (macStatus.StatusID == 204999)
  607. {
  608. biStatus.Status_Code = "204908";
  609. }
  610. biStatus.Description = standard.FName;
  611. if (macStatus.StatusID == 3)
  612. {
  613. biStatus.Status_Code = "0";
  614. }
  615. }
  616. else
  617. {
  618. status = 2049;
  619. biStatus.Status_Code = "204908";
  620. biStatus.Description = "其他";
  621. }
  622. #endregion
  623. biStatus.Status = status;
  624. biStatus.FDate = macStatus.STime;
  625. if (biStatus.Status != 2049 && biStatus.Status != 5)
  626. {
  627. biStatus.Status_Code = "0";
  628. biStatus.Description = standard.FName;
  629. }
  630. if (biStatus.Description == "运行")
  631. biStatus.Description = "稼动";
  632. if (biStatus.Description == "空闲")
  633. biStatus.Description = "待机";
  634. list.Add(biStatus);
  635. }
  636. await CallEESServiceMacStatusBatch(list);
  637. }
  638. }
  639. /// <summary>
  640. /// 推送机台状态到BI接口
  641. /// </summary>
  642. /// <param name="bIOutput"></param>
  643. private async Task CallEESServiceMacStatus(IEnumerable<BIMachineStatus> bIMachineStatus)
  644. {
  645. EES.EESDeviceReportServiceClient client = null;
  646. var str = JsonConvert.SerializeObject(bIMachineStatus.First(), new JsonSerializerSettings
  647. {
  648. DateFormatString = "yyyy-MM-dd HH:mm:ss"
  649. });
  650. try
  651. {
  652. client = new EES.EESDeviceReportServiceClient();
  653. var body = await client.eesDeviceStatusReportAsync(str);
  654. // var body = client.eesDeviceStatusReport(str);
  655. var res = body.Body.@return;
  656. if (!string.IsNullOrEmpty(res))
  657. {
  658. var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(res);
  659. if (dictionary != null && dictionary.ContainsKey("resultCode") && dictionary["resultCode"] == "OK")
  660. {
  661. LogHelper<BIMachineStatus>.LogError($"推送BI数据成功-->{JsonConvert.SerializeObject(bIMachineStatus)}", "BI大数据", string.Empty);
  662. }
  663. else
  664. {
  665. var msg = dictionary.ContainsKey("msg") ? dictionary["msg"] : "推送失败";
  666. LogHelper<BIMachineStatus>.LogError($"推送BI数据失败-->{msg}", "BI大数据", string.Empty);
  667. using (IDatabase eapDb = DbFactory.Base("eap"))
  668. {
  669. if (CurrDb.InsertFor<BIMachineStatus>(bIMachineStatus.First(), string.Empty) < 0)
  670. {
  671. LogHelper<BIMachineStatus>.LogError($"保存推送失败数据错误-->{str}", "BI大数据", string.Empty);
  672. }
  673. else
  674. {
  675. LogHelper<BIMachineStatus>.LogError($"保存推送失败数据成功-->{str}", "BI大数据", string.Empty);
  676. }
  677. }
  678. }
  679. }
  680. else
  681. {
  682. LogHelper<BIMachineStatus>.LogError($"推送BI数据失败-->接口返回NULL", "BI大数据", string.Empty);
  683. using (IDatabase eapDb = DbFactory.Base("eap"))
  684. {
  685. if (CurrDb.InsertFor<BIMachineStatus>(bIMachineStatus.First(), string.Empty) < 0)
  686. {
  687. LogHelper<BIMachineStatus>.LogError($"保存推送失败数据错误-->{str}", "BI大数据", string.Empty);
  688. }
  689. else
  690. {
  691. LogHelper<BIMachineStatus>.LogError($"保存推送失败数据成功-->{str}", "BI大数据", string.Empty);
  692. }
  693. }
  694. }
  695. }
  696. catch (Exception ex)
  697. {
  698. LogHelper<BIMachineStatus>.LogError($"推送BI数据失败-->{ex.Message}", "BI大数据", string.Empty);
  699. using (IDatabase eapDb = DbFactory.Base("eap"))
  700. {
  701. if (CurrDb.InsertFor<BIMachineStatus>(bIMachineStatus.First(), string.Empty) < 0)
  702. {
  703. LogHelper<BIMachineStatus>.LogError($"保存推送失败数据错误-->{str}", "BI大数据", string.Empty);
  704. }
  705. else
  706. {
  707. LogHelper<BIMachineStatus>.LogError($"保存推送失败数据成功-->{str}", "BI大数据", string.Empty);
  708. }
  709. }
  710. }
  711. finally
  712. {
  713. await client.CloseAsync();
  714. }
  715. }
  716. private DataTable GetMesMacID(string maccode, ref string errorinfo)
  717. {
  718. IDatabase db = null;
  719. try
  720. {
  721. db = DbFactory.Base("ofilmoracle");
  722. //string sqlstr = $"select * from APPSERVER";
  723. string sqlstr = $@"select t.EQUIPMENT_NAME from ccmmesprd.ccm_equipset_v t
  724. where t.ORG_RRN=10000
  725. and t.EQUIPMENT_ID='{maccode}'
  726. and t.IS_ACTIVE='Y'";
  727. DataTable dt = db.FindTable(sqlstr);
  728. return dt;
  729. }
  730. catch (Exception ex)
  731. {
  732. errorinfo = ex.ToString();
  733. return null;
  734. }
  735. finally
  736. {
  737. if (db != null)
  738. db.Close();
  739. }
  740. }
  741. /// <summary>
  742. /// 调用改机接口
  743. /// </summary>
  744. /// <param name="maccode"></param>
  745. /// <returns></returns>
  746. public int CallQis(MacStatus status, string oldRecipe, ref string errorinfo)
  747. {
  748. try
  749. {
  750. var maccode = status.MacCode;
  751. DataTable tempdt = GetMesMacID(maccode, ref errorinfo);
  752. if (tempdt == null)
  753. {
  754. errorinfo = $"读取MES库错误:{errorinfo}";
  755. return -1;
  756. }
  757. if (tempdt.Rows.Count <= 0)
  758. {
  759. errorinfo = $"MES库中未找到机台编号={maccode}对应的信息";
  760. return -1;
  761. }
  762. if (string.IsNullOrEmpty(tempdt.Rows[0]["EQUIPMENT_NAME"].ToString()))
  763. {
  764. errorinfo = $"MES库中找到机台编号={maccode}对应的信息为:{tempdt.Rows[0]["EQUIPMENT_NAME"].ToString()}";
  765. return -1;
  766. }
  767. var alarmInfo = string.Empty;
  768. var recipe = status.Remark.Replace(" ", "-").Replace("_", "-").Split("-")[0];
  769. alarmInfo = $"{status.STime.ToString("yyyy-MM-dd HH:mm")}未来城园区一楼,生产机台编号{tempdt.Rows[0]["EQUIPMENT_NAME"].ToString()}," +
  770. $"因由{oldRecipe}机种切换到{recipe}机种自动触发停机单";
  771. string jsonstr = "{ \"businessUnitCode\": \"751754\",\"businessUnitName\": \"未来城园区\",\"model\": \"" + recipe + "\",\"floor\": \"一楼\",\"equipmentName\": \""
  772. + tempdt.Rows[0]["EQUIPMENT_NAME"].ToString() + "\",\"stopMachineDesc\": \"" + alarmInfo + "\",\"stopType\": \"改机首件停机\"}";
  773. LogHelper<BIMachineStatus>.LogError(jsonstr, "改机", string.Empty);
  774. // var body = await client.eesDeviceStatusListReportAsync(str);
  775. Qis.ReceiveStopMachineFromMesClient clinet = new Qis.ReceiveStopMachineFromMesClient();
  776. string result = clinet.receive(jsonstr);
  777. if (string.IsNullOrEmpty(result))
  778. {
  779. errorinfo = $"机台编号={maccode}调用改机接口失败,未知错误......";
  780. return -1;
  781. }
  782. var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
  783. if (dictionary != null && dictionary.ContainsKey("code") && dictionary["code"] == "1")
  784. {
  785. LogHelper<BIMachineStatus>.LogError($"调用QIS接口成功-->机台编号={maccode}", "改机", string.Empty);
  786. return 1;
  787. }
  788. else
  789. {
  790. var msg = dictionary.ContainsKey("message") ? dictionary["message"] : "调用改机失败";
  791. LogHelper<BIMachineStatus>.LogError($"调用改机失败-->机台编号={maccode}", "改机", string.Empty);
  792. LogHelper<BIMachineStatus>.LogError(JsonConvert.SerializeObject(dictionary), "改机", string.Empty);
  793. errorinfo = msg;
  794. return -1;
  795. }
  796. }
  797. catch (Exception ex)
  798. {
  799. LogHelper<BIMachineStatus>.LogError($"调用改机发生异常-->{ex.ToString()}", "改机", string.Empty);
  800. errorinfo = ex.ToString();
  801. return -1;
  802. }
  803. }
  804. private async Task<bool> CallEESServiceMacStatusBatch(IEnumerable<BIMachineStatus> bIMachineStatuses)
  805. {
  806. EES.EESDeviceReportServiceClient client = null;
  807. string errorinfo = string.Empty;
  808. try
  809. {
  810. client = new EES.EESDeviceReportServiceClient();
  811. var obj = new EqpStatusDataList() { EesEqpDataList = bIMachineStatuses.ToList() };
  812. var str = JsonConvert.SerializeObject(obj, new JsonSerializerSettings
  813. {
  814. DateFormatString = "yyyy-MM-dd HH:mm:ss"
  815. });
  816. // var body = await client.eesDeviceStatusListReportAsync(str);
  817. var body = client.eesDeviceStatusListReport(str);
  818. var res = body;
  819. if (!string.IsNullOrEmpty(res))
  820. {
  821. var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(res);
  822. if (dictionary != null && dictionary.ContainsKey("resultCode") && dictionary["resultCode"] == "OK")
  823. {
  824. LogHelper<BIMachineStatus>.LogError($"推送BI数据成功-->{str}", "BI大数据", string.Empty);
  825. return true;
  826. }
  827. else
  828. {
  829. var msg = dictionary.ContainsKey("msg") ? dictionary["msg"] : "推送失败";
  830. var content = $"推送BI状态数据失败[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}],服务器:[{AppConfigurtaionServices.Configuration["SystemCode"]}],异常为:{msg}";
  831. ServiceErrorNoticeHelper.Notice(content, ref errorinfo);
  832. LogHelper<BIMachineStatus>.LogError($"推送BI数据失败-->{msg}", "BI大数据", string.Empty);
  833. return false;
  834. }
  835. }
  836. return false;
  837. }
  838. catch (Exception ex)
  839. {
  840. LogHelper<BIMachineStatus>.LogError($"推送BI数据失败-->{ex.ToString()}", "BI大数据", string.Empty);
  841. var content = $"推送BI数据失败[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}],服务器:[{AppConfigurtaionServices.Configuration["SystemCode"]}],异常为:{ex.Message}";
  842. ServiceErrorNoticeHelper.Notice(content, ref errorinfo);
  843. return false;
  844. }
  845. finally
  846. {
  847. await client.CloseAsync();
  848. }
  849. }
  850. public async Task<bool> PushFailedDatas(string errorifo)
  851. {
  852. var datas = CurrDb.FindListForCondition<BIMachineStatus>(string.Empty, ref errorifo);
  853. if (datas == null || datas.Count() <= 0)
  854. {
  855. return true;
  856. }
  857. var idArray = datas.Select(c => c.Id).ToList();
  858. var res = await CallEESServiceMacStatusBatch(datas);
  859. if (res)
  860. {
  861. var sql = $"DELETE FROM bimachinestatus where id in ({string.Join(",", idArray)})";
  862. if (CurrDb.ExecuteBySql(sql) < 0)
  863. {
  864. LogHelper<BIMachineStatus>.LogError($"更新临时表数据失败-->", "BI大数据", string.Empty);
  865. return false;
  866. }
  867. LogHelper<BIMachineStatus>.LogError($"更新临时表数据成功-->", "BI大数据", string.Empty);
  868. return true;
  869. }
  870. return false;
  871. }
  872. }
  873. }