Blame view

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

        [ObservableProperty]
        private bool btnStopEnabled = false;

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

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

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

        /// <summary>
        /// 数据压缩
        /// </summary>
        /// <remarks>True时,对于持续不变的数据,记录开始和结束时间再上传</remarks>
        [ObservableProperty]
        private bool dataCompression;
唐召明 authored
56
57
58
59

        /// <summary>
        /// 每次提交的数据量
        /// </summary>
60
        private int _commitCount = 100;
61
62
        private readonly SystemLog _log = SystemLog.GetInstance();
        private readonly CenterService _centerService;
唐召明 authored
63
        private readonly HttpService _httpService;
唐召明 authored
64
        private readonly IFreeSql _freeSql;
65
唐召明 authored
66
        public MainVM(IFreeSql freeSql, CenterService centerService, HttpService httpService)
唐召明 authored
67
68
        {
            _centerService = centerService;
唐召明 authored
69
            _httpService = httpService;
唐召明 authored
70
            _freeSql = freeSql;
唐召明 authored
71
72
73
74
75
            Initial();
        }

        private void Initial()
        {
唐召明 authored
76
            //GenerateData();
唐召明 authored
77
            var commitCountConfig = ConfigurationManager.AppSettings["CommitCount"];
78
            _ = bool.TryParse(ConfigurationManager.AppSettings["AutoExecute"], out var autoExecute);
79
            _ = bool.TryParse(ConfigurationManager.AppSettings["DataCompression"], out var _dataCompression);
唐召明 authored
80
            _ = int.TryParse(commitCountConfig, out _commitCount);
81
            DataCompression = _dataCompression;
唐召明 authored
82
83
            if (_commitCount <= 0)
            {
唐召明 authored
84
85
                //未配置,则默认100
                _commitCount = 100;
唐召明 authored
86
87
            }
            RefreshLog();
唐召明 authored
88
            UploadEquipmentDataToCloud();
89
            UpdateClientStatus();
90
            //UpdateEquipmentStatus();
91
92
93
94
            if (autoExecute)
            {
                Start();
            }
95
        }
96
唐召明 authored
97
98
99
100
101
102
103
        /// <summary>
        /// 上传数据至IOTClound
        /// </summary>
        private void UploadEquipmentDataToCloud()
        {
            Task.Run(async () =>
            {
104
                //缓存时间,分钟
105
                const int cacheMinutesTime = 3;
106
                var _lastAExecution = DateTime.MinValue;
唐召明 authored
107
108
109
110
111
                while (true)
                {
                    try
                    {
                        await Task.Delay(1000);
112
                        var haveRecord = _freeSql.Queryable<EquipmentDataQueue>().Any();
唐召明 authored
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
                        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);
                                }
                            }

                            //自动上传启用,且数据库无未上传的数据,则直接推送
128
                            if (AutoCommit && !DataCompression && !haveRecord)
唐召明 authored
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
                            {
                                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();
                            }
唐召明 authored
150
                            //自动上传关闭或数据库存在未上传的记录,则需要存入数据库
唐召明 authored
151
152
153
154
155
156
157
158
                            else
                            {
                                commitFailureRecords.AddRange(temps);
                            }

                            //将上传失败的数据存入数据库
                            if (commitFailureRecords.Count > 0)
                            {
159
                                //节流模式
160
161
                                if (DataCompression)
                                {
唐召明 authored
162
163
                                    var dictionaryUpdateTemps = new Dictionary<string, EquipmentDataQueue>();
                                    var dictionaryAddTemps = new Dictionary<string, List<EquipmentDataQueue>>();
164
                                    foreach (var item in commitFailureRecords.GroupBy(x => x.EquipmentCode))
165
                                    {
166
167
                                        var lastRecord = _freeSql.Queryable<EquipmentDataQueue>().Where(x => x.EquipmentCode == item.Key).OrderByDescending(x => x.SourceTimestamp).First();
                                        var addTemps = new List<EquipmentDataQueue>();
唐召明 authored
168
                                        dictionaryAddTemps[item.Key] = addTemps;//传递集合引用
169
                                        foreach (var record in item.OrderBy(x => x.SourceTimestamp).ToList())
170
                                        {
171
172
                                            var lastTemp = lastRecord;
                                            if (addTemps.Count > 0)
173
                                            {
174
                                                lastTemp = addTemps.OrderByDescending(x => x.SourceTimestamp).First();
175
                                            }
176
177
178
179
180
181
182
183
184
185

                                            if (lastTemp != null)
                                            {
                                                var currentRecordTime = DateTimeOffset.FromUnixTimeMilliseconds(record.SourceTimestamp).LocalDateTime;
                                                var lastRecordTime = (lastTemp.Updated ?? lastTemp.Created).Value;
                                                if (lastTemp.Reported == record.Reported && currentRecordTime.Date == lastRecordTime.Date
                                                && (currentRecordTime - lastRecordTime).TotalSeconds <= 5)
                                                {
                                                    lastTemp.Updated = currentRecordTime;
唐召明 authored
186
                                                    //是数据库里面的数据,有变化需要更新
187
188
                                                    if (lastTemp.Id != Guid.Empty && lastTemp.Id == lastRecord.Id)
                                                    {
唐召明 authored
189
                                                        dictionaryUpdateTemps[item.Key] = lastTemp;
190
191
192
193
194
195
196
                                                    }
                                                    continue;
                                                }
                                            }
                                            //其他情况,新增记录
                                            addTemps.Add(record);
                                        }
唐召明 authored
197
                                    }
198
唐召明 authored
199
200
201
202
203
204
                                    var allUpdateTemps = dictionaryUpdateTemps.Select(x => x.Value).ToList();
                                    if (allUpdateTemps.Count > 0)
                                    {
                                        _freeSql.Update<EquipmentDataQueue>().SetSource(allUpdateTemps).UpdateColumns(x => x.Updated).ExecuteAffrows();
                                        _log.LogInfo($"更新[{allUpdateTemps.Count}]条设备记录");
                                    }
205
唐召明 authored
206
207
208
209
210
                                    var allAddTemps = dictionaryAddTemps.SelectMany(x => x.Value).ToList();
                                    if (allAddTemps.Count > 0)
                                    {
                                        _freeSql.Insert(allAddTemps).ExecuteAffrows();
                                        _log.LogInfo($"新增{allAddTemps.Count}条设备记录");
211
212
213
214
215
216
217
218
                                    }
                                }
                                //实时存储
                                else
                                {
                                    _freeSql.Insert(commitFailureRecords).ExecuteAffrows();
                                    _log.LogInfo($"新增{commitFailureRecords.Count}条数据记录");
                                }
219
220
                                //更新状态
                                haveRecord = _freeSql.Queryable<EquipmentDataQueue>().Any();
221
                            }
唐召明 authored
222
223
                        }
224
225
226
227
228
229
230
231
232
233
234
                        var timeSpan = TimeSpan.FromSeconds(5);//默认5秒一次
                        var equipmentTotal = _freeSql.Queryable<EquipmentExtend>().Where(x => !x.Disable).Count();
                        var recordsTotal = _freeSql.Queryable<EquipmentDataQueue>().Count();
                        if (recordsTotal >= equipmentTotal * _commitCount)
                        {
                            //数据较多时,1秒一次
                            timeSpan = TimeSpan.FromSeconds(1);
                        }

                        //推送数据
                        if (AutoCommit && (DateTime.Now - _lastAExecution) >= timeSpan && haveRecord)
唐召明 authored
235
                        {
236
                            _lastAExecution = DateTime.Now;
唐召明 authored
237
                            var equipmentCodes = _freeSql.Queryable<EquipmentDataQueue>().Distinct().ToList(x => x.EquipmentCode);
唐召明 authored
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
                            var commitSuccessRecordIds = new List<Guid>();

                            //是否存在更新时间为空的记录,最后一条记录不算
                            var haveUpdateIsNull = equipmentCodes.Where(equipmentCode =>
                            {
                                //第一条更新时间为空的记录
                                var firstTemp = _freeSql.Queryable<EquipmentDataQueue>().Where(x => x.EquipmentCode == equipmentCode && x.Updated == null).OrderBy(x => x.SourceTimestamp).First(x => x.Id);
                                if (firstTemp == default)
                                {
                                    //无记录
                                    return false;
                                }
                                //最后一条记录
                                var lastTemp = _freeSql.Queryable<EquipmentDataQueue>().Where(x => x.EquipmentCode == equipmentCode).OrderByDescending(x => x.SourceTimestamp).First(x => x.Id);
                                //第一条与最后一条是同一条,则排除
                                if (firstTemp == lastTemp)
                                {
                                    return false;
                                }
                                //存在多条
                                return true;
                            }).Any();

                            //节流模式
                            if (DataCompression && !haveUpdateIsNull)
                            {
                                //超过设定时间的数据
                                var records = _freeSql.Queryable<EquipmentDataQueue>().Where(x => DateTime.Now.AddMinutes(-(cacheMinutesTime + 1)) >= x.Created).OrderBy(x => x.SourceTimestamp).Take(_commitCount).OrderBy(x => x.Created).ToList();
                                if (records.Count == 0)
                                {
                                    continue;
                                }
                                var stopwatch = Stopwatch.StartNew();
                                var result = _httpService.SendEquipmentDataV2(records);
                                var currentEquipmentCodes = records.Select(x => x.EquipmentCode).Distinct().ToList();
                                if (!result.Success)
                                {
                                    _log.LogError($"推送设备[{string.Join(',', currentEquipmentCodes)}]数据失败,{result.Msg},耗时:{stopwatch.ElapsedMilliseconds}ms");
                                    continue;
                                }
                                _log.LogSuccess($"成功推送{records.Count}条设备[{string.Join(',', currentEquipmentCodes)}]数据,耗时:{stopwatch.ElapsedMilliseconds}ms");
                                commitSuccessRecordIds = records.Select(x => x.Id).ToList();
                                _freeSql.Delete<EquipmentDataQueue>().Where(x => commitSuccessRecordIds.Contains(x.Id)).ExecuteAffrows();
                                continue;
                            }
唐召明 authored
284
285
286
287
288
289
290
                            //推送成功的数据集合
                            var tasks = new List<Task<List<EquipmentDataQueue>>>();
                            foreach (var equipmentCode in equipmentCodes)
                            {
                                tasks.Add(Task.Run(() =>
                                {
                                    Stopwatch stopwatch = Stopwatch.StartNew();
291
292
293
                                    var successRecords = new List<EquipmentDataQueue>();
                                    var records = _freeSql.Queryable<EquipmentDataQueue>().Where(x => x.EquipmentCode == equipmentCode && !x.IsCommit).OrderBy(x => x.SourceTimestamp).Take(_commitCount).ToList();
                                    if (records.Count == 0)
唐召明 authored
294
                                    {
295
                                        return successRecords;
唐召明 authored
296
                                    }
297
298
299
                                    var temp1s = new List<List<EquipmentDataQueue>>();
                                    var temp2s = new List<EquipmentDataQueue>();
                                    foreach (var record in records)
唐召明 authored
300
                                    {
301
302
                                        //是最后一条记录,且启用了节流模式
                                        if (DataCompression && record == records.Last())
303
                                        {
304
305
306
307
308
309
                                            //创建时间距离现在的时间未超过设定时间,则不推送
                                            if ((DateTime.Now - record.Created.Value).TotalMinutes < cacheMinutesTime)
                                            {
                                                break;
                                            }
唐召明 authored
310
311
312
                                            //队列还有缓存的数据,且持续时间未达到设定值,则不推送
                                            if (!_centerService.EquipmentDataQueues.IsEmpty && record.Updated != null
                                            && (record.Updated - record.Created).Value.TotalMinutes < cacheMinutesTime)
313
314
315
                                            {
                                                break;
                                            }
316
317
318
319
320
321
322
323
324
325
                                        }

                                        if (temp2s.Count == 0)
                                        {
                                            temp2s.Add(record);
                                            continue;
                                        }

                                        var lastItem = temp2s.Last();
                                        var lastType = lastItem.Updated > lastItem.Created;
326
                                        var currentType = record.Updated > record.Created;
327
328
329
330
331
332
333
334
335
                                        if (lastType == currentType)
                                        {
                                            temp2s.Add(record);
                                        }
                                        else
                                        {
                                            temp1s.Add(temp2s);
                                            temp2s = new List<EquipmentDataQueue>
                                            {
唐召明 authored
336
                                                    record
337
338
339
340
341
342
343
                                            };
                                        }
                                    }
                                    if (temp2s.Count > 0)
                                    {
                                        temp1s.Add(temp2s);
                                        temp2s = new List<EquipmentDataQueue>();
唐召明 authored
344
                                    }
345
346
347
348
349
350
351
352
353
354
355
356
357
358

                                    foreach (var item in temp1s)
                                    {
                                        //某段时间的数据
                                        if (item.All(x => x.Updated > x.Created))
                                        {
                                            var result = _httpService.SendEquipmentDataV2(item);
                                            if (!result.Success)
                                            {
                                                _log.LogError($"推送设备[{equipmentCode}]数据失败,{result.Msg},耗时:{stopwatch.ElapsedMilliseconds}ms");
                                                break;//推送失败,后续的数据也暂停推送
                                            }
                                            _log.LogSuccess($"成功推送{records.Count}条设备[{equipmentCode}]数据,耗时:{stopwatch.ElapsedMilliseconds}ms");
                                            successRecords.AddRange(item);
唐召明 authored
359
                                            continue;
360
                                        }
唐召明 authored
361
362
                                        //一秒一条记录的数据
唐召明 authored
363
364
                                        var result2 = _httpService.SendEquipmentData(item);
                                        if (!result2.Success)
365
                                        {
唐召明 authored
366
367
                                            _log.LogError($"推送设备[{equipmentCode}]数据失败,{result2.Msg},耗时:{stopwatch.ElapsedMilliseconds}ms");
                                            break;//推送失败,后续的数据也暂停推送
368
                                        }
唐召明 authored
369
370
                                        _log.LogSuccess($"成功推送{records.Count}条设备[{equipmentCode}]数据,耗时:{stopwatch.ElapsedMilliseconds}ms");
                                        successRecords.AddRange(item);
371
372
                                    }
                                    return successRecords;
唐召明 authored
373
374
375
                                }));
                            }
                            Task.WaitAll(tasks.ToArray());
唐召明 authored
376
377
378
                            commitSuccessRecordIds = tasks.SelectMany(x => x.Result).Select(x => x.Id).ToList();
                            _freeSql.Delete<EquipmentDataQueue>().Where(x => commitSuccessRecordIds.Contains(x.Id)).ExecuteAffrows();
唐召明 authored
379
380
381
382
383
384
385
386
387
388
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.LogException($"数据上传线程异常:{ex.Message}");
                    }
                }
            });
        }
389
        private void UpdateClientStatus()
390
391
392
393
394
        {
            Task.Run(async () =>
            {
                while (true)
                {
395
                    await Task.Delay(TimeSpan.FromSeconds(1));
396
397
398
399
400
                    if (BtnStartEnabled)
                    {
                        continue;
                    }
                    _ = Guid.TryParse(ConfigurationManager.AppSettings["ClientId"], out var clientId);
401
402
403
404
405
406
                    if (clientId == default)
                    {
                        _log.LogError($"更新客户端状态失败:当前程序[ClientId]未配置!");
                        continue;
                    }
407
408
409
410
411
                    var result = _httpService.UpdateClientStatus(clientId);
                    if (!result.Success)
                    {
                        _log.LogError($"更新客户端状态失败:{result.Msg}");
                    }
唐召明 authored
412
413
414
415
416
                    else
                    {
                        //更新成功,则等待
                        await Task.Delay(TimeSpan.FromMinutes(1));
                    }
417
418
                }
            });
唐召明 authored
419
420
421
422
423
        }

        [RelayCommand]
        public void Start()
        {
424
425
426
427
428
429
430
431
432
433
434
            _ = bool.TryParse(ConfigurationManager.AppSettings["PrivacyInfoStatus"], out var privacyInfoStatus);
            if (!privacyInfoStatus)
            {
                var vm = new PrivacyInfoView();
                var result = vm.ShowDialog();
                if (result != true)
                {
                    return;
                }
            }
唐召明 authored
435
436
437
438
439
440
441
442
443
444
445
446
447
            BtnStartEnabled = false;
            BtnStopEnabled = true;
            _centerService.Start();
        }

        [RelayCommand]
        public void Stop()
        {
            BtnStartEnabled = true;
            BtnStopEnabled = false;
            _centerService.Stop();
        }
唐召明 authored
448
        private void RefreshLog()
唐召明 authored
449
450
451
452
453
454
455
456
457
        {
            Task.Run(() =>
            {
                Application.Current.Dispatcher.Invoke(async () =>
                {
                    do
                    {
                        while (!_log.IsEmpty)
                        {
458
                            QueueCount = _centerService.EquipmentDataQueues.Count;
唐召明 authored
459
                            var log = _log.GetLog();
唐召明 authored
460
                            if (log == null)
唐召明 authored
461
                            {
唐召明 authored
462
463
464
465
466
467
468
469
470
471
472
473
474
                                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
475
                                {
唐召明 authored
476
477
478
479
480
481
482
483
                                    LogType = log.LogType,
                                    Messages = log.Messages,
                                    CreateTime = log.CreateTime
                                });
                            }
                            if (LogModels.Count > 50)
                            {
                                LogModels.Remove(LogModels.Last());
唐召明 authored
484
485
486
487
488
489
490
                            }
                        }
                        await Task.Delay(100);
                    } while (true);
                });
            });
        }
唐召明 authored
491
492

        /// <summary>
唐召明 authored
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
        /// 生成数据
        /// </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
558
559
560
561
        private void GenerateStationMonitorEquipment(IEnumerable<string> stationCode, string ip, string destinationArea)
        {
            try
            {
唐召明 authored
562
563
                var equipmentType = _freeSql.Queryable<EquipmentTypeExtend>().Where(x => x.Code == EquipmentTypeConst.StationMonitor.ToString()).First();
                var equipmentPropTemps = _freeSql.Queryable<EquipmentTypePropTemplateExtend>().Where(x => x.EquipmentTypeId == equipmentType.Id).ToList();
唐召明 authored
564
565
566
567
568
569
570

                var equipmentTemps = new List<Equipment>();
                foreach (var station in stationCode)
                {
                    var equipment = new Equipment
                    {
                        Code = station,
唐召明 authored
571
                        Name = $"{station}站台监控",
唐召明 authored
572
573
574
575
576
577
578
579
580
                        EquipmentTypeId = equipmentType.Id,
                        IP = ip,
                        Created = DateTime.Now,
                        DestinationArea = destinationArea,
                        Description = station,
                        ConnectName = station
                    };
                    equipmentTemps.Add(equipment);
                }
唐召明 authored
581
                _freeSql.Insert(equipmentTemps).ExecuteAffrows();
唐召明 authored
582
583
584

                var dbStart1 = 0;
                var dbStart2 = 0;
唐召明 authored
585
                var equipmentProps = new List<EquipmentPropExtend>();
唐召明 authored
586
587
                foreach (var equipment in equipmentTemps)
                {
唐召明 authored
588
                    var equipmentId = _freeSql.Queryable<EquipmentExtend>().Where(x => x.ConnectName == equipment.ConnectName && x.IP == x.IP && x.DestinationArea == destinationArea).First(x => x.Id);
唐召明 authored
589
590
591
592
593
594
595
596
597
598
599
600
601

                    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
602
603
                            StationMonitorProp.StationReverse => $"DB3200.{(dbStart2 + 1) / 8}.{(dbStart2 + 1) % 8}",
                            StationMonitorProp.StationHighSpeed => $"DB3200.{(dbStart2 + 2) / 8}.{(dbStart2 + 2) % 8}",
唐召明 authored
604
605
                            _ => string.Empty,
                        };
唐召明 authored
606
                        var prop = new EquipmentPropExtend
唐召明 authored
607
608
609
610
611
612
613
614
615
616
617
618
619
                        {
                            EquipmentId = equipmentId,
                            EquipmentTypePropTemplateId = item.Id,
                            EquipmentTypePropTemplateCode = item.Code,
                            Address = address,
                            Remark = item.Name,
                            Created = DateTime.Now,
                        };
                        equipmentProps.Add(prop);
                    }
                    dbStart1 += 30;
                    dbStart2 += 3;
                }
唐召明 authored
620
                _freeSql.Insert(equipmentProps).ExecuteAffrows();
唐召明 authored
621
622
623
624
625
626
            }
            catch (Exception ex)
            {
                _log.LogError(ex.Message);
            }
        }
唐召明 authored
627
628

        /// <summary>
629
        /// 将本地设备数据同步至IOT云平台
唐召明 authored
630
631
632
        /// </summary>
        private void SyncEquipmentDataToIotCloud()
        {
633
            var connectionString = "";//云平台数据库连接字符串
唐召明 authored
634
            var iotCloundFreeSql = new FreeSqlBuilder().UseConnectionString(DataType.SqlServer, connectionString)
唐召明 authored
635
                .UseAutoSyncStructure(false).Build();
唐召明 authored
636
            var localEquipmentTypes = _freeSql.Queryable<EquipmentTypeExtend>().Where(x => x.Code == "SingleForkSRM").ToList();
637
            foreach (var localEquipmentType in localEquipmentTypes)
唐召明 authored
638
            {
639
640
641
642
643
644
645
646
                const string equipmentTypeTableName = "daq_equipment_type";
                const string equipmentTypePropTemplateTableName = "daq_equipment_type_prop_template";
                const string equipmentTableName = "daq_equipment";
                const string equipmentPropTableName = "daq_equipment_prop";

                //设备类型
                var cloudEquipmentType = iotCloundFreeSql.Queryable<EquipmentTypeExtend>().AsTable((x, y) => equipmentTypeTableName).Where(x => x.Code == localEquipmentType.Code).First();
                if (cloudEquipmentType == null)
唐召明 authored
647
                {
648
649
650
651
652
653
654
655
                    cloudEquipmentType = new EquipmentTypeExtend
                    {
                        Code = localEquipmentType.Code,
                        Name = localEquipmentType.Name,
                        Description = localEquipmentType.Description,
                        Created = DateTime.Now,
                    };
                    cloudEquipmentType.Id = (int)iotCloundFreeSql.Insert(cloudEquipmentType).AsTable(equipmentTypeTableName).ExecuteIdentity();
唐召明 authored
656
                }
657
658
659
660
661

                //设备类型模板
                var cloudEquipmentTypePropTemps = iotCloundFreeSql.Queryable<EquipmentTypePropTemplateExtend>().AsTable((x, y) => equipmentTypePropTemplateTableName).Where(x => x.EquipmentTypeId == cloudEquipmentType.Id).ToList();

                if (cloudEquipmentTypePropTemps.Count == 0)
唐召明 authored
662
                {
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
                    var temps = _freeSql.Queryable<EquipmentTypePropTemplateExtend>().Where(x => x.EquipmentTypeId == localEquipmentType.Id).ToList(x => new EquipmentTypePropTemplateExtend
                    {
                        Code = x.Code,
                        Name = x.Name,
                        Address = x.Address,
                        MonitorCompareValue = x.MonitorCompareValue,
                        MonitorFailure = x.MonitorFailure,
                        MonitorNormal = x.MonitorNormal,
                        DataType = x.DataType,
                        PropType = x.PropType,
                        Description = x.Description,
                        EquipmentTypeId = cloudEquipmentType.Id,
                        Created = DateTime.Now
                    });
                    if (temps.Count == 0)
                    {
                        continue;
                    }
                    cloudEquipmentTypePropTemps = iotCloundFreeSql.Insert(temps).AsTable(equipmentTypePropTemplateTableName).ExecuteInserted();
唐召明 authored
682
683
                }
684
685
686
687
688
689
690
                var localEquipments = _freeSql.Queryable<EquipmentExtend>().Where(x => x.EquipmentTypeId == localEquipmentType.Id).IncludeMany(x => x.EquipmentProps).ToList();
                foreach (var localEquipment in localEquipments)
                {
                    //设备
                    var cloudEquipment = iotCloundFreeSql.Queryable<EquipmentExtend>().AsTable((x, y) => equipmentTableName).Where(x => x.Code == localEquipment.Code).First();
                    if (cloudEquipment == null)
                    {
唐召明 authored
691
                        //新增设备后需要在数据库手动维护项目编号和仓库编号数据
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
                        cloudEquipment = new EquipmentExtend
                        {
                            Code = localEquipment.Code,
                            Name = localEquipment.Name,
                            ConnectName = localEquipment.ConnectName,
                            IP = localEquipment.IP,
                            Description = localEquipment.Description,
                            DestinationArea = localEquipment.DestinationArea,
                            Disable = localEquipment.Disable,
                            EquipmentTypeId = cloudEquipmentType.Id,
                            Created = DateTime.Now,
                        };
                        cloudEquipment.Id = (int)iotCloundFreeSql.Insert(cloudEquipment).AsTable(equipmentTableName).ExecuteIdentity();
                    }

                    //设备属性
                    var cloudEquipmentProps = iotCloundFreeSql.Queryable<EquipmentPropExtend>().AsTable((x, y) => equipmentPropTableName).Where(x => x.EquipmentId == cloudEquipment.Id).ToList();

                    if (cloudEquipmentProps.Count == 0)
                    {
唐召明 authored
712
                        var temps = _freeSql.Queryable<EquipmentPropExtend>().Where(x => x.EquipmentId == localEquipment.Id).ToList(x => new EquipmentProp
713
714
715
716
717
718
719
720
721
722
723
724
725
726
                        {
                            EquipmentTypePropTemplateCode = x.EquipmentTypePropTemplateCode,
                            Address = x.Address,
                            EquipmentId = cloudEquipment.Id,
                            EquipmentTypePropTemplateId = 0,
                            Value = string.Empty,
                            Remark = x.Remark,
                            Created = DateTime.Now,
                        });

                        if (temps.Count == 0)
                        {
                            continue;
                        }
唐召明 authored
727
728
729
730
731
732
                        temps.ForEach(x =>
                        {
                            x.EquipmentTypePropTemplateId = cloudEquipmentTypePropTemps.Find(t => t.Code == x.EquipmentTypePropTemplateCode).Id;
                        });
唐召明 authored
733
                        iotCloundFreeSql.Insert(temps).AsTable(equipmentPropTableName).ExecuteAffrows();
734
735
736
737
738
739
740
741
742
743
                    }
                }
            }
        }

        private void GenerateEquipment()
        {
            try
            {
                var equipmentCodes = new List<string>
唐召明 authored
744
                {
745
746
747
748
749
750
751
                    "HH-LDHW-20240725-01-RGV1201"
                };
                var allEquipment = _freeSql.Queryable<EquipmentExtend>().Where(x => equipmentCodes.Contains(x.Code)).ToList();
                foreach (var group in allEquipment.GroupBy(x => x.EquipmentTypeId))
                {
                    var equipmentType = _freeSql.Queryable<EquipmentTypeExtend>().Where(x => x.Id == group.Key).First();
                    if (equipmentType == null)
唐召明 authored
752
                    {
753
754
755
756
757
                        continue;
                    }

                    var equipmentTypePropTemplate = _freeSql.Queryable<EquipmentTypePropTemplateExtend>().Where(x => x.EquipmentTypeId == equipmentType.Id).ToList();
                    if (equipmentTypePropTemplate.Count == 0)
唐召明 authored
758
                    {
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
                        continue;
                    }

                    foreach (var equipment in group)
                    {
                        //设备属性
                        if (_freeSql.Queryable<EquipmentPropExtend>().Where(x => x.EquipmentId == equipment.Id).Any())
                        {
                            //有数据则跳过
                            continue;
                        }

                        var temps = equipmentTypePropTemplate.Select(x => new EquipmentPropExtend
                        {
                            EquipmentTypePropTemplateCode = x.Code,
                            EquipmentId = equipment.Id,
                            EquipmentTypePropTemplateId = x.Id,
                            Remark = x.Description,
                            Value = string.Empty,
                            Address = x.Address,
                            Created = DateTime.Now,
                        }).ToList();
                        var total = _freeSql.Insert(temps).ExecuteAffrows();
                        _log.LogError($"设备[{equipment.Code}]成功生成{total}条设备属性数据");
                    }
唐召明 authored
784
                }
唐召明 authored
785
            }
786
787
788
789
790
            catch (Exception ex)
            {
                _log.LogError($"生成设备数据出现异常:{ex.Message}");
            }
唐召明 authored
791
        }
唐召明 authored
792
793
    }
}