wanshenmean
2025-04-15 97ae26c59fe8c0f967903538e147240f8c1600a5
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
using WIDESEAWCS_Common.AGVEnum;
using WIDESEAWCS_Common.TaskEnum;
using WIDESEAWCS_DTO.TaskInfo;
using WIDESEAWCS_ITaskInfoRepository;
using WIDESEAWCS_Model.Models;
using WIDESEAWCS_QuartzJob;
 
namespace WIDESEAWCS_Tasks
{
    public class UpdateTaskAGV
    {
        private static int _readUpdateAGVTaskSignalso = 0;
 
        public void UpdateTask2(AGV plcClient, ITaskRepository _taskRepository)
        {
            //TODO: Update the task status and result in the database
            if (Interlocked.Exchange(ref _readUpdateAGVTaskSignalso, 1) == 0)
            {
                try
                {
                    if (plcClient == null)
                    {
                        return;
                    }
                    //读取任务状态
 
                    var taskFbInteractiveR = plcClient.DeviceProDTOs.Where(r => r.DeviceProParamName == TaskDBName.taskFbInteractiveR.ToString()).FirstOrDefault().DeviceProAddress;
                    var taskFbInteractive2 = plcClient.DeviceProDTOs.Where(r => r.DeviceProParamName == TaskDBName.taskFbInteractiveW.ToString()).FirstOrDefault().DeviceProAddress;
                    var resetTaskFbInteractiveR = plcClient.DeviceProDTOs.Where(r => r.DeviceProParamName == TaskDBName.resetTaskFbInteractiveR.ToString()).FirstOrDefault().DeviceProAddress;
                    var taskIDFb = plcClient.DeviceProDTOs.Where(r => r.DeviceProParamName == TaskDBName.taskIDFb.ToString()).FirstOrDefault().DeviceProAddress;
                    var taskStatusFb = plcClient.DeviceProDTOs.Where(r => r.DeviceProParamName == TaskDBName.taskStatusFb.ToString()).FirstOrDefault().DeviceProAddress;
                    int taskFbInteractive = plcClient.Communicator.Read<int>(taskFbInteractiveR);
                    int taskFbInteractiveW = plcClient.Communicator.Read<int>(taskFbInteractive2);
                    int resetTaskFbInteractiver = plcClient.Communicator.Read<int>(resetTaskFbInteractiveR);
                    //0初始状态 1 RCS更新了一条任务状态
                    if (resetTaskFbInteractiver == 1)
                    {
                        plcClient.Communicator.Write(taskFbInteractive2, 0);
                        for (int i = 0; i < 5; i++)
                        {
                            Thread.Sleep(300);
                            var agvnumber = plcClient.Communicator.Read<int>(taskFbInteractive2);
                            if (agvnumber != 0)
                            {
                                plcClient.Communicator.Write(taskFbInteractive2, 0);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    if (1 == taskFbInteractive && taskFbInteractiveW == 0)
                    {
                        string taskId = plcClient.Communicator.Read<int>(taskIDFb).ToString();//任务ID
                        if (taskId.Contains("\b")) { taskId = taskId.Remove(0, 1); }
                        int taskState = plcClient.Communicator.Read<int>(taskStatusFb);//1起点执行中,2起点已完成,3终点执行中,4终点已完成
                        if (0 == taskState)//无含义
                            return;
                        //WriteLog.Info("AGV更新任务状态").Write("任务号" + taskId + "任务状态" + taskState, "AGV更新任务状态");
                        Dt_Task agvTask = _taskRepository.QueryFirst(r => r.TaskNum.ToString() == taskId);
 
                        if (1 == taskState)//任务起点执行中
                        {
                            if (null == agvTask)
                            {
                                plcClient.Communicator.Write(taskFbInteractive2, 1);
                                //WriteLog.Info("AGV更新任务状态").Write("WCS写入AGV任务号,当前任务号不存在任务列表里," + taskId + DateTime.Now + "任务起点执行中状态确认1", "AGV更新任务状态");
                            }
                            if (agvTask.TaskState == (int)TaskInStatusEnum.Line_InExecuting)
                            {
                                plcClient.Communicator.Write(taskFbInteractive2, 1);
                                //WriteLog.Info("AGV更新任务状态").Write("WCS再次写入AGV任务号" + taskId + DateTime.Now + "任务起点执行中状态确认1", "AGV更新任务状态");
                            }
                            int nextStatus = agvTask.TaskState.GetNextNotCompletedStatus<TaskInStatusEnum>();
                            agvTask.TaskState = nextStatus;
 
                            _taskRepository.UpdateData(agvTask);
                            plcClient.Communicator.Write(taskFbInteractive2, 1);
                            for (int i = 0; i < 5; i++)
                            {
                                Thread.Sleep(300);
                                var agvnumber = plcClient.Communicator.Read<int>(taskFbInteractive2);
                                if (agvnumber != 1)
                                {
                                    plcClient.Communicator.Write(taskFbInteractive2, 1);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            //WriteLog.Info("AGV更新任务状态").Write("WCS写入AGV任务号" + taskId + "任务起点执行中状态确认1", "AGV更新任务状态");
                        }
                        else if (2 == taskState)//任务起点已完成
                        {
                            if (null == agvTask)
                            {
                                plcClient.Communicator.Write(taskFbInteractive2, 1);
                                //WriteLog.Info("AGV更新任务状态").Write("WCS写入AGV任务号,当前任务号不存在任务列表里," + taskId + DateTime.Now + "任务起点完成状态确认1", "AGV更新任务状态");
                                return;
                            }
                            if (agvTask.TaskState == (int)TaskInStatusEnum.Line_InFinish)
                            {
                                plcClient.Communicator.Write(taskFbInteractive2, 1);
                                //WriteLog.Info("AGV更新任务状态").Write("WCS再次写入AGV任务号" + taskId + DateTime.Now + "任务起点完成状态确认1", "AGV更新任务状态");
                            }
                            else if (agvTask.TaskState == (int)TaskInStatusEnum.Line_InExecuting)
                            {
                                plcClient.Communicator.Write(taskFbInteractive2, 1);
                                //WriteLog.Info("AGV更新任务状态").Write("WCS写入AGV任务号,当前任务号的任务状态不是起点执行中," + taskId + DateTime.Now + "任务起点完成状态确认1", "AGV更新任务状态");
                            }
 
                            int nextStatus = agvTask.TaskState.GetNextNotCompletedStatus<TaskInStatusEnum>();
                            agvTask.TaskState = nextStatus;
 
                            _taskRepository.UpdateData(agvTask);
                            plcClient.Communicator.Write(taskFbInteractive2, 1);
                            for (int i = 0; i < 5; i++)
                            {
                                Thread.Sleep(300);
                                var agvnumber = plcClient.Communicator.Read<int>(taskFbInteractive2);
                                if (agvnumber != 1)
                                {
                                    plcClient.Communicator.Write(taskFbInteractive2, 1);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            //WriteLog.Info("AGV更新任务状态").Write("WCS写入AGV任务号" + taskId + DateTime.Now + "任务起点完成状态确认1", "AGV更新任务状态");
                        }
                        else if (3 == taskState)//任务终点执行中
                        {
                            if (null == agvTask)
                            {
                                plcClient.Communicator.Write(taskFbInteractive2, 1);
                                //WriteLog.Info("AGV更新任务状态").Write("WCS写入AGV任务号,当前任务号不存在任务列表里," + taskId + DateTime.Now + "任务终点执行中状态确认1", "AGV更新任务状态");
                            }
                            if (agvTask.TaskState == (int)TaskInStatusEnum.SC_InExecuting)
                            {
                                plcClient.Communicator.Write(taskFbInteractive2, 1);
                                //WriteLog.Info("AGV更新任务状态").Write("WCS再次写入AGV任务号" + taskId + DateTime.Now + "任务终点执行中状态确认1", "AGV更新任务状态");
                            }
 
                            int nextStatus = agvTask.TaskState.GetNextNotCompletedStatus<TaskInStatusEnum>();
                            agvTask.TaskState = nextStatus;
 
                            _taskRepository.UpdateData(agvTask);
                            plcClient.Communicator.Write(taskFbInteractive2, 1);
                            for (int i = 0; i < 5; i++)
                            {
                                Thread.Sleep(300);
                                var agvnumber = plcClient.Communicator.Read<int>(taskFbInteractive2);
                                if (agvnumber != 1)
                                {
                                    plcClient.Communicator.Write(taskFbInteractive2, 1);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            //WriteLog.Info("AGV更新任务状态").Write("WCS写入AGV任务号" + taskId + DateTime.Now + "任务终点执行中状态确认1", "AGV更新任务状态");
                        }
                        else if (4 == taskState)//任务终点完成
                        {
                            if (null == agvTask)
                            {
                                plcClient.Communicator.Write(taskFbInteractive2, 1);
                                //WriteLog.Info("AGV更新任务状态").Write("WCS写入AGV任务号,当前任务号不存在任务列表里," + taskId + DateTime.Now + "任务终点完成状态确认1", "AGV更新任务状态");
                                return;
                            }
                            else if (agvTask.TaskState != (int)TaskInStatusEnum.SC_InExecuting)
                            {
                                plcClient.Communicator.Write(taskFbInteractive2, 1);
                                //throw new Exception("任务状态更改为4终点已完成失败,任务ID:" + agvTask.agv_tasknum + DateTime.Now + ",任务状态不是终点执行中!");
                            }
                            if (agvTask.TargetAddress.Contains("HXWLX"))
                            {
                                if (agvTask.SourceAddress.Contains("KPHLX"))
                                {
                                    // 空盘线进烘箱
                                    // TODO: 调用创智接口获取完整条码
                                    var materials = new List<BakingClass>
                                    {
                                            new BakingClass { BarCode = "1", MaterialType = "1" },
                                    };
                                    MESback WMSbackresult = MESAPIInvoke.BakingFeedingBinding(agvTask.TargetAddress, materials);
                                    if (WMSbackresult.Code > 0) { new Exception(WMSbackresult.Message); return; }
                                }
                                else
                                {
                                    // 提升机进烘箱
                                    // TODO: 调用创智接口获取完整条码
                                    var materials = new List<BakingClass>
                                    {
                                            new BakingClass { BarCode = "1", MaterialType = "1" },
                                    };
                                    MESback WMSbackresult = MESAPIInvoke.BakingFeedingBinding(agvTask.TargetAddress, materials);
                                    if (WMSbackresult.Code > 0) { new Exception(WMSbackresult.Message); return; }
                                }
                            }
 
                            //agvtask_HtyRepository.AddTaskHistory(agvTask, OperateType.Finished.ToString());
                            _taskRepository.DeleteData(agvTask);
                            plcClient.Communicator.Write(taskFbInteractive2, 1);
                            for (int i = 0; i < 5; i++)
                            {
                                Thread.Sleep(300);
                                var agvnumber = plcClient.Communicator.Read<int>(taskFbInteractive2);
                                if (agvnumber != 1)
                                {
                                    plcClient.Communicator.Write(taskFbInteractive2, 1);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            //WriteLog.Info("AGV更新任务状态").Write("WCS写入AGV任务号" + taskId + DateTime.Now + "任务终点完成状态确认1", "AGV更新任务状态");
                        }
                        else if (5 == taskState)
                        {
                            plcClient.Communicator.Write(taskFbInteractive2, 1);
                        }
                    }
                    //if (taskFbInteractive == 1 && taskFbInteractiveW == 1)//反馈没收到重新反馈
                    //    plcClient.Communicator.Write(taskFbInteractive2, 0);
                    if (taskFbInteractive == 0 && taskFbInteractiveW == 1)
                    {
                        plcClient.Communicator.Write(taskFbInteractive2, 0);
                        for (int i = 0; i < 5; i++)
                        {
                            Thread.Sleep(300);
                            var agvnumber = Convert.ToInt32(plcClient.Communicator.Read<int>(taskFbInteractive2));
                            if (agvnumber != 0)
                            {
                                plcClient.Communicator.Write(taskFbInteractive2, 0);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    //WriteLog.Info("AGV更新任务状态").Write("WCS接收AGV任务反馈异常" + ex.Message.ToString() + DateTime.Now, "AGV更新任务状态");
                }
                finally
                {
                    Interlocked.Exchange(ref _readUpdateAGVTaskSignalso, 0);
                }
            }
        }
 
        public static void UpdateTask(AGV plcClient, ITaskRepository taskRepository, ITaskCZRepository _taskCZRepository, ITaskCZDetailsRepository _detailsRepository)
        {
            // 使用Interlocked.Exchange保证同一时间只有一个线程可以执行任务更新
            if (Interlocked.Exchange(ref _readUpdateAGVTaskSignalso, 1) == 0)
            {
                try
                {
                    if (plcClient == null)
                    {
                        return;
                    }
 
                    // 从AGV设备中获取各个任务状态的地址
                    var taskFbInteractiveR = plcClient.DeviceProDTOs.FirstOrDefault(r => r.DeviceProParamName == TaskDBName.taskFbInteractiveR.ToString())?.DeviceProAddress;
                    var taskFbInteractive2 = plcClient.DeviceProDTOs.FirstOrDefault(r => r.DeviceProParamName == TaskDBName.taskFbInteractiveW.ToString())?.DeviceProAddress;
                    var resetTaskFbInteractiveR = plcClient.DeviceProDTOs.FirstOrDefault(r => r.DeviceProParamName == TaskDBName.resetTaskFbInteractiveR.ToString())?.DeviceProAddress;
                    var taskIDFb = plcClient.DeviceProDTOs.FirstOrDefault(r => r.DeviceProParamName == TaskDBName.taskIDFb.ToString())?.DeviceProAddress;
                    var taskStatusFb = plcClient.DeviceProDTOs.FirstOrDefault(r => r.DeviceProParamName == TaskDBName.taskStatusFb.ToString())?.DeviceProAddress;
 
                    // 检查是否找到有效的地址,如果没有找到则直接返回
                    if (taskFbInteractiveR == null || taskFbInteractive2 == null || resetTaskFbInteractiveR == null || taskIDFb == null || taskStatusFb == null)
                    {
                        return;
                    }
 
                    // 读取任务状态
                    int taskFbInteractive = plcClient.Communicator.Read<int>(taskFbInteractiveR);
                    int taskFbInteractiveW = plcClient.Communicator.Read<int>(taskFbInteractive2);
                    int resetTaskFbInteractiveRValue = plcClient.Communicator.Read<int>(resetTaskFbInteractiveR);
 
                    // 如果resetTaskFbInteractiveR为1,则重置taskFbInteractiveW为0,并等待其变为0
                    if (resetTaskFbInteractiveRValue == 1)
                    {
                        plcClient.Communicator.Write(taskFbInteractive2, 0);
                        // 避免使用Thread.Sleep来等待状态变化,使用更高效的等待机制
                        for (int i = 0; i < 5; i++)
                        {
                            Task.Delay(300).Wait(); // 使用Task.Delay替代Thread.Sleep,避免阻塞线程池中的线程
                            int agvNumber = plcClient.Communicator.Read<int>(taskFbInteractive2);
                            if (agvNumber != 0)
                            {
                                plcClient.Communicator.Write(taskFbInteractive2, 0);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
 
                    // 只有当taskFbInteractive为1且taskFbInteractiveW为0时才处理任务状态
                    if (taskFbInteractive == 1 && taskFbInteractiveW == 0)
                    {
                        string taskId = plcClient.Communicator.Read<int>(taskIDFb).ToString(); // 任务ID
                        int taskState = plcClient.Communicator.Read<int>(taskStatusFb); // 任务状态
 
                        // 如果任务状态无效,则直接返回
                        if (taskState == 0)
                        {
                            return;
                        }
 
                        // 根据任务ID查询数据库中的任务
                        var agvTask = taskRepository.QueryFirst(r => r.TaskNum.ToString() == taskId);
                        if (agvTask == null)
                        {
                            plcClient.Communicator.Write(taskFbInteractive2, 1);
                            return; // 如果任务不存在,直接返回,不需要再次写入
                        }
 
                        // 根据任务状态更新任务状态
                        if (taskState == 1) // 任务起点执行中
                        {
                            UpdateTaskStatus(plcClient, agvTask, TaskInStatusEnum.Line_InExecuting, taskRepository, taskFbInteractive2);
                        }
                        else if (taskState == 2) // 任务起点已完成
                        {
                            UpdateTaskStatus(plcClient, agvTask, TaskInStatusEnum.Line_InFinish, taskRepository, taskFbInteractive2);
                        }
                        else if (taskState == 3) // 任务终点执行中
                        {
                            UpdateTaskStatus(plcClient, agvTask, TaskInStatusEnum.SC_InExecuting, taskRepository, taskFbInteractive2);
                        }
                        else if (taskState == 4) // 任务终点完成
                        {
                            if (agvTask.TaskState != (int)TaskInStatusEnum.SC_InExecuting)
                            {
                                // 如果任务状态不是终点执行中,抛出异常
                                throw new Exception($"任务状态更改为4终点已完成失败,任务ID:{taskId},当前状态:{agvTask.TaskState}");
                            }
 
                            if (agvTask.TargetAddress.Contains("HXWLX"))
                            {
                                if (agvTask.SourceAddress.Contains("KPHLX"))
                                {
                                    // 空盘线进烘箱
                                    // TODO: 任务截取完整条码
                                    var materials = new List<BakingClass>();
 
                                    MESback WMSbackresult = MESAPIInvoke.BakingFeedingBinding(agvTask.TargetAddress, materials);
                                    if (WMSbackresult.Code > 0) { new Exception(WMSbackresult.Message); return; }
                                }
                                else
                                {
                                    // 提升机进烘箱
                                    // TODO: 调用创智接口获取完整条码
                                    //var czTask = _taskCZRepository.QueryFirst(x => x.Id == agvTask.WMSId);
                                    //CZTaskBarCodeDto barCodeDto = JsonConvert.DeserializeObject<CZTaskBarCodeDto>(czTask.DtCZTaskDetails);
                                    //var materials = Enumerable.Range(0, 2)
                                    //        .Select(i => new BakingClass
                                    //        {
                                    //            MaterialType = czTask.TaskProductCode,
                                    //            BarCode = GetBarCodeByIndex(barCodeDto, i, hasDesc: !string.IsNullOrEmpty(czTask.TaskDesc))
                                    //        })
                                    //        .ToList();
 
                                    var details = _detailsRepository.QueryData(x => x.TaskEndAddress == agvTask.TargetAddress && x.TaskName == agvTask.Roadway).OrderBy(x => x.CreateDate).ToList();
 
                                    if (details.Count >= 2)
                                    {
                                        details = details.Take(2).ToList();
                                    }
 
                                    var materials = details.Select(x => new BakingClass
                                    {
                                        MaterialType = x.MaterialType,
                                        BarCode = x.MaterialBarCode,
                                    }).ToList();
 
                                    MESback WMSbackresult = MESAPIInvoke.BakingFeedingBinding(agvTask.TargetAddress, materials);
                                    if (WMSbackresult.Code > 0) { new Exception(WMSbackresult.Message); return; }
                                    else
                                    {
                                        // 删除details数据
                                        _detailsRepository.DeleteData(details);
                                    }
                                }
                            }
 
                            // 删除已完成的任务
                            taskRepository.DeleteData(agvTask);
                            plcClient.Communicator.Write(taskFbInteractive2, 1);
                            EnsureTaskFeedback(taskFbInteractive2, plcClient);
                        }
                        else if (taskState == 5)
                        {
                            plcClient.Communicator.Write(taskFbInteractive2, 1);
                        }
                    }
 
                    // 如果taskFbInteractive为0且taskFbInteractiveW为1,则重置taskFbInteractiveW为0
                    if (taskFbInteractive == 0 && taskFbInteractiveW == 1)
                    {
                        plcClient.Communicator.Write(taskFbInteractive2, 0);
                        EnsureTaskFeedback(taskFbInteractive2, plcClient);
                    }
                }
                catch (Exception ex)
                {
                    // 记录异常信息
                    Console.WriteLine($"WCS接收AGV任务反馈异常 {ex.Message}");
                }
                finally
                {
                    Interlocked.Exchange(ref _readUpdateAGVTaskSignalso, 0);
                }
            }
        }
 
        // 更新任务状态并写入AGV反馈地址
        private static void UpdateTaskStatus(AGV plcClient, Dt_Task agvTask, TaskInStatusEnum targetStatus, ITaskRepository taskRepository, string taskFbInteractive2)
        {
            if (agvTask.TaskState != (int)targetStatus)
            {
                plcClient.Communicator.Write(taskFbInteractive2, 1); // 状态不匹配,写入反馈
            }
 
            // 更新任务状态为下一个未完成状态
            agvTask.TaskState = agvTask.TaskState.GetNextNotCompletedStatus<TaskInStatusEnum>();
            taskRepository.UpdateData(agvTask);
            plcClient.Communicator.Write(taskFbInteractive2, 1);
            EnsureTaskFeedback(taskFbInteractive2, plcClient);
        }
 
        // 确保任务反馈地址的状态为1
        private static void EnsureTaskFeedback(string taskFbInteractive2, AGV plcClient)
        {
            for (int i = 0; i < 5; i++)
            {
                Task.Delay(300).Wait();
                int agvNumber = plcClient.Communicator.Read<int>(taskFbInteractive2);
                if (agvNumber != 1)
                {
                    plcClient.Communicator.Write(taskFbInteractive2, 1);
                }
                else
                {
                    break;
                }
            }
        }
 
        // 辅助方法
        private static string GetBarCodeByIndex(CZTaskBarCodeDto dto, int index, bool hasDesc)
        {
            return (index, hasDesc) switch
            {
                (0, false) => dto.BarCode1,
                (1, false) => dto.BarCode2,
                (0, true) => dto.BarCode3,
                (1, true) => dto.BarCode4,
                _ => throw new IndexOutOfRangeException()
            };
        }
    }
 
    public class BakingFeedingClass
    {
        public string Devid { get; set; }
 
        public List<BakingClass> Materials { get; set; }
    }
 
    public class BakingClass
    {
        public string MaterialType { get; set; }
        public string BarCode { get; set; }
    }
}