-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphWindow.xaml.cs
333 lines (285 loc) · 10.4 KB
/
GraphWindow.xaml.cs
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#nullable enable
namespace PingTestTool
{
// -------------------- Constants --------------------
public static class Constant
{
public const int MaxVisiblePoints = 100;
public const int MinPingInterval = 100;
}
// -------------------- Interfaces --------------------
public interface IGraphWindow
{
bool IsLoaded { get; }
WindowState WindowState { get; set; }
bool IsVisible { get; }
Visibility Visibility { get; set; }
void SetPingData(List<int> roundtripTimes);
void Show();
void Close();
event EventHandler? Closed;
}
public interface IGraphManager : IDisposable
{
void UpdateMaxVisiblePoints(int maxVisiblePoints);
void UpdateGraph(int maxVisiblePoints);
void SetData(IEnumerable<int> data);
}
public interface IStatisticsManager : IDisposable
{
void UpdateMaxVisiblePoints(int maxVisiblePoints);
void SetPingData(IEnumerable<int> data);
PingStatistics GetStatistics(List<int> data);
}
// -------------------- Data Structures --------------------
public readonly record struct PingStatistics(
double Min,
double Avg,
double Max,
double Cur);
// -------------------- Implementations --------------------
public partial class GraphWindow : Window, INotifyPropertyChanged, IDisposable, IGraphWindow
{
private readonly ILoggingService _logger;
private readonly IGraphManager _graphManager;
private readonly IStatisticsManager _statisticsManager;
private readonly DispatcherTimer _updateTimer;
private int _maxVisiblePoints = Constant.MaxVisiblePoints;
public PlotModel PingPlotModel { get; }
public event PropertyChangedEventHandler? PropertyChanged;
public int MaxVisiblePoints
{
get => _maxVisiblePoints;
set
{
if (_maxVisiblePoints != value)
{
_maxVisiblePoints = value;
OnPropertyChanged(nameof(MaxVisiblePoints));
_graphManager.UpdateMaxVisiblePoints(value);
_statisticsManager.UpdateMaxVisiblePoints(value);
_graphManager.UpdateGraph(_maxVisiblePoints);
}
}
}
public GraphWindow(int pingInterval, ILoggingService logger)
{
InitializeComponent();
DataContext = this;
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
PingPlotModel = new PlotModel
{
Title = "График по времени отклика для Ping",
Background = OxyColors.White
};
_statisticsManager = new StatisticsManager();
_graphManager = new GraphManager(
logger,
PingPlotModel,
UpdateTextFields,
_statisticsManager);
_updateTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(Math.Max(pingInterval, Constant.MinPingInterval))
};
_updateTimer.Tick += (_, _) => Application.Current.Dispatcher.Invoke(() =>
_graphManager.UpdateGraph(_maxVisiblePoints));
_updateTimer.Start();
}
public void SetPingData(List<int>? data)
{
if (data is null || !data.Any())
{
_logger.Warning("[GraphWindow] Пустые или нулевые данные получены для пинга.");
return;
}
_statisticsManager.SetPingData(data);
_graphManager.SetData(data);
_graphManager.UpdateGraph(MaxVisiblePoints);
}
private void UpdateTextFields(string min, string avg, string max, string cur)
{
Dispatcher.Invoke(() =>
{
txtMin.Text = min;
txtAvg.Text = avg;
txtMax.Text = max;
txtCur.Text = cur;
});
}
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void Dispose()
{
_updateTimer.Stop();
_graphManager.Dispose();
_statisticsManager.Dispose();
}
}
public class GraphManager : IGraphManager
{
private readonly PlotModel _plotModel;
private readonly Action<string, string, string, string> _updateTextFields;
private readonly ConcurrentDictionary<DateTime, double> _realtimeData = new();
private readonly IStatisticsManager _statisticsManager;
private readonly LineSeries _normalSeries;
private readonly ILoggingService _logger;
private readonly object _lock = new();
private bool _disposed;
private int _maxVisiblePoints = Constant.MaxVisiblePoints;
public GraphManager(ILoggingService logger, PlotModel plotModel, Action<string, string, string, string> updateTextFields, IStatisticsManager statisticsManager)
{
_plotModel = plotModel;
_updateTextFields = updateTextFields;
_statisticsManager = statisticsManager ??
throw new ArgumentNullException(nameof(statisticsManager));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
_normalSeries = new LineSeries
{
Title = "Ping",
Color = OxyColor.FromRgb(0, 114, 189),
MarkerType = MarkerType.Circle,
MarkerSize = 3,
MarkerStroke = OxyColor.FromRgb(0, 114, 189),
MarkerFill = OxyColors.White,
};
InitializeGraphComponents();
}
private void InitializeGraphComponents()
{
_plotModel.Axes.Add(new DateTimeAxis
{
Position = AxisPosition.Bottom,
Title = "Время",
StringFormat = "HH:mm:ss",
});
_plotModel.Axes.Add(new LinearAxis
{
Position = AxisPosition.Left,
Title = "Время отклика (мс)",
AbsoluteMinimum = 0,
});
_plotModel.Series.Add(_normalSeries);
}
public void UpdateMaxVisiblePoints(int maxVisiblePoints)
{
_maxVisiblePoints = maxVisiblePoints;
TrimDataToMaxVisiblePoints();
}
private void TrimDataToMaxVisiblePoints()
{
lock (_lock)
{
while (_realtimeData.Count > _maxVisiblePoints)
{
var oldestKey = _realtimeData.Keys.Min();
_realtimeData.TryRemove(oldestKey, out _);
}
}
}
public void UpdateGraph(int maxVisiblePoints)
{
if (_realtimeData.IsEmpty)
{
_logger.Warning("[GraphManager] No data to update graph.");
return;
}
var sortedData = FilterAndSortData(maxVisiblePoints);
_normalSeries.Points.Clear();
_normalSeries.Points.AddRange(sortedData);
var dataValues = _realtimeData.Values.Select(d => (int)d).ToList();
var stats = _statisticsManager.GetStatistics(dataValues);
_logger.Information($"[GraphManager] Min: {stats.Min}, Avg: {stats.Avg}, Max: {stats.Max}, Cur: {stats.Cur}");
_updateTextFields(
$"{stats.Min:F1}",
$"{stats.Avg:F1}",
$"{stats.Max:F1}",
$"{stats.Cur:F1}"
);
_plotModel.InvalidatePlot(true);
}
private List<DataPoint> FilterAndSortData(int maxVisiblePoints)
{
List<DataPoint> sortedData;
lock (_lock)
{
sortedData = _realtimeData
.OrderBy(kvp => kvp.Key)
.Skip(Math.Max(0, _realtimeData.Count - maxVisiblePoints))
.Select(kvp => new DataPoint(DateTimeAxis.ToDouble(kvp.Key), kvp.Value))
.Where(dp => dp.Y > 0)
.ToList();
}
return sortedData;
}
public void SetData(IEnumerable<int> data)
{
var timestamp = DateTime.Now;
lock (_lock)
{
foreach (var value in data.Where(x => x > 0))
{
_realtimeData[timestamp] = value;
TrimDataToMaxVisiblePoints();
}
}
_logger.Information("[GraphManager] Graph data updated. Current data count: {Count}", _realtimeData.Count);
}
public void Dispose()
{
if (_disposed) return;
lock (_lock)
{
_realtimeData.Clear();
}
_statisticsManager.Dispose();
_disposed = true;
}
}
public class StatisticsManager : IStatisticsManager
{
private ConcurrentQueue<int> _pingData = new();
private int _maxDataPoints = Constant.MaxVisiblePoints;
private bool _disposed;
public void UpdateMaxVisiblePoints(int maxVisiblePoints)
{
_maxDataPoints = maxVisiblePoints;
TrimDataToMaxVisiblePoints();
}
private void TrimDataToMaxVisiblePoints()
{
while (_pingData.Count > _maxDataPoints)
{
_pingData.TryDequeue(out _);
}
}
public void SetPingData(IEnumerable<int> data)
{
foreach (var value in data.Where(x => x > 0))
{
_pingData.Enqueue(value);
TrimDataToMaxVisiblePoints();
}
}
public PingStatistics GetStatistics(List<int> data)
{
if (data == null || data.Count == 0)
return new PingStatistics(0, 0, 0, 0);
return new PingStatistics(
data.Min(),
data.Average(),
data.Max(),
data.Last()
);
}
public void Dispose()
{
if (_disposed) return;
while (_pingData.TryDequeue(out _)) { }
_disposed = true;
}
}
}