Program.cs
13.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
using HHECS.BllModel;
using HHECS.DAQHandle;
using HHECS.DAQHandle.Common.Enums;
using HHECS.DAQHandle.Common.Utils;
using HHECS.DAQHandle.DataAccess;
using HHECS.DAQHandle.Dto;
using HHECS.DAQHandle.EquipmentHandle;
using HHECS.DAQHandle.Models;
using HHECS.EquipmentModel;
using System.Configuration;
using System.Diagnostics;
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();
Startup(appConfig);
}
catch (Exception ex)
{
SystemLog.PrintWarn($"程序启动出现异常:{ex.Message}");
}
}
private static void Startup(AppConfig config)
{
var equipments = new List<EquipmentExtend>();
var equipmentTypes = new List<EquipmentType>();
var equipmentTypeCodes = config.EquipmentTypeCodes;
while (true)
{
try
{
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 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 parameter = new AnalysisParameter
{
Equipments = equipments.Where(x => x.EquipmentTypeId == currentEquipmentType.Id).ToList(),
EquipmentType = currentEquipmentType,
AppConfig = config,
EquipmentTotalAlarmCode = equipmentTypeCode switch
{
EquipmentTypeConst.SingleForkSRM => SRMProps.TotalError.ToString(),
EquipmentTypeConst.DoubleForkSRM => SRMProps.TotalError.ToString(),
EquipmentTypeConst.SingleForkSSRM => SRMProps.TotalError.ToString(),
EquipmentTypeConst.SingleForkSSRMV132 => SRMProps.TotalError.ToString(),
EquipmentTypeConst.WeldRobot => RobotProp.Alarm.ToString(),
EquipmentTypeConst.AGVForklift => "",//待完善
EquipmentTypeConst.RGVStation => RGVProps.Fault.ToString(),
EquipmentTypeConst.StationMonitor => StationProps.StationError.ToString(),
EquipmentTypeConst.Hoist => HoistProps.HoistStatus.ToString(),
_ => string.Empty,
}
};
IAnalysis handle = equipmentTypeCode switch
{
EquipmentTypeConst.SingleForkSRM => new SingleForkSRMAnalysis(parameter),
EquipmentTypeConst.DoubleForkSRM => new DoubleForkSRMAnalysis(parameter),
EquipmentTypeConst.SingleForkSSRM => new SingleForkSSRMAnalysis(parameter),
EquipmentTypeConst.SingleForkSSRMV132 => new SingleForkSSRMV132Analysis(parameter),
EquipmentTypeConst.WeldRobot => new WeldRobotAnalysis(parameter),
EquipmentTypeConst.AGVForklift => new AGVAnalysis(parameter),
EquipmentTypeConst.RGVStation => new RGVStationAnalysis(parameter),
EquipmentTypeConst.StationMonitor => new StationMonitorAnalysis(parameter),
EquipmentTypeConst.Hoist => new HoistAnalysis(parameter),
_ => null
};
//未知类型,则跳过
if (handle is null)
{
SystemLog.PrintWarn($"未实现设备类型[{currentEquipmentType.Code}]对应的处理方法");
return;
}
try
{
using var context = new DataContext();
var equipmentCodes = equipments.Where(x => x.EquipmentTypeId == currentEquipmentType.Id).Select(x => x.Code).ToList();
var equipmentDataRecords = context.EquipmentDataRecord
.Where(x => equipmentCodes.Contains(x.EquipmentCode) && !x.IsHandle && x.Version == config.Version)
.OrderBy(x => x.Timestamp).Take(config.ProcessingDataVolume).ToList();
var result = handle.Execute(equipmentDataRecords);
if (!result.Success)
{
SystemLog.PrintError($"设备类型[{currentEquipmentType.Code}]解析失败,{result.Msg},数量{equipmentDataRecords.Count},耗时{stopwatch.ElapsedMilliseconds}ms");
return;
}
context.EquipmentDataRecord.RemoveRange(equipmentDataRecords);
context.SaveChanges();
SystemLog.PrintInfo($"设备类型[{currentEquipmentType.Code}]解析完成,数量{equipmentDataRecords.Count},耗时{stopwatch.ElapsedMilliseconds}ms");
}
catch (Exception ex)
{
SystemLog.PrintError($"{handle.GetType().Name}线程数据解析出现异常:{ex.Message}");
}
}));
}
Task.WaitAll(tasks.ToArray());
Thread.Sleep(100);
const string tempString = "——————————————————";
Console.WriteLine($"{tempString}[总耗时:{stopwatch.Elapsed}]{tempString}");
}
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);
if (processingDataVolumeValue <= 0)
{
processingDataVolumeValue = 100;
}
if (isProductionEnvironmentValue)
{
Console.Title = "IOT数据处理端";
}
else
{
Console.Title = "IOT数据处理端(测试版)";
}
var appConfig = new AppConfig
{
ClientId = clientIdValue,
WarehouseCode = ConfigurationManager.AppSettings["WarehouseCode"],
DataTimeOut = dataTimeOutValue,
IsProductionEnvironment = isProductionEnvironmentValue,
ProcessingDataVolume = processingDataVolumeValue,
EquipmentTypeCodes = ConfigurationManager.AppSettings["EquipmentType"].Split(',').ToList(),
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 (string.IsNullOrWhiteSpace(appConfig.WarehouseCode))
{
return BllResultFactory.Error($"仓库编号[{nameof(appConfig.WarehouseCode)}]未配置!");
}
if (appConfig.EquipmentTypeCodes == null || appConfig.EquipmentTypeCodes.Count == 0)
{
return BllResultFactory.Error($"设备类型[{appConfig.EquipmentTypeCodes}]未配置!");
}
if (appConfig.Version == 0)
{
return BllResultFactory.Error($"程序版本[{appConfig.Version}]未配置!");
}
return BllResultFactory.Success();
}
catch (Exception ex)
{
return BllResultFactory.Error(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<EquipmentExtend> equipments, ref List<EquipmentType> equipmentTypes)
{
try
{
var context = new DataContext();
if (equipmentTypes.Count == 0)
{
equipmentTypes = context.EquipmentType.Where(x => equipmentTypeCodes.Contains(x.Code)).IncludeMany(x => x.EquipmentTypePropTemplates).ToList();
}
var equipmentTypeIds = equipmentTypes.Select(x => x.Id).ToList();
var equipmentIds = context.Equipment.Where(x => equipmentTypeIds.Contains(x.EquipmentTypeId)).ToList(x => x.Id);
var equipmentTotal = equipmentIds.Count;
var equipmentPropTotal = context.EquipmentProp.Where(x => equipmentIds.Contains(x.EquipmentId)).Count();
if (equipments.Count != equipmentTotal || equipments.SelectMany(x => x.EquipmentProps).Count() != equipmentPropTotal)
{
equipments = context.Equipment.Where(x => equipmentTypeIds.Contains(x.EquipmentTypeId)).IncludeMany(x => x.EquipmentProps).ToList();
foreach (var item in equipments)
{
var equipmentType = equipmentTypes.Find(x => x.Id == item.EquipmentTypeId);
item.EquipmentType = equipmentType;
item.EquipmentProps.ForEach(x => x.EquipmentTypePropTemplate = equipmentType.EquipmentTypePropTemplates.Find(t => t.Id == x.EquipmentTypePropTemplateId));
}
}
return BllResultFactory.Success();
}
catch (Exception ex)
{
return BllResultFactory.Error(ex.Message);
}
}
/// <summary>
/// 更新客户端状态
/// </summary>
private static void UpdateClientStatus()
{
Task.Run(async () =>
{
var context = new DataContext();
while (true)
{
try
{
await Task.Delay(5000);
//更新客户端状态
_ = Guid.TryParse(ConfigurationManager.AppSettings["ClientId"], out var clientId);
if (clientId != Guid.Empty)
{
var client = context.ClientStatus.Where(x => x.ClientKeys == clientId).First();
if (client != null)
{
context.ClientStatus.Attach(client);
client.LastSeenDate = DateTime.Now;
context.ClientStatus.Update(client);
context.SaveChanges();
}
}
}
catch (Exception ex)
{
SystemLog.PrintError($"客户端状态更新线程异常:{ex.Message}");
}
}
});
}
}