123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893 |
- using Cksoft.Data;
- using Cksoft.Data.Repository;
- using Cksoft.Unity;
- using Cksoft.Unity.Log4NetConfig;
- using DllEapCommon.Notice;
- using DllEapEntity;
- using DllEapEntity.Dtos;
- using DllEapEntity.OFILM;
- using Microsoft.Extensions.Logging;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Schema;
- using SharpCifs.Util.Sharpen;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace DllEapDal.OFILM
- {
- /// <summary>
- /// BI系统数据推送
- /// </summary>
- public class BICollectDal
- {
- private IDatabase CurrDb = null;
- public BICollectDal(IDatabase db)
- {
- CurrDb = db;
- }
- public BICollectDal()
- {
- }
- /// <summary>
- /// 获取未推送到BI的报警数据
- /// </summary>
- /// <returns></returns>
- private IEnumerable<McaEventStatisticByDay> GetAlarms()
- {
- string sql = $@"select a.Id,f.FCode as Manufacturer,a.EventCode,
- b.RegionId,b.FactoryId,g.Factory,
- a.AlarmCode,a.AlarmDesc,a.McaCode,b.FName as McaName,
- e.FName as MacModelName,a.StartTime,a.EndTime,a.TimeSpan,a.IsInProducing,a.IsHandled,
- e.FCode as MacModel,e.SoftVersion,c.PCode,d.FName as PName,b.IpAddress
- from McaEventStatisticByDay a
- left join Machine b on a.McaCode=b.FCode
- left join MacTProcess c on b.id=c.MacID
- left join TProcess d on c.PCode=d.FCode
- left join MacModel e on b.MModeId=e.id
- left join Supplier f on e.SupplierId=f.id
- left join FactoryRegion g on b.FactoryId=g.id "
- + $" where 1=1 and a.EventCode='C00007' and a.IsBICollect=0 ";
- return CurrDb.FindList<McaEventStatisticByDay>(sql);
- }
- /// <summary>
- /// 获取当前关机的机台
- /// </summary>
- /// <returns></returns>
- private IEnumerable<MacStatus> GetShutdownConnMacs(IDatabase db)
- {
- var sql = "select * from macstatus where statusid=204906";
- return db.FindList<MacStatus>(sql);
- }
- /// <summary>
- /// 获取机台状态
- /// </summary>
- /// <returns></returns>
- private IEnumerable<MacStatus> GetMacStatuses(DateTime dateStart, ref string errorinfo)
- {
- string sql = $@"select a.*,d.FName as Supplier,b.IpAddress,b.RegionId,
- g.FName as Factory,c.SoftVersion,f.FCode as ProcessCode,h.Project,
- c.FCode as MacModel,c.FName as MacModelName
- from macstatus a
- left join machine b on a.maccode=b.fcode
- left join macmodel c on b.mmodeid=c.id
- left join supplier d on c.supplierid =d.id
- left join MacTProcess e on b.id=e.MacID
- left join TProcess f on e.PCode=f.FCode
- left join FactoryRegion g on b.factoryId=g.Id
- left join projectandprogram h on {OfilmRecipeProvider.GenRecipeString("a")} = h.Recipe
- where (a.etime>='{dateStart}' or
- a.etime='0001-01-01 00:00:00') ";
- return CurrDb.FindList<MacStatus>(sql);
- }
- /// <summary>
- /// 获取产量数据
- /// </summary>
- /// <returns></returns>
- private IEnumerable<OutputDto> GetOutputDatas(DateTime start, DateTime end, IDatabase db)
- {
- string sql = $@"select a.fcount as count,e.fcode as pcode,e.fname as pname,f.fcode as macmodel,
- f.fname as macmodelname,c.fcode as code,c.fname as name,
- b.timelen as TimeLen,a.Id as DetailId,b.EDate as Fdate,
- {OfilmRecipeProvider.GenRecipeString("b", "pName")} programName,
- g.fName as factory,h.FName as line,i.FName as floor,k.FName Plant,
- e.fCode Work_Process,f.FCode Dev_Type,j.Project
- from maccountdetail a
- left join maccountmst b on a.mstid=b.id
- left join machine c on b.macid=c.id
- left join mactprocess d on c.id=d.macid
- left join tprocess e on d.pcode=e.fcode
- left join macmodel f on c.mmodeid=f.id
- left join factoryregion g on c.FactoryId = g.id
- left join factoryregion h on c.RegionId=h.id
- left join factoryregion i on h.ParentId=i.id
- left join factoryregion k on i.ParentId=k.id
- left join projectandprogram j on j.Recipe = {OfilmRecipeProvider.GenRecipeString("b", "PName")}
- 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")}'
- and a.paramcode='{DllHsms.StandardCode.SVID_FinishUnit}' ";
- return db.FindList<OutputDto>(sql);
- }
- /// <summary>
- /// 推送机台状态信息
- /// </summary>
- /// <param name="errorinfo"></param>
- /// <returns></returns>
- public int CollectMacStatus(ref string errorinfo)
- {
- var lastHistory = CurrDb.FindListForCondition<BIHistory>($" " +
- $"and a.Type=1 and a.Status=1 order by fdate desc", ref errorinfo).FirstOrDefault();
- DateTime dateStart;
- if (lastHistory == null)
- {
- dateStart = Convert.ToDateTime("2020-08-25 17:00:00");
- }
- else
- {
- dateStart = lastHistory.FDate;
- }
- Stopwatch watch = new Stopwatch();
- watch.Start();
- var statuses = this.GetMacStatuses(dateStart, ref errorinfo).OrderBy(c => c.RecTime);
- long ticks = watch.ElapsedMilliseconds;
- watch.Reset();
- watch.Restart();
- DateTime now = DateTime.Now;
- var biStatuses = new List<BIMachineStatus>();
- var regionDal = new FactoryRegionDal(CurrDb);
- var ids = new List<int>();
- var machines = CurrDb.FindListForCondition<Machine>(string.Empty, ref errorinfo);
- var allRegions = regionDal.Get(1, 10000, "ID", "asc", string.Empty, errorinfo);
- foreach (var item in machines)
- {
- var floor = string.Empty;
- var line = string.Empty;
- // 获取楼层及产线
- if (item.RegionId != 0)
- {
- var fullRegionName = regionDal.GetFullRegionName(item.RegionId, allRegions);
- var arr = fullRegionName.Split('/');
- if (arr.Count() == 2)
- {
- floor = arr[1];
- }
- else if (arr.Count() == 3)
- {
- floor = arr[1];
- line = arr[2];
- }
- item.Floor = floor;
- item.Line = line;
- }
- }
- if (statuses != null && statuses.Count() > 0)
- {
- foreach (var item in statuses)
- {
- var mac = machines.FirstOrDefault(c => c.FCode.ToUpper() == item.MacCode.ToUpper());
- if (mac == null)
- {
- continue;
- }
- var recipe = "";
- if (item.Remark != null)
- {
- recipe = item.Remark.Split(new char[] { '-', '_', ' ' },
- StringSplitOptions.RemoveEmptyEntries)[0];
- }
- var status = 5;
- #region 将EAP的状态码转换为BI大数据通用状态码
- if (item.StatusID == 1) // 未连接
- {
- status = 1;
- }
- else if (item.StatusID == 2) // 准备
- {
- status = 33;
- }
- else if (item.StatusID == 3) // 空闲
- {
- status = 2049;
- }
- else if (item.StatusID == 4) // 运行
- {
- status = 3;
- }
- else if (item.StatusID == 6)
- {
- status = 5;
- }
- else if (item.StatusID == 204906)
- {
- status = 2;
- }
- else
- {
- status = item.StatusID;
- }
- #endregion
- var fdate = now;
- if (item.ETime.ToString("yyyy-MM-dd HH:mm:ss") == "0001-01-01 00:00:00")
- {
- if (item.STime >= dateStart)
- {
- fdate = item.STime;
- }
- else
- {
- fdate = dateStart;
- }
- }
- else
- {
- if (item.STime >= dateStart)
- {
- fdate = item.STime;
- }
- else
- {
- fdate = dateStart;
- }
- }
- var entity = new BIMachineStatus
- {
- Description = item.AlarmDescribe == "报警解除" ? "" : item.AlarmDescribe,
- Device_Code = item.MacCode,
- Dev_IP = item.IpAddress,
- Dev_Type = item.MacModelName,
- Status_Code = item.AlarmCode,
- Factory = item.Factory,
- FDate = fdate,
- Floor = mac.Floor,
- Line = mac.Line,
- Recipe = recipe,
- Status = status,
- Version = item.SoftVersion,
- Work_Process = item.ProcessCode,
- Project = item.Project ?? "异常"
- };
- biStatuses.Add(entity);
- ids.Add(item.ID);
- }
- watch.Stop();
- long t2 = watch.ElapsedMilliseconds;
- long count = statuses.Count();
- watch.Reset();
- watch.Restart();
- var sb = new StringBuilder("insert into BIMachineStatus (Device_Code,FDate,Status,Status_Code,Description," +
- "Factory,Floor,Project,Recipe,Work_Process,Dev_Type,Line,Version," +
- "Dev_IP) Values");
- foreach (var item in biStatuses)
- {
- sb.Append($@"('{item.Device_Code}','{item.FDate}','{item.Status}','{item.Status_Code}',
- '{item.Description}','{item.Factory}','{item.Floor}','{item.Project}','{item.Recipe}',
- '{item.Work_Process}','{item.Dev_Type}','{item.Line}','{item.Version}','{item.Dev_IP}'),");
- }
- sb.Remove(sb.Length - 1, 1);
- sb.Append(";");
- if (CurrDb.ExecuteBySql(sb.ToString()) < 0)
- {
- errorinfo = "数据汇总失败";
- return -1;
- }
- watch.Stop();
- long t3 = watch.ElapsedMilliseconds;
- var history = new BIHistory
- {
- FDate = now,
- Status = 1,
- Type = 1
- };
- CurrDb.InsertFor(history, string.Empty);
- }
- return 1;
- }
- /// <summary>
- /// 推送机台
- /// </summary>
- /// <param name="errorinfo"></param>
- /// <returns></returns>
- public int CollectOutput(int delay, ref string errorinfo)
- {
- var now = DateTime.Now.AddMinutes(-delay);
- var lastPushDate = CurrDb.FindListForCondition<BIHistory>(" and 1=1 order by id desc limit 0,1",
- ref errorinfo).FirstOrDefault();
- var lastTime = now.AddMinutes(-10);
- if (lastPushDate != null && lastPushDate.FDate > now.AddHours(-5))
- {
- lastTime = lastPushDate.FDate;
- }
- //lastTime = now.AddMinutes(-30);
- var times = Math.Floor((now - lastTime).TotalMinutes / 10);
- for (int i = 0; i < times; i++)
- {
- var start = lastTime.AddMinutes(i * 10);
- var end = start.AddMinutes(10);
- using (IDatabase db = DbFactory.Base("eap"))
- {
- var shutdownMacs = this.GetShutdownConnMacs(db);
- var datas = this.GetOutputDatas(start, end, db);
- if (datas != null && datas.Count() > 0)
- {
- var macRecipeGroups = datas.GroupBy(c => new { c.Code, c.ProgramName });
- var list = new List<BIOutput>();
- foreach (var item in macRecipeGroups)
- {
- var entity = new BIOutput
- {
- All_Product = item.Sum(c => c.Count),
- Device_Code = item.Key.Code,
- FDate = end,
- Goods = item.Sum(c => c.Count),
- Recipe = item.Key.ProgramName,
- Factory = item.FirstOrDefault().Factory,
- Plant = item.FirstOrDefault()?.Plant,
- Floor = item.FirstOrDefault().Floor,
- Line = item.FirstOrDefault().Line,
- Project = item.FirstOrDefault().Project,
- Dev_Type = item.FirstOrDefault().Dev_Type,
- Work_Process = item.FirstOrDefault().Work_Process
- };
- list.Add(entity);
- }
- if (list != null && list.Count > 0)
- {
- foreach (var item in list)
- {
- if (string.IsNullOrEmpty(item.Device_Code) || item.Device_Code.Length != 7)
- {
- continue;
- }
- var status = db.FindListForCondition<MacStatus01>($" and a.maccode='{item.Device_Code}' order by id desc",
- ref errorinfo).FirstOrDefault();
- if (status != null && (status.StatusID == 1 || status.StatusID == 204906) && item.Goods == 0)
- {
- continue;
- }
- CallEESServiceOutput(item);
- }
- }
- var pushHistory = new BIHistory
- {
- FDate = end,
- Type = 1
- };
- if (db.InsertFor(pushHistory, string.Empty) < 0)
- {
- errorinfo = "新增推送历史失败";
- continue;
- }
- //}
- }
- }
- }
- return 1;
- }
- /// <summary>
- /// 推送产量数据到BI接口
- /// </summary>
- /// <param name="bIOutput"></param>
- private void CallEESServiceOutput(BIOutput bIOutput)
- {
- string errorinfo = string.Empty;
- EES.EESDeviceReportServiceClient client = null;
- try
- {
- client = new EES.EESDeviceReportServiceClient();
- var str = JsonConvert.SerializeObject(bIOutput, new JsonSerializerSettings
- {
- DateFormatString = "yyyy-MM-dd HH:mm:ss"
- });
- var res = client.eesProductSumReport(str);
- if (!string.IsNullOrEmpty(res))
- {
- var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(res);
- if (dictionary != null && dictionary.ContainsKey("resultCode") && dictionary["resultCode"] == "OK")
- {
- LogHelper<BIMachineStatus>.LogError($"推送产量BI数据成功-->{JsonConvert.SerializeObject(bIOutput)}", "BI大数据", string.Empty);
- }
- else
- {
- var msg = dictionary.ContainsKey("msg") ? dictionary["msg"] : "推送失败";
- var content = $"推送BI数据失败[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}],异常为:{msg}";
- ServiceErrorNoticeHelper.Notice(content, ref errorinfo);
- LogHelper<BIMachineStatus>.LogError($"推送BI产量数据成功-->{JsonConvert.SerializeObject(bIOutput)}", "BI大数据", string.Empty);
- }
- }
- }
- catch (Exception ex)
- {
- var content = $"推送BI数据失败[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}],异常为:{ex.Message}";
- ServiceErrorNoticeHelper.Notice(content, ref errorinfo);
- LogHelper<BIMachineStatus>.LogError($"推送BI产量数据失败-->{ex.ToString()}", "BI大数据", string.Empty);
- }
- finally
- {
- client.CloseAsync();
- }
- }
- /// <summary>
- /// 将机台状态转换成BI接口接收的实体并调用接口推送
- /// </summary>
- /// <param name="macStatus"></param>
- /// <param name="errorinfo"></param>
- public void PushStatusToBI(IEnumerable<MacStatus> macStatuses, string errorinfo)
- {
- Task.Run(() =>
- {
- if (macStatuses != null && macStatuses.Count() > 0)
- {
- var list = new List<BIMachineStatus>();
- foreach (var macStatus in macStatuses)
- {
- var recipe = string.Empty;
- if (!string.IsNullOrEmpty(macStatus.Remark))
- {
- recipe = macStatus.Remark.Replace(".", "-").Replace("_", "-").Replace(" ", "-").Split("-")?[0];
- }
- var sql = $@"select a.FCode Device_Code,a.IpAddress Dev_IP,b.FCode Dev_Type,b.SoftVersion Version,
- c.FCode Work_Process,d.FName Factory,e.FName Floor,f.FName Line,h.FName Plant
- from Machine a
- left join MacModel b on a.MModeID=b.Id
- left join MacTProcess g on a.id=g.macid
- left join TProcess c on g.PCode=c.FCode
- left join FactoryRegion d on a.FactoryId=d.id
- left join FactoryRegion f on a.RegionId=f.id
- left join FactoryRegion e on f.ParentId=e.id
- left join FactoryRegion h on e.ParentId=h.id
- where a.FCode='{macStatus.MacCode}'";
- var biStatus = CurrDb.FindList<BIMachineStatus>(sql).FirstOrDefault();
- var project = "未维护";
- if (!string.IsNullOrEmpty(recipe))
- {
- sql = $"select project from projectandprogram where recipe='{recipe}'";
- project = CurrDb.FindList<string>(sql).FirstOrDefault() ?? "未维护";
- }
- biStatus.Recipe = recipe;
- // biStatus.Status = macStatus.StatusID;
- biStatus.Status_Code = macStatus.AlarmCode;
- biStatus.Description = macStatus.AlarmDescribe;
- biStatus.Project = project;
- var standard = CurrDb.FindListForCondition<StandardStatus>($" and a.StatusVal={macStatus.StatusID}", ref errorinfo)
- .FirstOrDefault();
- var status = 1;
- #region 将EAP的状态码转换为BI大数据通用状态码
- if (macStatus.StatusID == 1) // 未连接
- {
- status = 1;
- }
- else if (macStatus.StatusID == 4) // 运行
- {
- status = 3;
- }
- else if (macStatus.StatusID == 6)
- {
- if (string.IsNullOrEmpty(macStatus.AlarmDescribe))
- {
- biStatus.Description = "故障";
- biStatus.Status_Code = "0";
- }
- status = 5;
- }
- else if (macStatus.StatusID == 204906)
- {
- status = 2;
- }
- else if (macStatus.StatusID == 3 || macStatus.StatusID == 10 || (macStatus.StatusID > 200000
- && macStatus.StatusID != 204906)) // 空闲
- {
- status = 2049;
- biStatus.Status_Code = macStatus.StatusID.ToString();
- if (macStatus.StatusID == 204907)
- {
- biStatus.Status_Code = "204906";
- }
- else if (macStatus.StatusID == 204908)
- {
- biStatus.Status_Code = "204907";
- }
- else if (macStatus.StatusID == 204999)
- {
- biStatus.Status_Code = "204908";
- }
- biStatus.Description = standard.FName;
- if (macStatus.StatusID == 3)
- {
- biStatus.Status_Code = "0";
- }
- }
- else
- {
- status = 2049;
- biStatus.Status_Code = "204908";
- biStatus.Description = "其他";
- }
- #endregion
- biStatus.Status = status;
- biStatus.FDate = macStatus.STime;
- if (biStatus.Status != 2049 && biStatus.Status != 5)
- {
- biStatus.Status_Code = "0";
- biStatus.Description = standard.FName;
- }
- if (biStatus.Description == "运行")
- biStatus.Description = "稼动";
- if (biStatus.Description == "空闲")
- biStatus.Description = "待机";
- list.Add(biStatus);
- }
- CallEESServiceMacStatus(list);
- }
- });
- }
- public async Task PushStatusToBIBatch(IEnumerable<MacStatus> macStatuses, string errorinfo)
- {
- if (macStatuses != null && macStatuses.Count() > 0)
- {
- var list = new List<BIMachineStatus>();
- foreach (var macStatus in macStatuses)
- {
- var recipe = string.Empty;
- if (!string.IsNullOrEmpty(macStatus.Remark))
- {
- recipe = macStatus.Remark.Replace(".", "-").Replace("_", "-").Replace(" ", "-").Split("-")?[0];
- }
- var sql = $@"select a.FCode Device_Code,a.IpAddress Dev_IP,b.FCode Dev_Type,b.SoftVersion Version,
- c.FCode Work_Process,d.FName Factory,e.FName Floor,f.FName Line,h.FName Plant
- from Machine a
- left join MacModel b on a.MModeID=b.Id
- left join MacTProcess g on a.id=g.macid
- left join TProcess c on g.PCode=c.FCode
- left join FactoryRegion d on a.FactoryId=d.id
- left join FactoryRegion f on a.RegionId=f.id
- left join FactoryRegion e on f.ParentId=e.id
- left join FactoryRegion h on e.ParentId=h.id
- where a.FCode='{macStatus.MacCode}'";
- var biStatus = CurrDb.FindList<BIMachineStatus>(sql).FirstOrDefault();
- if (biStatus == null)
- continue;
- var project = "未维护";
- if (!string.IsNullOrEmpty(recipe))
- {
- sql = $"select project from projectandprogram where recipe='{recipe}'";
- project = CurrDb.FindList<string>(sql).FirstOrDefault() ?? "未维护";
- }
- biStatus.Recipe = recipe;
- // biStatus.Status = macStatus.StatusID;
- biStatus.Status_Code = macStatus.AlarmCode;
- biStatus.Description = macStatus.AlarmDescribe;
- biStatus.Project = project;
- var standard = CurrDb.FindListForCondition<StandardStatus>($" and a.StatusVal={macStatus.StatusID}", ref errorinfo)
- .FirstOrDefault();
- var status = 1;
- #region 将EAP的状态码转换为BI大数据通用状态码
- if (macStatus.StatusID == 1) // 未连接
- {
- status = 1;
- }
- else if (macStatus.StatusID == 4) // 运行
- {
- status = 3;
- }
- else if (macStatus.StatusID == 6)
- {
- if (string.IsNullOrEmpty(macStatus.AlarmDescribe))
- {
- biStatus.Description = "故障";
- biStatus.Status_Code = "0";
- }
- status = 5;
- if (macStatus.AlarmCode == "SVID")
- {
- status = 2049;
- biStatus.Status_Code = "0";
- biStatus.Description = "空闲";
- }
- }
- else if (macStatus.StatusID == 204906)
- {
- status = 2;
- }
- else if (macStatus.StatusID == 3 || macStatus.StatusID == 10 || (macStatus.StatusID > 200000
- && macStatus.StatusID != 204906)) // 空闲
- {
- status = 2049;
- biStatus.Status_Code = macStatus.StatusID.ToString();
- if (macStatus.StatusID == 204907)
- {
- biStatus.Status_Code = "204906";
- }
- else if (macStatus.StatusID == 204908)
- {
- biStatus.Status_Code = "204907";
- }
- else if (macStatus.StatusID == 204999)
- {
- biStatus.Status_Code = "204908";
- }
- biStatus.Description = standard.FName;
- if (macStatus.StatusID == 3)
- {
- biStatus.Status_Code = "0";
- }
- }
- else
- {
- status = 2049;
- biStatus.Status_Code = "204908";
- biStatus.Description = "其他";
- }
- #endregion
- biStatus.Status = status;
- biStatus.FDate = macStatus.STime;
- if (biStatus.Status != 2049 && biStatus.Status != 5)
- {
- biStatus.Status_Code = "0";
- biStatus.Description = standard.FName;
- }
- if (biStatus.Description == "运行")
- biStatus.Description = "稼动";
- if (biStatus.Description == "空闲")
- biStatus.Description = "待机";
- list.Add(biStatus);
- }
- await CallEESServiceMacStatusBatch(list);
- }
- }
- /// <summary>
- /// 推送机台状态到BI接口
- /// </summary>
- /// <param name="bIOutput"></param>
- private async Task CallEESServiceMacStatus(IEnumerable<BIMachineStatus> bIMachineStatus)
- {
- EES.EESDeviceReportServiceClient client = null;
- var str = JsonConvert.SerializeObject(bIMachineStatus.First(), new JsonSerializerSettings
- {
- DateFormatString = "yyyy-MM-dd HH:mm:ss"
- });
- try
- {
- client = new EES.EESDeviceReportServiceClient();
- var body = await client.eesDeviceStatusReportAsync(str);
- // var body = client.eesDeviceStatusReport(str);
- var res = body.Body.@return;
- if (!string.IsNullOrEmpty(res))
- {
- var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(res);
- if (dictionary != null && dictionary.ContainsKey("resultCode") && dictionary["resultCode"] == "OK")
- {
- LogHelper<BIMachineStatus>.LogError($"推送BI数据成功-->{JsonConvert.SerializeObject(bIMachineStatus)}", "BI大数据", string.Empty);
- }
- else
- {
- var msg = dictionary.ContainsKey("msg") ? dictionary["msg"] : "推送失败";
- LogHelper<BIMachineStatus>.LogError($"推送BI数据失败-->{msg}", "BI大数据", string.Empty);
- using (IDatabase eapDb = DbFactory.Base("eap"))
- {
- if (CurrDb.InsertFor<BIMachineStatus>(bIMachineStatus.First(), string.Empty) < 0)
- {
- LogHelper<BIMachineStatus>.LogError($"保存推送失败数据错误-->{str}", "BI大数据", string.Empty);
- }
- else
- {
- LogHelper<BIMachineStatus>.LogError($"保存推送失败数据成功-->{str}", "BI大数据", string.Empty);
- }
- }
- }
- }
- else
- {
- LogHelper<BIMachineStatus>.LogError($"推送BI数据失败-->接口返回NULL", "BI大数据", string.Empty);
- using (IDatabase eapDb = DbFactory.Base("eap"))
- {
- if (CurrDb.InsertFor<BIMachineStatus>(bIMachineStatus.First(), string.Empty) < 0)
- {
- LogHelper<BIMachineStatus>.LogError($"保存推送失败数据错误-->{str}", "BI大数据", string.Empty);
- }
- else
- {
- LogHelper<BIMachineStatus>.LogError($"保存推送失败数据成功-->{str}", "BI大数据", string.Empty);
- }
- }
- }
- }
- catch (Exception ex)
- {
- LogHelper<BIMachineStatus>.LogError($"推送BI数据失败-->{ex.Message}", "BI大数据", string.Empty);
- using (IDatabase eapDb = DbFactory.Base("eap"))
- {
- if (CurrDb.InsertFor<BIMachineStatus>(bIMachineStatus.First(), string.Empty) < 0)
- {
- LogHelper<BIMachineStatus>.LogError($"保存推送失败数据错误-->{str}", "BI大数据", string.Empty);
- }
- else
- {
- LogHelper<BIMachineStatus>.LogError($"保存推送失败数据成功-->{str}", "BI大数据", string.Empty);
- }
- }
- }
- finally
- {
- await client.CloseAsync();
- }
- }
- private DataTable GetMesMacID(string maccode, ref string errorinfo)
- {
- IDatabase db = null;
- try
- {
- db = DbFactory.Base("ofilmoracle");
- //string sqlstr = $"select * from APPSERVER";
- string sqlstr = $@"select t.EQUIPMENT_NAME from ccmmesprd.ccm_equipset_v t
- where t.ORG_RRN=10000
- and t.EQUIPMENT_ID='{maccode}'
- and t.IS_ACTIVE='Y'";
- DataTable dt = db.FindTable(sqlstr);
- return dt;
- }
- catch (Exception ex)
- {
- errorinfo = ex.ToString();
- return null;
- }
- finally
- {
- if (db != null)
- db.Close();
- }
- }
- /// <summary>
- /// 调用改机接口
- /// </summary>
- /// <param name="maccode"></param>
- /// <returns></returns>
- public int CallQis(MacStatus status, string oldRecipe, ref string errorinfo)
- {
- try
- {
- var maccode = status.MacCode;
- DataTable tempdt = GetMesMacID(maccode, ref errorinfo);
- if (tempdt == null)
- {
- errorinfo = $"读取MES库错误:{errorinfo}";
- return -1;
- }
- if (tempdt.Rows.Count <= 0)
- {
- errorinfo = $"MES库中未找到机台编号={maccode}对应的信息";
- return -1;
- }
- if (string.IsNullOrEmpty(tempdt.Rows[0]["EQUIPMENT_NAME"].ToString()))
- {
- errorinfo = $"MES库中找到机台编号={maccode}对应的信息为:{tempdt.Rows[0]["EQUIPMENT_NAME"].ToString()}";
- return -1;
- }
- var alarmInfo = string.Empty;
- var recipe = status.Remark.Replace(" ", "-").Replace("_", "-").Split("-")[0];
- alarmInfo = $"{status.STime.ToString("yyyy-MM-dd HH:mm")}未来城园区一楼,生产机台编号{tempdt.Rows[0]["EQUIPMENT_NAME"].ToString()}," +
- $"因由{oldRecipe}机种切换到{recipe}机种自动触发停机单";
- string jsonstr = "{ \"businessUnitCode\": \"751754\",\"businessUnitName\": \"未来城园区\",\"model\": \"" + recipe + "\",\"floor\": \"一楼\",\"equipmentName\": \""
- + tempdt.Rows[0]["EQUIPMENT_NAME"].ToString() + "\",\"stopMachineDesc\": \"" + alarmInfo + "\",\"stopType\": \"改机首件停机\"}";
- LogHelper<BIMachineStatus>.LogError(jsonstr, "改机", string.Empty);
- // var body = await client.eesDeviceStatusListReportAsync(str);
- Qis.ReceiveStopMachineFromMesClient clinet = new Qis.ReceiveStopMachineFromMesClient();
- string result = clinet.receive(jsonstr);
- if (string.IsNullOrEmpty(result))
- {
- errorinfo = $"机台编号={maccode}调用改机接口失败,未知错误......";
- return -1;
- }
- var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
- if (dictionary != null && dictionary.ContainsKey("code") && dictionary["code"] == "1")
- {
- LogHelper<BIMachineStatus>.LogError($"调用QIS接口成功-->机台编号={maccode}", "改机", string.Empty);
- return 1;
- }
- else
- {
- var msg = dictionary.ContainsKey("message") ? dictionary["message"] : "调用改机失败";
- LogHelper<BIMachineStatus>.LogError($"调用改机失败-->机台编号={maccode}", "改机", string.Empty);
- LogHelper<BIMachineStatus>.LogError(JsonConvert.SerializeObject(dictionary), "改机", string.Empty);
- errorinfo = msg;
- return -1;
- }
- }
- catch (Exception ex)
- {
- LogHelper<BIMachineStatus>.LogError($"调用改机发生异常-->{ex.ToString()}", "改机", string.Empty);
- errorinfo = ex.ToString();
- return -1;
- }
- }
- private async Task<bool> CallEESServiceMacStatusBatch(IEnumerable<BIMachineStatus> bIMachineStatuses)
- {
- EES.EESDeviceReportServiceClient client = null;
- string errorinfo = string.Empty;
- try
- {
- client = new EES.EESDeviceReportServiceClient();
- var obj = new EqpStatusDataList() { EesEqpDataList = bIMachineStatuses.ToList() };
- var str = JsonConvert.SerializeObject(obj, new JsonSerializerSettings
- {
- DateFormatString = "yyyy-MM-dd HH:mm:ss"
- });
- // var body = await client.eesDeviceStatusListReportAsync(str);
- var body = client.eesDeviceStatusListReport(str);
- var res = body;
- if (!string.IsNullOrEmpty(res))
- {
- var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(res);
- if (dictionary != null && dictionary.ContainsKey("resultCode") && dictionary["resultCode"] == "OK")
- {
- LogHelper<BIMachineStatus>.LogError($"推送BI数据成功-->{str}", "BI大数据", string.Empty);
- return true;
- }
- else
- {
- var msg = dictionary.ContainsKey("msg") ? dictionary["msg"] : "推送失败";
- var content = $"推送BI状态数据失败[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}],服务器:[{AppConfigurtaionServices.Configuration["SystemCode"]}],异常为:{msg}";
- ServiceErrorNoticeHelper.Notice(content, ref errorinfo);
- LogHelper<BIMachineStatus>.LogError($"推送BI数据失败-->{msg}", "BI大数据", string.Empty);
- return false;
- }
- }
- return false;
- }
- catch (Exception ex)
- {
- LogHelper<BIMachineStatus>.LogError($"推送BI数据失败-->{ex.ToString()}", "BI大数据", string.Empty);
- var content = $"推送BI数据失败[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}],服务器:[{AppConfigurtaionServices.Configuration["SystemCode"]}],异常为:{ex.Message}";
- ServiceErrorNoticeHelper.Notice(content, ref errorinfo);
- return false;
- }
- finally
- {
- await client.CloseAsync();
- }
- }
- public async Task<bool> PushFailedDatas(string errorifo)
- {
- var datas = CurrDb.FindListForCondition<BIMachineStatus>(string.Empty, ref errorifo);
- if (datas == null || datas.Count() <= 0)
- {
- return true;
- }
- var idArray = datas.Select(c => c.Id).ToList();
- var res = await CallEESServiceMacStatusBatch(datas);
- if (res)
- {
- var sql = $"DELETE FROM bimachinestatus where id in ({string.Join(",", idArray)})";
- if (CurrDb.ExecuteBySql(sql) < 0)
- {
- LogHelper<BIMachineStatus>.LogError($"更新临时表数据失败-->", "BI大数据", string.Empty);
- return false;
- }
- LogHelper<BIMachineStatus>.LogError($"更新临时表数据成功-->", "BI大数据", string.Empty);
- return true;
- }
- return false;
- }
- }
- }
|