C#编辑的PLC工位间追溯与报警提示软件

📅 发布时间:2026/7/8 10:49:31 👁️ 浏览次数:
C#编辑的PLC工位间追溯与报警提示软件
PLC的工位间追溯于报警提示软件用C#编辑。 1.工位间追溯 2.生产参数配方式管理 3.过程数据上传数据库存储 4.实时报警监测 5.历史数据查询与导出excel 已经与西门子S71500PLC测试通过。 工位可以任意添加。 通讯变量的地址也可以随意编辑。 源码用于二次开发或者直接使用。最近在车间折腾了个挺有意思的玩意儿——基于C#的PLC工位监控系统。这系统跟西门子S7-1500 PLC联调成功了支持动态添加工位变量地址随便改源码扔GitHub上还能当二次开发模板用。直接上干货聊聊实现思路。PLC的工位间追溯于报警提示软件用C#编辑。 1.工位间追溯 2.生产参数配方式管理 3.过程数据上传数据库存储 4.实时报警监测 5.历史数据查询与导出excel 已经与西门子S71500PLC测试通过。 工位可以任意添加。 通讯变量的地址也可以随意编辑。 源码用于二次开发或者直接使用。工位追溯这块咱们用了个动态配置的字典结构。每个工位对应PLC的DB块地址代码里是这么玩的public class StationConfig { public string StationName { get; set; } public string DataBlockAddress { get; set; } // 例如DB100.DBD20 public int VariablesCount { get; set; } } // 运行时加载配置 var stations new ListStationConfig{ new StationConfig { StationName 压铸工位, DataBlockAddress DB101.DBD0, VariablesCount 8 }, new StationConfig { StationName 检测工位, DataBlockAddress DB102.DBD12, VariablesCount 5 } };生产参数管理搞了个配方系统用XML存不同产品的参数模板。这里用了LINQ来快速查询// 加载配方 var recipe XElement.Load(Recipes.xml) .Elements(Product) .FirstOrDefault(x x.Attribute(id).Value A-2024); // 绑定到UI控件 txtPressure.Text recipe?.Element(Pressure).Value; numTimeout.Value decimal.Parse(recipe?.Element(Timeout).Value);实时报警监测最刺激用了个后台线程轮询PLC的报警地址。注意这里用了内存映射提升性能// 报警缓存队列 ConcurrentQueueAlarm _alarmQueue new ConcurrentQueueAlarm(); void AlarmMonitorThread() { while (!_cancellationToken.IsCancellationRequested) { var status _plc.ReadBytes(DataType.DataBlock, 200, 0, 16); // 读取DB200的16个字节 if (status[0] 0x01) { _alarmQueue.Enqueue(new Alarm { Code BitConverter.ToInt32(status, 4), Timestamp DateTime.Now }); } Thread.Sleep(200); // 200ms轮询间隔 } }历史数据存MySQL但建议换成时序数据库更好。这里封装了个简单的插入操作public void LogData(StationData data) { using var cmd new MySqlCommand( INSERT INTO production_log (station_id, cycle_time, output) VALUES (sid, ct, out), _conn); cmd.Parameters.AddWithValue(sid, data.StationId); cmd.Parameters.AddWithValue(ct, data.CycleTime.TotalSeconds); cmd.Parameters.AddWithValue(out, data.OutputCount); cmd.ExecuteNonQuery(); }导出Excel用了EPPlus库比传统的COM组件稳定得多using (var pkg new ExcelPackage()) { var sheet pkg.Workbook.Worksheets.Add(生产报表); sheet.Cells[A1].LoadFromDataTable(dataTable, true); // 自动调整列宽 sheet.Cells[sheet.Dimension.Address].AutoFitColumns(); File.WriteAllBytes(Report.xlsx, pkg.GetAsByteArray()); }这系统最大的亮点是扩展性——新增工位只需改配置文件不用动代码。通讯层用了S7.Net Plus驱动实测1500PLC的读写速度能跑到10ms以内。源码里留了不少TODO注释方便后续加功能比如OPC UA支持或者MQTT上传数据。调试时踩过个坑PLC的DB块地址必须按字对齐不然会报长度错误。后来加了个地址校验函数才解决bool ValidateAddress(string address) { var match Regex.Match(address, ^DB(\d)\.DB([XBDW])(\d)$); if (!match.Success) return false; int offset int.Parse(match.Groups[3].Value); return offset % 2 0; // 校验偏移量是否为偶数 }有老铁问为啥不用WPF做界面其实WinForm更适合工控场景毕竟车间电脑很多还跑着Win7。整个方案在2核4G的工控机上实测CPU占用不到5%比组态软件轻量多了。