Blame view

HHECS.DAQClient/ViewModel/MainVM.cs 19.6 KB
唐召明 authored
1
2
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
唐召明 authored
3
4
using System.Configuration;
using System.Diagnostics;
唐召明 authored
5
using System.Windows;
唐召明 authored
6
using System.Windows.Controls;
唐召明 authored
7
8
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
唐召明 authored
9
using FreeSql;
唐召明 authored
10
using HHECS.DAQClient.Common;
唐召明 authored
11
using HHECS.DAQClient.Common.Enums;
-  
唐召明 authored
12
using HHECS.DAQClient.DataAccess;
唐召明 authored
13
using HHECS.DAQClient.Model;
唐召明 authored
14
using HHECS.DAQClient.Services;
15
using HHECS.DAQClient.View.CommunicationView;
唐召明 authored
16
using HHECS.DAQClient.View.EquipmentView;
唐召明 authored
17
using HHECS.EquipmentModel;
唐召明 authored
18
using static FreeSql.Internal.GlobalFilter;
-  
唐召明 authored
19
using MessageBox = HandyControl.Controls.MessageBox;
唐召明 authored
20
唐召明 authored
21
namespace HHECS.DAQClient.ViewModel
唐召明 authored
22
23
24
25
26
27
28
29
30
31
32
33
{
    internal partial class MainVM : ObservableObject
    {
        [ObservableProperty]
        private bool btnStartEnabled = true;

        [ObservableProperty]
        private bool btnStopEnabled = false;

        [ObservableProperty]
        private ObservableCollection<LogModel> logModels = new();
唐召明 authored
34
35
36
37
38
39
40
41
42
        [ObservableProperty]
        private Page communicationPage = new CommunicationPage();

        [ObservableProperty]
        private Page equipmentPage = new EquipmentPage();

        [ObservableProperty]
        private Page equipmentDataQueuePage = new EquipmentDataQueuePage();
唐召明 authored
43
44
45
46
47
48
49
50
51
52
        /// <summary>
        /// 自动上传数据
        /// </summary>
        [ObservableProperty]
        private bool autoCommit = true;

        /// <summary>
        /// 每次提交的数据量
        /// </summary>
        private int _commitCount = 30;
53
54
        private readonly SystemLog _log = SystemLog.GetInstance();
        private readonly CenterService _centerService;
唐召明 authored
55
        private readonly HttpService _httpService;
56
        private readonly DataContext _context;
唐召明 authored
57
        public MainVM(DataContext context, CenterService centerService, HttpService httpService)
唐召明 authored
58
59
        {
            _centerService = centerService;
唐召明 authored
60
            _httpService = httpService;
-  
唐召明 authored
61
            _context = context;
唐召明 authored
62
63
64
65
66
            Initial();
        }

        private void Initial()
        {
唐召明 authored
67
            //GenerateData();
唐召明 authored
68
69
70
71
            var commitCountConfig = ConfigurationManager.AppSettings["CommitCount"];
            _ = int.TryParse(commitCountConfig, out _commitCount);
            if (_commitCount <= 0)
            {
唐召明 authored
72
73
                //未配置,则默认100
                _commitCount = 100;
唐召明 authored
74
75
            }
            RefreshLog();
唐召明 authored
76
            UploadEquipmentDataToCloud();
77
78
79
            UpdataClientStatus();
        }
唐召明 authored
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
        /// <summary>
        /// 上传数据至IOTClound
        /// </summary>
        private void UploadEquipmentDataToCloud()
        {
            Task.Run(async () =>
            {
                var index = 0;
                while (true)
                {
                    try
                    {
                        await Task.Delay(1000);
                        if (!_centerService.EquipmentDataQueues.IsEmpty)
                        {
                            var temps = new List<EquipmentDataQueue>();
                            var commitFailureRecords = new List<EquipmentDataQueue>();
                            for (int i = 0; i < _commitCount; i++)
                            {
                                var result = _centerService.EquipmentDataQueues.TryDequeue(out var item);
                                if (!result) break;
                                if (item != null)
                                {
                                    temps.Add(item);
                                }
                            }

                            //自动上传启用,且数据库无未上传的数据,则直接推送
                            if (AutoCommit && !_context.EquipmentDataQueue.Where(x => true).Any())
                            {
                                var tasks = new List<Task<List<EquipmentDataQueue>>>();
                                foreach (var item in temps.GroupBy(x => x.EquipmentCode))
                                {
                                    tasks.Add(Task.Run(() =>
                                    {
                                        Stopwatch stopwatch = Stopwatch.StartNew();
                                        var records = item.OrderBy(x => x.SourceTimestamp).ToList();
                                        var result = _httpService.SendEquipmentData(records);
                                        if (!result.Success)
                                        {
                                            _log.LogError($"推送设备[{item.Key}]数据失败,{result.Msg},耗时:{stopwatch.ElapsedMilliseconds}ms");
                                            return records;
                                        }
                                        _log.LogSuccess($"成功推送{records.Count}条设备[{item.Key}]数据,耗时:{stopwatch.ElapsedMilliseconds}ms");
                                        return new List<EquipmentDataQueue>();
                                    }));
                                }
                                Task.WaitAll(tasks.ToArray());
                                commitFailureRecords = tasks.SelectMany(x => x.Result).ToList();
                            }
                            //自动上传关闭或数据库存在未上传的记录,则直接存入数据库
                            else
                            {
                                commitFailureRecords.AddRange(temps);
                            }

                            //将上传失败的数据存入数据库
                            if (commitFailureRecords.Count > 0)
                            {
                                _context.EquipmentDataQueue.AddRange(commitFailureRecords);
                                _context.SaveChanges();
                                _log.LogInfo($"新增{commitFailureRecords.Count}条数据记录");
                            }
                        }

                        if (BtnStartEnabled)
                        {
                            //未启动,1s/
                            index = 0;
                        }
                        else
                        {
                            //启动时,5s/
                            index++;
                        }

                        if (AutoCommit && index % 5 == 0)
                        {
                            if (!_context.EquipmentDataQueue.Where(x => true).Any())
                            {
                                continue;
                            }
                            var equipmentCodes = _context.EquipmentDataQueue.Where(x => true).Distinct().ToList(x => x.EquipmentCode);
                            //推送成功的数据集合
                            var tasks = new List<Task<List<EquipmentDataQueue>>>();
                            foreach (var equipmentCode in equipmentCodes)
                            {
                                tasks.Add(Task.Run(() =>
                                {
                                    Stopwatch stopwatch = Stopwatch.StartNew();
                                    var temps = _context.EquipmentDataQueue.Where(x => x.EquipmentCode == equipmentCode && !x.IsCommit).OrderBy(x => x.SourceTimestamp).Take(_commitCount).ToList();
                                    if (temps.Count == 0)
                                    {
                                        return new List<EquipmentDataQueue>();
                                    }
                                    var result = _httpService.SendEquipmentData(temps);
                                    if (!result.Success)
                                    {
                                        _log.LogError($"推送设备[{equipmentCode}]数据失败,{result.Msg},耗时:{stopwatch.ElapsedMilliseconds}ms");
                                        return new List<EquipmentDataQueue>();
                                    }
                                    _log.LogSuccess($"成功推送{temps.Count}条设备[{equipmentCode}]数据,耗时:{stopwatch.ElapsedMilliseconds}ms");
                                    return temps;
                                }));
                            }
                            Task.WaitAll(tasks.ToArray());
                            var commitSuccessRecords = tasks.SelectMany(x => x.Result).ToList();
                            if (commitSuccessRecords.Count > 0)
                            {
                                _context.EquipmentDataQueue.RemoveRange(commitSuccessRecords);
                                _context.SaveChanges();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.LogException($"数据上传线程异常:{ex.Message}");
                    }
                }
            });
        }
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
        private void UpdataClientStatus()
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    await Task.Delay(5000);
                    if (BtnStartEnabled)
                    {
                        continue;
                    }
                    _ = Guid.TryParse(ConfigurationManager.AppSettings["ClientId"], out var clientId);
                    var result = _httpService.UpdateClientStatus(clientId);
                    if (!result.Success)
                    {
                        _log.LogError($"更新客户端状态失败:{result.Msg}");
                    }
                }
            });
唐召明 authored
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
        }

        [RelayCommand]
        public void Start()
        {
            BtnStartEnabled = false;
            BtnStopEnabled = true;
            _centerService.Start();

        }

        [RelayCommand]
        public void Stop()
        {
            BtnStartEnabled = true;
            BtnStopEnabled = false;
            _centerService.Stop();
        }
唐召明 authored
240
        private void RefreshLog()
唐召明 authored
241
242
243
244
245
246
247
248
249
250
        {
            Task.Run(() =>
            {
                Application.Current.Dispatcher.Invoke(async () =>
                {
                    do
                    {
                        while (!_log.IsEmpty)
                        {
                            var log = _log.GetLog();
唐召明 authored
251
                            if (log == null)
唐召明 authored
252
                            {
唐召明 authored
253
254
255
256
257
258
259
260
261
262
263
264
265
                                await Task.Delay(100);
                                continue;
                            }

                            var oldItem = LogModels.Where(x => x.Messages.Equals(log.Messages)).FirstOrDefault();
                            if (oldItem != null)
                            {
                                oldItem.CreateTime = log.CreateTime;
                                LogModels = new ObservableCollection<LogModel>(LogModels.OrderByDescending(x => x.CreateTime));
                            }
                            else
                            {
                                LogModels.Insert(0, new LogModel()
唐召明 authored
266
                                {
唐召明 authored
267
268
269
270
271
272
273
274
                                    LogType = log.LogType,
                                    Messages = log.Messages,
                                    CreateTime = log.CreateTime
                                });
                            }
                            if (LogModels.Count > 50)
                            {
                                LogModels.Remove(LogModels.Last());
唐召明 authored
275
276
277
278
279
280
281
                            }
                        }
                        await Task.Delay(100);
                    } while (true);
                });
            });
        }
唐召明 authored
282
283

        /// <summary>
唐召明 authored
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
        /// 生成数据
        /// </summary>
        private void GenerateData()
        {
            var stationCodeArea1 = new List<string>
            {
                "P1001",
                "P1002",
                "P1004",
                "P1005",
                "P1007",
                "P1008",
                "P1009",
                "P1010",
                "P1011",
                "P1012",
                "P1013",
                "P1014",
                "P1015",
                "P1016",
                "P1017",
                "P1018",
            };

            var stationCodeArea2 = new List<string>
            {
                "P1001",
                "P1002",
                "P1004",
                "P1006",
                "P1007",
            };

            var stationCodeArea3 = new List<string>
            {
                "P1001",
                "P1002",
                "P1003",
                "P1004",
                "P1005",
                "P1006",
                "P1007",
                "P1008",
                "P1009",
                "P1010",
                "P1011",
                "P1012",
                "P1013",
                "P1014",
                "P1015",
                "P10161",
                "P10162",
            };

            //GenerateStationMonitorEquipment(stationCodeArea1, "192.168.10.103", "1");
            //GenerateStationMonitorEquipment(stationCodeArea2, "192.168.10.10", "2");
            //GenerateStationMonitorEquipment(stationCodeArea3, "192.168.10.50", "3");
        }

        /// <summary>
        /// 生成站台监控数据
        /// </summary>
        /// <param name="stationCode"></param>
        /// <param name="ip"></param>
        /// <param name="destinationArea"></param>
唐召明 authored
349
350
351
352
353
354
355
356
357
358
359
360
361
        private void GenerateStationMonitorEquipment(IEnumerable<string> stationCode, string ip, string destinationArea)
        {
            try
            {
                var equipmentType = _context.EquipmentType.Where(x => x.Code == EquipmentTypeConst.StationMonitor.ToString()).First();
                var equipmentPropTemps = _context.EquipmentTypePropTemplate.Where(x => x.EquipmentTypeId == equipmentType.Id).ToList();

                var equipmentTemps = new List<Equipment>();
                foreach (var station in stationCode)
                {
                    var equipment = new Equipment
                    {
                        Code = station,
唐召明 authored
362
                        Name = $"{station}站台监控",
唐召明 authored
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
                        EquipmentTypeId = equipmentType.Id,
                        IP = ip,
                        Created = DateTime.Now,
                        DestinationArea = destinationArea,
                        Description = station,
                        ConnectName = station
                    };
                    equipmentTemps.Add(equipment);
                }
                _context.Equipment.AddRange(equipmentTemps);
                _context.SaveChanges();

                var dbStart1 = 0;
                var dbStart2 = 0;
                var equipmentProps = new List<EquipmentProp>();
                foreach (var equipment in equipmentTemps)
                {
                    var equipmentId = _context.Equipment.Where(x => x.ConnectName == equipment.ConnectName && x.IP == x.IP && x.DestinationArea == destinationArea).First(x => x.Id);

                    foreach (var item in equipmentPropTemps)
                    {
                        _ = Enum.TryParse<StationMonitorProp>(item.Code, out var StationMonitorCode);
                        var address = StationMonitorCode switch
                        {
                            StationMonitorProp.StationMonitorBarcode => $"DB3002.{dbStart1},20",
                            StationMonitorProp.StationMonitorAutomation => $"DB3002.{dbStart1 + 20}",
                            StationMonitorProp.StationMonitorOccupied => $"DB3002.{dbStart1 + 22}",
                            StationMonitorProp.StationError => $"DB3002.{dbStart1 + 24}",
                            StationMonitorProp.StationDestination => $"DB3002.{dbStart1 + 26}",
                            StationMonitorProp.StationBackup => $"DB3002.{dbStart1 + 28}",
                            StationMonitorProp.StationCorotation => $"DB3200.{dbStart2 / 8}.{dbStart2 % 8}",
唐召明 authored
394
395
                            StationMonitorProp.StationReverse => $"DB3200.{(dbStart2 + 1) / 8}.{(dbStart2 + 1) % 8}",
                            StationMonitorProp.StationHighSpeed => $"DB3200.{(dbStart2 + 2) / 8}.{(dbStart2 + 2) % 8}",
唐召明 authored
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
                            _ => string.Empty,
                        };
                        var prop = new EquipmentProp
                        {
                            EquipmentId = equipmentId,
                            EquipmentTypePropTemplateId = item.Id,
                            EquipmentTypePropTemplateCode = item.Code,
                            Address = address,
                            Remark = item.Name,
                            ServerHandle = 0,
                            Created = DateTime.Now,
                        };
                        equipmentProps.Add(prop);
                    }
                    dbStart1 += 30;
                    dbStart2 += 3;
                }
                _context.EquipmentProp.AddRange(equipmentProps);
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                _log.LogError(ex.Message);
            }
        }
唐召明 authored
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469

        /// <summary>
        /// 同步设备数据至IOT云平台
        /// </summary>
        private void SyncEquipmentDataToIotCloud()
        {
            var connectionString = "";
            var iotCloundContext = new FreeSqlBuilder().UseConnectionString(DataType.SqlServer, connectionString)
                .UseAutoSyncStructure(false).Build();

            var localEquipmentData = _context.Equipment.Where(x => x.Id > 20).IncludeMany(x => x.EquipmentProps).ToList();
            var localEquipmentTypes = _context.EquipmentType.Where(x => true).ToList();

            var iotEquipmentTypes = iotCloundContext.Queryable<EquipmentType>().AsTable((t, x) => "daq_equipment_Type").ToList();
            foreach (var item in localEquipmentData)
            {
                var equipmentTypeCode = localEquipmentTypes.Where(x => x.Id == item.EquipmentTypeId).First().Code;

                var iotEquipmentType = iotEquipmentTypes.Find(x => x.Code == equipmentTypeCode);
                var equipment = new Equipment
                {
                    Code = item.Code,
                    Name = item.Name,
                    EquipmentTypeId = iotEquipmentType.Id,
                    IP = item.IP,
                    DestinationArea = item.DestinationArea,
                    Description = item.Description,
                    Created = DateTime.Now,
                    ConnectName = item.ConnectName
                };

                iotCloundContext.Insert(equipment).AsTable($"daq_{nameof(Equipment)}").ExecuteAffrows();
                var equipmentId = iotCloundContext.Queryable<Equipment>().AsTable((t, x) => "daq_equipment").Where(x => x.Code == equipment.Code && x.DestinationArea == equipment.DestinationArea).First(x => x.Id);

                var iotEquipmentTypePropTemplates = iotCloundContext.Queryable<EquipmentTypePropTemplate>().Where(x => x.EquipmentTypeId == iotEquipmentType.Id).AsTable((t, x) => "daq_equipment_type_prop_template").ToList();
                var props = item.EquipmentProps.Select(x => new EquipmentProp
                {
                    EquipmentId = equipmentId,
                    EquipmentTypePropTemplateId = iotEquipmentTypePropTemplates.Find(t => t.Code == x.EquipmentTypePropTemplateCode).Id,
                    EquipmentTypePropTemplateCode = x.EquipmentTypePropTemplateCode,
                    Address = x.Address,
                    Remark = x.Remark,
                    Created = DateTime.Now,
                    ServerHandle = 0
                }).ToList();

                iotCloundContext.Insert(props).AsTable($"daq_equipment_prop").ExecuteAffrows();
            }
        }
唐召明 authored
470
471
    }
}