AnalysisBase.cs
52 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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
using HHECS.BllModel;
using HHECS.DAQHandle.Dto;
using HHECS.DAQShared.Common.Enums;
using HHECS.DAQShared.Common.Utils;
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)
{
_ = UpdateTagValue(equipment, lastRecord);
//更新报警
var alarmHandleResult = UpdateEquipmentAlarm(equipment, orderItems);
if (!alarmHandleResult.Success)
{
return alarmHandleResult;
}
//更新状态
var statusHandleResult = UpdateEquipmentStatus(equipment, orderItems);
if (!statusHandleResult.Success)
{
return statusHandleResult;
}
//记录手动状态
_ = UpdateEquipmentManualRecord(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
{
using var equipmentAlarmRecordRepository = freeSql.GetRepository<EquipmentAlarmRecord>();
using var equipmentAlarmRecordDetailRepository = freeSql.GetRepository<EquipmentAlarmRecordDetail>();
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)
{
//结束当前设备的超时主报警
var needEndAlaremRecords = equipmentAlarmRecordRepository.Where(x => x.EquipmentCode == equipment.Code && !x.IsEnd).OrderBy(x => x.CreateTime).Limit(100)
.ToList(x => new EquipmentAlarmRecord
{
Id = x.Id,
});
foreach (var item in needEndAlaremRecords)
{
equipmentAlarmRecordRepository.Attach(item);
item.IsEnd = true;
}
equipmentAlarmRecordRepository.Update(needEndAlaremRecords);
//结束当前设备的超时报警明细
var mainAlarmIds = needEndAlaremRecords.Select(x => x.Id).ToList();
var needEndAlaremDetailRecords = equipmentAlarmRecordDetailRepository.Where(x => mainAlarmIds.Contains(x.EquipmentAlarmRecordId) && x.EquipmentCode == equipment.Code && !x.IsEnd).OrderBy(x => x.CreateTime).ToList(x => new EquipmentAlarmRecordDetail
{
Id = x.Id,
});
foreach (var item in needEndAlaremDetailRecords)
{
equipmentAlarmRecordDetailRepository.Attach(item);
item.IsEnd = true;
}
equipmentAlarmRecordDetailRepository.Update(needEndAlaremDetailRecords);
//无报警则跳过
return BllResultFactory.Success();
}
var alarmRecordCacheTemps = alarmRecordCacheTempsResult.Data;
var oldAlarmRecord = equipmentAlarmRecordRepository.Where(x => x.EquipmentCode == equipment.Code && x.EquipmentPropCode == EquipmentTotalAlarmCode && !x.IsEnd).OrderByDescending(x => x.CreateTime).First();
var lastCacheTemp = alarmRecordCacheTemps.OrderByDescending(x => x.CreateTime).First();
var addTemps = new List<EquipmentAlarmRecord>();
//数据库无报警记录
if (oldAlarmRecord == null)
{
foreach (var item in alarmRecordCacheTemps)
{
//不是最后一条记录的数据需要结束
if (!item.Equals(lastCacheTemp))
{
item.IsEnd = true;
}
addTemps.Add(item);
}
equipmentAlarmRecordRepository.Insert(addTemps);
var allAlarmDetail = addTemps.SelectMany(x => x.EquipmentAlarmRecordDetails).ToList();
equipmentAlarmRecordDetailRepository.Insert(allAlarmDetail);
return BllResultFactory.Success();
}
//数据库有报警记录,则需要校验
foreach (var item in alarmRecordCacheTemps)
{
//对于之前的数据,这里暂时不做处理
if (oldAlarmRecord.UpdateTime >= item.UpdateTime)
{
continue;
}
//日期为同一天,在设定时间以内,则更新
if (oldAlarmRecord.UpdateTime.Date == item.CreateTime.Date && (item.CreateTime - oldAlarmRecord.UpdateTime).TotalSeconds <= AppConfig.DataTimeOut)
{
equipmentAlarmRecordRepository.Attach(oldAlarmRecord);
//不是最后一条记录,说明已经成为历史报警,需要结束标记
if (!item.Equals(lastCacheTemp))
{
oldAlarmRecord.IsEnd = true;
}
//无具体报警信息,则更新报警文本,这里的文本需要与数据组装方法“AssemblyAlarmData”里面的文本内容一致
if (oldAlarmRecord.AlarmMessage.Contains("无具体报警信息") && oldAlarmRecord.AlarmMessage != item.AlarmMessage)
{
oldAlarmRecord.AlarmMessage = item.AlarmMessage;
}
oldAlarmRecord.ErrorDuration = (int)(item.UpdateTime - oldAlarmRecord.CreateTime).TotalSeconds;
oldAlarmRecord.UpdateTime = item.UpdateTime;
oldAlarmRecord.HandleTime = DateTime.Now;
equipmentAlarmRecordRepository.Update(oldAlarmRecord);
//更新报警明细
var allAlarmDetail = equipmentAlarmRecordDetailRepository.Where(x => !x.IsEnd &&
x.EquipmentAlarmRecordId == oldAlarmRecord.Id).ToList();
var addAlarmDetailTemps = new List<EquipmentAlarmRecordDetail>();
//报警明细
var equipmentAlarmRecordDetails = item.EquipmentAlarmRecordDetails.Select(x => new EquipmentAlarmRecordDetail
{
EquipmentAlarmRecordId = oldAlarmRecord.Id,
EquipmentCode = x.EquipmentCode,
EquipmentName = x.EquipmentName,
EquipmentPropCode = x.EquipmentPropCode,
EquipmentPropName = x.EquipmentPropName,
EquipmentTypeCode = x.EquipmentTypeCode,
ErrorDuration = x.ErrorDuration,
AlarmMessage = x.AlarmMessage,
ProjectCode = x.ProjectCode,
FactoryCode = x.FactoryCode,
IsEnd = oldAlarmRecord.IsEnd,
CreateTime = x.CreateTime,
UpdateTime = x.UpdateTime,
}).ToList();
foreach (var alarmDetailGroup in equipmentAlarmRecordDetails.GroupBy(x => x.EquipmentPropCode))
{
//缓存里面的第一条记录
var firstCacheTemp = alarmDetailGroup.OrderBy(x => x.CreateTime).First();
//数据库里面的最后一条记录
var lastDBTemp = allAlarmDetail.Where(x => x.EquipmentPropCode == alarmDetailGroup.Key).OrderByDescending(x => x.CreateTime).FirstOrDefault();
//存在记录,且在设定时间之内,则需要更新
if (lastDBTemp != null && (firstCacheTemp.CreateTime - lastDBTemp.UpdateTime).TotalSeconds <= AppConfig.DataTimeOut)
{
equipmentAlarmRecordDetailRepository.Attach(lastDBTemp);
lastDBTemp.ErrorDuration = (int)(firstCacheTemp.UpdateTime - lastDBTemp.CreateTime).TotalSeconds;
lastDBTemp.UpdateTime = firstCacheTemp.UpdateTime;
//状态有编号,则更新
if (lastDBTemp.IsEnd != oldAlarmRecord.IsEnd)
{
lastDBTemp.IsEnd = oldAlarmRecord.IsEnd;
}
equipmentAlarmRecordDetailRepository.Update(lastDBTemp);
addAlarmDetailTemps.AddRange(alarmDetailGroup.Where(x => !x.Equals(firstCacheTemp)).ToList());
continue;
}
addAlarmDetailTemps.AddRange(alarmDetailGroup.ToList());
}
equipmentAlarmRecordDetailRepository.Insert(addAlarmDetailTemps);
continue;
}
//其他情况需要新增记录
//不是最后一条记录
if (!item.Equals(lastCacheTemp))
{
item.IsEnd = true;
}
addTemps.Add(item);
}
equipmentAlarmRecordRepository.Insert(addTemps);
equipmentAlarmRecordDetailRepository.Insert(addTemps.SelectMany(x => x.EquipmentAlarmRecordDetails).ToList());
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 UpdateEquipmentStatus(EquipmentExtend equipment, IEnumerable<EquipmentDataRecord> records)
{
try
{
using var equipmentStatusRecordRepository = freeSql.GetRepository<EquipmentStatusRecord>();
using var equipmentStatusRecordHistoryRepository = freeSql.GetRepository<EquipmentStatusRecordHistory>();
//结束当前设备的超时状态
var needEndAlaremRecords = equipmentStatusRecordHistoryRepository.Where(x => x.EquipmentCode == equipment.Code && !x.IsEnd && x.UpdateTime < DateTime.Now.AddSeconds(-AppConfig.DataTimeOut)).OrderBy(x => x.CreateTime).Limit(100)
.ToList(x => new EquipmentStatusRecordHistory
{
Id = x.Id,
});
foreach (var item in needEndAlaremRecords)
{
equipmentStatusRecordHistoryRepository.Attach(item);
item.IsEnd = true;
}
equipmentStatusRecordHistoryRepository.Update(needEndAlaremRecords);
//组装数据
var statusRecordCacheTempsResult = AssemblyStatusData(equipment, records);
if (!statusRecordCacheTempsResult.Success)
{
return BllResultFactory.Error(statusRecordCacheTempsResult.Msg);
}
if (statusRecordCacheTempsResult.Data.Count == 0)
{
//无数据则跳过
return BllResultFactory.Success();
}
var statusRecordCacheTemps = statusRecordCacheTempsResult.Data;
//实时状态表中的实时状态记录
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 = (int)(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);
}
}
//异常情况:倘若当前设备在实时状态表存在多条数据,应将其他数据删除
var temps = equipmentStatusRecordRepository.Where(x => x.EquipmentCode == equipmentStatusRecord.EquipmentCode && x.Id != equipmentStatusRecord.Id)
.ToList(x => new EquipmentStatusRecord
{
Id = x.Id,
});
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
{
//现有记录时间之后的数据
statusRecordCacheTemps = statusRecordCacheTemps.Where(x => x.CreateTime >= equipmentStatusRecordHistory.UpdateTime).ToList();
if (statusRecordCacheTemps.Count == 0)
{
return BllResultFactory.Success();
}
var firstCacheStatusRecord = statusRecordCacheTemps.OrderBy(x => x.CreateTime).First();
//需新增的数据
var addTemps = new List<EquipmentStatusRecordHistory>();
foreach (var item in statusRecordCacheTemps.OrderBy(x => x.CreateTime))
{
//是第一条记录,与历史记录表的数据进行比较
if (item.Equals(firstCacheStatusRecord))
{
//状态一致,日期为同一天,且在设定超时时间范围内,则更新记录
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 = !item.Equals(lastCacheStatusRecord);
equipmentStatusRecordHistory.HandleTime = DateTime.Now;
equipmentStatusRecordHistory.UpdateTime = item.UpdateTime;
equipmentStatusRecordHistory.StatusDuration = (int)(item.UpdateTime - equipmentStatusRecordHistory.CreateTime).TotalSeconds;
equipmentStatusRecordHistoryRepository.Update(equipmentStatusRecordHistory);
continue;
}
//超过设定时间,需要结束历史记录
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);
}
//不是最后一条记录,需加上结束标记
if (!item.Equals(lastCacheStatusRecord))
{
item.IsEnd = true;
}
addTemps.Add(item);
}
if (addTemps.Count > 0)
{
equipmentStatusRecordHistoryRepository.Insert(addTemps);
}
}
#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 virtual BllResult UpdateEquipmentManualRecord(EquipmentExtend equipment, IEnumerable<EquipmentDataRecord> records)
{
try
{
var statusRecordCacheTempsResult = AssemblyManualStatusData(equipment, records);
if (!statusRecordCacheTempsResult.Success)
{
return BllResultFactory.Error(statusRecordCacheTempsResult.Msg);
}
var statusRecordCacheTemps = statusRecordCacheTempsResult.Data;
if (statusRecordCacheTemps.Count == 0)
{
//无数据则跳过
return BllResultFactory.Success();
}
var equipmentManualStatusRecordRepository = freeSql.GetRepository<EquipmentManualStatusRecord>();
var lastRecord = equipmentManualStatusRecordRepository.Where(x => x.EquipmentCode == equipment.Code).OrderByDescending(x => x.CreateTime).First();
//无记录,全部新增
if (lastRecord == null)
{
equipmentManualStatusRecordRepository.Insert(statusRecordCacheTemps);
return BllResultFactory.Success();
}
//存在记录,只记录历史状态时间之后的数据
var cacheTemps = statusRecordCacheTemps.Where(x => x.CreateTime >= lastRecord.UpdateTime).OrderBy(x => x.CreateTime).ToList();
var addTemps = new List<EquipmentManualStatusRecord>();
foreach (var cacheTemp in cacheTemps)
{
if (cacheTemp.CreateTime.Date == lastRecord.UpdateTime.Date
&& (cacheTemp.CreateTime - lastRecord.UpdateTime).TotalSeconds <= AppConfig.DataTimeOut)
{
equipmentManualStatusRecordRepository.Attach(lastRecord);
lastRecord.UpdateTime = cacheTemp.UpdateTime;
equipmentManualStatusRecordRepository.Update(lastRecord);
continue;
}
addTemps.Add(cacheTemp);
}
if (addTemps.Count > 0)
{
equipmentManualStatusRecordRepository.Insert(addTemps);
}
return BllResultFactory.Success();
}
catch (Exception ex)
{
return BllResultFactory.Error(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))
.DistinctBy(x => x.EquipmentTypePropTemplate.Code)
.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)
{
//状态有变化,则结束最后一条报警记录
var lastTemp = temps.Where(x => !x.IsEnd).OrderByDescending(x => x.CreateTime).FirstOrDefault();
if (lastTemp != null)
{
lastTemp.IsEnd = true;
lastTemp.EquipmentAlarmRecordDetails.ForEach(x => x.IsEnd = true);
}
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 && !x.IsEnd)
.OrderByDescending(x => x.CreateTime).FirstOrDefault();
//间隔在设定时间内,认为是同一个主报警
if (cacheTemp != null && cacheTemp.UpdateTime.Date == time.Date &&
(time - cacheTemp.UpdateTime).TotalSeconds <= AppConfig.DataTimeOut)
{
cacheTemp.UpdateTime = time;
cacheTemp.ErrorDuration = (int)(time - cacheTemp.CreateTime).TotalSeconds;
//结束其他报警明细
var alarmCodes = detailAlarms.Select(x => x.Key).ToList();
foreach (var oldAlarm in cacheTemp.EquipmentAlarmRecordDetails)
{
if (oldAlarm.IsEnd)
{
continue;
}
if (!alarmCodes.Contains(oldAlarm.EquipmentPropCode))
{
//本次无报警的记录,需要结束
oldAlarm.IsEnd = true;
}
}
//更新报警明细
foreach (var newAlarm in detailAlarms)
{
var lastItem = cacheTemp.EquipmentAlarmRecordDetails.Where(x => x.EquipmentPropCode == newAlarm.Key && !x.IsEnd).FirstOrDefault();
if (lastItem == null)
{
var newItem = new EquipmentAlarmRecordDetail
{
EquipmentAlarmRecordId = cacheTemp.Id,
EquipmentCode = equipment.Code,
EquipmentName = equipment.Name,
EquipmentPropCode = newAlarm.Key,
EquipmentPropName = monitorPropTemps.Where(p => p.EquipmentTypePropTemplateCode == newAlarm.Key).Select(p => p.Remark).FirstOrDefault(),
EquipmentTypeCode = CurrentEquipmentType.Code,
ProjectCode = equipment.ProjectCode,
FactoryCode = equipment.FactoryCode,
AlarmMessage = newAlarm.Value,
IsEnd = false,
ErrorDuration = 1,
CreateTime = time,
UpdateTime = time,
};
cacheTemp.EquipmentAlarmRecordDetails.Add(newItem);
continue;
}
//记录不为空,更新时间
lastItem.UpdateTime = time;
lastItem.ErrorDuration = (int)(time - lastItem.CreateTime).TotalSeconds;
}
continue;
}
//获取设备故障坐标
GetEquipmentAlarmPoints(equipment, tagItems, out string axis, out string points);
var alarmMessage = string.Join(";", detailAlarms.Select(x => x.Value));
if (string.IsNullOrWhiteSpace(alarmMessage))
{
alarmMessage = $"{mainAlarm},无具体报警信息";
}
var mainAlarmRecord = new EquipmentAlarmRecord
{
Id = Guid.NewGuid(),
EquipmentCode = equipment.Code,
EquipmentName = equipment.Name,
EquipmentPropCode = totalAlarmProp.EquipmentTypePropTemplateCode,
EquipmentPropName = totalAlarmProp.EquipmentTypePropTemplate.Name,
EquipmentTypeCode = CurrentEquipmentType.Code,
ErrorDuration = 1,
IsEnd = false,
AlarmMessage = alarmMessage,
FactoryCode = equipment.FactoryCode,
ProjectCode = equipment.ProjectCode,
HandleTime = DateTime.Now,
CreateTime = time,
UpdateTime = time,
Axis = axis,
Points = points
};
mainAlarmRecord.EquipmentAlarmRecordDetails = detailAlarms.Select(x => new EquipmentAlarmRecordDetail
{
EquipmentAlarmRecordId = mainAlarmRecord.Id,
EquipmentCode = equipment.Code,
EquipmentName = equipment.Name,
EquipmentPropCode = x.Key,
EquipmentPropName = monitorPropTemps.Where(p => p.EquipmentTypePropTemplateCode == x.Key).Select(p => p.Remark).FirstOrDefault(),
EquipmentTypeCode = CurrentEquipmentType.Code,
ProjectCode = equipment.ProjectCode,
FactoryCode = equipment.FactoryCode,
AlarmMessage = x.Value,
IsEnd = false,
ErrorDuration = 1,
CreateTime = time,
UpdateTime = time,
}).ToList();
//其他情况,新增
temps.Add(mainAlarmRecord);
}
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 && (time - cacheTemp.UpdateTime).TotalSeconds <= AppConfig.DataTimeOut)
{
cacheTemp.StatusDuration = (int)(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="records"></param>
/// <returns></returns>
protected BllResult<List<EquipmentManualStatusRecord>> AssemblyManualStatusData(EquipmentExtend equipment, IEnumerable<EquipmentDataRecord> records)
{
try
{
var result = new List<EquipmentManualStatusRecord>();
_ = Enum.TryParse<EquipmentTypeConst>(equipment.EquipmentType.Code, out var equipmentType);
foreach (var record in records.OrderBy(x => x.Timestamp))
{
var time = TimestampConvertToLocalDateTime(record.Timestamp);
var tagResult = JsonConvertToTagList(record.Tags);
if (!tagResult.Success)
{
continue;
}
var currentRecordStatusResult = EquipmentStatusHelper.GetEquipmentStatusV2(equipmentType, equipment.EquipmentProps, tagResult.Data);
if (!currentRecordStatusResult.Success)
{
continue;
}
//非手动状态,不记录数据
if (currentRecordStatusResult.Data != EquipmentStatus.Manual)
{
continue;
}
var currentStatus = currentRecordStatusResult.Data.ToString();
var cacheTemp = result.OrderByDescending(x => x.CreateTime).FirstOrDefault();
//缓存集合有数据、数据在设定时间内、状态无变化、日期为同一天
if (cacheTemp != null && cacheTemp.UpdateTime.Date == time.Date && (time - cacheTemp.UpdateTime).TotalSeconds <= AppConfig.DataTimeOut)
{
cacheTemp.UpdateTime = time;
continue;
}
//其他情况,新增记录
result.Add(new EquipmentManualStatusRecord
{
EquipmentCode = equipment.Code,
EquipmentName = equipment.Name,
EquipmentTypeCode = equipment.EquipmentType.Code,
FactoryCode = equipment.FactoryCode,
ProjectCode = equipment.ProjectCode,
Status = currentStatus,
CreateTime = time,
UpdateTime = time,
});
}
return BllResultFactory.Success(result);
}
catch (Exception ex)
{
return BllResultFactory.Error<List<EquipmentManualStatusRecord>>(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, Dictionary<string, 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)
.ToDictionary(x => x.EquipmentTypePropTemplate.Code, y => y.EquipmentTypePropTemplate.MonitorFailure);
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 static 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 static 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>
/// 获取设备故障点位的坐标
/// </summary>
/// <param name="equipment"></param>
/// <param name="tagItems"></param>
/// <param name="axis"></param>
/// <param name="points"></param>
private static void GetEquipmentAlarmPoints(EquipmentExtend equipment, List<TagItemDto> tagItems, out string axis, out string points)
{
axis = string.Empty;
points = string.Empty;
//AGV叉车
if (equipment.EquipmentType?.Code == EquipmentTypeConst.AGVForklift.ToString())
{
var xAxis = tagItems.Where(x => x.Tag == AGVForkliftProp.CoordX.ToString()).Select(x => x.Value).FirstOrDefault();
var yAxis = tagItems.Where(x => x.Tag == AGVForkliftProp.CoordY.ToString()).Select(x => x.Value).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(xAxis) && !string.IsNullOrWhiteSpace(yAxis))
{
axis = $"{xAxis},{yAxis}";
}
points = tagItems.Where(x => x.Tag == AGVForkliftProp.CurrentBarcode.ToString()).Select(x => x.Value).FirstOrDefault();
}
//堆垛机设备
var srmEquipmentTypes = new List<EquipmentTypeConst>
{
EquipmentTypeConst.SingleForkSRM,
EquipmentTypeConst.SingleForkSRMV2,
EquipmentTypeConst.DoubleForkSRM,
EquipmentTypeConst.DoubleForkSRMV2,
EquipmentTypeConst.SingleForkSSRM,
EquipmentTypeConst.SingleForkSSRMV132
}.Select(x => x.ToString()).ToList();
if (srmEquipmentTypes.Contains(equipment.EquipmentType?.Code))
{
var xAxis = tagItems.Where(x => x.Tag == SRMProps.Fork1XPosition.ToString()).Select(x => x.Value).FirstOrDefault();
var yAxis = tagItems.Where(x => x.Tag == SRMProps.Fork1YPosition.ToString()).Select(x => x.Value).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(xAxis) && !string.IsNullOrWhiteSpace(yAxis))
{
axis = $"{xAxis},{yAxis}";
}
points = tagItems.Where(x => x.Tag == SRMProps.CurrentColumn.ToString()).Select(x => x.Value).FirstOrDefault();
}
if (equipment.EquipmentType?.Code == EquipmentTypeConst.RGVStation.ToString())
{
points = tagItems.Where(x => x.Tag == RGVStationProps.StationRGVActualPositionID.ToString()).Select(x => x.Value).FirstOrDefault();
}
}
/// <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();
}
}
}