1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using HslCommunication.Profinet.Siemens;
using System;
using System.Threading;
using System.Threading.Tasks;
 
namespace PLCHelper
{
    public class DataChangedArg<T>
    {
        public T oldValue { get; set; }
        public T newValue { get; set; }
    }
 
    public class IntReader
    {
        private int lastVallue = 0;
 
        private string Address = string.Empty;
        private int Timeout = 1000;
 
        private SiemensS7Net client;
 
        private volatile bool isRunning = false;
 
        public event EventHandler<DataChangedArg<int>> DataChanged;
 
        public IntReader(SiemensS7Net client, string address, int initValue = 0)
        {
            this.client = client;
            this.Address = address;
            this.lastVallue = initValue;
        }
 
        public void Stop()
        {
            isRunning = false;
        }
 
        public void Run()
        {
            isRunning = true;
            Task.Run(() =>
            {
                while (isRunning)
                {
                    var res = client.ReadInt16(Address);
                    if (res.IsSuccess)
                    {
                        int val = res.Content;
                        if (val != lastVallue)
                        {
                            DataChanged?.Invoke(this, new DataChangedArg<int>
                            {
                                oldValue = lastVallue,
                                newValue = val
                            });
                            lastVallue = val;
                        }
                    }
                    Thread.Sleep(Timeout);
                }
            });
        }
    }
}