123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442 |
- using MainForm.ClassFile;
- using ModBusClientSimple.Util;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace MainForm.FaForm
- {
- public partial class Form_PLCDB_ShowInfo : Form
- {
- #region ModbusTCP
- ModbusClientHelper plc1 = new ModbusClientHelper(GlobalContext.Machine1Address, GlobalContext.MachinePort, 499);
- #endregion ModbusTCP
- #region 变量
- /// <summary>
- /// 展示的工位名称
- /// </summary>
- private string _StationName;
- /// <summary>
- /// 记录信息方法的载体窗体
- /// </summary>
- private Form_PLCDB _Form_PLCDB;
- /// <summary>
- /// “工位可调试点位预览表.xlsx”文件的地址
- /// </summary>
- private string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\DBFile\\工位可调试点位预览表.xlsx";
- private DataTable dt;
- #endregion 变量
- #region 单例
- private static Form_PLCDB_ShowInfo _Form_PLCDB_ShowInfo;
- public static Form_PLCDB_ShowInfo Singleton(string stationName, Form_PLCDB form_PLCDB)
- {
- if (_Form_PLCDB_ShowInfo == null)
- {
- _Form_PLCDB_ShowInfo = new Form_PLCDB_ShowInfo();
- }
- _Form_PLCDB_ShowInfo._StationName = stationName;
- _Form_PLCDB_ShowInfo._Form_PLCDB = form_PLCDB;
- _Form_PLCDB_ShowInfo.OnLoadData(); // 加载点位数据
- return _Form_PLCDB_ShowInfo;
- }
- #endregion 单例
- #region 窗体事件
- public Form_PLCDB_ShowInfo()
- {
- InitializeComponent();
- }
- private void Form_PLCDB_ShowInfo_Load(object sender, EventArgs e)
- {
- try
- {
- this.Text = string.Concat(_StationName, " 工位DB详情");
- // dgv_S0
- dgv_DBInfo.ColumnHeadersDefaultCellStyle.BackColor = Color.WhiteSmoke;
- dgv_DBInfo.ColumnHeadersDefaultCellStyle.ForeColor = Color.Black;
- dgv_DBInfo.RectColor = Color.Gainsboro;
- dgv_DBInfo.GridColor = Color.Gainsboro;
- dgv_DBInfo.BackgroundColor = Color.White;
- }
- catch (Exception ex)
- {
- string str = ex.StackTrace;
- MessageBox.Show("PLC交互工位DB详情页面初始化出错!异常信息:" + ex.Message);
- _Form_PLCDB.AddMessage(LogType.Error, "PLC交互工位DB详情页面初始化出错!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
- }
- }
- private void Form_PLCDB_ShowInfo_VisibleChanged(object sender, EventArgs e)
- {
- if (!this.IsDisposed && this.Visible)
- {
- SBtn_GetDBValue_LoopStart.Enabled = true;
- SBtn_GetDBValue_LoopStop.Enabled = false;
- }
- else if (!this.IsDisposed && !this.Visible)
- {
- if (cts != null)
- {
- cts.Cancel();
- }
- SBtn_GetDBValue_LoopStart.Enabled = true;
- SBtn_GetDBValue_LoopStop.Enabled = false;
- }
- }
- #endregion 窗体事件
- #region 方法
- /// <summary>
- /// dgv加载数据
- /// </summary>
- private void OnLoadData()
- {
- try
- {
- if (!File.Exists(filePath))
- {
- MessageBox.Show($"‘{filePath}’文件不存在!未读到调试点位数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
- return;
- }
- dt = NPOIHelper.ReadExcel(filePath);
- if (dt != null && dt.Rows.Count > 0)
- {
- dt.Rows.RemoveAt(0);
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- if (dt.Rows[i][1] == DBNull.Value || !dt.Rows[i][1].ToString().Trim().Equals(_StationName))
- {
- dt.Rows.RemoveAt(i);
- i--;
- }
- }
- dgv_DBInfo.DataSource = dt.DefaultView;
- }
- else
- {
- dgv_DBInfo.DataSource = new DataTable().DefaultView;
- MessageBox.Show($"‘{filePath}’文件未包含任何需要读取的数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
- }
- }
- catch (Exception ex)
- {
- string str = ex.StackTrace;
- MessageBox.Show("PLC交互工位DB详情页面表格加载数据出错!异常信息:" + ex.Message);
- _Form_PLCDB.AddMessage(LogType.Error, "PLC交互工位DB详情页面表格加载数据出错!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
- }
- }
- #endregion 方法
- // 刷新当前值
- private void SBtn_GetDBValue_One_Click(object sender, EventArgs e)
- {
- try
- {
- if (dt == null)
- {
- return;
- }
- if (!plc1.IsConnected)
- {
- plc1.Connect();
- }
- int rowNum = 0;
- foreach (DataRow row in dt.Rows)
- {
- if (row[5] != DBNull.Value && row[4] != DBNull.Value && !string.IsNullOrEmpty(row[5].ToString()) && !string.IsNullOrEmpty(row[4].ToString()))
- {
- string value = string.Empty;
- string plcType = row[4].ToString();
- int plcAddress = Convert.ToInt32(row[5].ToString());
- switch (plcType)
- {
- case "Bool":
- value = (plc1.ReadHoldingRegisters(plcAddress, 1).FirstOrDefault() == 1).ToString(); // 读取
- break;
- case "Int16":
- value = plc1.ReadHoldingRegisters<short>(plcAddress).ToString(); // 读取
- break;
- case "Int32":
- value = plc1.ReadHoldingRegisters<int>(plcAddress).ToString(); // 读取
- break;
- case "String<32>":
- value = plc1.ReadHoldingRegisters(plcAddress, 32, 32).ToString(); // 读取
- break;
- case "Float":
- value = plc1.ReadHoldingRegisters<float>(plcAddress).ToString(); // 读取
- break;
- case "Bype<3>": // 日期yyyyMMdd;yyyy、MM、dd共占用3个地址位
- string plcDate_Y = plc1.ReadHoldingRegisters(plcAddress, 1).FirstOrDefault().ToString("0000"); // 产品序列号的 当前日期_年
- string plcDate_M = plc1.ReadHoldingRegisters(plcAddress + 1, 1).FirstOrDefault().ToString("00"); // 产品序列号的 当前日期_月
- string plcDate_D = plc1.ReadHoldingRegisters(plcAddress + 2, 1).FirstOrDefault().ToString("00"); // 产品序列号的 当前日期_日
- value = string.Concat(plcDate_Y, plcDate_M, plcDate_D); // 产品序列号的 当前日期
- break;
- default:
- break;
- }
- dgv_DBInfo.Rows[rowNum].Cells[9].Value = value;
- }
- rowNum++;
- }
- }
- catch (Exception ex)
- {
- string str = ex.StackTrace;
- MessageBox.Show("PLC交互工位DB详情页面刷新当前值出错!异常信息:" + ex.Message);
- _Form_PLCDB.AddMessage(LogType.Error, "PLC交互工位DB详情页面刷新当前值出错!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
- }
- }
- #region 循环刷新
- /// <summary>
- /// 循环线程结束标志
- /// </summary>
- private CancellationTokenSource cts;
- /// <summary>
- /// 循环刷新当前值
- /// </summary>
- private async void SBtn_GetDBValue_LoopStart_Click(object sender, EventArgs e)
- {
- cts = new CancellationTokenSource();
- SBtn_GetDBValue_LoopStart.Enabled = false;
- SBtn_GetDBValue_LoopStop.Enabled = true;
- await Task.Run(() => ThreadCode(cts.Token));
- }
- /// <summary>
- /// 停止循环刷新当前值
- /// </summary>
- private void SBtn_GetDBValue_LoopStop_Click(object sender, EventArgs e)
- {
- cts.Cancel();
- SBtn_GetDBValue_LoopStop.Enabled = false;
- SBtn_GetDBValue_LoopStart.Enabled = true;
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="token"></param>
- private void ThreadCode(CancellationToken token)
- {
- while (!token.IsCancellationRequested)
- {
- try
- {
- if (dt == null)
- {
- return;
- }
- if (!plc1.IsConnected)
- {
- plc1.Connect();
- }
- int rowNum = 0;
- foreach (DataRow row in dt.Rows)
- {
- if (row[5] != DBNull.Value && row[4] != DBNull.Value && !string.IsNullOrEmpty(row[5].ToString()) && !string.IsNullOrEmpty(row[4].ToString()))
- {
- string value = string.Empty;
- string plcType = row[4].ToString();
- int plcAddress = Convert.ToInt32(row[5].ToString());
- switch (plcType)
- {
- case "Bool":
- value = (plc1.ReadHoldingRegisters(plcAddress, 1).FirstOrDefault() == 1).ToString(); // 读取
- break;
- case "Int16":
- value = plc1.ReadHoldingRegisters<short>(plcAddress).ToString(); // 读取
- break;
- case "Int32":
- value = plc1.ReadHoldingRegisters<int>(plcAddress).ToString(); // 读取
- break;
- case "String<32>":
- value = plc1.ReadHoldingRegisters(plcAddress, 32, 32).ToString(); // 读取
- break;
- case "Float":
- value = plc1.ReadHoldingRegisters<float>(plcAddress).ToString(); // 读取
- break;
- case "Bype<3>": // 日期yyyyMMdd;yyyy、MM、dd共占用3个地址位
- string plcDate_Y = plc1.ReadHoldingRegisters(plcAddress, 1).FirstOrDefault().ToString("0000"); // 产品序列号的 当前日期_年
- string plcDate_M = plc1.ReadHoldingRegisters(plcAddress + 1, 1).FirstOrDefault().ToString("00"); // 产品序列号的 当前日期_月
- string plcDate_D = plc1.ReadHoldingRegisters(plcAddress + 2, 1).FirstOrDefault().ToString("00"); // 产品序列号的 当前日期_日
- value = string.Concat(plcDate_Y, plcDate_M, plcDate_D); // 产品序列号的 当前日期
- break;
- default:
- break;
- }
- dgv_DBInfo.Invoke(new Action(() =>
- {
- dgv_DBInfo.Rows[rowNum].Cells[9].Value = value;
- }));
- }
- rowNum++;
- }
- }
- catch (Exception ex)
- {
- string str = ex.StackTrace;
- MessageBox.Show("PLC交互工位DB详情页面循环刷新当前值出错!异常信息:" + ex.Message);
- cts.Cancel();
- this.Invoke(new Action(() =>
- {
- SBtn_GetDBValue_LoopStart.Enabled = true;
- SBtn_GetDBValue_LoopStop.Enabled = false;
- }));
- _Form_PLCDB.AddMessage(LogType.Error, "PLC交互工位DB详情页面循环刷新当前值出错!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
- }
- Thread.Sleep(1000); // 等待
- }
- }
- #endregion 循环刷新
- /// <summary>
- /// 写入
- /// </summary>
- private void 写入ToolStripMenuItem_Click(object sender, EventArgs e)
- {
- try
- {
- int selectedRowIndex = dgv_DBInfo.SelectedIndex;
- if (selectedRowIndex < 0 || selectedRowIndex > dgv_DBInfo.RowCount - 1)
- {
- MessageBox.Show("请先选择要写入的‘当前值’单元格", "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
- return;
- }
- if (!plc1.IsConnected)
- {
- plc1.Connect();
- }
- if (dgv_DBInfo.Rows[selectedRowIndex].Cells[5].Value != DBNull.Value && dgv_DBInfo.Rows[selectedRowIndex].Cells[4].Value != DBNull.Value && !string.IsNullOrEmpty(dgv_DBInfo.Rows[selectedRowIndex].Cells[5].ToString()) && !string.IsNullOrEmpty(dgv_DBInfo.Rows[selectedRowIndex].Cells[4].ToString()))
- {
- string plcVName = dgv_DBInfo.Rows[selectedRowIndex].Cells[3].Value?.ToString(); // DB点位的变量名称
- string plcType = dgv_DBInfo.Rows[selectedRowIndex].Cells[4].Value.ToString(); // DB点位的类型
- int plcAddress = Convert.ToInt32(dgv_DBInfo.Rows[selectedRowIndex].Cells[5].Value.ToString()); // DB点位的地址
- string plcVValue = dgv_DBInfo.Rows[selectedRowIndex].Cells[9].Value.ToString(); // DB点位的值
- switch (plcType)
- {
- case "Bool":
- if (plcVValue.ToLower() == "true")
- {
- plcVValue = "1";
- }
- else if (plcVValue.ToLower() == "false")
- {
- plcVValue = "0";
- }
- else
- {
- MessageBox.Show("写入失败!写入的值不是Bool类型!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
- return;
- }
- plc1.WriteSingleRegister(plcAddress, Convert.ToInt32(plcVValue)); // 写入
- MessageBox.Show("写入成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
- break;
- case "Int16":
- int value = 0;
- try
- {
- value = Convert.ToInt32(plcVValue);
- }
- catch
- {
- MessageBox.Show("写入失败!写入的值不是Int16类型!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
- return;
- }
- plc1.WriteSingleRegister(plcAddress, value); // 写入
- MessageBox.Show("写入成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
- break;
- case "Int32":
- int value1 = 0;
- try
- {
- value1 = Convert.ToInt32(plcVValue);
- }
- catch
- {
- MessageBox.Show("写入失败!写入的值不是Int32类型!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
- return;
- }
- plc1.WriteMultipleRegisters<int>(plcAddress, value1); // 写入
- MessageBox.Show("写入成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
- break;
- case "Float":
- float value2 = 0;
- try
- {
- value2 = Convert.ToSingle(plcVValue);
- }
- catch
- {
- MessageBox.Show("写入失败!写入的值不是Float类型!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
- return;
- }
- plc1.WriteMultipleRegisters<float>(plcAddress, value2); // 写入
- MessageBox.Show("写入成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
- break;
- case "String<32>":
- if (plcVValue == null || plcVValue.Length < 1)
- {
- MessageBox.Show("写入失败!写入值的长度必须 > 1!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
- return;
- }
- plc1.WriteMultipleRegisters<string>(plcAddress, plcVValue, 32); // 写入
- MessageBox.Show("写入成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
- break;
- //case "Bype<3>": // 日期yyyyMMdd;yyyy、MM、dd共占用3个地址位
- default:
- MessageBox.Show("不支持修改该类型的数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
- return;
- break;
- }
- _Form_PLCDB.AddMessage(LogType.Info, $"用户【{_Form_PLCDB.currentRole}】将‘{plcVName}’【{plcAddress}】的DB值修改为‘{plcVValue}’!");
- }
- }
- catch (Exception ex)
- {
- string str = ex.StackTrace;
- MessageBox.Show("写入值失败!错误信息:" + ex.Message);
- _Form_PLCDB.AddMessage(LogType.Error, "PLC交互工位DB详情页面写入当前值出错!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
- }
- }
- }
- }
|