private void TimerReadPLC_Tick(object sender, EventArgs e) { // 每秒执行一次去读取PLC数据,此处简便操作,放在前台执行,正常逻辑应该放到后台 HslCommunication.OperateResult <byte[]> read = siemensTcp.ReadFromPLC("M100", 24); if (read.IsSuccess) { handler.UpdateMachineOne("1#", read.Content); } else { // 读取失败,应该提示并记录日志,此处省略 MessageBox.Show(read.ToMessageShowString()); } }
private void userButton9_Click(object sender, EventArgs e) { for (int i = 0; i < 10; i++) { OperateResult <byte[]> read = siemensTcpNet.ReadFromPLC("M100", 6); if (read.IsSuccess) { TextBoxAppendStringLine(HslCommunication.BasicFramework.SoftBasic.ByteToHexString(read.Content)); } else { MessageBox.Show(read.ToMessageShowString()); if (read.Content != null) { textBox1.Text = HslCommunication.BasicFramework.SoftBasic.ByteToHexString(read.Content); } } } }
private void button25_Click(object sender, EventArgs e) { try { OperateResult <byte[]> read = siemensTcpNet.ReadFromPLC(textBox3.Text, ushort.Parse(textBox9.Text)); if (read.IsSuccess) { textBox10.Text = "结果:" + HslCommunication.BasicFramework.SoftBasic.ByteToHexString(read.Content); } else { MessageBox.Show("读取失败:" + read.ToMessageShowString( )); } } catch (Exception ex) { MessageBox.Show("读取失败:" + ex.Message); } }
private void ThreadBackgroundReadPlc( ) { // 此处假设我们读取的是西门子PLC的数据,其实三菱的数据读取原理是一样的,可以仿照西门子的开发 /************************************************************************************************** * * 假设一:M100,M101存储了一个温度值,举例,100.5℃数据为1005 * 假设二:M102存储了设备启停信号,0为停止,1为启动 * 假设三:M103-M106存储了一个产量值,举例:12345678 * **************************************************************************************************/ while (true) { if (isReadingPlc) { // 这里仅仅演示了西门子的数据读取 // 事实上你也可以改成三菱的,无非解析数据的方式不一致而已,其他数据推送代码都是一样的 HslCommunication.OperateResult <byte[]> read = siemensTcpNet.ReadFromPLC("M100", 7); if (read.IsSuccess) { failed = 0; // 读取失败次数清空 netComplex.SendAllClients(1, read.Content); // 群发所有客户端 ShowReadContent(read.Content); // 在主界面进行显示,此处仅仅是测试,实际项目中不建议在服务端显示数据信息 } else { failed++; ShowFailedMessage(failed); // 显示出来读取失败的情况 } } System.Threading.Thread.Sleep(500); // 两次读取的时间间隔 } }