using DataEntity; using DataEntity.Share; using DataRWDAL; using DriverLib.Engine; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.IO; using System.Net; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; using System.Xml; using XCommon.Log; using XCore; using XCoreBLL; using XHandler.Class; using XHandler.Controls; using XHandler.View; using XImaging.Automation.Service.Interface; using XImagingXhandler.XDAL; using DataEntity; using System.ComponentModel; using System.Reflection; using Sodao.FastSocket.Server.Config; using System.Collections.ObjectModel; using System.Text; using MySqlX.XDevAPI.Common; using XImaging.Automation.Service.Instruction; namespace XHandler.Runtime { class DeviceRuntime : IRuntime { public ErrorHandleDelegate errorHandle { get; set; } public ErrorHandleDelegate abortHandle { get; set; } public FinishHandleDelegate finishHandle { get; set; } public string ErrorState { get; set; } public RuntimeState State { get; set; } public int TroubleShoot { get; set; } DeviceSimulator deviceSimulator = new DeviceSimulator(); #region 回零 /// /// 运行回到设备零位 /// /// /// public JObject Home(Object obj) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); State = RuntimeState.OnBusy; JObject result = new JObject(); try { JObject job = obj as JObject; string strParam = string.Empty; bool isSimulator = false; strParam = job["parameters"].ToString(); //string experimentId = job["experiment_id"].ToString(); //string workflowid = job["workflow_id"].ToString(); LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【home】remote progress: " + obj.ToString()); JObject jobParms = JObject.Parse(strParam); isSimulator = jobParms["IsSimulator"].ToString().ToLower() == "true" ? true : false; string experimentnum = jobParms["Experimentnum"].ToString(); //调用复位方法全部轴复位回零 //调用执行方法,更新执行结果字符串 HomeControl homeControl = new HomeControl(Shared.SoftwareInformation.currentculture); HomeBll homeBll = new HomeBll(); float xAxisSafeVal = (float)Convert.ToDouble(ConfigurationManager.AppSettings["xAxisSafeVal"]); float yAxisSafeVal = (float)Convert.ToDouble(ConfigurationManager.AppSettings["yAxisSafeVal"]); float zAxisSafeVal = (float)Convert.ToDouble(ConfigurationManager.AppSettings["zAxisSafeVal"]); HomeMParam homeMParam = new HomeMParam(); int iresult = 1; homeMParam.xAxisVal = xAxisSafeVal; homeMParam.yAxisVal = yAxisSafeVal; homeMParam.zAxisVal = zAxisSafeVal; isStop = false; SaveState(_isStopFilePath, 2, false);//重新开始流程 HxResult ret = new HxResult(); ret = CommonBll.StatusLamp(4, false); ret = homeBll.ExecuteHome(homeMParam, isSimulator); _manualResetEvent = new ManualResetEvent(false); SaveState(_filePath, 1, false);//存储暂停控制信号状态 Application.Current.Dispatcher.Invoke(new Action(() => { RunWnd runWnd = new RunWnd(); runWnd.mainWindow = (MainWindow)Application.Current.MainWindow; runWnd.isRemotingOper = true; runWnd.EnableSimulator = isSimulator; if (runWnd.mainWindow.socketTcpListener != null) { if (runWnd.isRemotingOper) { if (Shared.SoftwareInformation.software_device_number == DeviceCategory.DeviceChoice) { MethodMsg methodMsgS = new MethodMsg(Guid.NewGuid().ToString(), "ID202_Choice_machine", 2, "", "ClawOpen", "", "", 1, 0); //if (!runWnd.mainWindow.socketTcpListener.IsConnect()) //{ // runWnd.mainWindow.socketTcpListener.ReConnect(); //} // 拍照 runWnd.mainWindow.socketTcpListener.SendMessage(runWnd.mainWindow.socketTcpListener.CreateSendOpenCraw(methodMsgS), true); System.Threading.Thread.Sleep(5000); } if (ret.Result != ResultType.Success) { MethodAction.Instance.StatusLamp(7); errorHandle?.Invoke(obj, "EC-1039", 5, "home is fail! error information:" + ret.AlarmInfo, 2); LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【home】progress: home is fail! error information:" + ret.AlarmInfo); iresult = 0; } else { LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【home】progress: home is success!"); } } } })); if (ret.Result != ResultType.Success) { errorHandle?.Invoke(obj, "EC-1039", 5, "home is fail! error information:" + ret.AlarmInfo, 2); LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【home】progress: home is fail! error information:" + ret.AlarmInfo); iresult = 0; } else { LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【home】progress: home is success!"); } LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【home】progress: complete;"); if (iresult == 0) { State = RuntimeState.OnError; result = JObject.Parse("{method_status:3}"); errorHandle?.Invoke(obj, "EC-1039", 5, "home is fail! error information:" + ret.AlarmInfo.ToString(), 1); } else if (iresult == 1) { State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:2}"); } else if (iresult == 2) { State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:4}"); } try { GenerateRunLogBase(experimentnum, "", iresult == 1 ? 1 : 0); GenerateRunLog(experimentnum); } catch(Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); } } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); State = RuntimeState.OnError; errorHandle?.Invoke(obj, "EC-1039", 5, "home is fail! error information:" + ex.Message.ToString(), 2); } finally { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } return result; } #endregion #region 运行时实验日志 /// /// 实验记录入库 /// public void GenerateRunLogBase(string experimentid, string workflowid, int result) { ExperimentModel experiment = new ExperimentModel(); string methodFileName = workflowid; experiment.ExperimentId = experimentid; experiment.ExperimentName = ""; experiment.ExperimentXmlContent = ""; experiment.ExperimentFile = methodFileName; experiment.LunchTime = DateTime.Now; experiment.Status = result; experiment.OperaterName = "中控"; ExperimentDB.Add(experiment); } #endregion #region 运行开始时日志 public ExperimentRunLog GenerateRunLog(string experimentId) { ExperimentRunLog experimentRunLog = new ExperimentRunLog(); try { experimentRunLog.experimentrunid = experimentId; experimentRunLog.experimentid = experimentId; experimentRunLog.lunchtime = DateTime.Now; experimentRunLog.endtime = DateTime.Now; experimentRunLog.operatorname = "中控"; experimentRunLog.status = 0; int iResult = ExperimentRunLogDB.AddExperimentRunLogIntodb(experimentRunLog); if (iResult == 1) { } else { experimentRunLog = null; } } catch (Exception ex) { LoggerHelper.ErrorLog("添加运行记录时错误:" + ex.ToString()); } return experimentRunLog; } #endregion #region 成像专用--拍照参数 /// /// 设置挑菌参数 /// /// /// public JObject Method_PhotoParam(Object obj) { bool bRet = false; string path = ConfigurationManager.AppSettings.Get("choiceFilePath"); Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); State = RuntimeState.OnBusy; JObject result = new JObject(); try { if (File.Exists(path)) { if (File.Exists(path.Split('.')[0] + "_1." + path.Split('.')[1])) { File.Delete(path.Split('.')[0] + "_1." + path.Split('.')[1]); } File.Copy(path, path.Split('.')[0] + "_1." + path.Split('.')[1]); File.Delete(path); } JObject Obj = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【PhotoParam】remote progress:get data: " + obj.ToString()); string objstr = Obj["parameters"].ToString(); //通过URL获取参数 Dictionary strdata = JsonConvert.DeserializeObject>(objstr); string jsonURL = strdata["SetBacteriaParam_param"].ToString(); string jsonFilePath = ConfigurationManager.AppSettings["captureFilePath"].ToString() + "\\downJson"; LoggerHelper.InfoLog("the opeate of write file is starting...1"); int fiMax = 1; if (Directory.Exists(jsonFilePath)) { //获取目录下文件的最大名称值 string[] files = Directory.GetFiles(jsonFilePath); foreach (string f in files) { string f1 = f.Split('.')[0]; int startIndex = f1.LastIndexOf('\\'); string namestr = f1.Substring(startIndex + 1, f1.Length - startIndex - 1); int fileName = Convert.ToInt32(namestr); if (fileName > fiMax) { fiMax = fileName; } } } else { Directory.CreateDirectory(jsonFilePath); } LoggerHelper.InfoLog("the opeate of write file is starting...2"); using (WebClient client = new WebClient()) { string fullJsonFileName = string.Empty; if (Directory.Exists(jsonFilePath)) { fullJsonFileName = jsonFilePath + "\\" + (fiMax + 1).ToString() + ".json"; if (File.Exists(fullJsonFileName)) { File.Delete(fullJsonFileName); } client.DownloadFile(jsonURL, fullJsonFileName); } LoggerHelper.InfoLog("the opeate of write file is starting...3"); string jsonText = File.ReadAllText(fullJsonFileName); //JObject ObjTxt = JObject.Parse(jsonText); //string strParams = ObjTxt["parameters"].ToString(); JObject objParam = JObject.Parse(jsonText); string experiment_id = objParam["experiment_id"].ToString(); string experimentnum = objParam["experimentnum"].ToString(); string barcode = objParam["barcode"].ToString(); string bacterias = objParam["bacterias"].ToString(); string shape = objParam["shape"].ToString(); string edge = objParam["edge"].ToString(); string color = objParam["color"].ToString(); string min_diameterSize = objParam["min_diam"].ToString(); string max_diameterSize = objParam["max_diam"].ToString(); string proximity = objParam["prox"].ToString(); string choice_mode = objParam["choice_mode"].ToString(); string choice_distance_mode = objParam["choice_distance_mode"].ToString(); string choice_distance_value = objParam["choice_distance_value"].ToString(); string choice_xAxis_offsite = objParam["choice_xAxis_offsite"].ToString(); string choice_yAxis_offsite = objParam["choice_yAxis_offsite"].ToString(); string coating_bottom_distance = objParam["coating_bottom_distance"].ToString(); string coating_xAxis_offsite = objParam["coating_xAxis_offsite"].ToString(); string coating_yAxis_offsite = objParam["coating_yAxis_offsite"].ToString(); string coating_mode = objParam["coating_mode"].ToString(); LoggerHelper.InfoLog("the opeate of write file is starting...4"); DataTable dtResult = GenerateDataTableByChoiceParams(objParam); LoggerHelper.InfoLog("the opeate of write file is starting..."); bRet = ExcelAndCsvHelper.WriteDataTableToExcelFile(dtResult, path); LoggerHelper.InfoLog("write file=" + path + ", return=" + bRet.ToString()); bRet = false; } result = JObject.Parse("{method_status:2}"); State = RuntimeState.OnIdle; } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); } finally { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); State = RuntimeState.OnIdle; if (!bRet) { if (!File.Exists(path)) { File.Copy(path.Split('.')[0] + "_1." + path.Split('.')[1], path); } if (File.Exists(path.Split('.')[0] + "_1." + path.Split('.')[1])) { File.Delete(path.Split('.')[0] + "_1." + path.Split('.')[1]); } result = JObject.Parse("{method_status:3}"); State = RuntimeState.OnError; } else { if (File.Exists(path.Split('.')[0] + "_1." + path.Split('.')[1])) { File.Delete(path.Split('.')[0] + "_1." + path.Split('.')[1]); } } } return result; } public DataTable GenerateDataTableByChoiceParams(JObject objParam) { //构建datatable DataTable dataResult = new DataTable(); DataColumn dc = new DataColumn(); dc.ColumnName = "中文名"; dataResult.Columns.Add(dc); dc = new DataColumn(); dc.ColumnName = "属性名"; dataResult.Columns.Add(dc); dc = new DataColumn(); dc.ColumnName = "属性值"; dataResult.Columns.Add(dc); DataRow dr = dataResult.NewRow(); dr["中文名"] = "实验ID"; dr["属性名"] = "experiment_id"; dr["属性值"] = objParam["experiment_id"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "皿的二维码信息"; dr["属性名"] = "barcode"; dr["属性值"] = objParam["barcode"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "菌名称"; dr["属性名"] = "bacterias"; dr["属性值"] = objParam["bacterias"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "形状"; dr["属性名"] = "shape"; dr["属性值"] = objParam["shape"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "边缘"; dr["属性名"] = "edge"; dr["属性值"] = objParam["edge"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "颜色"; dr["属性名"] = "color"; dr["属性值"] = objParam["color"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "最小直径"; dr["属性名"] = "min_diam"; dr["属性值"] = objParam["min_diam"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "最大直径"; dr["属性名"] = "max_diam"; dr["属性值"] = objParam["max_diam"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "临近度"; dr["属性名"] = "prox"; dr["属性值"] = objParam["prox"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "挑菌模式"; dr["属性名"] = "choice_mode"; dr["属性值"] = objParam["choice_mode"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "挑菌距离底部或菌类形"; dr["属性名"] = "choice_distance_mode"; dr["属性值"] = objParam["choice_distance_mode"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "挑菌距离底部或菌类距离"; dr["属性名"] = "choice_distance_value"; dr["属性值"] = objParam["choice_distance_value"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "挑菌时x轴偏移量"; dr["属性名"] = "choice_xAxis_offsite"; dr["属性值"] = objParam["choice_xAxis_offsite"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "挑菌时y轴偏移量"; dr["属性名"] = "choice_yAxis_offsite"; dr["属性值"] = objParam["choice_yAxis_offsite"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "涂布距离底部距离"; dr["属性名"] = "coating_bottom_distance"; dr["属性值"] = objParam["coating_bottom_distance"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "涂布时x轴偏移量"; dr["属性名"] = "coating_xAxis_offsite"; dr["属性值"] = objParam["coating_xAxis_offsite"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "涂布时y轴偏移量"; dr["属性名"] = "coating_yAxis_offsite"; dr["属性值"] = objParam["coating_yAxis_offsite"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "涂布方式"; dr["属性名"] = "coating_mode"; dr["属性值"] = objParam["coating_mode"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "涂布速度"; dr["属性名"] = "coating_speed"; dr["属性值"] = objParam["coating_speed"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "模型类型"; dr["属性名"] = "model_type"; dr["属性值"] = objParam["model_type"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "合并识别"; dr["属性名"] = "merge_masks"; dr["属性值"] = objParam["merge_masks"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "降采样率"; dr["属性名"] = "ds_ratio"; dr["属性值"] = objParam["ds_ratio"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "平均直径"; dr["属性名"] = "mean_diam"; dr["属性值"] = objParam["mean_diam"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "到边缘距离"; dr["属性名"] = "dist_to_edge"; dr["属性值"] = objParam["dist_to_edge"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "菌标记颜色"; dr["属性名"] = "mark_color"; dr["属性值"] = objParam["mark_color"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "菌标记序号"; dr["属性名"] = "draw_label"; dr["属性值"] = objParam["draw_label"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "菌标记字体大小"; dr["属性名"] = "fontsize"; dr["属性值"] = objParam["fontsize"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "顶部背光亮度"; dr["属性名"] = "top_light"; dr["属性值"] = objParam["top_light"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "底部背光亮度"; dr["属性名"] = "bottom_light"; dr["属性值"] = objParam["bottom_light"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "挑菌落方式"; dr["属性名"] = "choice_category"; dr["属性值"] = objParam["choice_category"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "挑菌时下压的距离"; dr["属性名"] = "press_distanceval"; dr["属性值"] = objParam["press_distanceval"].ToString(); dataResult.Rows.Add(dr); dr = dataResult.NewRow(); dr["中文名"] = "实验编号"; dr["属性名"] = "experimentnum"; dr["属性值"] = objParam["experimentnum"].ToString(); dataResult.Rows.Add(dr); return dataResult; } #endregion #region 成像专用--涂布 /// /// 设置涂布数据 /// /// /// public JObject Method_RunDataParamC(Object obj) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); JObject result = new JObject(); try { State = RuntimeState.OnBusy; DataTable dt = new DataTable(); dt.Columns.Add("序号", typeof(string)); dt.Columns.Add("来源板", typeof(string)); dt.Columns.Add("来源板码", typeof(string)); dt.Columns.Add("来源孔", typeof(string)); dt.Columns.Add("目标板", typeof(string)); dt.Columns.Add("目标板码", typeof(string)); dt.Columns.Add("目标孔", typeof(string)); dt.Columns.Add("移液体积", typeof(string)); dt.Columns.Add("是否更换吸头", typeof(string)); JObject Obj = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【RunDataParam】remote progress:get data: " + obj.ToString()); string objstr = Obj["parameters"].ToString(); Dictionary strdata = JsonConvert.DeserializeObject>(objstr); string jsonURL = strdata["Method_Coatingfile_Param"].ToString(); string jsonFilePath = ConfigurationManager.AppSettings["captureFilePath"].ToString() + "\\downJson"; int fiMax = 1; if (Directory.Exists(jsonFilePath)) { //获取目录下文件的最大名称值 string[] files = Directory.GetFiles(jsonFilePath); foreach (string f in files) { string f1 = f.Split('.')[0]; int startIndex = f1.LastIndexOf('\\'); string namestr = f1.Substring(startIndex + 1, f1.Length - startIndex - 1); int fileName = Convert.ToInt32(namestr); if (fileName > fiMax) { fiMax = fileName; } } } else { Directory.CreateDirectory(jsonFilePath); } using (WebClient client = new WebClient()) { string fullJsonFileName = string.Empty; if (Directory.Exists(jsonFilePath)) { fullJsonFileName = jsonFilePath + "\\" + (fiMax + 1).ToString() + ".json"; if (File.Exists(fullJsonFileName)) { File.Delete(fullJsonFileName); } client.DownloadFile(jsonURL, fullJsonFileName); } string jsonText = File.ReadAllText(fullJsonFileName); //JObject jsonObj = JObject.Parse(jsonText); List strdata1 = JsonConvert.DeserializeObject>(jsonText); foreach (SetCoatingData_param sd in strdata1) { DataRow dr = dt.NewRow(); int i = 0; dr["序号"] = sd.CoatingDataId.ToString(); dr["来源板"] = sd.SourcePlateID.ToString(); dr["来源板码"] = sd.SourcePlateBarcode.ToString(); dr["来源孔"] = sd.SourcePlateWell.ToString(); dr["目标板"] = sd.TargetPlateID.ToString(); dr["目标板码"] = sd.TargetPlateBarcode.ToString(); dr["目标孔"] = sd.TargetPlateWell.ToString(); dr["移液体积"] = sd.Volume.ToString(); dr["是否更换吸头"] = sd.changetips.ToString(); dt.Rows.Add(dr); } string filePath = strdata["PickAndCoatTable"].ToString(); string file = filePath; string path = file.Substring(0, file.LastIndexOf('\\')); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); LoggerHelper.InfoLog("creat directory: " + path); } ExcelAndCsvHelper.WriteDataTableToCSV(dt, file); bool bRet = true; LoggerHelper.InfoLog("write file=" + file + ", return=" + bRet.ToString()); if (!bRet) { State = RuntimeState.OnError; result = JObject.Parse("{method_status:3}"); throw new Exception("Execute was failed!"); } else if (bRet) { State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:2}"); } } } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); } finally { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } return result; } /// /// 运行方法 /// /// /// public JObject Method_Run(Object obj) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); State = RuntimeState.OnBusy; JObject result = new JObject(); try { JObject job = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【Run】remote progress:get data: " + obj.ToString()); string strParam = string.Empty; string methodFileName = string.Empty; string strParam2 = string.Empty; bool isSimulator = false; string experimentrunid = job["experiment_id"].ToString(); strParam = job["parameters"].ToString(); JObject jobParms = JObject.Parse(strParam); methodFileName = jobParms["FlowName"].ToString(); strParam2 = jobParms["PickAndCoatTable"].ToString(); isSimulator = jobParms["isSimulator"].ToString().ToLower() == "true" ? true : false; string shortDir = ConfigurationManager.AppSettings["MethodFileBasePath"].ToString(); string fullName = shortDir + "\\" + methodFileName + ".xmed"; if (File.Exists(fullName)) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(fullName); MethodListBll methodListBll = new MethodListBll(); XmlNodeList xmlNodeMethodList = xmlDocument.SelectNodes("root/method[@id>=3]"); for (int n = 0; n < xmlNodeMethodList.Count; n++) { string MethodName = xmlNodeMethodList[n].SelectSingleNode("name").InnerText; int iNum = methodListBll.getNumByMethodName(MethodName); switch (iNum) { case (int)MethodNameEnum.coatingfile: if (xmlNodeMethodList[n].SelectSingleNode("status").InnerText == "enable") { xmlNodeMethodList[n].SelectSingleNode("filePath").InnerText = strParam2; } break; default: break; } } App.Current.Dispatcher.Invoke(new Action(() => { RunWnd runWnd = new RunWnd(); runWnd.xmlDocument = xmlDocument; runWnd.isRemotingOper = true; runWnd.EnableSimulator = isSimulator; // 从文件中读取已经使用的Tip信息 RunWnd.currentIsUsedWellLattice = runWnd.GetUsedTipFromXML(); TaskFactory taskFactory = new TaskFactory(); int iresult = runWnd.LoadLabwareOnRunningRemote(); if (iresult == 0) { State = RuntimeState.OnError; result = JObject.Parse("{method_status:3}"); throw new Exception("Execute was failed!"); } else if (iresult == 1) { State = RuntimeState.OnIdle; runWnd.xmlDocument.Save(fullName); var dt = DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss"); string fileNameStr = dt + ".json"; string fileNameImg = dt + ".jpg"; // 从拍照的json文件中,读取菌属性值,打包成涂布报告的格式 string jsonFilePath = ConfigurationManager.AppSettings["captureFilePath"].ToString(); string[] files = Directory.GetFiles(jsonFilePath); int fiMax = 1; foreach (string f in files) { string f1 = f.Split('.')[0]; int startIndex = f1.LastIndexOf('\\'); string namestr = f1.Substring(startIndex + 1, f1.Length - startIndex - 1); if (namestr.Contains("_原")) { continue; } int fileName = Convert.ToInt32(namestr); if (fileName > fiMax) { fiMax = fileName; } } string fullJsonFileName = jsonFilePath + "\\" + (fiMax).ToString() + ".jpg"; string folder = "UploadFolder"; string uploadPath = AppDomain.CurrentDomain.BaseDirectory + folder; if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } string pathStr = uploadPath + "\\" + fileNameImg; string pathStrJson = uploadPath + "\\" + fileNameStr; //改图像名,存入新的路径下 File.Copy(fullJsonFileName, pathStr, true); string ip = HttpServer.GetLocalIP(); string port = ConfigurationManager.AppSettings["socketURLPort"].ToString(); string server = $"http://{ip}:{port}/UploadFolder/"; string strResultJson = runWnd.GenerateCoatingReport(server + fileNameImg); HttpServer.CreateFileContent(pathStrJson, strResultJson); //string fullPath = HttpServer.Init(HttpServer.GetLocalIP(), "8081", fileNameStr, runWnd.GenerateCoatingReport()); //string fullPathImg = HttpServer.Init(HttpServer.GetLocalIP(), "8081", fileNameImg, ""); result = JObject.Parse("{json:\"" + server + fileNameStr + "\"" + "}"); } else if (iresult == 2) { State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:2}"); } })); } else { //弹出窗口提示所执行的方法不存在 } State = RuntimeState.OnIdle; } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); State = RuntimeState.OnError; throw new Exception() { }; } finally { //HxResult ret = MethodAction.Instance.StatusLamp(7); Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } return result; } #endregion #region 成像专用--拍照 /// /// 拍照 /// /// /// public JObject Method_TakePhoto(Object obj) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); State = RuntimeState.OnBusy; JObject result = new JObject(); try { JObject job = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【TakePhoto】remote progress:get data: " + obj.ToString()); string strParam = string.Empty; string methodFileName = string.Empty; bool isSimulator = false; //查询出最后一条实验记录id string experimentId = job["experiment_id"].ToString(); strParam = job["parameters"].ToString(); JObject jobParms = JObject.Parse(strParam); methodFileName = jobParms["FlowName"].ToString(); isSimulator = jobParms["isSimulator"].ToString().ToLower() == "true" ? true : false; string shortDir = ConfigurationManager.AppSettings["MethodFileBasePath"].ToString(); string fullName = shortDir + "\\" + methodFileName + ".xmed"; if (File.Exists(fullName)) { XmlDocument xmlDocument = new XmlDocument(); //XmlDocument xmlDocument.Load(fullName); Application.Current.Dispatcher.Invoke(new Action(() => { RunWnd runWnd = new RunWnd(); runWnd.xmlDocument = xmlDocument; runWnd.mainWindow = (MainWindow)Application.Current.MainWindow; runWnd.isRemotingOper = true; runWnd.EnableSimulator = isSimulator; TaskFactory taskFactory = new TaskFactory(); int iresult = runWnd.LoadLabwareOnRunningRemote(); if (iresult == 0) { State = RuntimeState.OnError; result = JObject.Parse("{method_status:3}"); // errorHandle("10001", 7, "Execute was failed!Can't get any bacteria,please check algorithm on camera system."); throw new Exception("Execute was failed!Can't get any bacteria,please check algorithm on camera system."); } else if (iresult == 1) { if (!string.IsNullOrEmpty(runWnd.captureData)) { result = JObject.Parse(runWnd.captureData); } else { result = JObject.Parse("{method_status:2}"); //errorHandle("10001", 7, "Can't get any bacteria,please check algorithm on camera system."); throw new Exception("Execute was failed!Can't get any bacteria,please check algorithm on camera system."); } } else if (iresult == 2) { result = JObject.Parse("{method_status:4}"); } }), DispatcherPriority.Send); } else { //弹出窗口提示所执行的方法不存在 } } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } finally { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); State = RuntimeState.OnIdle; } return result; } #endregion #region 抓板转移 /// /// 运行抓板方法,抓耗材命令 /// /// /// public JObject Method_MoveBoard(Object obj) { State = RuntimeState.OnBusy; JObject result = new JObject(); try { JObject job = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【Method_MoveBoard】remote progress:get data: " + obj.ToString()); string strParam = string.Empty; string methodFileName = string.Empty; string strSrouceLatticeName = string.Empty; string strTargetLatticeName = string.Empty; int iGripperLabwarePos = 1; int iSrcGripperLatticeDriector = 1; int iTarGripperLatticeDriector = 1; string iGripPickObject = "1"; bool isSimulator = false; strParam = job["parameters"].ToString(); LoggerHelper.InfoLog("Start Method_MoveBoard"); JObject jobParms = JObject.Parse(strParam); methodFileName = jobParms["MethodName"].ToString(); strSrouceLatticeName = jobParms["SrcPosition"].ToString(); strTargetLatticeName = jobParms["TarPosition"].ToString(); iSrcGripperLatticeDriector = Convert.ToInt32(jobParms["SrcGriperpos"].ToString()); iTarGripperLatticeDriector = Convert.ToInt32(jobParms["TarGriperpos"].ToString()); iGripperLabwarePos = Convert.ToInt32(jobParms["Boardpos"].ToString()); iGripPickObject = jobParms["BoardId"].ToString(); string shortDir = ConfigurationManager.AppSettings["MethodFileBasePath"].ToString(); isSimulator = jobParms["IsSimulator"].ToString().ToLower() == "true" ? true : false; string fullName = shortDir + "\\" + methodFileName + ".xmed"; if (File.Exists(fullName)) { XmlDocument xmlDocument = new XmlDocument(); //XmlDocument xmlDocument.Load(fullName); xmlDocument = deviceSimulator.UpdateGripMoveParamByxml(xmlDocument, jobParms); App.Current.Dispatcher.Invoke(new Action(() => { RunWnd runWnd = new RunWnd(); runWnd.OnError += (p1, p2, p3, p4, p5) => { this.errorHandle(p1, p2, p3, p4, p5); }; runWnd.remoteObjectCmd = obj; runWnd.xmlDocument = xmlDocument; runWnd.mainWindow = (MainWindow)Application.Current.MainWindow; runWnd.isRemotingOper = true; runWnd.EnableSimulator = isSimulator; SaveState(_filePath, 1, false);//存储暂停控制信号状态 int iresult = runWnd.LoadLabwareOnRunningRemote(); if (iresult == 0) { State = RuntimeState.OnError; result = JObject.Parse("{method_status:3}"); errorHandle?.Invoke(obj, "EC-1041", 5, "程序运行中遇到错误(具体原因请查看日志),运行方法终止.", 2); } else if (iresult == 1) { State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:2}"); } else if (iresult == 2) { State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:4}"); } })); } else { //弹出窗口提示所执行的方法不存在 errorHandle?.Invoke(obj, "EC-1041", 5, "程序运行中遇到错误(具体原因请查看日志),运行方法终止.", 2); } State = RuntimeState.OnIdle; LoggerHelper.InfoLog("end Method_MoveBoard"); } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); State = RuntimeState.OnError; throw new Exception() { }; } finally { Application.Current.Dispatcher.Invoke(new Action(() => { RunWnd.IsRunning = false; var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } return result; } #endregion #region 移液专用--移液参数 /// /// 设置移液的数据 /// /// /// public JObject Method_RunDataParam(Object obj) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); JObject result = new JObject(); try { State = RuntimeState.OnBusy; JObject Obj = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【RunDataParam】remote progress:get data: " + obj.ToString()); string objstr = Obj["parameters"].ToString(); Dictionary strdata = JsonConvert.DeserializeObject>(objstr); string jsonURL = strdata["Method_Param_URL"].ToString(); LoggerRunHelper.InfoLog("remote jsonURL:" + jsonURL.ToString()); string jsonFilePath = ConfigurationManager.AppSettings["captureFilePath"].ToString() + "\\downJson"; LoggerRunHelper.InfoLog("remote jsonFilePath:" + jsonFilePath.ToString()); int fiMax = 1; if (Directory.Exists(jsonFilePath)) { // 获取目录下文件的最大名称值 string[] files = Directory.GetFiles(jsonFilePath); foreach (string f in files) { string f1 = f.Split('.')[0]; int startIndex = f1.LastIndexOf('\\'); string namestr = f1.Substring(startIndex + 1, f1.Length - startIndex - 1); int fileName = Convert.ToInt32(namestr); if (fileName > fiMax) { fiMax = fileName; } } } else { Directory.CreateDirectory(jsonFilePath); } LoggerRunHelper.InfoLog("remote fiMax:" + fiMax.ToString()); using (WebClient client = new WebClient()) { string fullJsonFileName = string.Empty; if (Directory.Exists(jsonFilePath)) { fullJsonFileName = jsonFilePath + "\\" + (fiMax + 1).ToString() + ".json"; if (File.Exists(fullJsonFileName)) { File.Delete(fullJsonFileName); } LoggerRunHelper.InfoLog("remote fullJsonFileName:" + fullJsonFileName.ToString()); client.DownloadFile(jsonURL, fullJsonFileName); } string jsonText = File.ReadAllText(fullJsonFileName); LoggerRunHelper.InfoLog("remote local jsonText:" + jsonText.ToString()); DataTable dt = new DataTable(); List strdata1 = JsonConvert.DeserializeObject>(jsonText); #region 构建表结构 foreach (dynamic newObj in strdata1) { // 获取所有属性名称 var propertyNames = ((JObject)newObj).Properties(); // 属性名称 foreach (var propertyName in propertyNames) { dt.Columns.Add(propertyName.Name, typeof(string)); } //var items =((JObject)newObj).Children(); //for(int i=0;i { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } return result; } #endregion #region 查询设备状态 public JObject Method_GetStatus(Object obj) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); State = RuntimeState.OnBusy; JObject result = new JObject(); try { JObject job = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【Method_GetStatus】remote progress:get data: " + obj.ToString()); string strParam = string.Empty; string strType = string.Empty; if (MethodAction.Instance != null) { if (!MethodAction.Instance.Connected) { HxResult ret = MethodAction.Instance.Connect(); if (ret.Result == ResultType.Success) { //State = RuntimeState.OnIdle; //result = JObject.Parse("{method_status:2}"); } else { string strDetail = string.Empty; foreach(string content in ret.Details) { strDetail += content; } errorHandle?.Invoke(obj, "EC-1000", 5, "设备连接异常,详情:"+strDetail, 2); } } else { State = RuntimeState.OnIdle; result = JObject.Parse("{equipment_status:1}"); } } //State = RuntimeState.OnIdle; //result = JObject.Parse("{method_status:2}"); LoggerHelper.InfoLog("end Method_GetStatus"); } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); State = RuntimeState.OnError; //throw new Exception() { }; errorHandle?.Invoke(obj, "EC-1000", 5, "设备连接异常,详情:" + ex.Message.ToString(), 2); } finally { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } return result; } #endregion #region 移动到安全位置 public JObject Method_MoveToSafePosition(Object obj) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); State = RuntimeState.OnBusy; JObject result = new JObject(); try { JObject job = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【Method_MoveToSafePosition】remote progress:get data: " + obj.ToString()); string strParam = string.Empty; string strType = string.Empty; string xAxisSafeVal = ConfigurationManager.AppSettings["xAxisSafeVal"].ToString(); string yAxisSafeVal = ConfigurationManager.AppSettings["yAxisSafeVal"].ToString(); if (MethodAction.Instance != null) { HxResult ret = MethodAction.Instance.Move((float)Convert.ToDouble(xAxisSafeVal), (float)Convert.ToDouble(yAxisSafeVal), Shared.GripperArmId); if (ret.Result == ResultType.Success) { //State = RuntimeState.OnIdle; //result = JObject.Parse("{method_status:2}"); } else { string strDetail = string.Empty; foreach (string content in ret.Details) { strDetail += content; } errorHandle?.Invoke(obj, "EC-1054", 5, "设备移动到安全位置异常,详情:" + strDetail, 2); } } LoggerHelper.InfoLog("end Method_MoveToSafePosition"); } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); State = RuntimeState.OnError; //throw new Exception() { }; errorHandle?.Invoke(null, "EC-1054", 5, "设备移动到安全位置异常,详情:" + ex.Message.ToString(), 2); } finally { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } return result; } #endregion #region 查询工作站所有的应用方法 public JObject Method_GetAllMethod(Object obj) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); State = RuntimeState.OnBusy; JObject result = new JObject(); result = JObject.Parse("{ methodname:\"\"" + "}"); try { JObject job = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【Method_GetAllMethod】remote progress:get data: " + obj.ToString()); string strParam = string.Empty; string strType = string.Empty; string basePath = System.AppDomain.CurrentDomain.BaseDirectory; string runFolderPath = //basePath + ConfigurationManager.AppSettings["MethodFileBasePath"].ToString();//方法所在目录 if (Directory.Exists(runFolderPath)) { string[] runFileInfo = Directory.GetFiles(runFolderPath); string methodNameCollection = string.Empty; foreach (string file in runFileInfo) { string filename = file.Substring(file.LastIndexOf('\\') + 1, file.Length - file.LastIndexOf('\\')-1); methodNameCollection += filename.Substring(0, filename.LastIndexOf('.')) + ","; } if (methodNameCollection != string.Empty) { methodNameCollection = methodNameCollection.Substring(0, methodNameCollection.Length - 1); } //byte[] utf8Bytes = Encoding.GetEncoding("utf8").GetString(methodNameCollection); //string resultText = DecFileName(methodNameCollection); string resultText = methodNameCollection; result = JObject.Parse("{ methodname:\"" + resultText + "\"" + "}"); } State = RuntimeState.OnIdle; LoggerHelper.InfoLog("end Method_GetAllMethod"); } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); State = RuntimeState.OnError; throw new Exception() { }; } finally { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } return result; } #endregion public string DecFileName(string str) { Encoding utf8 = Encoding.GetEncoding("utf-8"); byte[] btArr = utf8.GetBytes(str); return Encoding.UTF8.GetString(btArr); } #region 查询工作站所有的耗材信息 public JObject Method_GetAllLabware(Object obj) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); State = RuntimeState.OnBusy; JObject result = new JObject(); result = JObject.Parse("{ labwareid:\"\"," + "labwarename:\"\""+ "}"); try { JObject job = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【Method_GetAllLabware】remote progress:get data: " + obj.ToString()); string strParam = string.Empty; string strType = string.Empty; ObservableCollection labwares = LabwareDB.GetLabware(2); string labwareIdCollection = string.Empty; string labwareNameCollection = string.Empty; foreach(Labware labware in labwares) { labwareIdCollection += labware.labware_id + ","; labwareNameCollection += labware.labware_name + ","; } if(labwareIdCollection!=string.Empty) { labwareIdCollection= labwareIdCollection.Substring(0, labwareIdCollection.Length - 1); labwareNameCollection = labwareNameCollection.Substring(0, labwareNameCollection.Length - 1); result = JObject.Parse("{ labwareid:\"" + labwareIdCollection + "\"," + "labwarename:\"" + labwareNameCollection + "\""+ "}"); } State = RuntimeState.OnIdle; LoggerHelper.InfoLog("end Method_GetAllLabware"); } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); State = RuntimeState.OnError; throw new Exception() { }; } finally { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } return result; } #endregion /// /// 设置移液的barcode数据 /// /// /// public JObject Method_MoveLiquidTo96Params(Object obj) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); JObject result = new JObject(); try { State = RuntimeState.OnBusy; //DataTable dt = new DataTable(); //dt.Columns.Add("Id", typeof(string)); //dt.Columns.Add("SrcCode", typeof(string)); //dt.Columns.Add("TarCode", typeof(string)); DataTable dt = new DataTable(); dt.Columns.Add("CoatingDataId", typeof(string)); dt.Columns.Add("SourceA", typeof(string)); dt.Columns.Add("SourceBarcode", typeof(string)); dt.Columns.Add("SourceWell", typeof(string)); dt.Columns.Add("TargetB", typeof(string)); dt.Columns.Add("TargetBarcode", typeof(string)); dt.Columns.Add("TargetWell", typeof(string)); dt.Columns.Add("Volume", typeof(string)); JObject Obj = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【RunDataParam】remote progress:get data: " + obj.ToString()); string objstr = Obj["parameters"].ToString(); Dictionary strdata = JsonConvert.DeserializeObject>(objstr); string jsonURL = strdata["Method_Coatingfile_Param"].ToString(); string jsonFilePath = ConfigurationManager.AppSettings["captureFilePath"].ToString() + "\\downJson"; int fiMax = 1; if (Directory.Exists(jsonFilePath)) { //获取目录下文件的最大名称值 string[] files = Directory.GetFiles(jsonFilePath); foreach (string f in files) { string f1 = f.Split('.')[0]; int startIndex = f1.LastIndexOf('\\'); string namestr = f1.Substring(startIndex + 1, f1.Length - startIndex - 1); int fileName = Convert.ToInt32(namestr); if (fileName > fiMax) { fiMax = fileName; } } } else { Directory.CreateDirectory(jsonFilePath); } using (WebClient client = new WebClient()) { string fullJsonFileName = string.Empty; if (Directory.Exists(jsonFilePath)) { fullJsonFileName = jsonFilePath + "\\" + (fiMax + 1).ToString() + ".json"; if (File.Exists(fullJsonFileName)) { File.Delete(fullJsonFileName); } client.DownloadFile(jsonURL, fullJsonFileName); } string jsonText = File.ReadAllText(fullJsonFileName); //JObject jsonObj = JObject.Parse(jsonText); List strdata1 = JsonConvert.DeserializeObject>(jsonText); //foreach (SetCoatingData_param sd in strdata1) //{ // DataRow dr = dt.NewRow(); // int i = 0; // dr["Id"] = sd.CoatingDataId.ToString(); // dr["SrcCode"] = sd.SourcePlateID.ToString(); // dr["TarCode"] = sd.SourcePlateBarcode.ToString(); // dt.Rows.Add(dr); //} foreach (SetMoveLiquidData_param sd in strdata1) { DataRow dr = dt.NewRow(); int i = 0; dr["CoatingDataId"] = sd.CoatingDataId.ToString(); dr["SourceA"] = sd.SourceA.ToString(); dr["SourceBarcode"] = sd.SourceBarcode.ToString(); dr["SourceWell"] = sd.SourceWell.ToString(); dr["TargetB"] = sd.TargetB.ToString(); dr["TargetBarcode"] = sd.TargetBarcode.ToString(); dr["TargetWell"] = sd.TargetWell.ToString(); dr["Volume"] = sd.Volume.ToString(); //dr["changetips"] = sd.changetips.ToString(); dt.Rows.Add(dr); } string filePath = strdata["PickAndCoatTable"].ToString(); string file = filePath; string path = file.Substring(0, file.LastIndexOf('\\')); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); LoggerHelper.InfoLog("creat directory: " + path); } ExcelAndCsvHelper.WriteDataTableToCSV(dt, file); bool bRet = true; LoggerHelper.InfoLog("write file=" + file + ", return=" + bRet.ToString()); if (!bRet) { State = RuntimeState.OnError; result = JObject.Parse("{method_status:3}"); throw new Exception("Execute was failed!"); } else if (bRet) { State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:2}"); } } } catch (Exception ex) { throw ex; } finally { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } return result; } private void DownloadFileForMoveLiquid(string jsonURL,string terminalPath) { string jsonFilePath = ConfigurationManager.AppSettings["captureFilePath"].ToString() + "\\downJson"; LoggerRunHelper.InfoLog("remote jsonFilePath:" + jsonFilePath.ToString()); int fiMax = 1; if (Directory.Exists(jsonFilePath)) { // 获取目录下文件的最大名称值 string[] files = Directory.GetFiles(jsonFilePath); foreach (string f in files) { string f1 = f.Split('.')[0]; int startIndex = f1.LastIndexOf('\\'); string namestr = f1.Substring(startIndex + 1, f1.Length - startIndex - 1); int fileName = Convert.ToInt32(namestr); if (fileName > fiMax) { fiMax = fileName; } } } else { Directory.CreateDirectory(jsonFilePath); } LoggerRunHelper.InfoLog("remote fiMax:" + fiMax.ToString()); using (WebClient client = new WebClient()) { client.Encoding = Encoding.UTF8; // 设置编码格式为UTF-8 string fullJsonFileName = string.Empty; if (Directory.Exists(jsonFilePath)) { fullJsonFileName = jsonFilePath + "\\" + (fiMax + 1).ToString() + ".json"; if (File.Exists(fullJsonFileName)) { File.Delete(fullJsonFileName); } LoggerRunHelper.InfoLog("remote fullJsonFileName:" + fullJsonFileName.ToString()); client.DownloadFile(jsonURL, fullJsonFileName); } string jsonText = File.ReadAllText(fullJsonFileName); LoggerRunHelper.InfoLog("remote local jsonText:" + jsonText.ToString()); DataTable dt = new DataTable(); List strdata1 = JsonConvert.DeserializeObject>(jsonText); #region 构建表结构 foreach (dynamic newObj in strdata1) { // 获取所有属性名称 var propertyNames = ((JObject)newObj).Properties(); // 属性名称 foreach (var propertyName in propertyNames) { dt.Columns.Add(propertyName.Name, typeof(string)); } break; } #endregion #region 构建表数据行 foreach (dynamic newObj in strdata1) { DataRow dr = dt.NewRow(); var propertyNames = ((JObject)newObj).Properties(); // 属性名称 foreach (var propertyName in propertyNames) { dr[propertyName.Name] = ((JObject)newObj)[propertyName.Name].ToString(); } dt.Rows.Add(dr); } #endregion string filePath = terminalPath; string file = filePath; string path = file.Substring(0, file.LastIndexOf('\\')); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); LoggerHelper.InfoLog("creat directory: " + path); } ExcelAndCsvHelper.WriteDataTableToCSV(dt, file); bool bRet = true; LoggerHelper.InfoLog("write file=" + file + ", return=" + bRet.ToString()); } } /// /// 运行移液方法 /// /// /// public JObject Method_RunMoveLiquid(Object obj) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); State = RuntimeState.OnBusy; JObject result = new JObject(); try { JObject job = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【Method_RunMoveLiquid】remote progress:get data: " + obj.ToString()); string strParam = string.Empty; string methodFileName = string.Empty; string strParam2 = string.Empty; bool isSimulator = false; string experimentrunid = job["experiment_id"].ToString(); strParam = job["parameters"].ToString(); JObject jobParms = JObject.Parse(strParam); methodFileName = jobParms["MethodName"].ToString(); string jsonURL = "";// jobParms["Method_Param_URL"].ToString(); //strParam2 = jobParms["FilePath"].ToString(); isSimulator = jobParms["IsSimulator"].ToString().ToLower() == "true" ? true : false; string shortDir = ConfigurationManager.AppSettings["MethodFileBasePath"].ToString(); string fullName = shortDir + "\\" + methodFileName + ".xmed"; if (File.Exists(fullName)) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(fullName); MethodListBll methodListBll = new MethodListBll(); XmlNodeList xmlNodeMethodList = xmlDocument.SelectNodes("root/method[@id>=3]"); for (int n = 0; n < xmlNodeMethodList.Count; n++) { string MethodName = xmlNodeMethodList[n].SelectSingleNode("name").InnerText; int iNum = methodListBll.getNumByMethodName(MethodName); switch (iNum) { //case (int)MethodNameEnum.VariableImport: // if (xmlNodeMethodList[n].SelectSingleNode("status").InnerText == "enable") // { // DownloadFileForMoveLiquid(jsonURL, xmlNodeMethodList[n].SelectSingleNode("filePath").InnerText); // //xmlNodeMethodList[n].SelectSingleNode("filePath").InnerText = strParam2; // strParam2 = xmlNodeMethodList[n].SelectSingleNode("filePath").InnerText; // } // break; case (int)MethodNameEnum.transferfile: if (xmlNodeMethodList[n].SelectSingleNode("status").InnerText == "enable") { //DownloadFileForMoveLiquid(jsonURL, xmlNodeMethodList[n].SelectSingleNode("filePath").InnerText); //xmlNodeMethodList[n].SelectSingleNode("filePath").InnerText = strParam2; strParam2 = xmlNodeMethodList[n].SelectSingleNode("filePath").InnerText; } break; case (int)MethodNameEnum.coatingfile: if (xmlNodeMethodList[n].SelectSingleNode("status").InnerText == "enable") { //xmlNodeMethodList[n].SelectSingleNode("filePath").InnerText = strParam2; DownloadFileForMoveLiquid(jsonURL, xmlNodeMethodList[n].SelectSingleNode("filePath").InnerText); strParam2 = xmlNodeMethodList[n].SelectSingleNode("filePath").InnerText; } break; default: break; } } App.Current.Dispatcher.Invoke(new Action(() => { RunWnd runWnd = new RunWnd(); runWnd.xmlDocument = xmlDocument; runWnd.isRemotingOper = true; runWnd.EnableSimulator = isSimulator; runWnd.remoteObjectCmd = obj; runWnd.OnError += (p1, p2, p3, p4, p5) => { this.errorHandle(p1, p2, p3, p4, p5); }; //从文件中读取已经使用的Tip信息 RunWnd.currentIsUsedWellLattice = runWnd.GetUsedTipFromXML(); runWnd.currentExperimentRunLog.experimentrunid = experimentrunid; TaskFactory taskFactory = new TaskFactory(); SaveState(_filePath, 1, false);//存储暂停控制信号状态 int iresult = runWnd.LoadLabwareOnRunningRemote(); if (iresult == 0) { State = RuntimeState.OnError; result = JObject.Parse("{method_status:3}"); throw new Exception("EC-1041 程序运行中遇到错误(具体原因请查看日志),运行方法终止!"); } else if (iresult == 1) { State = RuntimeState.OnIdle; var dt = DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss"); string fileNameStr = dt + ".json"; string folder = "UploadFolder"; string uploadPath = AppDomain.CurrentDomain.BaseDirectory + folder; string pathStrJson = uploadPath + "\\" + fileNameStr; string ip = HttpServer.GetLocalIP(); string port = ConfigurationManager.AppSettings["socketURLPort"].ToString(); string server = $"http://{ip}:{port}/UploadFolder/"; string strResultJson = runWnd.GenerateMoveLiquidReport(strParam2); HttpServer.CreateFileContent(pathStrJson, strResultJson); //string fullPath = HttpServer.Init(HttpServer.GetLocalIP(), "8081", fileNameStr, runWnd.GenerateCoatingReport()); //string fullPathImg = HttpServer.Init(HttpServer.GetLocalIP(), "8081", fileNameImg, ""); result = JObject.Parse("{json:\"" + server + fileNameStr + "\"" + "}"); } else if (iresult == 2) { State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:2}"); } })); } else { throw new Exception("EC-1041 程序运行中遇到错误(具体原因请查看日志),运行方法终止!"); } State = RuntimeState.OnIdle; LoggerHelper.InfoLog("end Method_RunMoveLiquid"); } catch (Exception ex) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); State = RuntimeState.OnError; throw ex; } finally { //HxResult ret = MethodAction.Instance.StatusLamp(7); Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } return result; } bool isRunningOfSwitch = false; /// /// 开关灯、等 /// /// /// public JObject Method_TurnOnOFF(Object obj) { JObject result = new JObject(); if (isRunningOfSwitch) { State = RuntimeState.OnBusy; return result; } isRunningOfSwitch = true; Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); try { JObject job = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【Method_TurnOnOFF】remote progress:get data: " + obj.ToString()); string strParam = string.Empty; string equipname = string.Empty; string equipstate = string.Empty; strParam = job["parameters"].ToString(); JObject jobParms = JObject.Parse(strParam); equipname = jobParms["EquipName"].ToString(); equipstate = jobParms["EquipState"].ToString(); bool isSimulator = jobParms["IsSimulator"].ToString().ToLower() == "true" ? true : false; HxResult ret = new HxResult(); string strType = string.Empty; if (equipstate == "0") { strType = "关闭"; } else if (equipstate == "1") { strType = "开启"; } if (isSimulator) { LoggerRunHelper.InfoLog(equipname + "已开启"); State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:4}"); LoggerHelper.InfoLog("end Method_TurnOnOFF"); } else { switch (equipname) { case "UV": ret = MethodAction.Instance.SterilizingLamp(Convert.ToInt32(equipstate)); break; case "FFU": ret = MethodAction.Instance.FFU(Convert.ToInt32(equipstate)); break; case "LED": ret = MethodAction.Instance.Floodlight(Convert.ToInt32(equipstate)); break; } if (ret.Result == ResultType.Success) { LoggerRunHelper.InfoLog(equipname + "已开启"); State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:4}"); } else if (ret.Result == ResultType.FailQ) { LoggerRunHelper.InfoLog("开启HEPA动作终止!"); throw new Exception("EC-1041 程序运行中遇到错误(具体原因请查看日志),运行方法终止!"); } else if (ret.Result == ResultType.Fail) { LoggerRunHelper.InfoLog(strType + equipname + "失败,信息:" + ret.AlarmInfo.ToString()); State = RuntimeState.OnError; result = JObject.Parse("{method_status:3}"); throw new Exception("EC-1041 程序运行中遇到错误(具体原因请查看日志),运行方法终止!"); //throw new Exception(strType + equipname + "失败,信息:" + ret.AlarmInfo.ToString()); //errorHandle?.Invoke(obj, "EC-1041", 5, "程序运行中遇到错误(具体原因请查看日志),运行方法终止.", 2); } State = RuntimeState.OnIdle; LoggerHelper.InfoLog("end Method_TurnOnOFF"); } } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); throw ex; } finally { isRunningOfSwitch = false; Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } return result; } /// /// 夹爪回零 /// /// /// public JObject Method_GriperZero(Object obj) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Hidden; a.remoteGrid.Visibility = Visibility.Visible; } })); State = RuntimeState.OnBusy; JObject result = new JObject(); try { JObject job = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【GriperZero】remote progress:get data: " + obj.ToString()); string strParam = string.Empty; HxResult ret = new HxResult(); string strType = string.Empty; ret = MethodAction.Instance.HomeZ(7); if (ret.Result == ResultType.Success) { LoggerRunHelper.InfoLog("夹爪已回零"); State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:4}"); } else if (ret.Result == ResultType.FailQ) { LoggerRunHelper.InfoLog("开启HEPA动作终止!"); } else if (ret.Result == ResultType.Fail) { LoggerRunHelper.InfoLog("夹爪回零失败,信息:" + ret.AlarmInfo.ToString()); State = RuntimeState.OnError; result = JObject.Parse("{method_status:3}"); throw new Exception("夹爪回零失败,信息:" + ret.AlarmInfo.ToString()); } State = RuntimeState.OnIdle; } catch (Exception ex) { LoggerHelper.ErrorLog("ERROR:", ex); Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); throw ex; } finally { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); } return result; } #region 运行时暂停/继续/停止 /// /// 运行时暂停/继续/停止 /// /// /// public JObject Method_PauseStopContinue(Object obj) { JObject result = new JObject(); try { JObject job = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【PauseStopContinue】remote progress:get data: " + obj.ToString()); string strParam = string.Empty; int equipstate = 0; strParam = job["parameters"].ToString(); JObject jobParms = JObject.Parse(strParam); equipstate = Convert.ToInt32(jobParms["RequestState"].ToString()); if (equipstate == -1)//停止 { LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【PauseStopContinue】remote progress:stop"); //把请求取消的请求放入文件中保存,在运行的函数中启动线程定时器进行实时监控,监控要取消,即可调用取消请求即可。 SaveState(_isStopFilePath, 2, true); HxResult ret = MethodAction.Instance.StatusLamp(7); Task.Factory.StartNew(() => MethodAction.Instance.Interrupt(3, true)); App.Current.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() => { RunWnd runWnd = new RunWnd(); runWnd.AddLogs("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】> Xhandler:实验停止指令已发出!!"); LoggerRunHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】> Xhandler:实验停止指令已发出!!"); })); State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:4}"); } else if (equipstate == 1)//暂停 { LoadState(_filePath, 1); LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【PauseStopContinue】remote progress:pause"); _manualResetEvent.Reset(); SaveState(_filePath, 1, false); HxResult ret = MethodAction.Instance.StatusLamp(5); Task.Factory.StartNew(() => MethodAction.Instance.Interrupt(1, true)); App.Current.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() => { RunWnd runWnd = new RunWnd(); runWnd.AddLogs("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】> Xhandler:实验暂停指令已发出!!"); LoggerRunHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】> Xhandler:实验暂停指令已发出!!"); })); State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:4}"); } else if (equipstate == 0)//继续 { LoadState(_filePath, 1); _manualResetEvent.Set(); SaveState(_filePath, 1, false); LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【PauseStopContinue】remote progress:continue"); HxResult ret = MethodAction.Instance.StatusLamp(4); MethodAction.Instance.Interrupt(2); App.Current.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() => { RunWnd runWnd = new RunWnd(); runWnd.AddLogs("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】> Xhandler:实验继续指令已发出!!"); LoggerRunHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】> Xhandler:实验继续指令已发出!!"); })); State = RuntimeState.OnIdle; result = JObject.Parse("{method_status:4}"); } State = RuntimeState.OnIdle; } catch (Exception ex) { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); throw ex; } finally { Application.Current.Dispatcher.Invoke(new Action(() => { var a = (MainWindow)Application.Current.MainWindow; if (a != null) { a.rootGrid.Visibility = Visibility.Visible; a.remoteGrid.Visibility = Visibility.Hidden; } })); State = RuntimeState.OnIdle; } return result; } #endregion #region 消除对话框 /// /// 消除对话框 /// /// /// public JObject Method_ClearPopWin(Object obj) { State = RuntimeState.OnBusy; JObject result = new JObject(); try { JObject job = obj as JObject; LoggerHelper.InfoLog("【" + DateTime.Now.ToString("HH:mm:ss:fff") + "】>Xhandler: 【ClearPopwin】remote progress:get data: " + obj.ToString()); string strParam = string.Empty; int dialogstate = 0; strParam = job["parameters"].ToString(); JObject jobParms = JObject.Parse(strParam); dialogstate = Convert.ToInt32(jobParms["dialogstate"].ToString()); if(dialogstate==1)//跳过 { ((MainWindow)((Window)Shared.Main)).remoteMark = 1; } else if(dialogstate==2)//重试 { ((MainWindow)((Window)Shared.Main)).remoteMark = 2; } else if (dialogstate == 3)//终止 { ((MainWindow)((Window)Shared.Main)).remoteMark = 3; } else if (dialogstate == 4)//确认继续 { ((MainWindow)((Window)Shared.Main)).remoteMark = 4; } State = RuntimeState.OnIdle; } catch (Exception ex) { } return result; } #endregion #region 序列化ManualResetEvent对象 ManualResetEvent _manualResetEvent = new ManualResetEvent(false); CancellationTokenSource _cancelSource = new CancellationTokenSource(); static string basePath = System.AppDomain.CurrentDomain.BaseDirectory; public string _filePath = basePath + @"Run\ManualResetEventState.bin"; public string _isStopFilePath = basePath + @"Run\isStop.bin"; public string _pauseStateFilePath = basePath + @"Run\pauseState.bin"; private bool isStop = true; private int pauseState = 0;//0:正常;1:暂停 /// /// 序列化对象状态存入BIN文件 /// /// 1:ManualResetEvent对象;2:isStop;3:pauseState; /// true;false /// 0未暂停;1暂停 public void SaveState(string filePath, int category, bool state, int pauseState = 0) { if (File.Exists(filePath)) { File.Delete(filePath); } string dirPath = filePath.Substring(0, filePath.LastIndexOf('\\')); if(!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } // 创建文件流,并使用二进制格式化器进行序列化 using (var fileStream = new FileStream(filePath, FileMode.Create)) { var formatter = new BinaryFormatter(); if (category.Equals(1)) { formatter.Serialize(fileStream, _manualResetEvent.WaitOne(0)); } else if (category.Equals(2)) { isStop = Convert.ToBoolean(isStop); formatter.Serialize(fileStream, isStop); } else if (category.Equals(3)) { pauseState = Convert.ToInt32(pauseState); formatter.Serialize(fileStream, pauseState); } fileStream.Close(); } } #endregion #region 反序列化ManualResetEvent对象 /// /// 反序列化ManualResetEvent对象 /// /// 1:ManualResetEvent对象;2:isStop;3:pauseState; public void LoadState(string filePath, int category) { // 如果文件存在,则反序列化并设置ManualResetEvent的状态 if (File.Exists(filePath)) { using (var fileStream = new FileStream(filePath, FileMode.Open)) { var formatter = new BinaryFormatter(); if (category.Equals(1)) { var isSet = (bool)formatter.Deserialize(fileStream); _manualResetEvent = new ManualResetEvent(isSet); } else if (category.Equals(2)) { var isSet = formatter.Deserialize(fileStream); isStop = Convert.ToBoolean(isSet); } else if (category.Equals(3)) { var isSet = formatter.Deserialize(fileStream); pauseState = Convert.ToInt32(isSet); } fileStream.Close(); } } } #endregion #region 接口中的3个方法 public void ReplyAbort() { } public void ReplyRetry() { } public void ReplyIgnore() { } #endregion public void Dispose(string methodName) { if (errorHandle == null) return; var list = errorHandle.GetInvocationList(); foreach (Delegate del in list) { TaskInstruction taskInstruction = del.Target as TaskInstruction; if (taskInstruction.InsName == methodName) { object delObj = del.GetType().GetProperty("Method").GetValue(del, null); string funcName = (string)delObj.GetType().GetProperty("Name").GetValue(delObj, null); Console.WriteLine(funcName); errorHandle -= del as ErrorHandleDelegate; } } } } }