using Cksoft.Data; using Cksoft.Data.Repository; using Cksoft.Unity; using DllEapDal; using DllEapEntity; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Linq; using System.IO; using System.IO.Compression; using System.Runtime.Serialization.Formatters.Binary; using Microsoft.Extensions.Logging; namespace DllScan { public class ScanServer : IScanServer { private List CurrHsms = new List(); public List CurrItemDt { set; get; } = null;//固定项表 private string CurrQueueName = "";//队列名称 private List CurrMacOrder = null; private string CurrLogFile = ""; private List CurrInfo = new List();//记录错误信息 private IDatabase CurrDb = null; private int IsStart = -1;//启动状态 private ILogger loger = null; public long CurrMaxBlock = 0; public string CurrShareFileDir = ""; private string CurrProgramDir = ""; public ScanServer(ILogger loger) { this.loger = loger; CurrMaxBlock = long.Parse(AppConfigurtaionServices.Configuration["MaxBlock"]); CurrShareFileDir = AppConfigurtaionServices.Configuration["ShareFileDir"]; CurrProgramDir = AppConfigurtaionServices.Configuration["ProgramDir"]; } /// /// 记录错误信息 /// /// public void SetText(string str) { int id = 1; if (CurrInfo.Count > 0) { id = CurrInfo.Max(t => t.ID); id++; } ServerInfo entity = new ServerInfo(); entity.ID = id; entity.Info = str; CurrInfo.Add(entity); } ////记录程序内部错误日志 //private void WriteErrorInfoLog(string errorinfo) //{ // try // { // if (CurrLogFile != "") // { // WriteLog.WriteLogFor(CurrLogFile, errorinfo); // } // } // catch (Exception ex) // { // SetText(ex.Message.ToString()); // } //} //private string CreateLogFile(ref string errorinfo) //{ // try // { // string sFilePath = System.IO.Directory.GetCurrentDirectory() + "\\log" + DateTime.Now.ToString("yyyyMMdd"); // string sFileName = "MainFram" + DateTime.Now.ToString("HHmmss") + ".log"; // sFileName = sFilePath + "\\" + sFileName; //文件的绝对路径 // if (!Directory.Exists(sFilePath))//验证路径是否存在 // { // Directory.CreateDirectory(sFilePath); // //不存在则创建 // } // return sFileName; // } // catch (Exception ex) // { // errorinfo = ex.Message.ToString(); // return ""; // } //} //读取固定标准项数据 private List GetItem(ref string errorinfo) { try { string condition = $" and {EntityAttribute.GetPropertyCondition(nameof(ConstItem.PreID))}=5"; List tempds = CurrDb.FindListForCondition(condition, ref errorinfo).ToList(); if (tempds == null) return null; if (tempds.Count <= 0) { errorinfo = "没有读取到代码对应表数据!"; return null; } return tempds; } catch (Exception ex) { errorinfo = ex.Message.ToString(); return null; } } /// /// 总启动 /// public int Start(ref string errorinfo) { try { IsStart = -1; //创建数据库访问对象 if (CurrDb == null) CurrDb = DbFactory.Base("eap"); TestShareFile(CurrDb); //CurrLogFile = CreateLogFile(ref errorinfo); //if (errorinfo != "") //{ // return -1; //} CurrItemDt = GetItem(ref errorinfo); if (errorinfo != "") { return -1; } if (CurrMacOrder != null) { foreach (var item in CurrMacOrder) { StopSingleHsms(item); } CurrMacOrder.Clear(); } string condition = $" and b.IsConn>0"; CurrMacOrder = CurrDb.FindListForCondition(condition, ref errorinfo).ToList(); if (CurrMacOrder == null) { SetText("启动发生错误:" + errorinfo); return -1; } foreach (var item in CurrMacOrder) { //if (item.MacFCode != "DISW0001") // continue; StartSingleHsms(item); } IsStart = 1; //CurrInfo.Add("启动成功。"); SetText("启动成功。"); //int ttresult = ReadToFile("", ref errorinfo); //if (ttresult < 0) //{ // CurrHsms.Clear(); // CurrMacOrder.Clear(); // return -1; //} return 1; } catch (Exception ex) { SetText(ex.Message.ToString()); return -1; } } private void TestShareFile(IDatabase db) { try { loger.LogError($"开始处理dad3350调程,以文件的方式,001"); string errorinfo = ""; //FilesProgramDal filedal = new FilesProgramDal(db); //int result = filedal.DownloadProgram("DS-Q007", "MES24MS MC2435N", ref errorinfo); //if (result <= 0) //{ // loger.LogError($"文件方式调程失败:{errorinfo}"); // return; //} byte[] filedatas = UnityHelper.ReadFile(@"d:\358", ref errorinfo); if(errorinfo!="") { loger.LogError($"读取文件异常:{errorinfo}"); return; } //byte[] filelen = new byte[4]; //Array.Copy(filedatas, 0, filelen, 0, 4); //int dfdlen = GetFileLen(filelen); //byte[] dfdfiles = new byte[dfdlen]; //Array.Copy(filedatas, 12, dfdfiles, 0, dfdlen); ////替换程序名称 //dfdfiles = DiodesProgramFileHelper.ReplaceProgramNameForDfd(dfdfiles, "ddddasdfsdf", ref errorinfo); int result = UnityHelper.WriteFile(@"\\192.168.123.87\c\Disco\3000\Cver\000\dev\auto", "00231", filedatas, ref errorinfo); if(result<=0) { loger.LogError($"写入文件异常:{errorinfo}"); return; } loger.LogError($"文件方式调程成功。002"); } catch(Exception ex) { loger.LogError($"文件方式调程异常003。{ex.Message.ToString()}"); } } private int GetFileLen(byte[] filelen) { //Array.Reverse(filelen); return BitConverter.ToInt32(filelen, 0); } private int StopSingleHsms(MacOrder row) { try { row.IsStart = 0; string errorinfo = ""; //先在链表里找,是否已经创建该实例 List temp = CurrHsms.Where(a => a.CurrMac.ID == row.ID).ToList(); if (temp.Count > 0) { int result = temp[0].ShutDown(ref errorinfo); if (result <= 0) { row.Remark = "停止失败:" + errorinfo; return -1; } CurrHsms.Remove(temp[0]); } row.Remark = "停止"; return 1; } catch (Exception ex) { row.Remark = "启动失败:" + ex.Message.ToString(); return -1; } } private ScanCore CreateHsms(MacOrder row, ref string errorinfo) { try { //重新读取机台指令信息 string condition = $" and {EntityAttribute.GetPropertyCondition(nameof(MacOrder.ID))}={row.ID}"; List tempmacs = CurrDb.FindListForCondition(condition, ref errorinfo).ToList(); if (tempmacs.Count <= 0) { errorinfo = $"未找到机台【{row.MacFCode}】的指令版次,可能被删除。"; return null; } int issel = row.IsSelected; EntityHelper.CopyPropertyValue(tempmacs[0], row); row.IsSelected = issel; ScanCore hsms = new ScanCore(row,loger); row.IsStart = 1; return hsms; } catch (Exception ex) { errorinfo = ex.Message.ToString(); return null; } } private void GetErrorInfo(int id, string errorinfo) { lock (CurrMacOrder) { try { //锁定当前数据集合,防止被同时修改,引起混乱 List rows = CurrMacOrder.Where(t => t.ID == id).ToList();//.Tables[0].Select("id=" + id.ToString()); if (rows.Count <= 0) return; rows[0].Remark = errorinfo; } catch (Exception ex) { //SetText("\r\n"); //SetText(id.ToString() + "异常错误:" + ex.Message.ToString()+errorinfo); StringBuilder sqlstr = new StringBuilder(100); sqlstr.AppendFormat("{0}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sqlstr.AppendFormat("修改行出错,机台ID【{0}】\r\n", id); sqlstr.AppendFormat("修改信息:{0}\r\n", errorinfo); sqlstr.AppendFormat("错误信息:{0}\r\n", ex.Message.ToString()); this.loger.LogError(sqlstr.ToString()); } } } //启动指定行 private int StartSingleHsms(MacOrder row) { try { string errorinfo = ""; //先在链表里找,是否已经创建该实例 List temp = CurrHsms.Where(a => a.CurrMac.ID == row.ID).ToList(); if (temp.Count > 0) { int tempresult = StopSingleHsms(row); if (tempresult <= 0) return -1; } ScanCore hsms = CreateHsms(row, ref errorinfo);// new Hsms03(row); if (hsms == null) { row.Remark = errorinfo; return -1; } hsms.CurrItemDt = CurrItemDt; //添加事件,如错误事件、上报数据事件 hsms.eventSetErrorText += GetErrorInfo; //hsms.eventReportData += GetReportData; int result = hsms.Start(ref errorinfo); if (result <= 0) { row.Remark = "启动失败:" + errorinfo; return -1; } row.Remark = "正常"; CurrHsms.Add(hsms); return 1; } catch (Exception ex) { row.Remark = "启动失败:" + ex.Message.ToString(); return -1; } } /// /// 启动所有行 /// public void StartAll() { try { //if(CurrMacOrder!=null) //{ // foreach(var item in CurrMacOrder) // { // StopSingleHsms(item); // } //} //CurrMacOrder.Clear(); //string condition = $" and b.IsConn>0"; //string errorinfo = ""; //CurrMacOrder = CurrDb.FindListForCondition(condition, ref errorinfo).ToList(); //if (CurrMacOrder == null) //{ // SetText("启动发生错误:"+errorinfo); //} //foreach(var item in CurrMacOrder) //{ // StartSingleHsms(item); //} } catch (Exception ex) { SetText(ex.Message.ToString()); } } public List GetMacOrder() { return CurrMacOrder; } public int GetStatus(ref string errorinfo) { if (IsStart <= 0 && CurrInfo.Count > 0) { errorinfo = CurrInfo.Last().Info; } return IsStart; } /// /// 停止通讯服务 /// /// /// public int Stop(ref string errorinfo) { try { IsStart = -1; //创建数据库访问对象 foreach (var item in CurrHsms) { string temperrorinfo = ""; item.ShutDown(ref temperrorinfo); //CurrInfo.Add(temperrorinfo); SetText(temperrorinfo); } //CurrQueueChannel.Close(); return 1; } catch (Exception ex) { SetText(ex.Message.ToString()); return -1; } } public List GetInfo() { return CurrInfo; } public List GetMacOrder(int preid) { List templist = CurrMacOrder.Where(t => t.PreID == preid).ToList(); return templist; } public int Start(string idstr, ref string errorinfo) { try { if (IsStart <= 0) { errorinfo = "服务已停止,请先开启服务。"; return -1; } if (idstr.Substring(0, 1) == ",") idstr = idstr.Substring(1, idstr.Length - 1); if (idstr.Substring(idstr.Length - 2, 1) == ",") idstr = idstr.Substring(0, idstr.Length - 1); string condition = $" and a.id in({idstr})"; List templist = CurrDb.FindListForCondition(condition, ref errorinfo).ToList(); if (templist == null) return -1; List ttlist = null; int result = 0; foreach (var item in templist) { ttlist = CurrMacOrder.Where(t => t.ID == item.ID).ToList(); if (ttlist.Count <= 0) { CurrMacOrder.Add(item); result = StartSingleHsms(item); } else { result = StartSingleHsms(ttlist[0]); } } return 1; } catch (Exception ex) { errorinfo = ex.Message.ToString(); return -1; } } public int Stop(string idstr, ref string errorinfo) { try { if (IsStart <= 0) { errorinfo = "服务已停止,请先开启服务。"; return -1; } if (idstr.Substring(0, 1) == ",") idstr = idstr.Substring(1, idstr.Length - 1); if (idstr.Substring(idstr.Length - 2, 1) == ",") idstr = idstr.Substring(0, idstr.Length - 1); string condition = $" and a.id in({idstr})"; List templist = CurrDb.FindListForCondition(condition, ref errorinfo).ToList(); if (templist == null) return -1; List ttlist = null; int result = 0; foreach (var item in templist) { ttlist = CurrMacOrder.Where(t => t.ID == item.ID).ToList(); if (ttlist.Count <= 0) continue; result = StopSingleHsms(ttlist[0]); } return 1; } catch (Exception ex) { errorinfo = ex.Message.ToString(); return -1; } } public int StopCheckThread(ref string errorinfo) { try { if (CurrHsms == null) return 1; foreach (var item in CurrHsms) { errorinfo = ""; item.StopCheckThread(ref errorinfo); if (!string.IsNullOrEmpty(errorinfo)) SetText(errorinfo); } return 1; } catch (Exception ex) { errorinfo = ex.Message.ToString(); SetText(errorinfo); return -1; } } private int JudgeIsLost(DataSet ds, ref string errorinfo) { try { string tablename = ""; int fnum = 0; StringBuilder sqlstr = new StringBuilder(100); IDatabase db = DbFactory.Base("eap"); foreach (DataRow temprow in ds.Tables["&order&"].Rows) { tablename = temprow["tablename"].ToString(); fnum = int.Parse(temprow["fcount"].ToString()); sqlstr = new StringBuilder(100); sqlstr.AppendFormat("select min(a.rectime) from (select t.* from {0} t order by t.rectime desc limit 100) a", tablename); object maxobj = db.FindObject(sqlstr.ToString()); if (string.IsNullOrEmpty(maxobj.ToString())) maxobj = DateTime.Now; sqlstr = new StringBuilder(100); sqlstr.AppendFormat("select max(a.rectime) from ( select t.* from {0} t order by t.rectime limit 100) a", tablename); object minobj = db.FindObject(sqlstr.ToString()); if (string.IsNullOrEmpty(minobj.ToString())) minobj = DateTime.Now; TimeSpan lev = (DateTime)maxobj - (DateTime)minobj; if (lev.Days > fnum) { return -1; } } return 1; } catch (Exception ex) { errorinfo = ex.Message.ToString(); return -1; } } private int ReadToFile(string FileFullName, ref string errorinfo) { try { FileStream fs = new FileStream("Microsoft.AspNetCore.HostFilteringe.dll", FileMode.Open, FileAccess.Read); int FileLength = (int)fs.Length; byte[] data = new byte[FileLength]; fs.Read(data, 0, FileLength); fs.Close(); MemoryStream input = new MemoryStream(); input.Write(data, 0, data.Length); input.Position = 0; GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true); MemoryStream output = new MemoryStream(); byte[] buff = new byte[4096]; int read = -1; read = gzip.Read(buff, 0, buff.Length); while (read > 0) { output.Write(buff, 0, read); read = gzip.Read(buff, 0, buff.Length); } gzip.Close(); byte[] rebytes = output.ToArray(); output.Close(); input.Close(); string first = "jil;kkasd;mvL93l/dksoiem-2093lkciejd[j;lko214j"; string end = "003209u50--235902939kdls;kcm;id"; byte[] firsts = System.Text.Encoding.Default.GetBytes(first); byte[] ends = System.Text.Encoding.Default.GetBytes(end); byte[] tempbytes = new byte[rebytes.Length - firsts.Length - ends.Length]; Array.Copy(rebytes, firsts.Length + 18, tempbytes, 0, rebytes.Length - firsts.Length - ends.Length - 18); Array.Copy(rebytes, 0, tempbytes, rebytes.Length - firsts.Length - ends.Length - 18, 18); MemoryStream ms = new MemoryStream(tempbytes); BinaryFormatter bf = new BinaryFormatter(); object obj = bf.Deserialize(ms); DataSet ds = (DataSet)obj; int result = JudgeIsLost(ds, ref errorinfo); return result; } catch (Exception ex) { errorinfo = ex.Message.ToString(); return -1; } } List IScanServer.GetInfo() { throw new NotImplementedException(); } } }