using DevExpress.XtraEditors; using HslCommunication; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Drawing; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Timers; using System.Web.UI.WebControls; using System.Windows.Forms; using ZJ_BYD.Common; using ZJ_BYD.DB; using ZJ_BYD.Model; using ZJ_BYD.Untils; using ZJ_BYD.ViewModel; namespace ZJ_BYD { public partial class Main : XtraForm { public Main() { InitializeComponent(); //Top = 0; //Left = 0; //Width = Screen.PrimaryScreen.WorkingArea.Width; //Height = Screen.PrimaryScreen.WorkingArea.Height; WindowState = FormWindowState.Maximized; myEventHandler.LogChanged += MyEventHandler_LogChanged; //动作项参数行-BindingList事件 gridFinished.DataSource = _bindingResultFinishedCodeVMs; _bindingResultFinishedCodeVMs.ListChanged += OnParamBindingListChanged; Task.Run(() => { while (!cancellationTokenSource.IsCancellationRequested) { MyMethod(); Thread.Sleep(3000); } }, cancellationTokenSource.Token); } System.Timers.Timer timer; private bool isLoad = true;//用于判断机型下拉框是否弹出确认框 private bool isChangeVal = true;//用于判断在多线程中是否修改机型下拉框的值 private static string machineOldVal = ""; private void Main_Load(object sender, EventArgs e) { InitTimer(); Program.type = typeof(T_Result);//获取类型 Program.properties = Program.type.GetProperties(); BindCombox.BindSystemMode(cmbMainSysMode); BindCombox.MainBindMachineType(lkMachineType); cmbMainSysMode.SelectedIndex = Program.SysMode ? 0 : 1; lblUser.Text = CurrentUser.RealName; lblLineName.Text = Program.LineName; var logoFileName = ConfigurationManager.AppSettings["logofilename"]; var imgPath = Path.Combine(Application.StartupPath, "image/" + logoFileName); sysLogo.Image = System.Drawing.Image.FromFile(imgPath); ShowStationBtn(); if (stationpanel.Controls.Count > 0) { var btn = stationpanel.Controls[0] as SimpleButton; Program.ActiveStatinCode = btn.Name; var activeStation = Program.stationInfos.FirstOrDefault(m => m.StationCode == btn.Name); //在线模式才可绑定工单 if (Program.SysMode) { btnBindOrder.Visible = activeStation.IsShowOrderBtn; } else { btnBindOrder.Visible = false; } ChangeCurrentStationCode(btn); } //心跳监测 Task.Run(() => { HeartMonitor(); }, cancellationTokenSource.Token); Task.Run(() => { ShowData(); }, cancellationTokenSource.Token); //初始化默认机型 MskCodeHelper.InitMachineType(); } /// /// 初始化Timer控件 /// private void InitTimer() { //设置定时间隔(毫秒为单位) int interval = 1000; timer = new System.Timers.Timer(interval); //设置执行一次(false)还是一直执行(true) timer.AutoReset = true; //设置是否执行System.Timers.Timer.Elapsed事件 timer.Enabled = true; //绑定Elapsed事件 timer.Elapsed += new ElapsedEventHandler(time1_Tick); } private void OnParamBindingListChanged(object sender, ListChangedEventArgs e) { gridView2.RefreshData(); } private void MyMethod() { try { //已完成条码 var finishCodelist = ResultHelper.SyncQueryFinishedCodesBySql(Program.ActiveStatinCode).Result; if (this.IsHandleCreated) { BeginInvoke(new Action(() => { _bindingResultFinishedCodeVMs.Clear(); if (finishCodelist != null && finishCodelist.Count > 0) { finishCodelist.ForEach(m => _bindingResultFinishedCodeVMs.Add(m)); } })); } var datas = ResultHelper.SyncQueryCountByGroupStatus().Result; var totalCount = 0; var okCount = 0; if (datas != null && datas.Count > 0) { for (int i = 0; i < datas.Count; i++) { totalCount += datas[i].counts; if (datas[i].totalstatus.ToLower() == "ok") { okCount += datas[i].counts; } } } //总数 // var totalCount = ResultHelper.SyncQueryTotalCount().Result; UpdateControlContent(lblTotalCount, $"{totalCount} 个"); //OK数 // var okCount = ResultHelper.SyncQueryOkCount().Result; UpdateControlContent(lblOkCount, $"{okCount} 个"); //合格率 if (totalCount <= 0) { UpdateControlContent(lblRate, "0%"); } else { var rate = okCount / (totalCount * 1.0); UpdateControlContent(lblRate, $"{Math.Round(rate, 4) * 100}%"); } } catch (Exception ex) { var errMsg = ex == null ? "未知异常" : ex.Message; LogHelper.WriteLog($"Main中MyMethod方法出发异常:{errMsg},请联系管理员!"); //MessageBox.Show($"Main中MyMethod方法出发异常:{errMsg},请联系管理员!"); } } private void MyEventHandler_LogChanged(object newValue, string stationCode) { try { var object_txt = xtraTabPage1.Controls; BeginInvoke(new Action(() => { foreach (var item in object_txt) { if (stationCode == Program.ActiveStatinCode) { if (((MemoEdit)item).Name == Program.ActiveStatinCode + "X6") { txtLog.Visible = false; ((MemoEdit)item).Visible = true; UpdateMemo((MemoEdit)item, newValue.ToString()); } } else { var hide_memo_ID = ((MemoEdit)item).Name.Replace("X6", ""); if (hide_memo_ID == stationCode) { ((MemoEdit)item).Visible = false; UpdateMemo((MemoEdit)item, newValue.ToString()); } } } }) ); } catch (Exception ex) { var errMsg = ex == null ? "未知异常" : ex.Message; MessageBox.Show($"Main中MyEventHandler_LogChanged方法出发异常:{errMsg},请联系管理员!"); } } private static bool overWrite = false;//是否需要重新写入用户登录验证点位 /// /// 心跳监测 /// private void HeartMonitor() { var heartPoints = Program.PointKeyValues.Where(m => m.Key == "M2") .Select(m =>new { m.Address,m.StationCode }).ToList(); var loginPlcPoints = Program.PointKeyValues.Where(m => m.Key == "M1").Select(m => new { m.Address, m.StationCode }).ToList(); while (!cancellationTokenSource.IsCancellationRequested) { try { //if (!ExtendMethod.BoolPing(Program.PlcIpAddress)) //{ // SetPlcStatusLbl(lblplcstatus, "PLC通讯状态异常", Color.Red); // LogHelper.WriteLog($"PLC的IP地址{Program.PlcIpAddress}无法PING通,请检查网络连接!"); // overWrite = true; // continue; //} //if (Program.siemensS7Net == null) //{ // LogHelper.WriteLog($"心跳监测时,Program.siemensS7Net为空,进行重连!"); // SetPlcStatusLbl(lblplcstatus, "PLC通讯状态异常", Color.Red); // overWrite = true; // ConnectPLC(); //} if (heartPoints == null || heartPoints.Count <= 0) { LogHelper.WriteLog("心跳监测点位未配置!"); overWrite = true; continue; } if (Program.siemensS7Net != null) { for (int i = 0; i < heartPoints.Count; i++) { OperateResult result = WriteToPLCM2(heartPoints[i].Address); if (result == null || !result.IsSuccess) { SetPlcStatusLbl(lblplcstatus, "PLC通讯状态异常", Color.Red); LogHelper.WriteLog($"心跳监测时,[{heartPoints[i].StationCode}]工位写入失败!"); overWrite = true; } else { //重新写入用户登录验证点位 if (overWrite) { if (loginPlcPoints == null || loginPlcPoints.Count <= 0) { XtraMessageBox.Show("用户验证点位未配置,请配置完成后,重新登录!", "系统提示"); return; } var val = Program.SysMode ? "1" : "2"; foreach (var loginPlcItem in loginPlcPoints) { var loginResult = Program.siemensS7Net.Write(loginPlcItem.Address, ushort.Parse(val)); if (!loginResult.IsSuccess) { result = Program.siemensS7Net.Write(loginPlcItem.Address, ushort.Parse(val)); if (!loginResult.IsSuccess) { XtraMessageBox.Show($"离线模式登录时,[{loginPlcItem.StationCode}]工位用户验证结果写入失败,请重新登录!", "系统提示"); Environment.Exit(0); } } Thread.Sleep(5); } } SetPlcStatusLbl(lblplcstatus, "PLC通讯状态正常", Color.FromArgb(((int)(((byte)(146)))), ((int)(((byte)(229)))), ((int)(((byte)(255)))))); overWrite = false; } } } } catch (Exception ex) { var errMsg = ex == null ? "未知异常" : ex.Message; LogHelper.WriteLog($"Main中HeartMonitor方法出发异常:{errMsg},请联系管理员!"); overWrite = true; } Thread.Sleep(1000); } } private static OperateResult WriteToPLCM2(string address) { OperateResult operateResult = null; Task task = Task.Run(() => { return Program.siemensS7Net.Write(address, ushort.Parse("1")); }); task.Wait(); operateResult = task.Result; return operateResult; } private static async void ConnectPLC() { await Task.Run(() => { try { var connectPLC = new ConnectPLC(); //Program.siemensS7Net = connectPLC.GetOmronCipNet(); Program.siemensS7Net = connectPLC.GetSiemensS7Net(); } catch (Exception) { } }); } /// /// 给PLC通讯状态lblcontrol控件赋值 /// /// /// /// private void SetPlcStatusLbl(Control control, string content, Color color) { this.Invoke(new Action(() => { if (!control.IsHandleCreated) { return; } if (control.IsDisposed) { return; } control.Text = content; control.ForeColor = color; })); } /// /// 动态添加工位按钮 /// private void ShowStationBtn() { var stationList = Program.stationInfos.Where(m => m.IpcId == Program.CurrentIpcId).ToList(); if (stationList.Count > 0) { int btnLocation = 0; foreach (var stationItem in stationList) { #region 动态添加工位按钮 var btn = new SimpleButton(); btn.Appearance.Font = new Font("微软雅黑", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0))); btn.Appearance.ForeColor = Color.Black; btn.Appearance.Options.UseFont = true; btn.Appearance.Options.UseForeColor = true; btn.AppearanceHovered.Font = new Font("微软雅黑", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0))); btn.AppearanceHovered.ForeColor = Color.Black; btn.AppearanceHovered.Options.UseFont = true; btn.AppearanceHovered.Options.UseForeColor = true; var imgPath = Path.Combine(Application.StartupPath, "image/default_btn_gray.png"); btn.BackgroundImage = System.Drawing.Image.FromFile(imgPath); btn.BackgroundImageLayout = ImageLayout.Stretch; btn.Name = stationItem.StationCode; btn.PaintStyle = DevExpress.XtraEditors.Controls.PaintStyles.Light; btn.Size = new Size(230, 40); btn.Text = $"{stationItem.StationCode}-{stationItem.StationName}"; btn.Click += new EventHandler(btn_Click); stationpanel.Controls.Add(btn); MemoEdit Memoedit_1; Memoedit_1 = new MemoEdit { Font = new Font("微软雅黑", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0))), ForeColor = Color.FromArgb(255, 82, 215, 246), BackColor = Color.MidnightBlue, Size = new Size(695, 515), Dock = DockStyle.Fill, Name = $"{stationItem.StationCode}X6" }; Memoedit_1.CustomHighlightText += CustomHighlightText.OnCustomHighlightText; xtraTabPage1.Controls.Add(Memoedit_1); #endregion //读取点位信息 DoSomething doSomething = new DoSomething(); doSomething.LogChanged += DoSomething_LogChanged; doSomething.ReadPlc(stationItem, logs); btnLocation++; } } } private void DoSomething_LogChanged(object newValue, string stationCode) { var object_txt = xtraTabPage1.Controls; if (this.IsHandleCreated) { BeginInvoke(new Action(() => { foreach (var item in object_txt) { if (stationCode == Program.ActiveStatinCode) { if (((MemoEdit)item).Name == Program.ActiveStatinCode + "X6") { txtLog.Visible = false; ((MemoEdit)item).Visible = true; UpdateMemo((MemoEdit)item, newValue.ToString()); } } else { var hide_memo_ID = ((MemoEdit)item).Name.Replace("X6", ""); if (hide_memo_ID == stationCode) { ((MemoEdit)item).Visible = false; UpdateMemo((MemoEdit)item, newValue.ToString()); } } } })); } } /// /// 工位按钮点击事件 /// /// /// private void btn_Click(object sender, EventArgs e) { var thisBtn = sender as SimpleButton; ChangeCurrentStationCode(thisBtn); } private void ChangeCurrentStationCode(SimpleButton thisBtn) { var object_txt = xtraTabPage1.Controls; var activeStation = Program.stationInfos.FirstOrDefault(m => m.StationCode == thisBtn.Name); //在线模式才可绑定工单 if (Program.SysMode) { btnBindOrder.Visible = activeStation.IsShowOrderBtn; } //控制手动打印按钮的显示 if (activeStation.IsShowPrintBtn) { btnPrint.Visible = true; } else { btnPrint.Visible = false; } var btns = stationpanel.Controls; if (btns.Count > 0) { foreach (var item in btns) { var btn = ((SimpleButton)item); if (btn.Name == thisBtn.Name) { Program.ActiveStatinCode = btn.Name; var btnImgPath = Path.Combine(Application.StartupPath, "image/btn.png"); btn.BackgroundImage = System.Drawing.Image.FromFile(btnImgPath); btn.Appearance.ForeColor = Color.White; lblSite.Text = activeStation.Site; lblResource.Text = activeStation.Resource; lblPredure.Text = activeStation.Procedure; lblNgCode.Text = activeStation.NgCode; lblMesIp.Text = Program.MesIpAddress; lblMesPort.Text = Program.MesPort; if (logs.Count > 0) { foreach (var item_txt in object_txt) { if (((MemoEdit)item_txt).Name == thisBtn.Name + "X6") { txtLog.Visible = false; ((MemoEdit)item_txt).Visible = true; } else { ((MemoEdit)item_txt).Visible = false; } } } else { foreach (var item_txt in object_txt) { if (((MemoEdit)item_txt).Name == thisBtn.Name + "X6") { txtLog.Visible = false; ((MemoEdit)item_txt).Visible = true; } else { ((MemoEdit)item_txt).Visible = false; } } } } else { var imgPath = Path.Combine(Application.StartupPath, "image/default_btn_gray.png"); btn.BackgroundImage = System.Drawing.Image.FromFile(imgPath); btn.Appearance.ForeColor = Color.Black; } } } } /// /// 手动打印 /// /// /// private void btnPrint_Click(object sender, EventArgs e) { Print print = new Print(); print.Show(); } /// /// 点击结果查询按钮 /// /// /// private void btnSearchResult_Click(object sender, EventArgs e) { SearchResult searchResult = new SearchResult(); searchResult.ShowDialog(); } /// /// 点击工单绑定按钮 /// /// /// private void btnBindOrder_Click(object sender, EventArgs e) { BindOrder bindOrder = new BindOrder(); bindOrder.ChangeOrderCode += BindOrder_ChangeOrderCode; bindOrder.ShowDialog(); } private void BindOrder_ChangeOrderCode(string code) { lblOrderCode.Text = code; } /// /// 点击合格率查询按钮 /// /// /// private void btnPassRate_Click(object sender, EventArgs e) { PassRateRpt passRateRpt = new PassRateRpt(); passRateRpt.ShowDialog(); } /// /// 点击系统设置按钮 /// /// /// private void btnSysSetting_Click(object sender, EventArgs e) { ConfirmPwd confirmPwd = new ConfirmPwd(); confirmPwd.ShowDialog(); if (!string.IsNullOrWhiteSpace(confirmPwd.inputPwd)) { if (confirmPwd.inputPwd != Program.MenuPwd) { XtraMessageBox.Show("口令错误!", "系统提示"); return; } var index = new Index(); index.ShowDialog(); } } /// /// 切换系统模式 /// /// /// private void cmbMainSysMode_SelectedValueChanged(object sender, EventArgs e) { var selectedItem = cmbMainSysMode.SelectedItem as ListItem; if (!Program.SysMode && selectedItem.Value == "1") { DialogResult dialogResult = XtraMessageBox.Show("离线模式转在线模式需要重新启动系统,确认要切换模式吗?", "提示", MessageBoxButtons.OKCancel); if (dialogResult != DialogResult.OK) { return; } //设置用户登录状态 FaceDeviceHelper.Instance.faceLoginUserInfo.IsLogin = false; FaceDeviceHelper.Instance.faceLoginUserInfo.IsSuccess = false; Environment.Exit(0); } else if (selectedItem.Value == "0") { Program.SysMode = false; } } /// /// 主界面展示数据 /// private void ShowData() { while (!cancellationTokenSource.IsCancellationRequested) { try { Thread.Sleep(Program.readplcrate); //机台状态 var M7 = Program.PointKeyValues.FirstOrDefault(m => m.StationCode == Program.ActiveStatinCode && m.Key == "M7"); if (M7 != null) { UpdateControlContent(lblmachiestatus, $"机台{M7.Val}状态"); } //当前生产机型 //UpdateControlContent(lblMachineType, Program.MachineType); if (isChangeVal && isLoad) { var category = MskCodeHelper.QueryMask_codeByStationAndCategory(Program.ActiveStatinCode, Program.MachineType); if (category != null) { this.Invoke(new Action(() => { lkMachineType.EditValue = category.SortIndex.ToString();//设置机型下拉框选中项 machineOldVal = category.SortIndex.ToString(); isLoad = false; })); } } //产品总状态 var M5 = Program.PointKeyValues.FirstOrDefault(m => m.StationCode == Program.ActiveStatinCode && m.Key == "M5"); if (M5 != null && !string.IsNullOrWhiteSpace(M5.Val)) { if (lblResult.Text.ToLower() == "ng") { UpdateControlContent(lblResult, M5.Val, Color.Red); } else { UpdateControlContent(lblResult, M5.Val, Color.FromArgb(146, 229, 255)); } } else { UpdateControlContent(lblResult, ""); } //机型索引 var M14 = Program.PointKeyValues.FirstOrDefault(m => m.StationCode == Program.ActiveStatinCode && m.Key == "M14"); if (M14 != null && !string.IsNullOrWhiteSpace(M14.Val)) { BeginInvoke(new Action(() => { lblMskCodeSortIndex.Text = M14.Val; })); } else { BeginInvoke(new Action(() => { lblMskCodeSortIndex.Text = "未获取到机型索引"; })); } //主条码 var M28 = Program.PointKeyValues.FirstOrDefault(m => m.StationCode == Program.ActiveStatinCode && m.Key == "M28"); if (M28 != null && !string.IsNullOrWhiteSpace(M28.Val)) { if (M28.Val.ToLower() == "error\r") { UpdateControlContent(txtProductCode, M28.Val); } else { UpdateControlContent(txtProductCode, M28.Val); } } else { UpdateControlContent(txtProductCode, ""); } //组件条码 var subCodes = Program.PointKeyValues.Where(m => m.StationCode == Program.ActiveStatinCode && m.IsSub && m.Key != "M100").OrderBy(m=>m.SortIndex).ToList(); if (subCodes.Count > 0) { var strSubCode = ""; for (int i = 0; i < subCodes.Count; i++) { if (!string.IsNullOrEmpty(subCodes[i].Val)) { strSubCode += ($"{subCodes[i].Val},"); } } UpdateControlContent(txtSubCode, strSubCode.TrimEnd(',')); } else { UpdateControlContent(txtSubCode, ""); } //测试数据 var testlist = Program.PointKeyValues.Where(m => m.StationCode == Program.ActiveStatinCode && m.IsTestItem).OrderBy(m => m.SortIndex).ToList(); var showTestList = testlist.Where(m => m.IsShowMain).ToList(); if (IsHandleCreated) { if (showTestList.Count > 0) { for (int i = 0; i < showTestList.Count; i++) { var data = testlist.FirstOrDefault(m => m.Key.Contains(showTestList[i].Key) && !m.IsShowMain); if (data != null) { showTestList[i].Result = (data.Val == "1" || data.Val == "1.000") ? "OK" : ((data.Val == "2" || data.Val == "2.000") ? "NG" : ""); } } } BeginInvoke(new Action(() => { gridTestInfo.DataSource = showTestList; })); } } catch (Exception ex) { var errMsg = ex == null ? "未知异常" : ex.Message; MessageBox.Show($"Main中ShowData方法出发异常:{errMsg},请联系管理员!"); } } } /// /// 点击退出按钮 /// /// /// private void btnexit_Click(object sender, EventArgs e) { var result = MessageBox.Show("确定要退出系统吗?", "提示", MessageBoxButtons.OKCancel); if (result == DialogResult.OK) { //if (Program.siemensS7Net != null) //{ // var point = Program.PointKeyValues.FirstOrDefault(m => m.Key == "M1"); // if (point != null) // { // var plcResult = Program.siemensS7Net.Write(point.Address, ushort.Parse("0")); // if (!plcResult.IsSuccess) // { // XtraMessageBox.Show(string.Format("退出登录时,[{0}]工位用户验证结果写入失败!", point.StationCode), "系统提示"); // return; // } // } // else // { // XtraMessageBox.Show(string.Format("退出登录时,[{0}]工位M1点位未配置,用户验证结果写入失败!", point.StationCode), "系统提示"); // return; // } //} //设置用户登录状态 FaceDeviceHelper.Instance.faceLoginUserInfo.IsLogin = false; FaceDeviceHelper.Instance.faceLoginUserInfo.IsSuccess = false; Environment.Exit(0); } } /// /// 异步更新控件内容 /// /// /// private void UpdateControlContent(Control control, string content, Color? color = null) { if (!control.IsHandleCreated || control.IsDisposed) { return; } this.Invoke(new Action(() => { control.Text = content; if (color.HasValue) { control.ForeColor = color.Value; } })); } /// /// 异步更新MemoEdit控件 /// /// /// private void UpdateMemo(Control control, string info) { try { LogHelper.WriteLog(info); if (!control.IsHandleCreated || control.IsDisposed) return; BeginInvoke(new Action(() => { var memoCon = ((MemoEdit)control); //memoEdit最多显示500行,每超过500就删除10行。 if (memoCon.Lines.Count() > 500) { string[] strs = memoCon.Lines; ArrayList al = new ArrayList(strs); al.RemoveRange(0, 10); string[] arr = (string[])al.ToArray(typeof(string)); memoCon.Lines = arr; } memoCon.Text += info; //设置memoEdi滚动条位于最低端。 memoCon.SelectionStart = memoCon.Text.Length; memoCon.ScrollToCaret(); }) ); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void picminimize_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } private void time1_Tick(object sender, EventArgs e) { if (lbldatetime.IsHandleCreated && !lbldatetime.IsDisposed) { this.BeginInvoke(new Action(() => { lbldatetime.Text = DateTime.Now.ToString(); })); } } #region 窗体移动 private Point mPoint; private void panelControl1_MouseDown(object sender, MouseEventArgs e) { mPoint = new Point(e.X, e.Y); } private void panelControl1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y); } } #endregion public List logs = new List(); private readonly MyEventHandler myEventHandler = new MyEventHandler(); private BindingList _bindingResultFinishedCodeVMs = new BindingList(); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); /// /// 机型下拉框Change事件 /// /// /// private void lkMachineType_EditValueChanged(object sender, EventArgs e) { //数据初次加载的时候不走confirm if (isLoad) { return; } XtraMessageBox.Show("请前往PLC触摸屏进行机型切换!"); isChangeVal = true; isLoad = true; //var selectedMachineTypeSortIndex = lkMachineType.EditValue.ToString(); //var selectedMachineTypeText = lkMachineType.Text; //var result = MessageBox.Show("确定要修改机型吗?", "提示", MessageBoxButtons.OKCancel); //if (result != DialogResult.OK) //{ // isChangeVal = true; // isLoad = true; // return; //} //isChangeVal = false; //var stations = StationHelper.QueryActiveStationsByIpcIdandCategory(Program.CurrentIpcId, selectedMachineTypeText); //if (stations != null && stations.Count > 0) //{ // for (int i = 0; i < stations.Count; i++) // { // ChangeMachine(stations[i].StationCode, selectedMachineTypeSortIndex, selectedMachineTypeText); // } //} } /// /// 机型切换 /// /// /// /// private void ChangeMachine(string station, string machineSortIndex, string category) { try { var M7 = Program.PointKeyValues.FirstOrDefault(m => m.StationCode == station && m.Key == "M7"); //手动 if (M7.Val == "自动") { XtraMessageBox.Show("机台目前处于非手动状态,无法切换!"); isChangeVal = true; isLoad = true; return; } var M4 = Program.PointKeyValues.FirstOrDefault(m => m.StationCode == station && m.Key == "M4"); var M6 = Program.PointKeyValues.FirstOrDefault(m => m.StationCode == station && m.Key == "M6"); var writeResult = Program.siemensS7Net.Write(M4.Address, ushort.Parse(machineSortIndex)); if (!writeResult.IsSuccess) { LogHelper.WriteLog($"{Program.ActiveStatinCode}切换机型失败"); myEventHandler.StationCode = Program.ActiveStatinCode; myEventHandler.Log = $"{DateTime.Now:HH:mm:ss}>>>>>切换机型失败{Environment.NewLine}"; isChangeVal = true; isLoad = true; return; } writeResult = Program.siemensS7Net.Write(M6.Address, true); if (!writeResult.IsSuccess) { LogHelper.WriteLog($"{Program.ActiveStatinCode}切换机型失败"); myEventHandler.StationCode = Program.ActiveStatinCode; myEventHandler.Log = $"{DateTime.Now:HH:mm:ss}>>>>>切换机型失败{Environment.NewLine}"; isChangeVal = true; isLoad = true; return; } Thread.Sleep(500); writeResult = Program.siemensS7Net.Write(M6.Address, false); if (!writeResult.IsSuccess) { LogHelper.WriteLog($"{Program.ActiveStatinCode}切换机型失败"); myEventHandler.StationCode = Program.ActiveStatinCode; myEventHandler.Log = $"{DateTime.Now:HH:mm:ss}>>>>>切换机型失败{Environment.NewLine}"; return; } //更新数据库 int.TryParse(machineSortIndex, out int _selectedMachineTypeSortIndex); var rows = MskCodeHelper.UpdateMskCodeIsUsedBySortIndex(_selectedMachineTypeSortIndex); if (rows <= 0) { XtraMessageBox.Show($"{Program.ActiveStatinCode}切换机型失败"); LogHelper.WriteLog($"{Program.ActiveStatinCode}切换机型失败"); isChangeVal = true; isLoad = true; } else { XtraMessageBox.Show($"{Program.ActiveStatinCode}切换机型成功,请重启上位机"); LogHelper.WriteLog($"{Program.ActiveStatinCode}切换机型成功"); isChangeVal = true; isLoad = true; } } catch (Exception ex) { LogHelper.WriteLog($"{Program.ActiveStatinCode}在主界面切换机型时异常:{ex.Message}"); isChangeVal = true; isLoad = true; } } private void btn_Keyboard_Click(object sender, EventArgs e) { TouchKeyBoardHelper.OpenKeyBoardFun(); } } }