RobotManager.cs
27.8 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
using log4net;
using OnlineStore.Common;
using OnlineStore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CtuDeviceLib;
using Mushiny;
using DeviceLibrary.CtuService.CtuTask;
using AGVLib;
using System.Security.Policy;
using System.Xml.Linq;
using DeviceLibrary.CtuService;
using DeviceLibrary.ESS;
using OnlineStore.DeviceLibrary.ESS;
using System.Reflection;
namespace DeviceLibrary
{
public static class RobotManager
{
public delegate void LoadFinish(bool state, string msg);
/// <summary>
/// 数据加载完成
/// </summary>
public static event LoadFinish DataInitEvent;
/// <summary>
/// 初始化完成
/// </summary>
public static event LoadFinish LoadFinishEvent;
public static event EventHandler<bool> UserPauseSet;
public static bool IsLoadOk = true;
public static bool IsConfigMode = false;
public static Thread mainThread;
static Thread subThread;
public static bool IsReadyUpdate = false;
/// <summary>
/// 系统是否运行的标志
/// </summary>
public static bool isRunning = false;
static string baseDir = Application.StartupPath;
public static CtuService.CtuService mainMachine;
static Node ClientNodeToNode(ClientNode node)
{
Node find = new Node();
find.id = node.id;
find.name = node.name;
find.status = (NodeStatus)node.status;
find.level = (NodeLevel)node.level;
find.shelf_id = node.shelf_id;
if (node.id == -1)
find.remark = node.ip;
else
find.remark = node.description;
return find;
}
#region 线体交互接口
static AGVService AgvService = new AGVService();
/// <summary>
/// 机器人请求放容器到输送线接口
/// </summary>
/// <param name="essModel"></param>
/// <returns></returns>
public static bool unloadContainerReq(EssModel essModel, out string errmsg)
{
errmsg = "";
try
{
string lineUrl = ConfigAppSettings.GetValue("LinesService_BaseAddr", "http://127.0.0.1:8080");
string str = JsonHelper.SerializeObject(essModel);
var rtnStr = HttpHelper.Post(lineUrl + "conveyor/unloadContainerReq", str);
LogUtil.info($"unloadContainerReq【{essModel}】【{rtnStr}】");
var result = JsonHelper.DeserializeJsonToObject<OnlineStore.DeviceLibrary.ESS.Result>(rtnStr);
if (result != null && result.code == 0) return true;
}
catch (Exception ex)
{
LogUtil.error($"unloadContainerReq【{essModel}】", ex);
}
return false;
}
/// <summary>
/// 机器人从输送线取容器完成通知接口-要等反馈
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static bool loadContainerFinish(EssModel model)
{
try
{
string lineUrl = ConfigAppSettings.GetValue("LinesService_BaseAddr", "http://127.0.0.1:8080");
string str = JsonHelper.SerializeObject(model);
var rtnStr = HttpHelper.Post(lineUrl + "/conveyor/loadContainerFinish", str);
LogUtil.info($"loadContainerFinish【{model}】【{rtnStr}】");
var result = JsonHelper.DeserializeJsonToObject<OnlineStore.DeviceLibrary.ESS.Result>(rtnStr);
if (result != null && result.code == 0) return true;
}
catch (Exception ex)
{
LogUtil.error($"loadContainerFinish【{model}】", ex);
}
return false;
}
/// <summary>
/// 机器人放容器到输送线完成通知接口--可不用等反馈
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static bool unloadContainerFinish(EssModel model)
{
try
{
string lineUrl = ConfigAppSettings.GetValue("LinesService_BaseAddr", "http://127.0.0.1:8080");
string str = JsonHelper.SerializeObject(model);
var rtnStr = HttpHelper.Post(lineUrl + "/conveyor/unloadContainerFinish", str);
LogUtil.info($"unloadContainerFinish【{model}】【{rtnStr}】");
var result = JsonHelper.DeserializeJsonToObject<OnlineStore.DeviceLibrary.ESS.Result>(rtnStr);
if (result != null && result.code == 0) return true;
}
catch (Exception ex)
{
LogUtil.error($"unloadContainerFinish【{model}】", ex);
}
return false;
}
/// <summary>
/// ESS任务状态上报接口
/// </summary>
/// <param name="taskStateInfo"></param>
/// <returns></returns>
public static bool taskCallBack(TaskStateInfo taskStateInfo)
{
try
{
string lineUrl = ConfigAppSettings.GetValue("LinesService_BaseAddr", "http://127.0.0.1:8080");
string str = JsonHelper.SerializeObject(taskStateInfo);
var rtnStr = HttpHelper.Post(lineUrl + "/task/callback", str);
LogUtil.info($"taskCallBack【{taskStateInfo}】【{rtnStr}】");
var result = JsonHelper.DeserializeJsonToObject<OnlineStore.DeviceLibrary.ESS.Result>(rtnStr);
if (result != null && result.code == 0) return true;
}
catch (Exception ex)
{
LogUtil.error($"taskCallBack【{taskStateInfo}】", ex);
}
return false;
}
/// <summary>
/// 异常上报接口
/// </summary>
/// <param name="errorStateInfo"></param>
/// <returns></returns>
public static bool exceptionCallBack(ErrorStateInfo errorStateInfo)
{
try
{
string lineUrl = ConfigAppSettings.GetValue("LinesService_BaseAddr", "http://127.0.0.1:8080");
string str = JsonHelper.SerializeObject(errorStateInfo);
var rtnStr = HttpHelper.Post(lineUrl + "/exception/callback", str);
LogUtil.info($"exceptionCallBack【{errorStateInfo}】【{rtnStr}】");
}
catch (Exception ex)
{
LogUtil.error($"exceptionCallBack【{errorStateInfo}】",ex);
}
return false;
}
#endregion
#region 节点状态交互
//static string agvLibUrl = ConfigAppSettings.GetValue("AGVLibService_BaseAddr", "http://127.0.0.1:9901");
//public static void SendToClientWitAPI(ClientNode clientNode)
//{
// Task.Factory.StartNew(() =>
// {
// var node = ClientNodeToNode(clientNode);
// string str = JsonHelper.SerializeObject(node);
// var rtnStr = HttpHelper.Post(agvLibUrl + "/agv/sendToClient", str);
// LogUtil.info($"SendToClientWitAPI[{clientNode.status}][{clientNode.shelf_id}][{rtnStr}]: {str}");
// });
//}
/// <summary>
/// 所有节点
/// </summary>
public static List<ClientNode> AllClientNodes;
static Task getClientNodeTask = null;
//public static void GetLastClientNodes()
//{
// if (getClientNodeTask == null || getClientNodeTask.IsCompleted)
// {
// getClientNodeTask = Task.Factory.StartNew(() =>
// {
// try
// {
// var str = HttpHelper.Get(agvLibUrl + $"/agv/getNodesByExecAgv?exec_agv={MushinyManager.CurRobotType}");
// AllClientNodes = JsonHelper.DeserializeJsonToList<ClientNode>(str);
// }
// catch (Exception e)
// {
// LogUtil.error($"获取节点状态失败", e);
// }
// });
// }
//}
/// <summary>
/// 获取所有出库分拣的入口名称
/// </summary>
/// <returns></returns>
public static List<string> GetOutLineIns()
{
var clientNodes = AllClientNodes?.FindAll(s => s.opened);
if (clientNodes == null) return null;
var outInDoors = clientNodes.FindAll(s => s.name.StartsWith(Setting_Init.outLine) && s.name.EndsWith(Setting_Init.dir_in));
if (outInDoors == null) return null;
var lst = new List<string>();
outInDoors.ForEach(s => lst.Add(s.name));
return lst;
}
#endregion
/// <summary>
/// 初始化
/// </summary>
/// <param name="param"></param>
public static void Init()
{
string msg = "";
try
{
//foreach (var item in outLineBoxSizes)
//{
// var tmp1 = item.Split('=');
// var name = tmp1[0];
// var sizes = tmp1[1].Split('#');
// outLineBoxSizeMap.Add(name, new List<string>(sizes));
//}
mainMachine = new CtuService.CtuService();
MushinyManager.Load();
//subThread = new Thread(new ThreadStart(subThreadProcess));
//subThread.Start();
// GC.KeepAlive(subThread);
string lineUrl = ConfigAppSettings.GetValue("AgvService_BaseAddr", "http://127.0.0.1:9901");
AgvService.Open(lineUrl);
DataInitEvent?.Invoke(true, msg);
}
catch (Exception ex)
{
LogUtil.error("Init ", ex);
LoadFinishEvent?.Invoke(false, ex.Message);
return;
}
LoadFinishEvent?.Invoke(IsLoadOk, msg);
}
static bool isGetInfo = true;
/// <summary>
/// 出料缓存线料箱缓存
/// </summary>
public static Dictionary<string, LineBoxCnt> BoxListAtOutLetBuff = new Dictionary<string, LineBoxCnt>();
static void subThreadProcess()
{
try
{
while (isGetInfo)
{
//获取节点状态
// RobotManager.GetLastClientNodes();
//获取入库分拣空箱
// TaskUtil.GetInletEmptyBoxes();
//获取空库位
//TaskUtil.GetEmptyPos();
//获取所有出库任务
// TaskUtil.GetAllShelfToLineTasks();
//获取所有入库
// TaskUtil.GetLineToShelfTasks();
// getRawOutBoxInfo();
uploadAgvStatus();
Thread.Sleep(1000);
}
}
catch (Exception ex)
{
LogUtil.error($"getInfoProcess error", ex);
}
}
static Task getRawOutBoxInfoTask = null;
static DateTime getRawOutBoxInfoTime = DateTime.Now;
/// <summary>
/// 获取出库缓存线料箱数量
/// </summary>
static void getRawOutBoxInfo()
{
if (getRawOutBoxInfoTask == null || getRawOutBoxInfoTask.IsCompleted)
{
if ((DateTime.Now - getRawOutBoxInfoTime).TotalSeconds < 1)
{
return;
}
getRawOutBoxInfoTime = DateTime.Now;
getRawOutBoxInfoTask = Task.Factory.StartNew(() =>
{
//if (Monitor.TryEnter(BoxListAtOutLetBuff, 100))
{
try
{
var outInDoors = AllClientNodes?.FindAll(s => s.name.StartsWith(Setting_Init.outLine) && s.name.EndsWith(Setting_Init.dir_in));
if (outInDoors != null && outInDoors.Count > 0)
{
outInDoors.ForEach(s =>
{
var outLinename = s.name;
var rtn = SMFManager.getRawOutBoxInfo(outLinename, out List<RawOutBoxInfo> rawoutBoxes);
if (rtn)
{
List<RawOutBoxInfo> fullBoxList = rawoutBoxes.FindAll(rawOutBox => rawOutBox.outMap.Count != 0);
int totalReelNum = 0;
fullBoxList.ForEach(box =>
{
box.outMap.ToList().ForEach(ss =>
{
totalReelNum = totalReelNum + ss.Value;
});
});
var reelNumToOut = totalReelNum;
if (BoxListAtOutLetBuff.ContainsKey(outLinename))
{
BoxListAtOutLetBuff[outLinename].WaitOutReelCnt = reelNumToOut;
}
else
{
BoxListAtOutLetBuff.Add(outLinename, new LineBoxCnt() { WaitOutReelCnt = reelNumToOut });
}
BoxListAtOutLetBuff[outLinename].UpdateTime = DateTime.Now;
}
rtn = SMFManager.getLineBoxNum(outLinename.Split('_')[0], out LineBoxInfo boxInfo);
if (rtn)
{
var totalBoxCount = boxInfo.emptyBoxNum + boxInfo.fullBoxNum;
if (BoxListAtOutLetBuff.ContainsKey(outLinename))
{
BoxListAtOutLetBuff[outLinename].TotalCnt = totalBoxCount;
BoxListAtOutLetBuff[outLinename].EmptyCnt = boxInfo.emptyBoxNum;
BoxListAtOutLetBuff[outLinename].FullCnt = boxInfo.emptyBoxNum;
}
else
{
BoxListAtOutLetBuff.Add(outLinename,
new LineBoxCnt()
{ TotalCnt = totalBoxCount, FullCnt = boxInfo.fullBoxNum, EmptyCnt = boxInfo.emptyBoxNum });
}
BoxListAtOutLetBuff[outLinename].UpdateTime = DateTime.Now;
}
});
}
}
catch (Exception ex)
{
LogUtil.error("getRawOutBoxInfo error", ex);
}
finally
{
//Monitor.Exit(BoxListAtOutLetBuff);
}
}
});
}
}
/// <summary>
/// 上报的信息
/// </summary>
public static Dictionary<string, string> UploadErrInfos = new Dictionary<string, string>
{
{ "40000001","离线"},
{ "40000002","急停"},
{ "40000003","电量过低"},
{ "40000004","请求进入限制区域超时"},
{ "40000005","停留时间过长报警"},
{ "40000006","运行异常,需要手动处理"},
{ "40000007","未扫到料箱码"},
{ "40000008","未扫到货架码"},
{ "40000009","地标码丢失"},
{ "40000010","检测到障碍物"},
{ "40000011","取货超时"},
{ "40000012","放货超时"},
};
static Task uploadAgvTask = null;
static DateTime uploadAgvTime = DateTime.Now;
static void uploadAgvStatus()
{
if (uploadAgvTask == null || uploadAgvTask.IsCompleted)
{
if ((DateTime.Now - uploadAgvTime).TotalSeconds < 3)
{
return;
}
uploadAgvTime = DateTime.Now;
uploadAgvTask = Task.Factory.StartNew(() =>
{
try
{
var allCtus = CTUManager.GetCTUs();
if (allCtus != null && allCtus.Count > 0)
{
foreach (var item in allCtus)
{
if (!item.Enabled) continue;
if (item.CurLandMark == 0) continue;
if (item.CurLandMark == 10001) continue;
try
{
var status = new AgvStatus();
string cid = MushinyManager.CurRobotType == 3 ? $"raw-material-ctu-{item.Name}" : $"semi-finished-ctu-{item.Name}";
status.cid = cid;
var statusInt = 0;
if (item.FaultInfo?.NeedResetFault ?? false)
{
statusInt = 2;
}
else if (item.RunState == RunState.Executing)
{
statusInt = 1;
}
status.status = statusInt;
status.data = new AgvData() { elec = item.SOC.ToString(), loc = item.CurLandMark.ToString() };
status.msgList = new List<AgvMsg>();
if (item.FaultInfo != null)
{
if (Mushiny.Common.GetFaultId(item.FaultInfo.FaultID, out FaultId faultId))
{
//{ "40000011","取货超时"},
//{ "40000012","放货超时"},
if (faultId == FaultId.急停触发)
{
status.msgList.Add(new AgvMsg()
{
errorCode = "40000002",
msg = UploadErrInfos["40000002"],
module = cid
});
}
else if (item.RunState == RunState.Offline)
{
status.msgList.Add(new AgvMsg()
{
errorCode = "40000001",
msg = UploadErrInfos["40000001"],
module = cid
});
}
else if (faultId == FaultId.料箱码丢失)
{
status.msgList.Add(new AgvMsg()
{
errorCode = "40000007",
msg = UploadErrInfos["40000007"],
module = cid
});
}
else if (faultId == FaultId.货架码丢失)
{
status.msgList.Add(new AgvMsg()
{
errorCode = "40000008",
msg = UploadErrInfos["40000008"],
module = cid
});
}
else if (faultId == FaultId.地址码贴歪严重
)//faultId == FaultId.直行末尾点丢码 || || faultId == FaultId.直行中丢码 || faultId == FaultId.转弯中丢码
{
status.msgList.Add(new AgvMsg()
{
errorCode = "40000009",
msg = UploadErrInfos["40000009"],
module = cid
});
}
else if (faultId == FaultId.直行前进中前雷达触发停止 || faultId == FaultId.直行后退中后雷达触发停止
|| faultId == FaultId.转弯过程中雷达触发停止 || faultId == FaultId.触边触发)
{
status.msgList.Add(new AgvMsg()
{
errorCode = "40000010",
msg = UploadErrInfos["40000010"],
module = cid
});
}
else if (faultId == FaultId.电池剩余电量过低)
{
status.msgList.Add(new AgvMsg()
{
errorCode = "40000003",
msg = UploadErrInfos["40000003"],
module = cid
});
}
}
else if (item.RunState == RunState.Offline)
{
status.msgList.Add(new AgvMsg()
{
errorCode = "40000001",
msg = UploadErrInfos["40000001"],
module = cid
});
}
}
else if (item.RunState == RunState.Offline)
{
status.msgList.Add(new AgvMsg()
{
errorCode = "40000001",
msg = UploadErrInfos["40000001"],
module = cid
});
}
SMFManager.UpdateAgvStatus(status);
}
catch (Exception ex)
{
LogUtil.error("uploadAgvStatus", ex);
}
}
}
}
catch (Exception ex)
{
}
});
}
}
public static void Start()
{
if (!IsLoadOk)
{
LogUtil.info("系统还未加载完毕,无法启动");
return;
}
if (isRunning)
{
LogUtil.info("系统已经在运行");
return;
}
foreach (var item in CTUManager.CTUs)
{
if (!item.Enabled) continue;
if (item.CtuTask == null)
item.CtuTask = new LoadBasketTask(item);
}
mainThread = new Thread(new ThreadStart(mainMachine.Start));
mainThread.Start();
isRunning = true;
GC.KeepAlive(mainThread);
UserPause($"isRunning = true", false);
}
public static void Stop()
{
LogUtil.info("开始停止系统.");
if (mainMachine != null)
{
mainMachine.Stop();
mainMachine.UserPause = false;
}
}
public static void ShutDown()
{
isGetInfo = false;
LogUtil.info("开始关闭系统.");
}
public static bool IsUserPause
{
get { return mainMachine.UserPause; }
}
/// <summary>
/// 用户暂停
/// </summary>
/// <param name="msg"></param>
/// <param name="userpause"></param>
public static void UserPause(string msg = "", bool userpause = true)
{
UserPauseSet?.Invoke(null, userpause);
if (userpause != mainMachine.UserPause)
{
if (userpause)
{
if (string.IsNullOrEmpty(msg))
LogUtil.info("用户暂停");
else
LogUtil.info("系统暂停: " + msg);
}
else
LogUtil.info("用户取消暂停:" + msg);
}
mainMachine.UserPause = userpause;
}
static Dictionary<string, List<string>> outLineBoxSizeMap = new Dictionary<string, List<string>>();
/// <summary>
/// 获取出料机构的可使用的料箱尺寸
/// </summary>
/// <param name="outLineName"></param>
/// <returns></returns>
public static List<string> GetOutLineInBoxSizes(string outLineName)
{
var boxSizes = new List<string>();
if (string.IsNullOrEmpty(outLineName)) return boxSizes;
if (outLineName.StartsWith(Setting_Init.outLine) && outLineName.EndsWith(Setting_Init.dir_in))
{
if (outLineBoxSizeMap.ContainsKey(outLineName))
{
return outLineBoxSizeMap[outLineName];
}
}
return boxSizes;
}
}
}