1
wankeda
2025-04-11 a206dda817a9f9615db1fa52e3ac193af9ac4a92
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
using System.Diagnostics;
using System.Text;
using WIDESEAWCS_Common.AGVEnum;
using WIDESEAWCS_Common.TaskEnum;
using WIDESEAWCS_ITaskInfoRepository;
using WIDESEAWCS_Model.Models;
using WIDESEAWCS_QuartzJob;
 
namespace WIDESEAWCS_Tasks
{
    public class SendTaskAGV
    {
        private static int _readSendAGVTaskSignalso = 0;
        private static bool isTrue1 = false;
        private static string name1 = "";
 
        public static void SendAGVTask1(AGV agv, ITaskRepository _taskRepository)
        {
            //TODO: Implement sending task to AGV
            try
            {
                if (agv == null)
                {
                    return;
                }
 
                var taskInteractiveR = agv.DeviceProDTOs.Where(r => r.DeviceProParamName == TaskDBName.taskInteractiveR.ToString()).FirstOrDefault().DeviceProAddress;
                var taskInteractiveW = agv.DeviceProDTOs.Where(r => r.DeviceProParamName == TaskDBName.taskInteractiveW.ToString()).FirstOrDefault().DeviceProAddress;
                var resetTaskW = agv.DeviceProDTOs.Where(r => r.DeviceProParamName == TaskDBName.resetTaskInteractiveW.ToString()).FirstOrDefault().DeviceProAddress;
                var resetTaskInteractiveR = agv.DeviceProDTOs.Where(r => r.DeviceProParamName == TaskDBName.resetTaskInteractiveR.ToString()).FirstOrDefault().DeviceProAddress;
                var taskID = agv.DeviceProDTOs.Where(r => r.DeviceProParamName == TaskDBName.taskID.ToString()).FirstOrDefault().DeviceProAddress;
 
                int TaskInteractive = agv.Communicator.Read<int>(taskInteractiveR);//1收到
                int TaskInteractiveW = agv.Communicator.Read<int>(taskInteractiveW);//0初始/1下发/2取消/3更改
                int resetTaskInteractiveW = agv.Communicator.Read<int>(resetTaskW);
                int resetTaskInteractiver = agv.Communicator.Read<int>(resetTaskInteractiveR);
                if (isTrue1 && name1 == agv.DeviceName)
                {
                    if (TaskInteractiveW != 0 || resetTaskInteractiveW != 0 || TaskInteractive != 0)
                    {
                        agv.Communicator.Write(resetTaskW, 1);
                        Task.Delay(2000).Wait();
                        resetTaskInteractiveW = agv.Communicator.Read<int>(resetTaskW);
                        if (resetTaskInteractiveW == 1)
                        {
                            agv.Communicator.Write(resetTaskW, 0);
                            agv.Communicator.Write(taskInteractiveW, 0);
                            Task.Delay(2000).Wait();
                        }
                        return;
                    }
                    else
                    {
                        isTrue1 = false;
                        name1 = "";
                    }
                }
                if (resetTaskInteractiver == 1)
                {
                    agv.Communicator.Write(taskInteractiveW, 0);
                    for (int i = 0; i < 5; i++)
                    {
                        Thread.Sleep(300);
                        var agvnumber = Convert.ToInt32(agv.Communicator.Read<int>(taskInteractiveW));
                        if (agvnumber != 0)
                        {
                            agv.Communicator.Write(taskInteractiveW, 0);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                if (0 == TaskInteractive && TaskInteractiveW == 0)
                {
                    Dt_Task agvTask = _taskRepository.QueryData(r => r.TaskState == (int)TaskInStatusEnum.InNew && r.Roadway == agv.DeviceName && r.TaskType == (int)TaskOutboundTypeEnum.Outbound).OrderBy(r => r.CreateDate).OrderByDescending(r => r.Grade).FirstOrDefault();
                    if (null != agvTask)
                    {
                        //写入任务信息
                        string rel = TaskWrite(agv, agvTask, AGVJobEnum.newTaskEnum);
                        Thread.Sleep(1000);
                        string taskId = agv.Communicator.Read<string>(taskID).ToString();
                        if (taskId != agvTask.TaskNum.ToString())
                        {
                            isTrue1 = true;
                            name1 = agv.DeviceName;
                            //WriteLog.Info("SendAGVTask").Write("给AGV写入任务失败," + agvTask.agv_tasknum + DateTime.Now, "SendAGVTask");
                            throw new Exception(string.Format("给AGV写入任务失败,任务号{0}", agvTask.TaskNum));
                        }
                        if (string.IsNullOrEmpty(rel))
                        {
                            //写入任务确认1
                            agv.Communicator.Write(taskInteractiveW, 1);
                            Thread.Sleep(1000);
                            //读取AGV信号
                            int ReadTask_1_OK = agv.Communicator.Read<int>(taskInteractiveR);
                            if (ReadTask_1_OK == 1)
                            {
                                //写入WCS确认信号0
                                agv.Communicator.Write(taskInteractiveW, 0);
                                Thread.Sleep(2000);
                                //读取AGV信号是否为0
                                int ReadTask_0_OK = agv.Communicator.Read<int>(taskInteractiveR);
                                if (ReadTask_0_OK == 0)
                                {
                                    int nextStatus = agvTask.TaskState.GetNextNotCompletedStatus<TaskInStatusEnum>();
                                    agvTask.TaskState = nextStatus;
                                    agvTask.Dispatchertime = DateTime.Now;
                                    _taskRepository.UpdateData(agvTask);
                                    // 上传AGV运行数据 by xiaoyang
                                    //SendMESTask.SendMesTask(agvTask, 0);
                                }
                                else
                                {
                                    isTrue1 = true;
                                    name1 = agv.DeviceName;
                                    throw new Exception(string.Format("给AGV写入任务确认0失败,任务号{0}", agvTask.TaskNum));
                                }
                            }
                            else if (ReadTask_1_OK == 11)
                            {
                                agv.Communicator.Write(taskInteractiveW, 0);
                                Thread.Sleep(2000);
                                int ReadTask_0_Error = agv.Communicator.Read<int>(taskInteractiveR);
                                if (ReadTask_0_Error == 0)
                                {
                                    int nextStatus = agvTask.TaskState.GetNextNotCompletedStatus<TaskOutStatusEnum>();
                                    agvTask.TaskState = nextStatus;
                                    agvTask.Dispatchertime = DateTime.Now;
                                    _taskRepository.UpdateData(agvTask);
                                }
                                else
                                {
                                    isTrue1 = true;
                                    name1 = agv.DeviceName;
                                    throw new Exception(string.Format("给AGV写入任务异常确认0失败,任务号{0}", agvTask.TaskNum));
                                }
                            }
                            else
                            {
                                isTrue1 = true;
                                name1 = agv.DeviceName;
                                throw new Exception(string.Format("给AGV写入任务确认1失败,任务号{0}", agvTask.TaskNum));
                            }
                        }
                        else
                        {
                            isTrue1 = true;
                            name1 = agv.DeviceName;
                            throw new Exception(string.Format("给AGV写入任务失败,任务号{0}" + rel, agvTask.TaskNum));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                StackTrace sta = new StackTrace(ex, true);
                StackTrace st = new StackTrace(new StackFrame(true));
                StackFrame sf = sta.GetFrame(0);
                //WriteLog.Info("SendAGVTask").Write(ex.Message + "行号" + sf.GetFileLineNumber(), "SendAGVTask");
            }
            finally
            {
                // WriteLog.Info("SendAGVTask").Write(agv.PLCName+"\t"+DateTime.Now, "SendAGVTask");
                Interlocked.Exchange(ref _readSendAGVTaskSignalso, 0);
            }
        }
 
        public static void SendAGVTask(AGV agv, ITaskRepository _taskRepository)
        {
            // 检查AGV是否为空
            if (agv == null)
            {
                return;
            }
 
            // 获取任务交互和重置交互的设备地址
            var taskInteractiveR = agv.DeviceProDTOs.FirstOrDefault(r => r.DeviceProParamName == TaskDBName.taskInteractiveR.ToString())?.DeviceProAddress;
            var taskInteractiveW1 = agv.DeviceProDTOs.FirstOrDefault(r => r.DeviceProParamName == TaskDBName.taskInteractiveW.ToString())?.DeviceProAddress;
            var resetTaskW = agv.DeviceProDTOs.FirstOrDefault(r => r.DeviceProParamName == TaskDBName.resetTaskInteractiveW.ToString())?.DeviceProAddress;
            var resetTaskInteractiveR = agv.DeviceProDTOs.FirstOrDefault(r => r.DeviceProParamName == TaskDBName.resetTaskInteractiveR.ToString())?.DeviceProAddress;
            var taskID = agv.DeviceProDTOs.FirstOrDefault(r => r.DeviceProParamName == TaskDBName.taskID.ToString())?.DeviceProAddress;
 
            // 如果地址未找到,直接返回
            if (taskInteractiveR is null || taskInteractiveW1 is null || resetTaskW is null || resetTaskInteractiveR is null || taskID is null)
            {
                return;
            }
 
            try
            {
                // 读取任务交互和重置交互的状态
                int taskInteractive = agv.Communicator.Read<Int16>(taskInteractiveR); // 1表示收到
                int taskInteractiveW = agv.Communicator.Read<Int16>(taskInteractiveW1); // 0初始/1下发/2取消/3更改
                int resetTaskInteractiveW = agv.Communicator.Read<Int16>(resetTaskW);
                int resetTaskInteractiver = agv.Communicator.Read<Int16>(resetTaskInteractiveR);
 
                // 处理任务交互W和重置交互W不为0的情况
                if (isTrue1 && name1 == agv.DeviceName)
                {
                    if (taskInteractiveW != 0 || resetTaskInteractiveW != 0 || taskInteractive != 0)
                    {
                        agv.Communicator.Write<UInt16>(resetTaskW, 1);
                        Task.Delay(2000).Wait();
                        resetTaskInteractiveW = agv.Communicator.Read<Int16>(resetTaskW);
 
                        if (resetTaskInteractiveW == 1)
                        {
                            agv.Communicator.Write<UInt16>(resetTaskW, 0);
                            agv.Communicator.Write<UInt16>(taskInteractiveW1, 0);
                            Task.Delay(2000).Wait();
                        }
                        return;
                    }
                    isTrue1 = false;
                    name1 = "";
                }
 
                // 如果重置交互R为1,则重置任务交互W
                if (resetTaskInteractiver == 1)
                {
                    agv.Communicator.Write<UInt16>(taskInteractiveW1, 0);
                    for (int i = 0; i < 5; i++)
                    {
                        Task.Delay(300).Wait(); // 用Task.Delay代替Thread.Sleep,以避免线程阻塞
                        int agvNumber = agv.Communicator.Read<Int16>(taskInteractiveW1);
                        if (agvNumber != 0)
                        {
                            agv.Communicator.Write<UInt16>(taskInteractiveW1, 0);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
 
                // 如果AGV没有任务且任务交互W为0
                if (taskInteractive == 0 && taskInteractiveW == 0)
                {
                    // 查询新任务
                    Dt_Task agvTask = _taskRepository.QueryData(r => r.TaskState == (int)TaskInStatusEnum.InNew && r.Roadway == agv.DeviceName && r.TaskType == (int)TaskOutboundTypeEnum.Outbound)
                        .OrderBy(r => r.CreateDate).ThenByDescending(r => r.Grade).FirstOrDefault();
 
                    if (agvTask != null)
                    {
                        // 写入任务信息
                        string rel = TaskWrite(agv, agvTask, AGVJobEnum.newTaskEnum);
                        Task.Delay(1000).Wait();
 
                        // 检查任务ID是否写入正确
                        string taskId = agv.Communicator.Read<string>(taskID);
                        string numberPart = taskId.Split('-')[1];
                        if (numberPart != agvTask.TaskNum.ToString())
                        {
                            throw new Exception($"给AGV写入任务失败,任务号{agvTask.TaskNum}");
                        }
 
                        // 如果任务信息写入成功
                        if (string.IsNullOrEmpty(rel))
                        {
                            // 写入任务确认信号1
                            agv.Communicator.Write<UInt16>(taskInteractiveW1, 1);
                            Task.Delay(1000).Wait();
 
                            // 读取AGV的确认信号
                            int readTask1Ok = agv.Communicator.Read<Int16>(taskInteractiveR);
                            if (readTask1Ok == 1)
                            {
                                // 写入WCS的确认信号0
                                agv.Communicator.Write<UInt16>(taskInteractiveW1, 0);
                                Task.Delay(2000).Wait();
 
                                // 再次读取AGV的确认信号
                                int readTask0Ok = agv.Communicator.Read<Int16>(taskInteractiveR);
                                if (readTask0Ok == 0)
                                {
                                    // 更新任务状态并保存
                                    int nextStatus = agvTask.TaskState.GetNextNotCompletedStatus<TaskInStatusEnum>();
                                    agvTask.TaskState = nextStatus;
                                    agvTask.Dispatchertime = DateTime.Now;
                                    _taskRepository.UpdateData(agvTask);
 
                                    // 上传AGV运行数据(注释掉的代码)
                                    // SendMESTask.SendMesTask(agvTask, 0);
                                }
                                else
                                {
                                    throw new Exception($"给AGV写入任务确认0失败,任务号{agvTask.TaskNum}");
                                }
                            }
                            else if (readTask1Ok == 11)
                            {
                                // 处理任务异常情况
                                agv.Communicator.Write<UInt16>(taskInteractiveW1, 0);
                                Task.Delay(2000).Wait();
                                int readTask0Error = agv.Communicator.Read<int>(taskInteractiveR);
 
                                if (readTask0Error == 0)
                                {
                                    // 更新任务状态为异常并保存
                                    int nextStatus = agvTask.TaskState.GetNextNotCompletedStatus<TaskOutStatusEnum>();
                                    agvTask.TaskState = nextStatus;
                                    agvTask.Dispatchertime = DateTime.Now;
                                    _taskRepository.UpdateData(agvTask);
                                }
                                else
                                {
                                    throw new Exception($"给AGV写入任务异常确认0失败,任务号{agvTask.TaskNum}");
                                }
                            }
                            else
                            {
                                throw new Exception($"给AGV写入任务确认1失败,任务号{agvTask.TaskNum}");
                            }
                        }
                        else
                        {
                            throw new Exception($"给AGV写入任务失败,任务号{agvTask.TaskNum} {rel}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录异常信息(注释掉的代码)
                // StackTrace sta = new StackTrace(ex, true);
                // StackFrame sf = sta.GetFrame(0);
                // WriteLog.Info("SendAGVTask").Write(ex.Message + " 行号 " + sf.GetFileLineNumber(), "SendAGVTask");
            }
            finally
            {
                // 记录日志(注释掉的代码)
                // WriteLog.Info("SendAGVTask").Write(agv.PLCName + "\t" + DateTime.Now, "SendAGVTask");
 
                // 重置信号量
                Interlocked.Exchange(ref _readSendAGVTaskSignalso, 0);
            }
        }
 
 
        public static string TaskWrite(AGV client, Dt_Task agvTask, AGVJobEnum jobEnum)
        {
            List<byte> sendData = new List<byte>();
            string tmp = "KH-" + agvTask.TaskNum.ToString();
            List<byte> taskID = Encoding.Default.GetBytes(tmp).ToList();//任务ID
            taskID.Insert(0, 30);
            taskID.Insert(1, Convert.ToByte(tmp.Length));
 
            for (int i = 0; i < 30 - tmp.Length; i++)
            {
                taskID.Add(0);
            }
            sendData.AddRange(taskID);
 
            List<byte> taskStart = Encoding.Default.GetBytes(agvTask.SourceAddress).ToList();
            taskStart.Insert(0, 20);
            taskStart.Insert(1, Convert.ToByte(agvTask.SourceAddress.Length));
 
            for (int i = 0; i < 20 - agvTask.SourceAddress.Length; i++)
            {
                taskStart.Add(0);
            }
            sendData.AddRange(taskStart);
 
            List<byte> taskEnd = Encoding.Default.GetBytes(agvTask.TargetAddress).ToList();
            taskEnd.Insert(0, 20);
            taskEnd.Insert(1, Convert.ToByte(agvTask.TargetAddress.Length));
 
            for (int i = 0; i < 20 - agvTask.TargetAddress.Length; i++)
            {
                taskEnd.Add(0);
            }
            sendData.AddRange(taskEnd);
 
            byte[] taskType = BitConverter.GetBytes((ushort)1).ToArray();
            Array.Reverse(taskType);
            sendData.AddRange(taskType);
 
            List<byte> containerType = Encoding.Default.GetBytes(agvTask.Barcode).ToList();
            containerType.Insert(0, 30);
            containerType.Insert(1, Convert.ToByte(agvTask.Barcode.Length));
 
            for (int i = 0; i < 30 - agvTask.Barcode.Length; i++)
            {
                containerType.Add(0);
            }
            sendData.AddRange(containerType);
 
            byte[] taskPriority = BitConverter.GetBytes((ushort)1).ToArray();
            Array.Reverse(taskPriority);
            sendData.AddRange(taskPriority);
 
            byte[] taskFlag = BitConverter.GetBytes((ushort)jobEnum).ToArray();
            Array.Reverse(taskFlag);
            sendData.AddRange(taskFlag);
 
            var operateResult = client.Communicator.Write("DB1000.0", sendData.ToArray());
            if (!operateResult)
                return "AGV发送任务失败";
            //WriteLog.Info("AGV发送任务").Write("任务号" + agvTask.agv_tasknum + "AGV编号" + client.PLCName + DateTime.Now, "AGV发送任务");
 
            return "";
        }
    }
}