Program.cs
31.4 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
using HHECS.BllModel;
using HHECS.DAQHandle;
using HHECS.DAQHandle.Common.Utils;
using HHECS.DAQHandle.Dto;
using HHECS.DAQHandle.EquipmentHandle;
using HHECS.DAQHandle.EquipmentHandle.SRM;
using HHECS.DAQHandle.EquipmentHandle.WeldRobot;
using HHECS.DAQShared.Common.Enums;
using HHECS.DAQShared.Dto;
using HHECS.DAQShared.Models;
using LinqKit;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.Exceptions;
using System.Configuration;
using System.Diagnostics;
using System.Text;
using System.Text.Json;
internal class Program
{
private static void Main(string[] args)
{
try
{
var appConfigResult = LoadAppConfig();
if (!appConfigResult.Success)
{
SystemLog.PrintError($"加载配置文件信息失败:{appConfigResult.Msg}");
return;
}
var appConfig = appConfigResult.Data;
var result = ValidationConfig(appConfig);
if (!result.Success)
{
SystemLog.PrintError($"配置信息校验失败:{result.Msg}");
return;
}
var connectionString = ConfigurationManager.ConnectionStrings[appConfig.IsProductionEnvironment ? "Production" : "Development"].ConnectionString;
GlobalVar.SetConnectionString(connectionString);
UpdateClientStatus();
StartupRabbitMQ(appConfig);
}
catch (Exception ex)
{
SystemLog.PrintWarn($"程序启动出现异常:{ex.Message}");
}
}
/// <summary>
/// 数据库分表处理
/// </summary>
/// <param name="config"></param>
[Obsolete]
private static void Startup(AppConfig config)
{
var equipments = new List<Equipment>();
var equipmentTypes = new List<EquipmentType>();
var equipmentTypeCodes = config.EquipmentTypeCodes;
SystemLog.PrintInfo($"正在初始化数据...");
var lastReloadTime = DateTime.MinValue;
while (true)
{
try
{
if ((DateTime.Now - lastReloadTime).TotalMinutes >= 1)
{
var result = InitialData(equipmentTypeCodes, ref equipments, ref equipmentTypes);
if (!result.Success)
{
SystemLog.PrintError($"初始化数据失败:{result.Msg}");
continue;
}
}
if (equipmentTypes.Count == 0)
{
SystemLog.PrintError($"获取设备类型[{string.Join(',', equipmentTypeCodes)}]数据失败,数据为空!");
continue;
}
Stopwatch stopwatch = Stopwatch.StartNew();
var freeSql = GlobalVar.FreeSql;
//获取所有设备记录表名称,FreeSql的分表查询,时间跨天后不能获取到新表,这里使用自定义方式实现
var tableNames = freeSql.Select<object>().WithSql("SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_name LIKE 'daq_equipment_data_record%'").OrderBy(x => "table_name").ToList<string>();
var tasks = new List<Task>();
foreach (var currentEquipmentType in equipmentTypes)
{
tasks.Add(Task.Run(() =>
{
Stopwatch stopwatch = Stopwatch.StartNew();
_ = Enum.TryParse<EquipmentTypeConst>(currentEquipmentType.Code, out var equipmentTypeCode);
var handleResult = CreateAnalysis(equipments, currentEquipmentType, config);
//未知类型,则跳过
if (!handleResult.Success)
{
SystemLog.PrintWarn($"未实现设备类型[{currentEquipmentType.Code}]对应的处理方法");
return;
}
var handle = handleResult.Data;
try
{
var limit = config.ProcessingDataVolume;
if (equipmentTypeCode == EquipmentTypeConst.StationMonitor)
{
//站台数据量比较大,目前不处理站台状态和报警,所以每次多取一些数据
limit *= 5;
}
using var equipmentDataRecordRepository = freeSql.GetRepository<EquipmentDataRecord>();
var equipmentCodes = equipments.Where(x => x.EquipmentTypeId == currentEquipmentType.Id).Select(x => x.Code).ToList();
//缓存有数据的表名称集合
var cacheTableNames = new List<string>();
var equipmentDataRecords = new List<EquipmentDataRecord>();
foreach (var tableName in tableNames)
{
//达到设定数量时停止往后查询
if (equipmentDataRecords.Count == limit)
{
break;
}
var filter = PredicateBuilder.New<EquipmentDataRecord>(true);
filter = filter.And(x => equipmentCodes.Contains(x.EquipmentCode));
filter = filter.And(x => !x.IsHandle);
if (config.Version != 0)
{
filter = filter.And(x => x.Version == config.Version);
}
//本次查询数量
var currentLimit = limit - equipmentDataRecords.Count;
var temps = freeSql.Queryable<EquipmentDataRecord>().AsTable((type, oldName) => tableName)
.Where(filter)
.OrderBy(x => x.Timestamp).Take(currentLimit).ToList();
if (temps.Count > 0)
{
equipmentDataRecords.AddRange(temps);
cacheTableNames.Add(tableName);
}
}
if (equipmentDataRecords.Count == 0)
{
SystemLog.PrintInfo($"设备类型[{currentEquipmentType.Code}]记录数据为空,跳过解析,耗时:{stopwatch.ElapsedMilliseconds}ms");
return;
}
var result = handle.Execute(equipmentDataRecords);
if (!result.Success)
{
SystemLog.PrintError($"设备类型[{currentEquipmentType.Code}]解析失败,{result.Msg},数量{equipmentDataRecords.Count},耗时:{stopwatch.ElapsedMilliseconds}ms");
return;
}
//删除数据
var ids = equipmentDataRecords.Select(x => x.Id).ToList();
foreach (var tableName in cacheTableNames)
{
freeSql.Delete<EquipmentDataRecord>().AsTable(tableName).Where(x => ids.Contains(x.Id)).CommandTimeout(300).ExecuteAffrows();
}
SystemLog.PrintSuccess($"设备类型[{currentEquipmentType.Code}]解析完成,数量{equipmentDataRecords.Count},耗时:{stopwatch.ElapsedMilliseconds}ms");
}
catch (Exception ex)
{
SystemLog.PrintError($"[{handle.GetType().Name}]线程数据解析出现异常:{ex.Message}");
}
}));
}
Task.WaitAll(tasks.ToArray());
Thread.Sleep(1000);
const string tempString = "——————————————————";
Console.WriteLine($"{tempString}[总耗时:{stopwatch.Elapsed}]{tempString}");
}
catch (Exception ex)
{
SystemLog.PrintError($"程序异常:{ex.Message}");
}
}
}
/// <summary>
/// RabbitMQ处理
/// </summary>
/// <param name="config"></param>
private static void StartupRabbitMQ(AppConfig config)
{
var equipments = new List<Equipment>();
var equipmentTypes = new List<EquipmentType>();
var factory = new ConnectionFactory()
{
HostName = "172.16.29.90",
UserName = "consumer",
Password = "Aa123456",
VirtualHost = config.IsProductionEnvironment ? "hhecs.daq" : "hhecs.daq.development"
};
using var connection = factory.CreateConnectionAsync().GetAwaiter().GetResult();
var actionA = DateTime.MinValue;
while (true)
{
try
{
Task.Delay(1000).Wait();
if ((DateTime.Now - actionA).TotalMinutes >= 10)
{
SyncBaseEquipmentData();
actionA = DateTime.Now;
}
var result = InitialData(config.EquipmentTypeCodes, ref equipments, ref equipmentTypes);
if (!result.Success)
{
SystemLog.PrintError($"加载设备基础数据失败:{result.Msg}");
continue;
}
if (equipmentTypes.Count == 0)
{
SystemLog.PrintError("设备类型数据为空!");
continue;
}
var actionTime = DateTime.Now;
var tasks = new List<Task>();
foreach (var equipmentType in equipmentTypes)
{
tasks.Add(Task.Run(async () =>
{
try
{
string exchangeName = equipmentType.Code;
//消费者
ushort limit = (ushort)config.ProcessingDataVolume;
var queueName = $"{equipmentType.Code}Queue";
var channelConsumer = await connection.CreateChannelAsync();
await channelConsumer.BasicQosAsync(0, limit, false);
await channelConsumer.ExchangeDeclareAsync(exchangeName, ExchangeType.Topic, true);
await channelConsumer.QueueDeclareAsync(queueName, true, false, false);
await channelConsumer.QueueBindAsync(queueName, exchangeName, $"{equipmentType.Code}.#");
var keyValues = new Dictionary<ulong, EquipmentDataDto>();
var consumer = new AsyncEventingBasicConsumer(channelConsumer);
var lastExecuteTime = DateTime.Now;
consumer.ReceivedAsync += async (model, ea) =>
{
try
{
uint currentLimit = limit;
var jsonString = Encoding.UTF8.GetString(ea.Body.ToArray());
var message = JsonSerializer.Deserialize<EquipmentDataDto>(jsonString);
if (message == null)
{
await channelConsumer.BasicAckAsync(ea.DeliveryTag, false);
return;
}
if (keyValues.Count < currentLimit)
{
keyValues.TryAdd(ea.DeliveryTag, message);
//Console.WriteLine($"[{equipmentType.Code}]Received message: {ea.DeliveryTag}");
}
if (keyValues.Count > 0 && (keyValues.Count >= currentLimit || (DateTime.Now - lastExecuteTime).TotalSeconds >= 5))
{
var stopwatch = Stopwatch.StartNew();
var handleResult = CreateAnalysis(equipments, equipmentType, config);
if (!handleResult.Success)
{
SystemLog.PrintWarn($"未实现设备类型[{equipmentType.Code}]对应的处理方法");
await channelConsumer.BasicNackAsync(ea.DeliveryTag, true, true);
return;
}
var handle = handleResult.Data;
var records = keyValues.Select(x =>
{
var data = x.Value;
return new EquipmentDataRecord
{
Id = data.Plmeid,
EquipmentCode = data.EquipmentSN,
Tags = JsonSerializer.Serialize(data.Reported),
Timestamp = data.Timestamp,
Version = data.Version,
CreateTime = DateTime.Now
};
}).ToList();
var result = handle.Execute(records);
if (!result.Success)
{
SystemLog.PrintError($"[{equipmentType.Code}]处理失败:{result.Msg}");
return;
}
await channelConsumer.BasicAckAsync(ea.DeliveryTag, true);
stopwatch.Stop();
SystemLog.PrintSuccess($"[{equipmentType.Code}]成功处理{records.Count}条记录数据,耗时:{stopwatch.ElapsedMilliseconds}ms");
keyValues.Clear();
lastExecuteTime = DateTime.Now;
}
}
catch (ObjectDisposedException) { }
catch (AlreadyClosedException) { }
catch (Exception ex)
{
SystemLog.PrintError($"[{equipmentType.Code}]Received事件异常:{ex.Message}");
}
};
await channelConsumer.BasicConsumeAsync(queueName, false, consumer);
while (DateTime.Now - actionTime <= TimeSpan.FromMinutes(1))
{
await Task.Delay(100);
}
await channelConsumer.CloseAsync();
}
catch (TimeoutException) { }
catch (AlreadyClosedException) { }
catch (Exception ex)
{
SystemLog.PrintError($"[{equipmentType.Code}]处理线程出现异常:{ex.Message}");
}
}));
}
Task.WaitAll(tasks.ToArray());
}
catch (Exception ex)
{
SystemLog.PrintError($"主线程异常:{ex.Message}");
}
}
}
/// <summary>
/// 加载配置文件信息
/// </summary>
/// <returns></returns>
private static BllResult<AppConfig> LoadAppConfig()
{
try
{
_ = int.TryParse(ConfigurationManager.AppSettings["DataTimeOut"], out int dataTimeOutValue);
_ = int.TryParse(ConfigurationManager.AppSettings["ProcessingDataVolume"], out int processingDataVolumeValue);
_ = int.TryParse(ConfigurationManager.AppSettings["DataRetentionDays"], out int dataRetentionDaysValue);
_ = int.TryParse(ConfigurationManager.AppSettings["Version"], out var version);
_ = bool.TryParse(ConfigurationManager.AppSettings["IsProductionEnvironment"], out var isProductionEnvironmentValue);
_ = Guid.TryParse((ConfigurationManager.AppSettings["ClientId"]), out var clientIdValue);
var equipmentTypeCodes = ConfigurationManager.AppSettings["EquipmentType"];
if (processingDataVolumeValue <= 0)
{
processingDataVolumeValue = 100;
}
if (isProductionEnvironmentValue)
{
Console.Title = "IOT数据处理端";
}
else
{
Console.Title = "IOT数据处理端(测试版)";
}
var appConfig = new AppConfig
{
ClientId = clientIdValue,
DataTimeOut = dataTimeOutValue,
IsProductionEnvironment = isProductionEnvironmentValue,
ProcessingDataVolume = processingDataVolumeValue,
EquipmentTypeCodes = equipmentTypeCodes?.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)).ToList() ?? new List<string>(),
Version = version
};
return BllResultFactory.Success(appConfig);
}
catch (Exception ex)
{
return BllResultFactory.Error<AppConfig>(ex.Message);
}
}
/// <summary>
/// 配置信息校验
/// </summary>
/// <param name="appConfig"></param>
/// <returns></returns>
private static BllResult ValidationConfig(AppConfig appConfig)
{
try
{
if (appConfig.EquipmentTypeCodes == null || appConfig.EquipmentTypeCodes.Count == 0)
{
SystemLog.PrintWarn($"设备类型[{nameof(appConfig.EquipmentTypeCodes)}]未配置,将默认匹配所有设备");
}
if (appConfig.Version == 0)
{
SystemLog.PrintWarn($"程序版本[{nameof(appConfig.Version)}]未配置,将匹配所有版本设备记录");
}
return BllResultFactory.Success();
}
catch (Exception ex)
{
return BllResultFactory.Error(ex.Message);
}
}
private static BllResult<IAnalysis> CreateAnalysis(List<Equipment> allEquipments, EquipmentType equipmentType, AppConfig config)
{
try
{
_ = Enum.TryParse<EquipmentTypeConst>(equipmentType.Code, out var equipmentTypeCode);
var parameter = new AnalysisParameter
{
Equipments = allEquipments.Where(x => x.EquipmentTypeId == equipmentType.Id).ToList(),
EquipmentType = equipmentType,
AppConfig = config,
EquipmentTotalAlarmCode = equipmentTypeCode switch
{
EquipmentTypeConst.SingleForkSRM or
EquipmentTypeConst.SingleForkSRMV2 => SRMProps.TotalError.ToString(),
EquipmentTypeConst.DoubleForkSRM or
EquipmentTypeConst.DoubleForkSRMV2 => SRMProps.TotalError.ToString(),
EquipmentTypeConst.SingleForkSSRM or
EquipmentTypeConst.SingleForkSSRMV2 => SRMProps.TotalError.ToString(),
EquipmentTypeConst.SingleForkSSRMV132 => SRMProps.TotalError.ToString(),
EquipmentTypeConst.WeldRobot => RobotProp.Alarm.ToString(),
EquipmentTypeConst.WeldRobotV2 => RobotV2Prop.Alarm.ToString(),
EquipmentTypeConst.AGVForklift => AGVForkliftProp.Error.ToString(),
EquipmentTypeConst.RGVStation => RGVStationProps.Fault.ToString(),
EquipmentTypeConst.StationMonitor => StationMonitorProp.StationError.ToString(),
EquipmentTypeConst.Hoist => HoistProps.HoistStatus.ToString(),
EquipmentTypeConst.CNC => CNCProp.RedLight.ToString(),
EquipmentTypeConst.SingleForkRGV or
EquipmentTypeConst.SingleForkRGV_LDHW_V1 or
EquipmentTypeConst.SingleForkRGV_LDHW_V2 or
EquipmentTypeConst.SingleForkRGV_LDHW_V3 => SingleForkRGVProp.TotalError.ToString(),
_ => string.Empty,
}
};
IAnalysis handle = equipmentTypeCode switch
{
EquipmentTypeConst.SingleForkSRM or
EquipmentTypeConst.SingleForkSRMV2 => new SingleForkSRMAnalysis(parameter),
EquipmentTypeConst.DoubleForkSRM or
EquipmentTypeConst.DoubleForkSRMV2 => new DoubleForkSRMAnalysis(parameter),
EquipmentTypeConst.SingleForkSSRM or
EquipmentTypeConst.SingleForkSSRMV2 => new SingleForkSSRMAnalysis(parameter),
EquipmentTypeConst.SingleForkSSRMV132 => new SingleForkSSRMV132Analysis(parameter),
EquipmentTypeConst.WeldRobot => new WeldRobotAnalysis(parameter),
EquipmentTypeConst.WeldRobotV2 => new WeldRobotV2Analysis(parameter),
EquipmentTypeConst.AGVForklift => new AGVForkliftAnalysis(parameter),
EquipmentTypeConst.RGVStation => new RGVStationAnalysis(parameter),
EquipmentTypeConst.SingleForkRGV or
EquipmentTypeConst.SingleForkRGV_LDHW_V1 or
EquipmentTypeConst.SingleForkRGV_LDHW_V2 or
EquipmentTypeConst.SingleForkRGV_LDHW_V3
=> new SingleForkRGVAnalysis(parameter),
EquipmentTypeConst.StationMonitor => new StationMonitorAnalysis(parameter),
EquipmentTypeConst.Hoist => new HoistAnalysis(parameter),
EquipmentTypeConst.CNC => new CNCAnalysis(parameter),
_ => null
};
return BllResultFactory.Success(handle);
}
catch (Exception ex)
{
return BllResultFactory.Error<IAnalysis>(ex.Message);
}
}
/// <summary>
/// 初始化数据
/// </summary>
/// <param name="equipmentTypeCodes">设备类型编号</param>
/// <param name="equipments">设备集合</param>
/// <param name="equipmentTypes">设备类型集合</param>
/// <remarks>则刷新数据</remarks>
private static BllResult InitialData(List<string> equipmentTypeCodes, ref List<Equipment> equipments, ref List<EquipmentType> equipmentTypes)
{
try
{
using var freeSql = GlobalVar.FreeSql;
var equipmentRepository = freeSql.GetRepository<Equipment>();
var equipmentPropRepository = freeSql.GetRepository<EquipmentProp>();
var equipmentTypeRepository = freeSql.GetRepository<EquipmentType>();
var filter = PredicateBuilder.New<EquipmentType>(true);
if (equipmentTypeCodes.Count > 0)
{
filter = filter.And(x => equipmentTypeCodes.Contains(x.Code));
}
equipmentTypes = equipmentTypeRepository.Where(filter).ToList();
var equipmentTypeIds = equipmentTypes.Select(x => x.Id).ToList();
var equipmentIds = equipmentRepository.Where(x => equipmentTypeIds.Contains(x.EquipmentTypeId)).ToList(x => x.Id);
var equipmentTotal = equipmentIds.Count;
var equipmentPropTotal = equipmentPropRepository.Where(x => equipmentIds.Contains(x.EquipmentId)).Count();
equipments = equipmentRepository.Where(x => equipmentTypeIds.Contains(x.EquipmentTypeId)).IncludeMany(x => x.EquipmentProps).ToList();
foreach (var item in equipments)
{
item.EquipmentType = equipmentTypes.Find(x => x.Id == item.EquipmentTypeId);
}
return BllResultFactory.Success();
}
catch (Exception ex)
{
return BllResultFactory.Error(ex.Message);
}
}
/// <summary>
/// 更新客户端状态
/// </summary>
private static void UpdateClientStatus()
{
Task.Run(async () =>
{
while (true)
{
try
{
await Task.Delay(5000);
using var clientStatusRepository = GlobalVar.FreeSql.GetRepository<ClientStatus>();
//更新客户端状态
_ = Guid.TryParse(ConfigurationManager.AppSettings["ClientId"], out var clientId);
if (clientId != Guid.Empty)
{
var client = clientStatusRepository.Where(x => x.ClientKeys == clientId).First();
if (client != null)
{
clientStatusRepository.Attach(client);
client.LastSeenDate = DateTime.Now;
clientStatusRepository.Update(client);
}
}
}
catch (Exception ex)
{
SystemLog.PrintError($"客户端状态更新线程异常:{ex.Message}");
}
}
});
}
/// <summary>
/// 同步IOT基础设备数据
/// </summary>
private static void SyncBaseEquipmentData()
{
try
{
var stopwatch = Stopwatch.StartNew();
SystemLog.PrintInfo($"正在同步基础设备数据......");
var total = 0;
var freeSql = GlobalVar.FreeSql;
using var iotEquipmentRepository = freeSql.GetRepository<BaseEquipment>();
var iotEquipments = iotEquipmentRepository.Where(x => true).ToList();
using var equipmentRepository = freeSql.GetRepository<Equipment>();
using var equipmentStatusHistoryRepository = freeSql.GetRepository<EquipmentStatusRecordHistory>();
using var equipmentAlarmRepository = freeSql.GetRepository<EquipmentAlarmRecord>();
using var equipmentAlarmRecordDetailRepository = freeSql.GetRepository<EquipmentAlarmRecordDetail>();
var _limit = 1000;
foreach (var iotEquipment in iotEquipments)
{
//同步设备名称
var equipment = equipmentRepository.Where(x => x.Code == iotEquipment.EquipmentCode && x.Name != iotEquipment.EquipmentName).First();
if (equipment != null)
{
equipmentRepository.Attach(equipment);
equipment.Name = iotEquipment.EquipmentName;
total += equipmentRepository.Update(equipment);
}
//纠正设备历史状态数据
var equipmentStatusHistorys = equipmentStatusHistoryRepository.Where(x => x.EquipmentCode == iotEquipment.EquipmentCode && x.EquipmentName != iotEquipment.EquipmentName).Take(_limit).ToList();
foreach (var equipmentStatusHistory in equipmentStatusHistorys)
{
equipmentStatusHistoryRepository.Attach(equipmentStatusHistory);
equipmentStatusHistory.EquipmentName = iotEquipment.EquipmentName;
}
total += equipmentStatusHistoryRepository.Update(equipmentStatusHistorys);
//纠正设备报警数据
var alarms = equipmentAlarmRepository.Where(x => x.EquipmentCode == iotEquipment.EquipmentCode && x.EquipmentName != iotEquipment.EquipmentName).Take(1000).ToList();
foreach (var alarm in alarms)
{
equipmentAlarmRepository.Attach(alarm);
alarm.EquipmentName = iotEquipment.EquipmentName;
}
total += equipmentAlarmRepository.Update(alarms);
//纠正设备报警明细数据
var alarmDetails = equipmentAlarmRecordDetailRepository.Where(x => x.EquipmentCode == iotEquipment.EquipmentCode && x.EquipmentName != iotEquipment.EquipmentName).Take(_limit).ToList();
foreach (var alarmRecordDetail in alarmDetails)
{
equipmentAlarmRecordDetailRepository.Attach(alarmRecordDetail);
alarmRecordDetail.EquipmentName = iotEquipment.EquipmentName;
}
total += equipmentAlarmRecordDetailRepository.Update(alarmDetails);
}
stopwatch.Stop();
SystemLog.PrintSuccess($"基础数据同步完成,变更数量:{total},耗时:{stopwatch.ElapsedMilliseconds}ms");
}
catch (Exception ex)
{
SystemLog.PrintError($"同步基础设备数据线程异常:{ex.Message}");
}
}
/// <summary>
/// 生成设备数据
/// </summary>
private static void GenerateEquipmentData()
{
try
{
var freeSql = GlobalVar.FreeSql;
var equipmentCodes = new List<string>
{
"HH-JLL-20240813-1-B001",
"HH-JLL-20240813-1-B002",
"HH-JLL-20240813-1-B003",
"HH-JLL-20240813-1-B004"
};
var allEquipment = freeSql.Queryable<Equipment>().Where(x => equipmentCodes.Contains(x.Code)).ToList();
foreach (var group in allEquipment.GroupBy(x => x.EquipmentTypeId))
{
var equipmentType = freeSql.Queryable<EquipmentType>().Where(x => x.Id == group.Key).First();
if (equipmentType == null)
{
continue;
}
var equipmentTypePropTemplate = freeSql.Queryable<EquipmentTypePropTemplate>().Where(x => x.EquipmentTypeId == equipmentType.Id).ToList();
if (equipmentTypePropTemplate.Count == 0)
{
continue;
}
foreach (var equipment in group)
{
//设备属性
if (freeSql.Queryable<EquipmentProp>().Where(x => x.EquipmentId == equipment.Id).Any())
{
//有数据则跳过
continue;
}
var temps = equipmentTypePropTemplate.Select(x => new EquipmentProp
{
Code = x.Code,
Name = x.Name,
EquipmentId = equipment.Id,
Remark = x.Description,
Value = string.Empty,
Address = x.Address,
Created = DateTime.Now,
}).ToList();
var total = freeSql.Insert(temps).ExecuteAffrows();
SystemLog.PrintSuccess($"设备[{equipment.Code}]成功生成{total}条设备属性数据");
}
}
}
catch (Exception ex)
{
SystemLog.PrintError($"生成设备数据出现异常:{ex.Message}");
}
}
}