BaseAnalysis.cs
37 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
using HHECS.BllModel;
using HHECS.DAQHandle.Common.Enums;
using HHECS.DAQHandle.Common.Utils;
using HHECS.DAQHandle.DataAccess;
using HHECS.DAQHandle.Dto;
using HHECS.DAQHandle.Models;
using HHECS.EquipmentModel;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Text.Json;
namespace HHECS.DAQHandle.EquipmentHandle
{
internal abstract class BaseAnalysis : IAnalysis
{
protected DataContext Context = new DataContext();
protected static int AlarmTimeOut = int.Parse(ConfigurationManager.AppSettings["AlarmTimeOut"]);
protected static int StatusTimeOut = int.Parse(ConfigurationManager.AppSettings["StatusTimeOut"]);
protected static int DataRetentionAmount = int.Parse(ConfigurationManager.AppSettings["DataRetentionAmount"]);
protected static int DataRetentionDays = int.Parse(ConfigurationManager.AppSettings["DataRetentionDays"]);
protected EquipmentType EquipmentType;
protected string WareHouse = ConfigurationManager.AppSettings["WarehouseCode"];
protected List<EquipmentTypePropTemplate> EquipmentTypePropTemps;
protected BaseAnalysis(EquipmentType equipmentType)
{
EquipmentType = equipmentType;
//EquipmentTypePropTemps = equipmentType.EquipmentTypePropTemplates;
////try
////{
//// var equipmentCodes = Program.EquipmentInfos.Where(x => x.Value.EquipmentType.Code == equipmentType.Code).Select(x => x.Value.Code).ToList();
//// //删除已完成并且超过配置保留天数的数据
//// Context.EquipmentDataRecord.Remove(x => x.IsHandle && equipmentCodes.Any(y => y == x.EquipmentCode) && (DateTime.Now - (DateTime)x.CreateTime).TotalDays > DataRetentionDays);
//// Context.SaveChanges();
////}
////catch (Exception ex)
////{
//// SystemLog.PrintError($"{ex}");
////}
//#region
//var handleStage = EquipmentDataRecord.SET_ERROR_HANDLE | EquipmentDataRecord.SET_STATUS_HANDLE | EquipmentDataRecord.SET_VAULE_HANDLE;
//var count = Context.EquipmentDataRecord.Where(x => x.IsHandle && x.HandleStage == handleStage).Count();
////保留9000-10000条数据
//if (count < DataRetentionAmount) return;
//var handleData = Context.EquipmentDataRecord.Where(x => x.IsHandle && x.HandleStage == handleStage).OrderBy(x => x.Timestamp).Take(1000).ToList();
//if (handleData.Count > 0)
//{
// try
// {
// Context.EquipmentDataRecord.RemoveRange(handleData);
// Context.SaveChanges();
// SystemLog.PrintInfo($"清除了{handleData.Count}条已处理数据");
// }
// catch (Exception ex)
// {
// SystemLog.PrintInfo($"清除已处理数据失败{ex}");
// }
//}
//#endregion
}
public virtual BllResult Execute(IEnumerable<EquipmentDataRecord> records)
{
try
{
var group = records.GroupBy(x => x.EquipmentCode);
using var enumerator = group.GetEnumerator();
enumerator.MoveNext();
do
{
//Task.Factory.StartNew(() =>
//{
var item = enumerator.Current;
var equipmentSN = item?.Key;
if (item != null)
{
Context.AttachRange(item);
var isSetValueSuccess = UpdateTagValue(item.OrderByDescending(x => x.Timestamp).FirstOrDefault());
foreach (var item1 in item)
{
//更新数据状态为设置数值报错
if (!isSetValueSuccess)
{
item1.HandleStage = (byte)(item1.HandleStage ^ EquipmentDataRecord.SET_VALUE_ERROR);
}
else
{
item1.HandleStage = (byte)(item1.HandleStage ^ EquipmentDataRecord.SET_VAULE_HANDLE);
}
}
////性能太慢
////更新状态到数据库
//if (item != null)
{
Context.UpdateRange(item);
Context.SaveChanges();
}
}
// Stopwatch sw = Stopwatch.StartNew();
var orderItem = item?.OrderBy(x => x.Timestamp);
UpdateEquipmentAlarm(equipmentSN, orderItem);
//sw.Stop();
//SystemLog.PrintInfo($"报警信息处理耗时{sw.ElapsedMilliseconds}");
//sw.Restart();
UpdateEquipmentStatus(equipmentSN, orderItem);
//sw.Stop();
//SystemLog.PrintInfo($"状态信息处理耗时{sw.ElapsedMilliseconds}");
//更新状态到数据库
if (item != null)
{
Context.UpdateRange(item);
Context.SaveChanges();
}
//});
//Thread.Sleep(10);
} while (enumerator.MoveNext());
return BllResultFactory.Success();
}
catch (Exception ex)
{
return BllResultFactory.Error($"[{nameof(SingleForkSRMAnalysis)}]解析出现异常:{ex}");
}
}
/// <summary>
/// 更新设备属性值
/// </summary>
/// <param name="record">取最后一条记录</param>
protected virtual bool UpdateTagValue(EquipmentDataRecord record)
{
try
{
if (record == null) return true;
DateTime acceptTime = DateTimeOffset.FromUnixTimeSeconds(record.Timestamp).LocalDateTime;
//获取所有修改时间小于当前数据时间的属性
if (!Program.EquipmentInfos.TryGetValue(record.EquipmentCode, out var equipment))
{
SystemLog.PrintError($"设备{record.EquipmentCode}不存在");
}
var props = Context.EquipmentProp.Where(x => x.EquipmentId == equipment.Id).ToList();
//if (props.Any(x => x.Updated != null && x.Updated > acceptTime))
if (props.Find(x => x.Updated != null && x.Updated > acceptTime) is var temp && temp != null)
{
SystemLog.PrintError($"更新设备属性数据:设备{record.EquipmentCode}的记录{record.Id}已经过期,数据上传时间{acceptTime},数据库记录时间{temp.Updated}");
return false;
}
foreach (var prop in props)
{
if (record.Props.TryGetValue(prop.Address, out string value))
{
prop.Value = value;
prop.Updated = acceptTime;
}
}
Context.EquipmentProp.UpdateRange(props);
Context.SaveChanges();
return true;
}
catch (Exception ex)
{
SystemLog.PrintError($"{ex}");
return false;
}
}
/// <summary>
/// 更新设备报警记录
/// </summary>
/// <param name="records"></param>
protected virtual void UpdateEquipmentAlarm(string equipmentSN, IEnumerable<EquipmentDataRecord> records)
{
#region 结束长时间未上传数据的报警
var first = records?.FirstOrDefault();
var lastAcceptTime = DateTime.Now;
if (first != null)
{
lastAcceptTime = DateTimeOffset.FromUnixTimeSeconds(first.Timestamp).LocalDateTime;
}
var endRecords = Context.EquipmentAlarmRecords.Where(x => !x.IsEnd && x.EquipmentCode == equipmentSN && x.EquipmentType == EquipmentType.ToString() && (lastAcceptTime - (DateTime)x.UpdateTime).TotalSeconds > AlarmTimeOut).ToList();
if (endRecords.Count > 0)
{
endRecords.ForEach(x =>
{
x.ErrorDuration = ((DateTime)x.UpdateTime - (DateTime)x.CreateTime).TotalSeconds;
x.IsEnd = true;
});
Context.UpdateRange(endRecords);
Context.SaveChanges();
}
#endregion
#region 上传数据的报警进行处理
if (records == null || !records.Any()) return;
records = records.Where(x => (x.HandleStage & EquipmentDataRecord.SET_ERROR_HANDLE) != EquipmentDataRecord.SET_ERROR_HANDLE);
try
{
var lastAlarm = Context.EquipmentAlarmRecords.Where(x => x.EquipmentCode == equipmentSN)
.WithLock(SqlServerLock.NoLock)
.OrderByDescending(x => x.UpdateTime)
.First();
foreach (var equipmentInfo in records)
{
try
{
var updateList = new List<EquipmentAlarmRecord>();
var addList = new List<EquipmentAlarmRecord>();
DateTime acceptTime = DateTimeOffset.FromUnixTimeSeconds(equipmentInfo.Timestamp).LocalDateTime;
if (lastAlarm != null)
{
if (acceptTime < lastAlarm.UpdateTime)
{
SystemLog.PrintError($"更新设备报警数据:设备{equipmentInfo.EquipmentCode}的记录{equipmentInfo.Id}已经过期,数据上传时间{acceptTime},数据库记录时间{lastAlarm.UpdateTime}");
continue;
}
}
if (!Program.EquipmentInfos.TryGetValue(equipmentInfo.EquipmentCode, out var equipment))
{
SystemLog.PrintError($"设备{equipmentInfo.EquipmentCode}不存在");
}
if (equipment.Name.IsNullOrWhiteSpace())
{
SystemLog.PrintError($"设备{equipmentInfo.EquipmentCode}名称为空");
}
var alarmRecords = Context.EquipmentAlarmRecords.Where(x => x.EquipmentCode == equipmentInfo.EquipmentCode && x.IsEnd == false).WithLock(SqlServerLock.NoLock).ToList();
var alarms = equipment.EquipmentPropTemps
.FindAll(x => x.PropType == EquipmentPropType.PLCMonitorAddress
&& equipmentInfo.Props[x.Address] != x.MonitorCompareValue);
foreach (var alarm in alarms)
{
//匹配数据库中已有记录,如果当前的时间戳小于已记录的异常,不做处理
var record = alarmRecords.Find(t => t.PropCode == alarm.Address);
if (record == null)
{
//说明记录中没有,或者超过5秒,则直接新增这个报警;
EquipmentAlarmRecord equipmentAlarm = new EquipmentAlarmRecord
{
EquipmentCode = equipmentInfo.EquipmentCode,
EquipmentName = equipment.Name,
EquipmentType = equipment.EquipmentType.Code,
PropCode = alarm.Address,
AlarmMessage = string.IsNullOrWhiteSpace(equipmentInfo.Props[alarm.Address]) ? "值为空" : alarm.MonitorFailure,
CreateTime = acceptTime,
UpdateTime = acceptTime,//确保不为null
HandleTime = DateTime.Now,
};
addList.Add(equipmentAlarm);
}
else
{
//更新这个报警
record.UpdateTime = acceptTime;
record.ErrorDuration = (acceptTime - (DateTime)record.CreateTime).TotalSeconds;
updateList.Add(record);
}
}
Context.UnitOfWork.GetOrBeginTransaction();
try
{
if (addList.Count > 0)
{
Context.EquipmentAlarmRecords.AddRange(addList);
}
if (updateList.Count > 0)
{
Context.EquipmentAlarmRecords.UpdateRange(updateList);
}
//设置状态为已经处理
equipmentInfo.HandleStage = (byte)(equipmentInfo.HandleStage ^ EquipmentDataRecord.SET_ERROR_HANDLE);
Context.Update(equipmentInfo);
Context.SaveChanges();
Context.UnitOfWork.Commit();
}
catch (Exception)
{
Context.UnitOfWork.Rollback();
equipmentInfo.HandleStage = (byte)(equipmentInfo.HandleStage ^ EquipmentDataRecord.SET_ALARM_ERROR);
Context.Update(equipmentInfo);
Context.SaveChanges();
throw;
}
//finally
//{
// transaction.Dispose();
//}
}
catch (Exception ex)
{
SystemLog.PrintError($"记录{equipmentInfo.Id}设置报警信息异常:{ex}");
}
}
}
catch (Exception ex)
{
SystemLog.PrintError($"{ex}");
}
#endregion
}
/// <summary>
/// 更新设备状态记录
/// </summary>
/// <param name="records"></param>
protected virtual void UpdateEquipmentStatus(string equipmentSN, IEnumerable<EquipmentDataRecord> records)
{
#region 实时状态
//if (Program.RealTimeStatus && !string.IsNullOrEmpty(equipmentSN))
//{
// var currData = Context.EquipmentDataRecord.Where(x => x.EquipmentCode == equipmentSN).WithLock(SqlServerLock.NoLock).OrderByDescending(x => x.Timestamp).First();
// stopwatch.Stop();
// SystemLog.PrintInfo($"{stopwatch.ElapsedMilliseconds}");
// stopwatch.Restart();
// //移除原有数据
// Context.EquipmentStatusRecords.Remove(x => x.EquipmentCode == equipmentSN);
// stopwatch.Stop();
// SystemLog.PrintInfo($"{stopwatch.ElapsedMilliseconds}");
// stopwatch.Restart();
// //插入新数据
// var currTime = DateTimeOffset.FromUnixTimeSeconds(currData.Timestamp).LocalDateTime;
// var newStatus = new EquipmentStatusRecord()
// {
// CreateTime = currTime,
// UpdateTime = currTime,
// Status = EquipmentStatusRecordStatus.Free.ToString(),
// EquipmentCode = currData.EquipmentCode,
// EquipmentName = currData.EquipmentName,
// IsEnd = false,
// HandleTime = DateTime.Now,
// EquipmentType = EquipmentType.Code,
// FactoryCode = WareHouse,
// };
// Context.EquipmentStatusRecords.Add(newStatus);
// Context.SaveChanges();
// stopwatch.Stop();
// SystemLog.PrintInfo($"{stopwatch.ElapsedMilliseconds}");
// stopwatch.Restart();
//}
#endregion
//历史状态
#region 结束原有状态
var first = records?.FirstOrDefault();
DateTime lastAcceptTime = DateTime.Now;
if (first != null)
{
lastAcceptTime = DateTimeOffset.FromUnixTimeSeconds(first.Timestamp).LocalDateTime;
}
var statusTimeOut = lastAcceptTime.AddSeconds(-StatusTimeOut);
var endRecords = Context.EquipmentStatusRecordHistorys
.Where(x => x.EquipmentCode == equipmentSN && !x.IsEnd && x.UpdateTime < statusTimeOut)
.WithLock(SqlServerLock.NoLock).ToList();
var addRecords = new List<EquipmentStatusRecordHistory>();
endRecords.ForEach(x =>
{
if (x.Status != EquipmentStatusRecordStatus.Free.ToString())
{
var updatetime = first == null ? x.UpdateTime : lastAcceptTime;
x.UpdateTime = updatetime;
x.IsEnd = true;
x.StatusDuration = (lastAcceptTime - (DateTime)x.CreateTime).TotalSeconds;
var newStatus = new EquipmentStatusRecordHistory()
{
CreateTime = updatetime,
UpdateTime = updatetime,
Status = EquipmentStatusRecordStatus.Free.ToString(),
EquipmentCode = x.EquipmentCode,
EquipmentName = x.EquipmentName,
IsEnd = false,
FactoryCode = x.FactoryCode,
Remark = "超过超时时间未上传数据,重置设备状态为空闲",
};
addRecords.Add(newStatus);
}
});
if (endRecords.Count > 0)
{
Context.UnitOfWork.GetOrBeginTransaction();
try
{
Context.EquipmentStatusRecordHistorys.UpdateRange(endRecords);
if (addRecords.Count > 0)
{
Context.EquipmentStatusRecordHistorys.AddRange(addRecords);
////移除原有数据
//Context.EquipmentStatusRecords.Remove(x => addRecords.Any(y => y.EquipmentCode == x.EquipmentCode));
////插入新数据
//Context.EquipmentStatusRecords.AddRange(addRecords);
}
Context.SaveChanges();
Context.UnitOfWork.Commit();
}
catch (Exception ex)
{
SystemLog.PrintError($"{ex}");
Context.UnitOfWork.Rollback();
}
}
#endregion
#region 更新状态
if (records == null || !records.Any()) return;
records = records.Where(x => (x.HandleStage & EquipmentDataRecord.SET_STATUS_HANDLE) != EquipmentDataRecord.SET_STATUS_HANDLE);
var statusRecords = Context.EquipmentStatusRecordHistorys.Where(t => t.EquipmentCode == equipmentSN && t.IsEnd == false).WithLock(SqlServerLock.NoLock).OrderBy(x => x.UpdateTime).ToList();
//与此设备相关的所有状态记录
if (statusRecords.Count == 0)
{
SystemLog.PrintError($"设备{equipmentSN}不存在未结束的状态;");
}
else if (statusRecords.Count > 1)
{
SystemLog.PrintError($"设备{equipmentSN}同时存在多条未结束的状态;{string.Join(",", statusRecords.Select(x => x.Status))}");
var statusRecord = statusRecords.First();
statusRecord.IsEnd = true;
statusRecord.Remark = $"同时存在多条未结束的状态,结束较早的数据{DateTime.Now}";
statusRecords.Remove(statusRecord);
Context.Update(statusRecord);
Context.SaveChanges();
}
foreach (var equipmentInfo in records)
{
try
{
DateTime acceptTime = DateTimeOffset.FromUnixTimeSeconds(equipmentInfo.Timestamp).LocalDateTime;
if (statusRecords.Count != 0 && acceptTime < statusRecords.First().UpdateTime)
{
SystemLog.PrintError($"更新设备状态数据:设备{equipmentInfo.EquipmentCode}的记录{equipmentInfo.Id}已经过期,数据上传时间{acceptTime},数据库记录时间{statusRecords.First().UpdateTime}");
continue;
}
//获取当前设备的状态,根据不同设备类型重载
EquipmentStatusRecordStatus? equipmentStatus = GetEquipmentStatus(equipmentInfo);
if (equipmentStatus != null)
{
RecordEquipmentStatus(equipmentInfo, statusRecords, (EquipmentStatusRecordStatus)equipmentStatus);
}
equipmentInfo.HandleStage = (byte)(equipmentInfo.HandleStage ^ EquipmentDataRecord.SET_STATUS_HANDLE);
}
catch (Exception ex)
{
SystemLog.PrintError($"记录{equipmentInfo.Id}状态记录处理失败:{ex}");
equipmentInfo.HandleStage = (byte)(equipmentInfo.HandleStage ^ EquipmentDataRecord.SET_STATUS_ERROR);
}
finally
{
//设置状态为已经处理
equipmentInfo.IsHandle = true;
//Context.Update(equipmentInfo);
//Context.SaveChanges();
}
}
try
{
if (statusRecords.Count > 0)
{
//实时状态更新
Context.EquipmentStatusRecords.Remove(x => x.EquipmentCode == equipmentSN);
Context.EquipmentStatusRecords.Add(statusRecords.LastOrDefault());
//历史状态
Context.Update(statusRecords.FirstOrDefault());
statusRecords.Remove(statusRecords.FirstOrDefault());
if (statusRecords.Count > 0)
Context.EquipmentStatusRecordHistorys.AddRange(statusRecords);
Context.SaveChanges();
}
}
catch (Exception ex)
{
SystemLog.PrintError($"批量更新设备状态{ex}");
}
#endregion
}
/// <summary>
/// 获取设备当前状态
/// </summary>
/// <param name="equipmentDataRecord"></param>
/// <returns></returns>
public virtual EquipmentStatusRecordStatus? GetEquipmentStatus(EquipmentDataRecord equipmentInfo)
{
EquipmentStatusRecordStatus? equipmentStatus = null;
var totalError = GetPropValue(equipmentInfo, SRMProps.TotalError);
//故障
if (string.IsNullOrWhiteSpace(totalError))
{
SystemLog.PrintError($"记录{equipmentInfo.Id}的totalError属性无有效数据");
}
else if (totalError == "True")
{
equipmentStatus = EquipmentStatusRecordStatus.Error;
}
else
{
var operationModel = GetPropValue(equipmentInfo, SRMProps.OperationModel);
var fork1TaskExcuteStatus = GetPropValue(equipmentInfo, SRMProps.Fork1TaskExcuteStatus);
if (string.IsNullOrWhiteSpace(operationModel) || string.IsNullOrWhiteSpace(fork1TaskExcuteStatus))
{
SystemLog.PrintError($"记录{equipmentInfo.Id}的operationModel属性无有效数据{operationModel}或fork1TaskExcuteStatus 无有效数据{fork1TaskExcuteStatus}");
}
if (operationModel == SRMOperationModel.Maintain.GetIndexString())
{//维修
//equipmentStatus = EquipmentStatusRecordStatus.Maintain;
equipmentStatus = EquipmentStatusRecordStatus.Free;
}
else if (operationModel == SRMOperationModel.Manual.GetIndexString()
|| operationModel == SRMOperationModel.StandAlone.GetIndexString()
|| operationModel == SRMOperationModel.Airborne.GetIndexString())
{
equipmentStatus = EquipmentStatusRecordStatus.Free;
}
else if (operationModel == SRMOperationModel.Online.GetIndexString()
&& fork1TaskExcuteStatus == SRMTaskExcuteStatus.TaskExecuting.GetIndexString())
{
equipmentStatus = EquipmentStatusRecordStatus.Running;
}
else if (operationModel == SRMOperationModel.Online.GetIndexString()
&& fork1TaskExcuteStatus == SRMTaskExcuteStatus.Standby.GetIndexString())
{
equipmentStatus = EquipmentStatusRecordStatus.Free;
}
else if (operationModel == SRMOperationModel.Online.GetIndexString()
&& (fork1TaskExcuteStatus == SRMTaskExcuteStatus.TaskInterruptError.GetIndexString()
|| fork1TaskExcuteStatus == SRMTaskExcuteStatus.TaskSendError.GetIndexString()))
{
equipmentStatus = EquipmentStatusRecordStatus.Free;
}
}
return equipmentStatus;
}
//public virtual EquipmentStatusRecordStatus? GetEquipmentStatus(EquipmentDataRecord equipmentInfo)
//{
// EquipmentStatusRecordStatus? equipmentStatus = null;
// var totalError = GetPropValue(equipmentInfo, SRMProps.TotalError);
// //故障
// if (string.IsNullOrWhiteSpace(totalError))
// {
// SystemLog.PrintError($"记录{equipmentInfo.Id}的totalError属性无有效数据");
// }
// else if (totalError == "True")
// {
// equipmentStatus = EquipmentStatusRecordStatus.Error;
// }
// else
// {
// var operationModel = GetPropValue(equipmentInfo, SRMProps.OperationModel);
// var fork1TaskExcuteStatus = GetPropValue(equipmentInfo, SRMProps.Fork1TaskExcuteStatus);
// if (string.IsNullOrWhiteSpace(operationModel) || string.IsNullOrWhiteSpace(fork1TaskExcuteStatus))
// {
// SystemLog.PrintError($"记录{equipmentInfo.Id}的operationModel属性无有效数据{operationModel}或fork1TaskExcuteStatus 无有效数据{fork1TaskExcuteStatus}");
// }
// if (operationModel == SRMOperationModel.Maintain.GetIndexString())
// {//维修
// equipmentStatus = EquipmentStatusRecordStatus.Maintain;
// }
// else if (operationModel == SRMOperationModel.Manual.GetIndexString()
// || operationModel == SRMOperationModel.StandAlone.GetIndexString()
// || operationModel == SRMOperationModel.Airborne.GetIndexString())
// {
// equipmentStatus = EquipmentStatusRecordStatus.Manual;
// }
// else if (operationModel == SRMOperationModel.Online.GetIndexString()
// && fork1TaskExcuteStatus == SRMTaskExcuteStatus.TaskExecuting.GetIndexString())
// {
// equipmentStatus = EquipmentStatusRecordStatus.Running;
// }
// else if (operationModel == SRMOperationModel.Online.GetIndexString()
// && fork1TaskExcuteStatus == SRMTaskExcuteStatus.Standby.GetIndexString())
// {
// equipmentStatus = EquipmentStatusRecordStatus.Free;
// }
// else if (operationModel == SRMOperationModel.Online.GetIndexString()
// && (fork1TaskExcuteStatus == SRMTaskExcuteStatus.TaskInterruptError.GetIndexString()
// || fork1TaskExcuteStatus == SRMTaskExcuteStatus.TaskSendError.GetIndexString()))
// {
// equipmentStatus = EquipmentStatusRecordStatus.TaskExcuteError;
// }
// }
// return equipmentStatus;
//}
/// <summary>
/// 记录设备状态
/// </summary>
/// <param name="srm"></param>
/// <param name="records"></param>
/// <param name="equipmentStatusRecordStatus"></param>
public void RecordEquipmentStatus(EquipmentDataRecord srm, List<EquipmentStatusRecordHistory> records, EquipmentStatusRecordStatus equipmentStatusRecordStatus)
{
var record = records.LastOrDefault(t => t.Status == equipmentStatusRecordStatus.ToString() && !t.IsEnd);
if (!Program.EquipmentInfos.TryGetValue(srm.EquipmentCode, out var equipment))
{
SystemLog.PrintError($"设备{srm.EquipmentCode}不存在");
}
DateTime acceptTime = DateTimeOffset.FromUnixTimeSeconds(srm.Timestamp).LocalDateTime;
EquipmentStatusRecordHistory equipmentStatusRecord = new EquipmentStatusRecordHistory();
//Context.UnitOfWork.GetOrBeginTransaction();
try
{
if (record == null)
{
//新建
equipmentStatusRecord.EquipmentCode = srm.EquipmentCode;
equipmentStatusRecord.EquipmentName = equipment.Name;
equipmentStatusRecord.EquipmentType = equipment.EquipmentType.Code;
equipmentStatusRecord.Status = equipmentStatusRecordStatus.ToString();
equipmentStatusRecord.UpdateTime = acceptTime;
equipmentStatusRecord.CreateTime = acceptTime;
equipmentStatusRecord.HandleTime = DateTime.Now;
//更新上一个状态
var lastRecord = records.LastOrDefault();
if (lastRecord != null)
{
lastRecord.UpdateTime = acceptTime;
lastRecord.IsEnd = true;
lastRecord.StatusDuration = (acceptTime - (DateTime)lastRecord.CreateTime).TotalSeconds;
// Context.EquipmentStatusRecordHistorys.Update(lastRecord);
}
records.Add(equipmentStatusRecord);
// Context.EquipmentStatusRecordHistorys.Add(equipmentStatusRecord);
}
else
{
//更新
record.UpdateTime = acceptTime;
record.StatusDuration = (acceptTime - (DateTime)record.CreateTime).TotalSeconds;
// Context.EquipmentStatusRecordHistorys.Update(record);
}
//Context.SaveChanges();
//Context.UnitOfWork.Commit();
}
catch (Exception ex)
{
//Context.UnitOfWork.Rollback();
//修改数据记录
srm.HandleStage = (byte)(srm.HandleStage ^ EquipmentDataRecord.SET_STATUS_ERROR);
SystemLog.PrintError($"记录{srm.Id}更新设备状态失败{ex}");
}
}
/// <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}");
}
}
public string? GetPropValue(EquipmentDataRecord equipmentInfo, Enum Prop)
{
var equipment = Program.EquipmentInfos[equipmentInfo.EquipmentCode];
var address = equipment.EquipmentPropTemps.Find(x => x.PropCode == Prop.ToString()).Address;
if (string.IsNullOrWhiteSpace(address))
{
SystemLog.PrintError($"{Prop}地址不存在,请检查设备模板");
return null;
}
var value = equipmentInfo.Props[address];
return value;
}
/// <summary>
/// 结束状态
/// </summary>
public void FinalState(IEnumerable<EquipmentDataRecord> records)
{
var first = records?.FirstOrDefault();
DateTime lastAcceptTime = DateTime.Now;
if (first != null)
{
lastAcceptTime = DateTimeOffset.FromUnixTimeSeconds(first.Timestamp).LocalDateTime;
}
var endRecords = Context.EquipmentStatusRecordHistorys.Where(x => !x.IsEnd && x.EquipmentType == EquipmentType.ToString() && (lastAcceptTime - (DateTime)x.UpdateTime).TotalSeconds > StatusTimeOut).WithLock(SqlServerLock.NoLock).ToList();
var addRecords = new List<EquipmentStatusRecordHistory>();
endRecords.ForEach(x =>
{
if (x.Status != EquipmentStatusRecordStatus.Free.ToString())
{
var updatetime = first == null ? x.UpdateTime : lastAcceptTime;
x.UpdateTime = updatetime;
x.IsEnd = true;
x.StatusDuration = (lastAcceptTime - (DateTime)x.CreateTime).TotalSeconds;
var newStatus = new EquipmentStatusRecordHistory()
{
CreateTime = updatetime,
UpdateTime = updatetime,
Status = EquipmentStatusRecordStatus.Free.ToString(),
EquipmentCode = x.EquipmentCode,
EquipmentName = x.EquipmentName,
IsEnd = false,
FactoryCode = x.FactoryCode,
Remark = "超过超时时间未上传数据,重置设备状态为空闲",
};
addRecords.Add(newStatus);
}
});
if (endRecords.Count > 0)
{
Context.UnitOfWork.GetOrBeginTransaction();
try
{
Context.EquipmentStatusRecordHistorys.UpdateRange(endRecords);
if (addRecords.Count > 0)
{
Context.EquipmentStatusRecordHistorys.AddRange(addRecords);
////移除原有数据
//Context.EquipmentStatusRecords.Remove(x => addRecords.Any(y => y.EquipmentCode == x.EquipmentCode));
////插入新数据
//Context.EquipmentStatusRecords.AddRange(addRecords);
}
Context.SaveChanges();
Context.UnitOfWork.Commit();
}
catch (Exception ex)
{
SystemLog.PrintError($"{ex}");
Context.UnitOfWork.Rollback();
}
}
}
/// <summary>
/// 结束报警
/// </summary>
public void FinalAlarm(IEnumerable<EquipmentDataRecord> records)
{
var first = records?.FirstOrDefault();
var lastAcceptTime = DateTime.Now;
if (first != null)
{
lastAcceptTime = DateTimeOffset.FromUnixTimeSeconds(first.Timestamp).LocalDateTime;
}
var endRecords = Context.EquipmentAlarmRecords.Where(x => !x.IsEnd && x.EquipmentType == EquipmentType.ToString() && (lastAcceptTime - (DateTime)x.UpdateTime).TotalSeconds > AlarmTimeOut).ToList();
if (endRecords.Count > 0)
{
endRecords.ForEach(x =>
{
x.ErrorDuration = ((DateTime)x.UpdateTime - (DateTime)x.CreateTime).TotalSeconds;
x.IsEnd = true;
});
Context.UpdateRange(endRecords);
Context.SaveChanges();
}
}
}
}