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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Window1.xaml 的交互逻辑
/// </summary>
public partial class Window1 : Window
{
PLC pLC;
public Window1()
{
InitializeComponent();
pLC = new PLC();
pLC.Init();
pLC.Do();
this.DataContext = pLC;
}
}
public class PLC:INotifyPropertyChanged
{
public bool IsFanOn { get; set; }
public bool IsPowerOn { get; set; }
public TimeSpan Elapsed { get; set; }
public ObservableCollection<UInt16> D800 { get; } = new ObservableCollection<ushort>();
FLY.Modbus.WithThread.ClientTCP client;
public PLC()
{
}
public void Init()
{
client = new FLY.Modbus.WithThread.ClientTCP(new System.Net.IPEndPoint(System.Net.IPAddress.Parse("192.168.1.1"), 502));
}
public void Do()
{
Task task = new Task(() =>
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
if (client.Do_01(3, 2, out IEnumerable<bool> values))
{
IsFanOn = values.ElementAt(0);
IsPowerOn = values.ElementAt(1);
}
IEnumerable<UInt16> values2;
int read_cnt = 30;
int offset = 0;
int cnt = 100;
while(offset<cnt)
{
if (offset + read_cnt > cnt)
{
read_cnt = 100 - offset;
}
if (client.Do_03((UInt16)(800 + offset), (UInt16)(read_cnt), out values2))
{
for (int i = 0; i < read_cnt; i++)
{
if (i + offset < D800.Count)
D800[i + offset] = values2.ElementAt(i);
else
D800.Add(values2.ElementAt(i));
}
offset += read_cnt;
}
else
{
break;
}
}
Elapsed = stopwatch.Elapsed;
stopwatch.Restart();
Thread.Sleep(0);
}
});
task.Start();
}
public event PropertyChangedEventHandler PropertyChanged;
}
}