1
wangxinhui
2025-06-12 e7be74e711076896e7e841b54691daa95067c567
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
using Microsoft.AspNetCore.Components.Routing;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIDESEAWCS_Common.APIEnum;
using WIDESEAWCS_Common.TaskEnum;
using WIDESEAWCS_Core;
using WIDESEAWCS_Core.Enums;
using WIDESEAWCS_Core.Helper;
using WIDESEAWCS_IBasicInfoRepository;
using WIDESEAWCS_ITaskInfoRepository;
using WIDESEAWCS_ITaskInfoService;
using WIDESEAWCS_Model.Models;
using WIDESEAWCS_QuartzJob;
using WIDESEAWCS_QuartzJob.DeviceBase;
using WIDESEAWCS_QuartzJob.Models;
using WIDESEAWCS_QuartzJob.Service;
using WIDESEAWCS_QuartzJob.StackerCrane.Enum;
using WIDESEAWCS_Tasks.HoisterJob;
using WIDESEAWCS_Tasks.StackerCraneJob;
using WIDESEAWCS_Core.Caches;
using WIDESEAWCS_Tasks.ConveyorLineJob;
using WIDESEAWCS_QuartzJob.Repository;
using WIDESEAWCS_DTO.TaskInfo;
using AutoMapper;
 
namespace WIDESEAWCS_Tasks
{
    [DisallowConcurrentExecution]
    public class StackerCraneJob_GM : JobBase, IJob
    {
        private readonly ICacheService _cacheService;
        private readonly ITaskService _taskService;
        private readonly ITaskExecuteDetailService _taskExecuteDetailService;
        private readonly ITaskRepository _taskRepository;
        private readonly IRouterService _routerService;
        private readonly IStationMangerRepository _stationMangerRepository;
        private readonly IRouterRepository _routerRepository;
        private readonly IMapper _mapper;
        private List<Dt_ApiInfo> apiInfos;
 
        public StackerCraneJob_GM(ITaskService taskService, ICacheService cacheService, ITaskExecuteDetailService taskExecuteDetailService, ITaskRepository taskRepository, IRouterService routerService, IStationMangerRepository stationMangerRepository, IRouterRepository routerRepository, IMapper mapper)
        {
            _taskService = taskService;
            _taskExecuteDetailService = taskExecuteDetailService;
            _taskRepository = taskRepository;
            _routerService = routerService;
            _stationMangerRepository = stationMangerRepository;
            _cacheService = cacheService;
            _routerRepository = routerRepository;
            _mapper = mapper;
 
            string? apiInfoStr = _cacheService.Get("apiInfos");
            if (!string.IsNullOrEmpty(apiInfoStr))
            {
                List<Dt_ApiInfo>? infos = JsonConvert.DeserializeObject<List<Dt_ApiInfo>>(apiInfoStr);
                if (infos == null || infos.Count == 0)
                {
                    apiInfos = new List<Dt_ApiInfo>();
                }
                else
                {
                    apiInfos = infos;
                }
            }
        }
 
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                CommonStackerCrane commonStackerCrane = (CommonStackerCrane)context.JobDetail.JobDataMap.Get("JobParams");
                if (commonStackerCrane != null)
                {
                    if (!commonStackerCrane.IsEventSubscribed)
                    {
                        commonStackerCrane.StackerCraneTaskCompletedEventHandler += CommonStackerCrane_StackerCraneTaskCompletedEventHandler;//订阅任务完成事件
                    }
                    commonStackerCrane.CheckStackerCraneTaskCompleted();//防止任务完成事件监测超时,再手动触发一次
                    if (commonStackerCrane.StackerCraneAutoStatusValue == StackerCraneAutoStatus.Automatic && commonStackerCrane.StackerCraneStatusValue == StackerCraneStatus.Normal && commonStackerCrane.StackerCraneWorkStatusValue == StackerCraneWorkStatus.Standby)
                    {
                        Dt_Task? task = GetTask(commonStackerCrane);
                        if (task != null)
                        {
                            StackerCraneTaskCommand? stackerCraneTaskCommand = ConvertToStackerCraneTaskCommand(task);
                            if (stackerCraneTaskCommand != null)
                            {
                                bool sendFlag = commonStackerCrane.SendCommand(stackerCraneTaskCommand);
                                if (sendFlag)
                                {
                                    commonStackerCrane.LastTaskType = task.TaskType;
                                    task.Dispatchertime = DateTime.Now;
                                    task.ExceptionMessage = "";
                                    if (task.TaskLength<=0)
                                    {
                                        WriteInfo(commonStackerCrane.DeviceCode, $"物料长度错误{task.TaskLength}");
                                        return Task.CompletedTask;
                                    }
                                    commonStackerCrane.Communicator.Write("DB105.58", (short)task.TaskLength);
                                    _taskService.UpdateTask(task, TaskStatusEnum.SC_Executing);
                                    commonStackerCrane.Communicator.Write("DB105.54", (short)1);
                                    //延时1s
                                    Thread.Sleep(1000);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteError(nameof(CommonStackerCraneJob), ex.Message, ex);
            }
            return Task.CompletedTask;
        }
 
        /// <summary>
        /// 任务完成事件订阅的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommonStackerCrane_StackerCraneTaskCompletedEventHandler(object? sender, WIDESEAWCS_QuartzJob.StackerCrane.StackerCraneTaskCompletedEventArgs e)
        {
            CommonStackerCrane? commonStackerCrane = sender as CommonStackerCrane;
            if (commonStackerCrane != null)
            {
                if (commonStackerCrane.GetValue<StackerCraneDBName, short>(StackerCraneDBName.WorkType) != 5)
                {
                    StackerCraneTaskCompleted(e.TaskNum, commonStackerCrane.DeviceCode);
                    commonStackerCrane.SetValue(StackerCraneDBName.WorkType, 5);
                }
            }
        }
 
        public WebResponseContent StackerCraneTaskCompleted(int taskNum, string deviceCode)
        {
            try
            {
                Dt_Task task = _taskRepository.QueryFirst(x => x.TaskNum == taskNum);
                if (task != null)
                {
                    if (task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.OutbondGroup)
                    {
                        Dt_StationManger stationManger = _stationMangerRepository.QueryFirst(x => x.StackerCraneStationCode == task.NextAddress);
                        if (stationManger == null)
                        {
                            _taskExecuteDetailService.AddTaskExecuteDetail(taskNum, $"输送线出库站点未配置,{task.NextAddress}");
                            _taskService.UpdateTaskExceptionMessage(taskNum, $"输送线出库站点未配置,{task.NextAddress}");
                            return WebResponseContent.Instance.Error($"输送线出库站点未配置,{task.NextAddress}");
                        }
 
                        int oldStatus = task.TaskState;
                        task.DeviceCode = stationManger.StationDeviceCode;
                        task.TaskState = TaskStatusEnum.Line_Execute.ObjToInt();
                        task.CurrentAddress = stationManger.StationCode;
                        _taskRepository.UpdateData(task);
                        _taskExecuteDetailService.AddTaskExecuteDetail(taskNum, $"系统自动流程,任务状态从【{oldStatus}】转到【{task.TaskState}】");
                        //todo 完成
                    }
                    else if (task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.InboundGroup || task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.RelocationGroup)
                    {
                        _taskService.TaskCompleted(taskNum);
                    }
                    else
                    {
                        WriteInfo(deviceCode, $"未找到该任务类型回调WMS任务完成接口,{task.TaskType}");
                        _taskExecuteDetailService.AddTaskExecuteDetail(taskNum, $"未找到该任务类型回调WMS任务完成接口,{task.TaskType}");
                        _taskService.UpdateTaskExceptionMessage(taskNum, $"未找到该任务类型回调WMS任务完成接口,{task.TaskType}");
                    }
                }
                else
                {
                    WriteInfo(deviceCode, $"未找到任务信息,任务号:{taskNum}");
                    return WebResponseContent.Instance.Error($"未找到任务信息,任务号:{taskNum}");
                }
 
                return WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                WriteError(deviceCode, $"任务完成错误", ex);
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
        /// <summary>
        /// 获取任务
        /// </summary>
        /// <param name="commonStackerCrane">堆垛机对象</param>
        /// <returns></returns>
        private Dt_Task? GetTask(CommonStackerCrane commonStackerCrane)
        {
            Dt_Task task;
            if (commonStackerCrane.LastTaskType == null)
            {
                task = _taskService.QueryStackerCraneTask(commonStackerCrane.DeviceCode);
            }
            else
            {
                if (commonStackerCrane.LastTaskType.GetValueOrDefault().GetTaskTypeGroup() == TaskTypeGroup.OutbondGroup)
                {
                    task = _taskService.QueryStackerCraneInTask(commonStackerCrane.DeviceCode);
                    if (task == null)
                    {
                        task = _taskService.QueryStackerCraneOutTask(commonStackerCrane.DeviceCode);
                    }
                }
                else
                {
                    task = _taskService.QueryStackerCraneOutTask(commonStackerCrane.DeviceCode);
                    if (task == null)
                    {
                        task = _taskService.QueryStackerCraneInTask(commonStackerCrane.DeviceCode);
                    }
                }
            }
 
            if (task != null && task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.OutbondGroup)
            {
                if (OutTaskStationIsOccupied(task) == null)
                {
                    bool flag = false;
                    List<string> otherOutStaionCodes = _routerService.QueryNextRoutes(commonStackerCrane.DeviceCode, task.NextAddress, task.TaskType).Select(x => x.ChildPosi).ToList();
                    List<Dt_Task> tasks = _taskService.QueryStackerCraneOutTasks(commonStackerCrane.DeviceCode, otherOutStaionCodes);
                    foreach (var item in tasks)
                    {
                        if (OutTaskStationIsOccupied(task) != null)
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        task = _taskService.QueryStackerCraneInTask(commonStackerCrane.DeviceCode);
                    }
                }
            }
 
            if (task != null && task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.OutbondGroup)
            {
                string? url = apiInfos.FirstOrDefault(x => x.ApiCode == APIEnum.WMSIsReloaction.ToString())?.ApiAddress;
                if (string.IsNullOrEmpty(url))
                {
                    _taskExecuteDetailService.AddTaskExecuteDetail(task.TaskNum, $"未找到WMS移库判断接口");
                    WriteError(commonStackerCrane.DeviceCode, $"未找到WMS移库判断接口");
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"未找到WMS移库判断接口");
                    return null;
                }
                string response = HttpHelper.Post($"{url}?taskNum={task.TaskNum}&locationCode={task.CurrentAddress}", "");//todo 调用WMS任务完成方法
                if (string.IsNullOrEmpty(response))
                {
                    _taskExecuteDetailService.AddTaskExecuteDetail(task.TaskNum, $"移库接口调用错误");
                    WriteError(commonStackerCrane.DeviceCode, $"移库接口调用错误");
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"移库接口调用错误");
                    return null;
                }
                WebResponseContent? responseContent = JsonConvert.DeserializeObject<WebResponseContent>(response);
                if (responseContent == null || !responseContent.Status)
                {
                    _taskExecuteDetailService.AddTaskExecuteDetail(task.TaskNum, $"移库接口调用错误");
                    WriteError(commonStackerCrane.DeviceCode, $"移库接口调用错误");
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"移库接口调用错误");
                    return null;
                }
                WMSTaskDTO? taskDTO = JsonConvert.DeserializeObject<WMSTaskDTO>(responseContent.Data.Serialize());
                if (taskDTO == null)
                {
                    _taskExecuteDetailService.AddTaskExecuteDetail(task.TaskNum, $"移库接口调用错误");
                    WriteError(commonStackerCrane.DeviceCode, $"移库接口调用错误");
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"移库接口调用错误");
                    return null;
 
                }
                if (task.TaskNum == taskDTO.TaskNum)
                {
                    return task;
                }
                else
                {
                    Dt_Task reloTask = _mapper.Map<Dt_Task>(taskDTO);
                    //判断移库货位任务是否已存在,如存在先执行
                    Dt_Task existTask = _taskService.QueryStackerExistTask(reloTask.PalletCode, reloTask.SourceAddress);
                    if (existTask != null)
                    {
                        return existTask;
                    }
                    else
                    {
                        reloTask.TaskState = TaskStatusEnum.SC_Execute.ObjToInt();
                        reloTask.CurrentAddress = taskDTO.SourceAddress;
                        reloTask.NextAddress = taskDTO.TargetAddress;
                        reloTask.DeviceCode = task.DeviceCode;
                        reloTask.TaskType = TaskTypeEnum.Relocation.ObjToInt();
                        int taskId = _taskRepository.AddData(reloTask);
                        reloTask.TaskId = taskId;
                    }
                    return reloTask;
 
                }
            }
 
            return task;
        }
 
        /// <summary>
        /// 出库任务判断出库站台是否被占用
        /// </summary>
        /// <param name="task">任务实体</param>
        /// <returns>如果未被占用,返回传入的任务信息,否则,返回null</returns>
        private Dt_Task? OutTaskStationIsOccupied([NotNull] Dt_Task task)
        {
            Dt_StationManger? stationManger = _stationMangerRepository.QueryFirst(x =>( x.StationCode == task.NextAddress || x.StackerCraneStationCode==task.NextAddress )&& x.StackerCraneCode == task.DeviceCode);
            if (stationManger != null)
            {
                IDevice? device = Storage.Devices.FirstOrDefault(x => x.DeviceCode == stationManger.StationDeviceCode);
                if (device != null)
                {
                    OtherDevice client = (OtherDevice)device;
                    bool ReadGood = client.GetValue<R_ConveyorLineDB, bool>(R_ConveyorLineDB.Goods, stationManger.StationCode);
                    if (!ReadGood)//出库站台未被占用
                    {
                        task.NextAddress = stationManger.StackerCraneStationCode;
                        _taskRepository.UpdateData(task);
                        return task;
                    }
                }
                else
                {
                    WriteInfo(task.DeviceCode, $"未找到出库站台【{stationManger.StationDeviceCode}】对应的通讯对象,无法判断出库站台是否被占用");
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"未找到出库站台【{stationManger.StationDeviceCode}】对应的通讯对象,无法判断出库站台是否被占用");
                }
            }
            else
            {
                WriteInfo(task.DeviceCode, $"未找到站台【{task.NextAddress}】信息,无法校验站台");
                _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"未找到站台【{task.NextAddress}】信息,无法校验站台");
            }
            return null;
        }
 
        /// <summary>
        /// 任务实体转换成命令Model
        /// </summary>
        /// <param name="task">任务实体</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public StackerCraneTaskCommand? ConvertToStackerCraneTaskCommand([NotNull] Dt_Task task)
        {
            StackerCraneTaskCommand stackerCraneTaskCommand = new StackerCraneTaskCommand();
 
            stackerCraneTaskCommand.Barcode = task.PalletCode;
            stackerCraneTaskCommand.TaskNum = task.TaskNum;
            stackerCraneTaskCommand.WorkType = 1;
            stackerCraneTaskCommand.TrayType = 0;
            if (task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.InboundGroup)//判断是否是入库任务
            {
                string[] startCodes = task.CurrentAddress.Split("-");
                if (startCodes.Length == 3)
                {
                    stackerCraneTaskCommand.StartRow = Convert.ToInt16(startCodes[0]);
                    stackerCraneTaskCommand.StartColumn = Convert.ToInt16(startCodes[1]);
                    stackerCraneTaskCommand.StartLayer = Convert.ToInt16(startCodes[2]);
                }
                else
                {
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"入库任务起点错误,起点:【{task.CurrentAddress}】");
                    WriteInfo(task.DeviceCode, $"入库任务起点错误,起点:【{task.CurrentAddress}】");
                    return null;
                }
 
                string[] targetCodes = task.NextAddress.Split("-");
                if (targetCodes.Length == 5)
                {
                    stackerCraneTaskCommand.EndRow = Convert.ToInt16(targetCodes[1]);
                    stackerCraneTaskCommand.EndColumn = Convert.ToInt16(targetCodes[2]);
                    stackerCraneTaskCommand.EndLayer = Convert.ToInt16(targetCodes[3]);
                }
                else
                {
                    //数据配置错误
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"入库任务终点错误,终点:【{task.NextAddress}】");
                    WriteInfo(task.DeviceCode, $"入库任务终点错误,终点:【{task.NextAddress}】");
                    return null;
                }
            }
            else if (task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.OutbondGroup)
            {
                string[] targetCodes = task.NextAddress.Split("-");
 
                if (targetCodes.Length == 3)
                {
                    stackerCraneTaskCommand.EndRow = Convert.ToInt16(targetCodes[0]);
                    stackerCraneTaskCommand.EndColumn = Convert.ToInt16(targetCodes[1]);
                    stackerCraneTaskCommand.EndLayer = Convert.ToInt16(targetCodes[2]);
                }
                else
                {
                    //数据配置错误
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"出库任务终点错误,终点:【{task.NextAddress}】");
                    WriteInfo(task.DeviceCode, $"出库任务终点错误,终点:【{task.NextAddress}】");
                    return null;
                }
 
                string[] sourceCodes = task.CurrentAddress.Split("-");
                if (sourceCodes.Length == 5)
                {
                    stackerCraneTaskCommand.StartRow = Convert.ToInt16(sourceCodes[1]);
                    stackerCraneTaskCommand.StartColumn = Convert.ToInt16(sourceCodes[2]);
                    stackerCraneTaskCommand.StartLayer = Convert.ToInt16(sourceCodes[3]);
                }
                else
                {
                    //数据配置错误
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"出库任务起点错误,起点:【{task.CurrentAddress}】");
                    WriteInfo(task.DeviceCode, $"出库任务起点错误,起点:【{task.CurrentAddress}】");
                    return null;
                }
            }
            else if (task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.RelocationGroup)
            {
                string[] targetCodes = task.NextAddress.Split("-");
                if (targetCodes.Length == 5)
                {
                    stackerCraneTaskCommand.EndRow = Convert.ToInt16(targetCodes[1]);
                    stackerCraneTaskCommand.EndColumn = Convert.ToInt16(targetCodes[2]);
                    stackerCraneTaskCommand.EndLayer = Convert.ToInt16(targetCodes[3]);
                }
                else
                {
                    //数据配置错误
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"移库任务终点错误,终点:【{task.NextAddress}】");
                    WriteInfo(task.DeviceCode, $"移库任务终点错误,终点:【{task.NextAddress}】");
                    return null;
                }
                string[] sourceCodes = task.CurrentAddress.Split("-");
                if (sourceCodes.Length == 5)
                {
                    stackerCraneTaskCommand.StartRow = Convert.ToInt16(sourceCodes[1]);
                    stackerCraneTaskCommand.StartColumn = Convert.ToInt16(sourceCodes[2]);
                    stackerCraneTaskCommand.StartLayer = Convert.ToInt16(sourceCodes[3]);
                }
                else
                {
                    //数据配置错误
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"移库任务起点错误,起点:【{task.CurrentAddress}】");
                    WriteInfo(task.DeviceCode, $"移库任务起点错误,起点:【{task.CurrentAddress}】");
                    return null;
                }
            }
            return stackerCraneTaskCommand;
        }
    }
}