2021-09-04 WPF上位机通用框架平台实战-全局监控对象

在这里插入图片描述
在程序启动的时候就实时监控设备

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        GlobalMonitor.Start();

        if (new LoginWindow().ShowDialog() == true)
        {
            new MainWindow().ShowDialog();
        }
        Application.Current.Shutdown();
    }

    protected override void OnExit(ExitEventArgs e)
    {
        GlobalMonitor.Stop();
        base.OnExit(e);
    }
}
public class GlobalMonitor
{
    public static ObservableCollection<DeviceModel> DeviceList { get; set; } = new ObservableCollection<DeviceModel>();

    static bool isRunning = true;
    static Task mainTask = null;

    public static void Start()
    {
        mainTask = Task.Run(async () =>
        {
            // 获取设备信息
            //DeviceList.Add(new DeviceModel { Name = "#1 Master device info" });
            //DeviceList.Add(new DeviceModel { Name = "#2 Master device info" });
            //DeviceList.Add(new DeviceModel { Name = "#3 Master device info" });
            //DeviceList.Add(new DeviceModel { Name = "#4 Master device info" });

            DeviceService deviceService = new DeviceService();
            var list = deviceService.GetDevices();
            if (list != null)
                foreach (var item in list)
                {
                    DeviceList.Add(item);
                }
            //DeviceList = new ObservableCollection<DeviceModel>(list);

            while (isRunning)
            {
                await Task.Delay(100);

                foreach (var item in DeviceList)
                {
                    if (item.CommType == 2 && item.S7 != null)// S7通信
                    {
                        Zhaoxi.Communication.Siemens.S7Net s7Net = new Communication.Siemens.S7Net(item.S7.IP, item.S7.Port, (byte)item.S7.Rock, (byte)item.S7.Slot);

                        List<string> addrList = item.MonitorValueList.Select(v => v.Address).ToList();
                        var result = s7Net.Read<ushort>(addrList);
                        if (result.IsSuccessed)
                        {
                            for (int i = 0; i < item.MonitorValueList.Count; i++)
                            {
                                item.MonitorValueList[i].Value = result.Datas[i];
                            }
                        }

                        s7Net.Close();
                    }
                }
            }
        });
    }

    public static void Stop()
    {
        isRunning = false;
        mainTask.ConfigureAwait(true);
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值