AnalysisBase.cs
36.7 KB
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
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
394
395
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
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
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
784
785
786
787
788
789
790
791
792
793
using HHECS.BllModel;
using HHECS.DAQHandle.Dto;
using HHECS.DAQShared.Common.Enums;
using HHECS.DAQShared.Dto;
using HHECS.DAQShared.Models;
using HHECS.EquipmentModel;
using System.Text.Json;
namespace HHECS.DAQHandle.EquipmentHandle
{
internal abstract class AnalysisBase : IAnalysis
{
protected readonly IFreeSql freeSql;
/// <summary>
/// 当前设备类型
/// </summary>
protected readonly EquipmentTypeExtend CurrentEquipmentType;
/// <summary>
/// 程序配置信息
/// </summary>
protected readonly AppConfig AppConfig;
/// <summary>
/// 当前类型设备数据
/// </summary>
protected readonly List<EquipmentExtend> Equipments;
/// <summary>
/// 设备总报警属性编码
/// </summary>
protected readonly string EquipmentTotalAlarmCode;
protected AnalysisBase(AnalysisParameter parameter)
{
Equipments = parameter.Equipments;
CurrentEquipmentType = parameter.EquipmentType;
AppConfig = parameter.AppConfig;
EquipmentTotalAlarmCode = parameter.EquipmentTotalAlarmCode;
freeSql = GlobalVar.FreeSql;
}
public virtual BllResult Execute(IEnumerable<EquipmentDataRecord> records)
{
try
{
foreach (var item in records.GroupBy(x => x.EquipmentCode))
{
var equipmentSN = item.Key;
var orderItems = item.OrderBy(x => x.Timestamp).ToList();
var lastRecord = orderItems.Last();
var equipment = Equipments.Where(x => x.Code == equipmentSN).FirstOrDefault();
if (equipment != null)
{
var result1 = UpdateTagValue(equipment, lastRecord);
var result2 = UpdateEquipmentAlarm(equipment, orderItems);
var result3 = UpdateEquipmentStatus(equipment, orderItems);
}
}
return BllResultFactory.Success();
}
catch (Exception ex)
{
return BllResultFactory.Error($"数据解析出现异常:{ex.Message}");
}
}
/// <summary>
/// 更新设备属性值
/// </summary>
/// <param name="equipment">设备</param>
/// <param name="record">最后一条记录</param>
/// <returns><see cref="BllResult"/></returns>
protected virtual BllResult UpdateTagValue(EquipmentExtend equipment, EquipmentDataRecord record)
{
try
{
var acceptTime = TimestampConvertToLocalDateTime(record.Timestamp);
var equipmetProps = equipment.EquipmentProps.Where(x => x.Updated < acceptTime || x.Updated == null).ToList();
if (equipmetProps.Count == 0)
{
return BllResultFactory.Error($"设备[{equipment.Code}]属性集合为空!");
}
var tagResult = JsonConvertToTagList(record.Tags);
if (!tagResult.Success)
{
return tagResult;
}
var tagData = tagResult.Data;
using var equipmentPropRepository = freeSql.GetRepository<EquipmentPropExtend>();
//待更新数据缓存
var temps = new List<EquipmentPropExtend>();
foreach (var prop in equipmetProps)
{
var tagCodes = new List<string>
{
prop.EquipmentTypePropTemplateCode,
prop.Address
};
var tag = tagData.Where(x => tagCodes.Contains(x.Tag, StringComparer.OrdinalIgnoreCase)).FirstOrDefault();
if (tag == null)
{
continue;
}
equipmentPropRepository.Attach(prop);
prop.Value = tag.Value;
prop.Updated = acceptTime;
temps.Add(prop);
}
equipmentPropRepository.Update(temps);
return BllResultFactory.Success();
}
catch (Exception ex)
{
return BllResultFactory.Error($"更新[{equipment.Code}]设备属性值失败:{ex.Message}");
}
}
/// <summary>
/// 更新设备报警记录
/// </summary>
/// <param name="equipment">设备</param>
/// <param name="records">记录数据</param>
/// <remarks>
/// <para>一台设备一次仅记录一条主报警信息,报警明细附加在明细字段</para>
/// <para>时间跨天的数据需要进行分割,方便后期清理数据</para>
/// </remarks>
/// <returns><see cref="BllResult"/></returns>
protected virtual BllResult UpdateEquipmentAlarm(EquipmentExtend equipment, IEnumerable<EquipmentDataRecord> records)
{
try
{
if (string.IsNullOrWhiteSpace(EquipmentTotalAlarmCode))
{
return BllResultFactory.Error($"设备[{equipment.Code}]总报警编码[{nameof(EquipmentTotalAlarmCode)}]字段不能为空!");
}
var alarmRecordCacheTempsResult = AssemblyAlarmData(equipment, records);
if (!alarmRecordCacheTempsResult.Success)
{
return BllResultFactory.Error(alarmRecordCacheTempsResult.Msg);
}
if (alarmRecordCacheTempsResult.Data.Count == 0)
{
return BllResultFactory.Error($"更新设备[{equipment.Code}]报警失败,组装数据结果为空!");
}
var alarmRecordCacheTemps = alarmRecordCacheTempsResult.Data;
using var equipmentAlarmRecordRepository = freeSql.GetRepository<EquipmentAlarmRecord>();
var oldAlarmRecord = equipmentAlarmRecordRepository.Where(x => x.EquipmentCode == equipment.Code && x.EquipmentPropCode == EquipmentTotalAlarmCode).OrderByDescending(x => x.CreateTime).First();
var lastCacheTemp = alarmRecordCacheTemps.OrderByDescending(x => x.CreateTime).First();
//数据库无报警记录
if (oldAlarmRecord == null)
{
var addTemps = new List<EquipmentAlarmRecord>();
foreach (var item in alarmRecordCacheTemps)
{
//不是最后一条记录的数据需要结束
if (!item.Equals(lastCacheTemp))
{
item.IsEnd = true;
}
addTemps.Add(item);
}
equipmentAlarmRecordRepository.Insert(addTemps);
}
//数据库有报警记录,则需要校验
else
{
var addTemps = new List<EquipmentAlarmRecord>();
foreach (var item in alarmRecordCacheTemps)
{
//对于之前的数据,这里暂时不做处理
if (oldAlarmRecord.UpdateTime >= item.UpdateTime)
{
continue;
}
//日期为同一天,在设定时间以内,且报警明细一致,则更新
if (oldAlarmRecord.UpdateTime.Date == item.CreateTime.Date && oldAlarmRecord.UpdateTime >= item.CreateTime.AddSeconds(-AppConfig.DataTimeOut) && oldAlarmRecord.Remark == item.Remark)
{
equipmentAlarmRecordRepository.Attach(oldAlarmRecord);
//不是最后一条记录,或时间超过设定时间,说明已经成为历史报警,需要结束标记
if (!item.Equals(lastCacheTemp) || item.UpdateTime < DateTime.Now.AddSeconds(-AppConfig.DataTimeOut))
{
oldAlarmRecord.IsEnd = true;
}
else
{
oldAlarmRecord.IsEnd = false;
}
if (oldAlarmRecord.ProjectCode != equipment.ProjectCode)
{
oldAlarmRecord.ProjectCode = equipment.ProjectCode;
}
if (oldAlarmRecord.FactoryCode != equipment.FactoryCode)
{
oldAlarmRecord.FactoryCode = equipment.FactoryCode;
}
oldAlarmRecord.ErrorDuration = (item.UpdateTime - oldAlarmRecord.CreateTime).TotalSeconds;
oldAlarmRecord.UpdateTime = item.UpdateTime;
oldAlarmRecord.HandleTime = DateTime.Now;
equipmentAlarmRecordRepository.Update(oldAlarmRecord);
continue;
}
//其他情况需要新增记录
//不是最后一条记录
if (!item.Equals(lastCacheTemp))
{
item.IsEnd = true;
}
addTemps.Add(item);
}
equipmentAlarmRecordRepository.Insert(addTemps);
}
//结束其他超时报警
var needEndAlaremRecords = equipmentAlarmRecordRepository.Where(x => x.EquipmentCode == equipment.Code
&& x.EquipmentPropCode == EquipmentTotalAlarmCode && !x.IsEnd && x.UpdateTime < DateTime.Now.AddSeconds(-AppConfig.DataTimeOut))
.ToList(x => new EquipmentAlarmRecord
{
Id = x.Id,
});
foreach (var item in needEndAlaremRecords)
{
equipmentAlarmRecordRepository.Attach(item);
item.IsEnd = true;
}
equipmentAlarmRecordRepository.Update(needEndAlaremRecords);
return BllResultFactory.Success();
}
catch (Exception ex)
{
return BllResultFactory.Error(ex.Message);
}
}
/// <summary>
/// 更新设备状态记录
/// </summary>
/// <param name="equipment">设备</param>
/// <param name="records">记录集合</param>
/// <remarks>
/// <para>实时记录表仅记录实时状态,历史表记录实时状态和历史状态</para>
/// <para>时间跨天的数据需要进行分割,方便后期清理数据</para>
/// </remarks>
/// <returns><see cref="BllResult"/></returns>
protected virtual BllResult UpdateEquipmentStatus(EquipmentExtend equipment, IEnumerable<EquipmentDataRecord> records)
{
try
{
var statusRecordCacheTempsResult = AssemblyStatusData(equipment, records);
if (!statusRecordCacheTempsResult.Success)
{
return BllResultFactory.Error(statusRecordCacheTempsResult.Msg);
}
if (statusRecordCacheTempsResult.Data.Count == 0)
{
return BllResultFactory.Error($"更新[{equipment.Code}]设备状态失败,数据组装集合为空!");
}
var statusRecordCacheTemps = statusRecordCacheTempsResult.Data;
using var equipmentStatusRecordRepository = freeSql.GetRepository<EquipmentStatusRecord>();
using var equipmentStatusRecordHistoryRepository = freeSql.GetRepository<EquipmentStatusRecordHistory>();
//实时状态表中的实时状态记录
var equipmentStatusRecord = equipmentStatusRecordRepository.Where(x => x.EquipmentCode == equipment.Code).OrderByDescending(x => x.CreateTime).First();
//历史状态表中的实时状态记录
var equipmentStatusRecordHistory = equipmentStatusRecordHistoryRepository.Where(x => x.EquipmentCode == equipment.Code).OrderByDescending(x => x.CreateTime).First();
//组装数据中的最后一条
var lastCacheStatusRecord = statusRecordCacheTemps.OrderByDescending(x => x.CreateTime).First();
#region 更新实时状态表数据
//实时记录表数据为空,则新增
if (equipmentStatusRecord == null)
{
var temp = new EquipmentStatusRecord
{
EquipmentCode = equipment.Code,
EquipmentName = equipment.Name,
EquipmentTypeCode = equipment.EquipmentType.Code,
Status = lastCacheStatusRecord.Status,
IsEnd = false,
ProjectCode = equipment.ProjectCode,
FactoryCode = equipment.FactoryCode,
CreateTime = lastCacheStatusRecord.CreateTime,
UpdateTime = lastCacheStatusRecord.UpdateTime,
HandleTime = DateTime.Now,
StatusDuration = lastCacheStatusRecord.StatusDuration,
};
equipmentStatusRecordRepository.Insert(temp);
}
//记录不为空,则更新
else
{
//新数据在记录数据时间之后
if (lastCacheStatusRecord.CreateTime >= equipmentStatusRecord.UpdateTime)
{
//状态一致,日期为同一天,且在超时时间范围内,且组装数据只有一条记录,更新结束时间
if (equipmentStatusRecord.Status == lastCacheStatusRecord.Status
&& lastCacheStatusRecord.CreateTime.Date == equipmentStatusRecord.UpdateTime.Date
&& (lastCacheStatusRecord.CreateTime - equipmentStatusRecord.UpdateTime).TotalSeconds <= AppConfig.DataTimeOut
&& statusRecordCacheTemps.Count == 1)
{
equipmentStatusRecordRepository.Attach(equipmentStatusRecord);
if (equipmentStatusRecord.ProjectCode != equipment.ProjectCode)
{
equipmentStatusRecord.ProjectCode = equipment.ProjectCode;
}
if (equipmentStatusRecord.FactoryCode != equipment.FactoryCode)
{
equipmentStatusRecord.FactoryCode = equipment.FactoryCode;
}
equipmentStatusRecord.HandleTime = DateTime.Now;
equipmentStatusRecord.UpdateTime = lastCacheStatusRecord.UpdateTime;
equipmentStatusRecord.StatusDuration = (lastCacheStatusRecord.UpdateTime - equipmentStatusRecord.CreateTime).TotalSeconds;
equipmentStatusRecordRepository.Update(equipmentStatusRecord);
}
//其他情况,更新历史起始和结束时间
else
{
equipmentStatusRecordRepository.Attach(equipmentStatusRecord);
if (equipmentStatusRecord.ProjectCode != equipment.ProjectCode)
{
equipmentStatusRecord.ProjectCode = equipment.ProjectCode;
}
if (equipmentStatusRecord.FactoryCode != equipment.FactoryCode)
{
equipmentStatusRecord.FactoryCode = equipment.FactoryCode;
}
equipmentStatusRecord.HandleTime = DateTime.Now;
equipmentStatusRecord.Status = lastCacheStatusRecord.Status;
equipmentStatusRecord.CreateTime = lastCacheStatusRecord.CreateTime;
equipmentStatusRecord.UpdateTime = lastCacheStatusRecord.UpdateTime;
equipmentStatusRecord.StatusDuration = lastCacheStatusRecord.StatusDuration;
equipmentStatusRecordRepository.Update(equipmentStatusRecord);
}
}
else
{
//对于之前的数据,这里暂不处理
}
//异常情况:倘若当前设备在实时状态表存在多条数据,应将其他数据删除
var temps = equipmentStatusRecordRepository.Where(x => x.EquipmentCode == equipmentStatusRecord.EquipmentCode && x.Id != equipmentStatusRecord.Id)
.ToList();
if (temps.Count > 0)
{
equipmentStatusRecordRepository.Delete(temps);
}
}
#endregion
#region 更新历史状态表
//历史表无记录
if (equipmentStatusRecordHistory == null)
{
foreach (var item in statusRecordCacheTemps)
{
if (!item.Equals(lastCacheStatusRecord))
{
//不是最后一条记录的数据加上结束标记
item.IsEnd = true;
}
}
equipmentStatusRecordHistoryRepository.Insert(statusRecordCacheTemps);
}
//历史记录表有数据
else
{
var firstCacheStatusRecord = statusRecordCacheTemps.OrderBy(x => x.CreateTime).First();
//新记录在现有记录时间之后
if (firstCacheStatusRecord.CreateTime >= equipmentStatusRecordHistory.UpdateTime)
{
//需新增的数据
var addTemps = new List<EquipmentStatusRecordHistory>();
foreach (var item in statusRecordCacheTemps.OrderBy(x => x.CreateTime))
{
//是第一条记录,与历史记录表的数据进行比较
if (item.Equals(firstCacheStatusRecord))
{
//组装的数据是否只有一条数据
var isOne = statusRecordCacheTemps.Count == 1;
//状态一致,日期为同一天,且在设定超时时间范围内,则更新记录
if (equipmentStatusRecordHistory.Status == item.Status
&& item.CreateTime.Date == equipmentStatusRecordHistory.UpdateTime.Date
&& (item.CreateTime - equipmentStatusRecordHistory.UpdateTime).TotalSeconds <= AppConfig.DataTimeOut)
{
equipmentStatusRecordHistoryRepository.Attach(equipmentStatusRecordHistory);
if (equipmentStatusRecordHistory.ProjectCode != equipment.ProjectCode)
{
equipmentStatusRecordHistory.ProjectCode = equipment.ProjectCode;
}
if (equipmentStatusRecordHistory.FactoryCode != equipment.FactoryCode)
{
equipmentStatusRecordHistory.FactoryCode = equipment.FactoryCode;
}
equipmentStatusRecordHistory.IsEnd = !isOne;
equipmentStatusRecordHistory.HandleTime = DateTime.Now;
equipmentStatusRecordHistory.UpdateTime = item.UpdateTime;
equipmentStatusRecordHistory.StatusDuration = (item.UpdateTime - equipmentStatusRecordHistory.CreateTime).TotalSeconds;
equipmentStatusRecordHistoryRepository.Update(equipmentStatusRecordHistory);
}
//超过设定时间,需要结束历史记录
else
{
equipmentStatusRecordHistoryRepository.Attach(equipmentStatusRecordHistory);
if (equipmentStatusRecord.ProjectCode != equipment.ProjectCode)
{
equipmentStatusRecord.ProjectCode = equipment.ProjectCode;
}
if (equipmentStatusRecord.FactoryCode != equipment.FactoryCode)
{
equipmentStatusRecord.FactoryCode = equipment.FactoryCode;
}
equipmentStatusRecordHistory.IsEnd = true;
equipmentStatusRecordHistory.HandleTime = DateTime.Now;
equipmentStatusRecordHistoryRepository.Update(equipmentStatusRecordHistory);
item.IsEnd = !isOne;
addTemps.Add(item);
}
continue;
}
//不是最后一条记录,需加上结束标记
if (!item.Equals(lastCacheStatusRecord))
{
item.IsEnd = true;
continue;
}
addTemps.Add(item);
}
if (addTemps.Count > 0)
{
equipmentStatusRecordHistoryRepository.Insert(addTemps);
}
}
else
{
//对于之前的数据记录,这里暂不处理
}
}
#endregion
return BllResultFactory.Success();
}
catch (Exception ex)
{
return BllResultFactory.Error($"更新[{equipment.Code}]设备状态记录失败:{ex.Message}");
}
}
/// <summary>
/// 组装报警数据
/// </summary>
/// <param name="equipment">设备</param>
/// <param name="records">记录</param>
/// <returns></returns>
protected BllResult<List<EquipmentAlarmRecord>> AssemblyAlarmData(EquipmentExtend equipment, IEnumerable<EquipmentDataRecord> records)
{
try
{
//获取设备总报警编号,仅在设备报总故障时才记录报警
var totalAlarmProp = equipment.EquipmentProps.Where(x => x.EquipmentTypePropTemplateCode == EquipmentTotalAlarmCode).FirstOrDefault();
if (totalAlarmProp == null)
{
return BllResultFactory.Error<List<EquipmentAlarmRecord>>($"设备[{equipment.Code}]总报警编码[{EquipmentTotalAlarmCode}]未配置!");
}
//当前设备监控地址属性模板
var monitorPropTemps = equipment.EquipmentProps.Where(x => x.EquipmentTypePropTemplate.PropType == EquipmentPropType.PLCMonitorAddress &&
!string.IsNullOrEmpty(x.EquipmentTypePropTemplate.MonitorCompareValue)).OrderBy(x => x.Id).ToList();
//数据组装
var temps = new List<EquipmentAlarmRecord>();
foreach (var item in records.OrderBy(x => x.Timestamp))
{
var currentRecordStatusResult = GetEquipmentStatus(equipment, item);
if (!currentRecordStatusResult.Success)
{
continue;
}
if (currentRecordStatusResult.Data != EquipmentStatus.Failure)
{
continue;
}
var time = TimestampConvertToLocalDateTime(item.Timestamp);
var tagResult = JsonConvertToTagList(item.Tags);
//数据不合法,则直接弃用这条记录
if (!tagResult.Success)
{
continue;
}
var tagItems = tagResult.Data;
var (mainAlarm, detailAlarms) = GenerateAlarmMessage(equipment, totalAlarmProp, monitorPropTemps, tagItems);
var cacheTemp = temps.Where(x => x.EquipmentPropCode == totalAlarmProp.EquipmentTypePropTemplateCode)
.OrderByDescending(x => x.CreateTime).FirstOrDefault();
var alarmMessageItems = string.Join(";", detailAlarms);
//间隔在设定时间内、报警文本无变化
if (cacheTemp != null && cacheTemp.Remark == alarmMessageItems &&
cacheTemp.UpdateTime.Date == time.Date && cacheTemp.UpdateTime >= time.AddSeconds(-AppConfig.DataTimeOut))
{
cacheTemp.UpdateTime = time;
cacheTemp.ErrorDuration = (time - cacheTemp.CreateTime).TotalSeconds;
continue;
}
//其他情况,新增
temps.Add(new EquipmentAlarmRecord
{
EquipmentCode = equipment.Code,
EquipmentName = equipment.Name,
EquipmentPropCode = totalAlarmProp.EquipmentTypePropTemplateCode,
EquipmentPropName = totalAlarmProp.EquipmentTypePropTemplate.Name,
EquipmentTypeCode = CurrentEquipmentType.Code,
ErrorDuration = 1,
IsEnd = false,
AlarmMessage = mainAlarm,
FactoryCode = equipment.FactoryCode,
ProjectCode = equipment.ProjectCode,
CreateTime = time,
UpdateTime = time,
Remark = alarmMessageItems
});
}
return BllResultFactory.Success(temps);
}
catch (Exception ex)
{
return BllResultFactory.Error<List<EquipmentAlarmRecord>>(ex.Message);
}
}
/// <summary>
/// 组装状态数据
/// </summary>
/// <param name="equipment"></param>
/// <param name="records"></param>
/// <returns></returns>
protected BllResult<List<EquipmentStatusRecordHistory>> AssemblyStatusData(EquipmentExtend equipment, IEnumerable<EquipmentDataRecord> records)
{
try
{
//数据组装(实时状态与历史状态实体之间为父子关系,这里用子类,可以省去手动转换操作)
var temps = new List<EquipmentStatusRecordHistory>();
foreach (var record in records.OrderBy(x => x.Timestamp))
{
var time = TimestampConvertToLocalDateTime(record.Timestamp);
var currentRecordStatusResult = GetEquipmentStatus(equipment, record);
if (!currentRecordStatusResult.Success)
{
continue;
}
//离线或无数据时,不记录数据
if (currentRecordStatusResult.Data == EquipmentStatus.None || currentRecordStatusResult.Data == EquipmentStatus.Offline)
{
continue;
}
var currentStatus = currentRecordStatusResult.Data.ToString();
var cacheTemp = temps.OrderByDescending(x => x.CreateTime).FirstOrDefault();
//缓存集合有数据、数据在设定时间内、状态无变化、日期为同一天
if (cacheTemp != null && cacheTemp.Status == currentStatus
&& cacheTemp.UpdateTime.Date == time.Date && cacheTemp.UpdateTime >= time.AddSeconds(-AppConfig.DataTimeOut))
{
cacheTemp.StatusDuration = (time - cacheTemp.CreateTime).TotalSeconds;
cacheTemp.UpdateTime = time;
continue;
}
//其他情况,新增记录
temps.Add(new EquipmentStatusRecordHistory
{
EquipmentCode = equipment.Code,
EquipmentName = equipment.Name,
EquipmentTypeCode = equipment.EquipmentType.Code,
FactoryCode = equipment.FactoryCode,
ProjectCode = equipment.ProjectCode,
Status = currentStatus,
HandleTime = DateTime.Now,
StatusDuration = 1,
IsEnd = false,
CreateTime = time,
UpdateTime = time,
});
}
return BllResultFactory.Success(temps);
}
catch (Exception ex)
{
return BllResultFactory.Error<List<EquipmentStatusRecordHistory>>(ex.Message);
}
}
/// <summary>
/// 获取报警信息
/// </summary>
/// <param name="equipment">设备</param>
/// <param name="totalAlarmProp">总报警属性</param>
/// <param name="monitorPropTemps">设备监控属性</param>
/// <param name="tagItems">节点数据集合</param>
/// <returns></returns>
protected virtual (string, List<string>) GenerateAlarmMessage(EquipmentExtend equipment, EquipmentPropExtend totalAlarmProp, IEnumerable<EquipmentPropExtend> monitorPropTemps, IEnumerable<TagItemDto> tagItems)
{
//主报警文本
var mainAlarm = totalAlarmProp.EquipmentTypePropTemplate.MonitorFailure;
if (string.IsNullOrWhiteSpace(mainAlarm))
{
mainAlarm = totalAlarmProp.EquipmentTypePropTemplate.Name;
}
//报警明细
var detailAlarms = monitorPropTemps.Where(monitorPropTemp =>
{
//总报警编码在这里需要跳过
if (monitorPropTemp.EquipmentTypePropTemplateCode == totalAlarmProp.EquipmentTypePropTemplateCode)
{
return false;
}
//校验不通过,则跳过
if (!EquipmentAlarmCodeValidation(equipment, monitorPropTemp.EquipmentTypePropTemplateCode).Success)
{
return false;
}
var tagCodes = new List<string>
{
monitorPropTemp.EquipmentTypePropTemplateCode,
monitorPropTemp.Address
};
var tagItem = tagItems.Where(x => tagCodes.Contains(x.Tag, StringComparer.OrdinalIgnoreCase)).FirstOrDefault();
//当前记录无此属性,则跳过
if (tagItem == null)
{
return false;
}
//值与比较值相等,则跳过
if (monitorPropTemp.EquipmentTypePropTemplate.MonitorCompareValue == tagItem.Value)
{
return false;
}
//其他情况,为报警
return true;
}).OrderBy(x => x.EquipmentTypePropTemplateCode).Select(x => x.EquipmentTypePropTemplate.MonitorFailure).ToList();
return (mainAlarm, detailAlarms);
}
/// <summary>
/// 获取设备状态
/// </summary>
/// <param name="equipment">设备</param>
/// <param name="record">某一时刻的记录</param>
/// <returns></returns>
protected abstract BllResult<EquipmentStatus> GetEquipmentStatus(EquipmentExtend equipment, EquipmentDataRecord record);
/// <summary>
/// Json转<see cref="TagItemDto"/>集合
/// </summary>
/// <param name="json">Json数据</param>
/// <returns><see cref="BllResult{T}"/></returns>
protected BllResult<List<TagItemDto>> JsonConvertToTagList(string json)
{
try
{
var jsonOption = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};
var tags = JsonSerializer.Deserialize<List<TagItemDto>>(json);
return BllResultFactory.Success(tags);
}
catch (Exception ex)
{
return BllResultFactory.Error<List<TagItemDto>>($"Json数据转换成Tag集合失败!{ex.Message}");
}
}
/// <summary>
/// 时间戳转本地时间
/// </summary>
/// <param name="timestamp">时间戳</param>
/// <returns></returns>
protected DateTime TimestampConvertToLocalDateTime(long timestamp)
{
var timestampLength = Math.Abs(timestamp).ToString().Length;
//时间戳为秒
if (timestampLength == 10)
{
return DateTimeOffset.FromUnixTimeSeconds(timestamp).LocalDateTime;
}
//时间戳为毫秒
else if (timestampLength == 13)
{
return DateTimeOffset.FromUnixTimeMilliseconds(timestamp).LocalDateTime;
}
//其他情况,无效数据
return default;
}
/// <summary>
/// 将Tag集合转换成Dictionary
/// </summary>
/// <param name="equipmentProps">设备属性</param>
/// <param name="tags">Tag集合</param>
/// <remarks>
/// <para>key:EquipmentTypePropTemplateCode</para>
/// <para>value:Tag值</para>
/// </remarks>
/// <returns></returns>
protected BllResult<Dictionary<string, string>> TagListConvertToDictionary(IEnumerable<EquipmentPropExtend> equipmentProps, IEnumerable<TagItemDto> tags)
{
try
{
var result = new Dictionary<string, string>();
foreach (var item in equipmentProps.DistinctBy(x => x.EquipmentTypePropTemplateCode))
{
var tagCodes = new List<string>
{
item.EquipmentTypePropTemplateCode,
item.Address
};
var temp = tags.Where(x => tagCodes.Contains(x.Tag, StringComparer.OrdinalIgnoreCase)).FirstOrDefault();
if (temp == null)
{
continue;
}
result.Add(item.EquipmentTypePropTemplateCode, temp.Value);
}
return BllResultFactory.Success(result);
}
catch (Exception ex)
{
return BllResultFactory.Error<Dictionary<string, string>>(ex.Message);
}
}
/// <summary>
/// 设备报警属性编号校验,用于自定义配置需要忽略的报警属性
/// </summary>
/// <param name="equipment">设备</param>
/// <param name="equipmentPropCode">设备报警属性编号</param>
/// <remarks>校验通过则记录,校验失败则忽略</remarks>
/// <returns></returns>
protected virtual BllResult EquipmentAlarmCodeValidation(EquipmentExtend equipment, string equipmentPropCode)
{
return BllResultFactory.Success();
}
/// <summary>
/// 验证是否存在空值
/// </summary>
/// <param name="vals"></param>
/// <returns></returns>
protected BllResult ValidationIsNullOrWhiteSpace(params string[] vals)
{
if (vals.Where(string.IsNullOrWhiteSpace).Any())
{
return BllResultFactory.Error($"存在空值!");
}
return BllResultFactory.Success();
}
}
}