wangxinhui
2024-09-23 a3eb67538c4716aef9967f1e6301720cce095e3c
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
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using WIDESEA_Common;
using WIDESEA_Common.CutomerModel;
using WIDESEA_Common.Tools;
using WIDESEA_Core.Utilities;
using WIDESEA_Entity.DomainModels;
using WIDESEA_Entity.DomainModels.Equipment;
using WIDESEA_Services.IRepositories;
using WIDESEA_Services.Repositories;
using WIDESEA_WCS.WCSClient;
 
namespace WIDESEA_WCS
{
    public class WCSService
    {
 
        /// <summary>
        /// PLC连接集合
        /// </summary>
        public static List<PLCClient> Clients;
 
        /// <summary>
        /// 调度中心
        /// </summary>
        public static ISchedulerCenterServer scheduler;
 
        /// <summary>
        /// Job集合
        /// </summary>
        static List<JobOptions> jobs = new List<JobOptions>();
        static List<HCJCenterEqDB> centerEqDBList;
        #region 开启服务
        /// <summary>
        /// 开启服务
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent StartService()
        {
            var configTxt = File.ReadAllText(Directory.GetCurrentDirectory() + "/time_allocation.json");
       
            var jsonObject = JObject.Parse(configTxt);
              jsonObject["MM"] = "456";
                var convertString = Convert.ToString(jsonObject);
                File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "time_allocation.json"), convertString);
                
                
                //File.WriteAllText(Path.Combine(_basePath, _appsettingsProductionJson), convertString);
 
            WebResponseContent responseContent = new WebResponseContent();
            try
            {
                if (!CheckServerState().Status)//开启服务之前检查调度是否已开启及PLC是否已连接
                {
                    WIDESEA.Helper.GetToken();//hsl授权
                    WebResponseContent content = ConnectServer();
                    if (content.Status)
                    {
                        responseContent = StartSchedule();
                        if (!responseContent.Status)
                        {
                            DisconnectServer();
                        }
                    }
                    else
                    {
                        DisconnectServer();
                        responseContent = content;
                    }
                }
                else
                {
                    responseContent = WebResponseContent.Instance.Error("服务已开启");
                }
            }
            catch (Exception ex)
            {
                responseContent = responseContent.Error(ex.Message);
            }
            return responseContent;
        }
        #endregion
 
        #region 关闭服务
        /// <summary>
        /// 关闭服务(调度及PLC连接)
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent CloseService()
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                //if (!UserContext.Current.UserName.Contains("admin"))
                //{
                //    content.Message = "未授权操作!";
                //    content.Status = false;
                //    return content;
                //}
                if (scheduler != null)
                {
                    CloseSchedule();
                    DisconnectServer();
                    scheduler = null;
                    content = content.OK();
                }
                else
                {
                    content = WebResponseContent.Instance.Error("任务调度已停止");
                }
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
        #endregion
 
        #region 检查服务状态
        /// <summary>
        /// 检查服务状态
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent CheckServerState()
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                if (scheduler != null && Clients.Any())
                {
                    content = content.OK(message: "");
                }
                else
                {
                    CloseService();
                    content = content.Error(message: "服务已关闭");
                }
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
        #endregion
 
        #region 暂停或恢复指定的计划任务
        /// <summary>
        /// 暂停或恢复指定的计划任务
        /// </summary>
        /// <param name="job"></param>
        /// <returns></returns>
        public static WebResponseContent PauseOrResumeJob(SaveModel saveModel)
        {
            return dt_equipmentinfoRepository.Instance.DbContextBeginTransaction(() =>
            {
                string equipment_name = saveModel.MainData["equipment_name"].ToString();
                Idt_equipmentinfoRepository repository = new dt_equipmentinfoRepository(new WIDESEA_Core.EFDbContext.VOLContext());
                dt_equipmentinfo equipmentinfo = repository.FindFirst(x => x.equipment_name == saveModel.MainData["equipment_name"].ToString());
                if (equipmentinfo == null)
                    return WebResponseContent.Instance.Error($"未找到该设备【{saveModel.MainData["equipNum"]}】");
                if (equipmentinfo.equipment_state == EquipmentState.Enable.ToString())
                    equipmentinfo.equipment_state = EquipmentState.DisEnable.ToString();
                else 
                    equipmentinfo.equipment_state = EquipmentState.Enable.ToString();
                if (dt_equipmentinfoRepository.Instance.Update(equipmentinfo, true) <= 0)
                    return WebResponseContent.Instance.Error("设备状态修改失败");
                JobOptions options = new JobOptions { JobName = equipmentinfo.equipment_name, JobGroup = equipmentinfo.equipment_type };
                if (scheduler == null)
                    return WebResponseContent.Instance.OK("设备状态修改成功");
 
                if (!scheduler.IsExistScheduleJobAsync(options).Result)
                {
                    return WebResponseContent.Instance.OK("设备状态修改成功");
                }
                if (saveModel.MainData["equipment_state"].ToString() == EquipmentState.Enable.ToString())
                {
                    return scheduler.PauseJob(options).Result;
                }
                else
                {
                    return scheduler.ResumeJob(options).Result;
                }
            });
 
        }
        #endregion
 
        #region 开启调度
        /// <summary>
        /// 开启调度
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent StartSchedule()
        {
            WebResponseContent responseContent = new WebResponseContent();
            try
            {
                StdSchedulerFactory factory = new StdSchedulerFactory();
                scheduler = new SchedulerCenterServer(factory);
                List<JobOptions> jobOptions = VV_DispatchRepository.Instance.FindToJobOptions(x => true && x.Enable == EquipmentState.Enable.ToString());
                jobOptions.ForEach(x => { x.JobParams = Clients.Where(y => y.PLCName == x.JobName).FirstOrDefault(); });
                //未连接plc,默认不开启调度
                //jobOptions = jobOptions.Where(t => t.JobParams != null).ToList();
                if (!jobOptions.Any())
                {
                    responseContent = WebResponseContent.Instance.Error("当前未配置调度,或调度PLC连接失败");
                    return responseContent;
                }
 
                for (int i = 0; i < jobOptions.Count; i++)
                {
                    WebResponseContent content = scheduler.AddScheduleJobAsync(jobOptions[i]).Result;
                    if (!content.Status)
                    {
                        factory = null;
                        scheduler = null;
                        return content;
                    }
                }
                responseContent = scheduler.StartScheduleAsync().Result;
            }
            catch (Exception ex)
            {
                responseContent = responseContent.Error(ex.Message);
                scheduler = null;
            }
            return responseContent;
        }
        #endregion
 
        #region 停止调度
        /// <summary>
        /// 停止调度
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent CloseSchedule()
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                content = scheduler.StopScheduleAsync().Result;
            }
            catch (Exception ex)
            {
                content = content.Error(ex.Message);
            }
            return content;
        }
        #endregion
 
        #region 连接PLC
        /// <summary>
        /// 连接PLC
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent ConnectServer()
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                if (Clients != null)
                {
                    DisconnectServer();
                }
                //jobs = new List<JobOptions>();
                //jobs = VV_DispatchRepository.Instance.FindJobOptions(x => true);
                List<string> plcNames = dt_equipmentinfoRepository.Instance.Find(x => x.equipment_state == EquipmentState.Enable.ToString()).Select(t => t.equipment_name).ToList();
 
                if (plcNames.Count == 0)
                    return content = WebResponseContent.Instance.Error("当前无PLC连接配置或设备被禁用");
                Clients = new List<PLCClient>();
                //根据设备的禁用启用,判断plc是否需要链接
                List<dt_plcinfohead> plcinfoheads = dt_plcinfoheadRepository.Instance.Find(x => plcNames.Contains(x.plcinfo_name));
                //plc协议
                List<dt_plcinfodetail> plcinfodetails = dt_plcinfodetailRepository.Instance.Find(x => true);
 
                //链接消息
                string connMs = string.Empty;
                //防止重复链接
                List<string> coonIpList = new List<string>();
                foreach (dt_plcinfohead head in plcinfoheads)
                {
                    try
                    {
                        PLCClient client = new PLCClient(head, plcinfodetails)
                        {
                            PLCName = head.plcinfo_name,
                            PLCDescroption = head.plcinfo_remark,
                            PLCDownLoc = head.plcinfo_down,
                            EquipType = head.plcinfo_equiptype
                        };
 
                        if (!coonIpList.Contains(head.plcinfo_ip) || true)//调试时用ture
                        {
                            coonIpList.Add(head.plcinfo_ip);
                            client.Connect();
                        }
                        //else
                        //{
                        //    switch (client.PLCType)
                        //    {
                        //        case "SiemensPLC":
                        //            client.SiemensPLCClient = Clients.FirstOrDefault(t => t.PLCName == haveCoonIpClient.plcinfo_name).SiemensPLCClient;
                        //            break;
                        //        case "MelsecPLC":
                        //            client.MelsecPLCClient = Clients.FirstOrDefault(t => t.PLCName == haveCoonIpClient.plcinfo_name).MelsecPLCClient;
                        //            break;
                        //        default:
                        //            break;
                        //    }
                        //}
                        Clients.Add(client);
                    }
                    catch (Exception ex)
                    {
                        connMs += $"{head.plcinfo_name},{ex.Message}\n";
                    }
                }
                WriteLog.GetLog().Write(connMs, "服务启动");
                content = WebResponseContent.Instance.OK("PLC连接成功!");
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
                Clients = null;
            }
            return content;
        }
        #endregion
 
        #region 断开与PLC的连接
        /// <summary>
        /// 断开与PLC的连接
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent DisconnectServer()
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                if (Clients != null && Clients.Any())
                {
                    for (int i = 0; i < Clients.Count; i++)
                    {
                        Clients[i]?.Disconnect();
                    }
                    content = WebResponseContent.Instance.OK(message: "已断开与PLC的连接!");
                }
                else
                {
                    content = WebResponseContent.Instance.Error("当前与PLC无连接!");
                }
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            finally
            {
                Clients = null;
            }
            return content;
        }
        #endregion
 
        #region ThreadMethod PLC连接内置线程 方法
        static void Read(PLCClient client)
        {
            //Console.Out.WriteLine(client.Read("DB3.0", "INT"));
        }
        #endregion
 
        #region 获取任务触发器状态
        /// <summary>
        /// 获取任务触发器状态
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent GetTaskStaus()
        {
            WebResponseContent responseContent = new WebResponseContent();
            List<TaskInfoDto> taskInfoDtos = new List<TaskInfoDto>();
            if (jobs.FirstOrDefault() == null)
                jobs = VV_DispatchRepository.Instance.FindJobOptions(x => true);
 
            for (int i = 0; i < jobs.Count; i++)
            {
                List<TaskInfoDto> temp = new List<TaskInfoDto>();
                if (scheduler == null)
                {
                    temp = new List<TaskInfoDto>
                    {
                        new TaskInfoDto()
                        {
                            JobId = jobs[i].JobName.ObjToString(),
                            JobGroup = jobs[i].JobGroup,
                            TriggerId = "",
                            TriggerGroup = "",
                            TriggerStatus = "不存在",
                            IsConnected = Clients.Where(x=>x.PLCName == jobs[i].JobName).FirstOrDefault()?.IsConnected??false
                        }
                    };
                }
                else
                {
                    temp = scheduler.GetTaskStaus(jobs[i]).Result;
                }
 
                taskInfoDtos.AddRange(temp);
            }
            return WebResponseContent.Instance.OK(data: taskInfoDtos);
        }
        #endregion
 
        #region 立即执行 一个任务
        /// <summary>
        /// 立即执行 一个任务
        /// </summary>
        /// <param name="jobName"></param>
        /// <returns></returns>
        public static WebResponseContent ExecuteJobAsync(string jobName)
        {
            WebResponseContent result = new WebResponseContent();
            try
            {
                JobOptions job = jobs.Where(x => x.JobName == jobName).FirstOrDefault();
                if (job == null)
                {
                    result = WebResponseContent.Instance.Error($"立即执行计划任务失败:未找到该任务计划,任务计划:{jobName}");
                }
                else
                {
                    result = scheduler.ExecuteJobAsync(job).Result;
                }
 
            }
            catch (Exception ex)
            {
                result.Message = $"立即执行计划任务失败:【{ex.Message}】";
            }
 
            return result;
        }
        #endregion
 
        #region 获取任务触发器状态
        /// <summary>
        /// 获取任务触发器状态
        /// </summary>
        /// <returns></returns>
        public static PageGridData<TaskInfoDto> GetPageData()
        {
            try
            {
                List<TaskInfoDto> taskInfoDtos = new List<TaskInfoDto>();
                if (jobs.FirstOrDefault() == null)
                    jobs = VV_DispatchRepository.Instance.FindJobOptions(x => true);
 
                for (int i = 0; i < jobs.Count; i++)
                {
                    List<TaskInfoDto> temp = new List<TaskInfoDto>();
                    if (scheduler == null)
                    {
 
                        temp = new List<TaskInfoDto>
                        {
                            new TaskInfoDto()
                            {
                                JobId = jobs[i].JobName.ObjToString(),
                                JobGroup = jobs[i].JobGroup,
                                TriggerId = "",
                                TriggerGroup = "",
                                TriggerStatus = "不存在",
                                PLCConnetState = jobs[i].PLCConnectState,
                                IsConnected = false
                            }
                        };
                    }
                    else
                    {
                        temp = scheduler.GetTaskStaus(jobs[i]).Result;
                        if (Clients != null)
                        {
                            for (int j = 0; j < temp.Count; j++)
                            {
                                temp[j].IsConnected = Clients.Where(x => x.PLCName == temp[j].JobId).FirstOrDefault()?.IsConnected ?? false;
                            }
                        }
                    }
 
                    taskInfoDtos.AddRange(temp);
                }
                return new PageGridData<TaskInfoDto> { rows = taskInfoDtos, total = taskInfoDtos?.Count ?? 0 };
            }
            catch (Exception ex)
            {
                return new PageGridData<TaskInfoDto> { rows = null, total = 0, status = 404, msg = ex.Message };
            }
 
        }
        #endregion
 
        public static JobOptions GetJobOptions(string jobName)
        {
            return jobs.Where(x => x.JobName == jobName).FirstOrDefault();
        }
        public static ResultMaterstateUp Updatestockstate(MESupdateMaterStateRequest request)
        {
            ResultMaterstateUp result = new ResultMaterstateUp();
            try
            {
                var stock = bill_group_stockRepository.Instance.FindFirst(v => v.BarCode == request.BarCode);
                if (stock == null)
                    throw new Exception(string.Format("当前物料编号{0}未查询到库存", request.BarCode));
                if (stock.location_id == null)
                    throw new Exception(string.Format("当前物料{0}未绑定货位", request.BarCode));
                var location = base_ware_locationRepository.Instance.FindFirst(v => v.id == stock.location_id);
                if (location.equipment_type == "TBHCJ")
                {
                    stock.TB_Status = request.MaterialStatus;
                }
                else if (location.equipment_type == "GYHCJ")
                {
                    stock.GY_Status = request.MaterialStatus;
                }
                else if (location.equipment_type == "QXHCJ")
                {
                    stock.QX_Status = request.MaterialStatus;
                }
                else
                {
                    stock.FQ_Status = request.MaterialStatus;
                }
                stock.MaterialStatus = request.MaterialStatus;
                stock.updated_time = DateTime.Now;
                bill_group_stockRepository.Instance.Update(stock, true);
 
                result.Code = 0;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
                result.Code = 1;
            }
            return result;
        }
 
        public static List<ResultLocationState> GetLocationState(string Devid)
        {
            List<ResultLocationState> result = new List<ResultLocationState>();
            try
            {
                if (Devid == null)
                {
                    var Id = base_ware_locationRepository.Instance.FindFirst(v => v.down_code == Devid || v.upper_code == Devid);
                    var location = bill_group_stockRepository.Instance.FindFirst(v => v.location_id == Id.id);
                    ResultLocationState content = new ResultLocationState();
                    content.BarCode = location.BarCode;
                    content.MaterialStatus = location.MaterialStatus;
                    content.MaterialType = location.MaterialType;
                    content.Devid = Devid;
                    result.Add(content);
                }
                else
                {
                    var IdList = base_ware_locationRepository.Instance.Find(v => v.down_code == Devid || v.upper_code == Devid).ToList();
                    for (int i = 0; i < IdList.Count; i++)
                    {
                        ResultLocationState content = new ResultLocationState();
                        var locationList = bill_group_stockRepository.Instance.FindFirst(v => v.location_id == IdList[i].id);
                        if (locationList != null)
                        {
                            content.BarCode = locationList.BarCode;
                            content.MaterialStatus = locationList.MaterialStatus;
                            content.MaterialType = locationList.MaterialType;
                            content.Devid = Devid;
                        }
                        else
                        {
                            content.BarCode = "";
                            content.MaterialStatus = "";
                            content.MaterialType = "";
                            content.Devid = IdList[i].down_code;//暂时不知道给那个
                        }
                        result.Add(content);
 
                    }
 
                }
                //
                //result.Code = 0;
            }
            catch (Exception)
            {
                //result.Code = 1;
            }
            return result;
        }
    }
}