patrick
2019-12-10 1c4426810c71eead57084be8a18ade8d314dd8c4
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
using Bro.Common.Base;
using Bro.Common.Helper;
using Bro.Common.Interface;
using Bro.Common.Model;
using Bro.Common.Model.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using static Bro.Common.Helper.EnumHelper;
 
namespace Bro.Device.AuboRobot
{
    [Device("AuboRobot", "奥博机器人", EnumHelper.DeviceAttributeType.Device)]
    public class AuboRobotDriver : DeviceBase, IMonitor
    {
        public Action<DateTime, AuboRobotDriver, RobotMsg> OnMsgReceived { get; set; }
 
        AuboRobotInitialConfig IConfig
        {
            get => InitialConfig as AuboRobotInitialConfig;
        }
 
        #region DeviceBase
        protected override void DeviceRun(IOperationConfig config)
        {
        }
 
        protected override void DeviceSet(IDeviceConfig config)
        {
        }
 
        protected override void Init()
        {
            oldValues = new List<int>();
 
            if (string.IsNullOrWhiteSpace(IConfig.EndChar))
            {
                throw new ProcessException("协议文本的结束字符不可为空,请检查配置");
            }
 
            client = new TcpClient();
            client.SendBufferSize = client.ReceiveBufferSize = 0;
            client.Client.Blocking = true;
            client.NoDelay = true;
            client.BeginConnect(IPAddress.Parse(IConfig.RobotIP), IConfig.RobotPort, OnConnect, null);
 
            replyHandleDict = new Dictionary<int, AutoResetEvent>();
            replyErrorCodeDict = new Dictionary<int, int>();
            taskHandleDict = new Dictionary<int, ManualResetEvent>();
        }
 
        protected override void Pause()
        {
        }
 
        protected override void Resume()
        {
        }
 
        RobotMsg scanMsg = new RobotMsg();
        protected override void Start()
        {
            //Query Robot IOs
            //SendMsg(RobotMsgType.Send, 0, true, RobotMsgAction.IO, RobotMsgParas.Query, new List<string>());
 
            scanMsg = new RobotMsg();
            scanMsg.Action = RobotMsgAction.IOQuery;
 
            Task.Run(() =>
            {
                Monitor();
            });
        }
 
        protected override void Stop()
        {
            replyHandleDict.Values.ToList().ForEach(h => h.Set());
            replyHandleDict.Clear();
 
            taskHandleDict.Values.ToList().ForEach(h => h.Set());
            taskHandleDict.Clear();
 
            if (client != null && client.Connected)
            {
                client.Close();
            }
        }
        #endregion
 
        TcpClient client = new TcpClient();
        NetworkStream stream = null;
        byte[] buffer = new byte[1024];
 
        private void OnConnect(IAsyncResult ar)
        {
            try
            {
                client.EndConnect(ar);
                stream = client.GetStream();
                stream.BeginRead(buffer, 0, buffer.Length, OnDataReceived, null);
            }
            catch (Exception ex)
            {
                //OnLog?.Invoke(DateTime.Now, this, ex.GetExceptionMessage());
                LogAsync(DateTime.Now, "连接异常", ex.GetExceptionMessage());
 
                if (client != null && client.Connected)
                {
                    client.Close();
                }
                client.BeginConnect(IPAddress.Parse(IConfig.RobotIP), IConfig.RobotPort, OnConnect, null);
            }
        }
 
        private void OnDataReceived(IAsyncResult ar)
        {
            try
            {
                int dataLength = stream.EndRead(ar);
                if (dataLength > 0)
                {
                    byte[] data = buffer.Take(dataLength).ToArray();
 
                    string dataStr = System.Text.Encoding.ASCII.GetString(data).Trim();
 
                    AnalyzeData(dataStr);
 
                    stream.BeginRead(buffer, 0, buffer.Length, OnDataReceived, null);
                }
                else
                {
                    if (!client.Connected)
                    {
                        //OnLog?.Invoke(DateTime.Now, this, "返回空数据,连接中断");
                        LogAsync(DateTime.Now, "连接中断", "返回空数据,连接中断");
                        client.BeginConnect(IPAddress.Parse(IConfig.RobotIP), IConfig.RobotPort, OnConnect, null);
                    }
                }
            }
            catch (Exception ex)
            {
                //OnLog?.Invoke(DateTime.Now, this, $"{Name}:{ex.GetExceptionMessage()}");
                LogAsync(DateTime.Now, "数据接收异常", ex.GetExceptionMessage());
            }
        }
 
        string msg = "";
        object analyzeLock = new object();
        private async void AnalyzeData(string data)
        {
            await Task.Run(() =>
            {
                lock (analyzeLock)
                {
                    msg += data;
 
                    var datas = msg.Split(new string[] { IConfig.EndChar }, StringSplitOptions.RemoveEmptyEntries);
 
                    if (msg.EndsWith(IConfig.EndChar))
                    {
                        msg = "";
                    }
                    else
                    {
                        msg = datas[datas.Length - 1];
                        datas = datas.Take(datas.Length - 1).ToArray();
                    }
 
                    AnalyzeDataList(datas);
                }
            });
        }
 
        private async void AnalyzeDataList(string[] datas)
        {
            await Task.Run(() =>
            {
                Array.ForEach(datas, data =>
                {
                    RobotMsg msg = RobotMsg.GetRobotMsg(data, IConfig.Seperator);
 
                    if (msg.Type == RobotMsgType.Rec)
                    {
                        replyErrorCodeDict[msg.ID] = msg.Para1;
                        if (replyHandleDict.ContainsKey(msg.ID))
                        {
                            replyHandleDict[msg.ID].Set();
                        }
                    }
                    else
                    {
                        if (msg.Action == RobotMsgAction.IOQuery)
                        {
                            newValues = new List<int>();
 
                            for (int i = msg.Para1.ToString().Length - 1; i >= 0; i--)
                            {
                                newValues.Add((msg.Para1 >> i) & 1);
                            }
 
                            MonitorHandle.Set();
                        }
                        else
                        {
                            canMonitor = true;
                            switch (msg.Action)
                            {
                                case RobotMsgAction.Move:
                                    CurrentPoint = msg.Point;
                                    break;
                                //case RobotMsgAction.Load:
                                //    //SlotIndex = msg.Para1;
                                //    break;
                                case RobotMsgAction.GetPosition:
                                    CurrentPoint = msg.Point;
                                    break;
                                default:
                                    break;
                            }
 
                            if (taskHandleDict.ContainsKey(msg.ID))
                            {
                                taskHandleDict[msg.ID].Set();
                            }
 
                            LogAsync(DateTime.Now, "指令反馈", msg.GetDisplayText());
                            OnMsgReceived?.BeginInvoke(DateTime.Now, this, msg, null, null);
                        }
                    }
                });
            });
        }
 
        int sid = 1;
        int SID
        {
            get
            {
                if (sid > 99)
                {
                    sid = 1;
                }
 
                return sid++;
            }
        }
 
        Dictionary<int, AutoResetEvent> replyHandleDict = new Dictionary<int, AutoResetEvent>();
        Dictionary<int, int> replyErrorCodeDict = new Dictionary<int, int>();
        Dictionary<int, ManualResetEvent> taskHandleDict = new Dictionary<int, ManualResetEvent>();
 
        public void SendReplyMsg(int replyId)
        {
            RobotMsg msg = new RobotMsg();
 
            msg.Type = RobotMsgType.Rec;
            msg.ID = replyId;
 
            SendMsg(msg, false);
        }
 
        bool canMonitor = true;
        object monitorLock = new object();
        public void SendMsg(RobotMsg msg, bool isWaitReply = true, bool isMonitorMsg = false)
        {
            replyErrorCodeDict[msg.ID] = 0;
 
            if (isWaitReply)
            {
                replyHandleDict[msg.ID] = new AutoResetEvent(false);
            }
 
            byte[] bytes = msg.GetMsgBytes(IConfig.Seperator, IConfig.EndChar, out string dataStr);
            if (!isMonitorMsg)
            {
                LogAsync(DateTime.Now, "指令发送", dataStr);
            }
 
            bool isNotTimeout = true;
            int reTryTime = IConfig.TimeoutRetryTimes;
            do
            {
                lock (monitorLock)
                {
                    if (!isMonitorMsg)
                    {
                        canMonitor = false;
                    }
 
                    if (isMonitorMsg && !canMonitor)
                        return;
 
                    stream.Write(bytes, 0, bytes.Length);
 
                    if (!isMonitorMsg)
                    {
                        LogAsync(DateTime.Now, "数据发送", BitConverter.ToString(bytes));
                    }
                }
 
                if (isWaitReply)
                {
                    int errorCode = replyErrorCodeDict[msg.ID];
 
                    if (errorCode != 0)
                    {
                        var desc = IConfig.RobotReplyWarnings.FirstOrDefault(u => u.WarningCode == errorCode);
                        throw new ProcessException($"{Name}{msg.ID}任务反馈异常{errorCode},异常描述:{(desc == null ? "无" : desc.WarningDescription)}");
                    }
 
                    isNotTimeout = replyHandleDict[msg.ID].WaitOne(IConfig.ReplyTimeout);
 
                    if (!isNotTimeout)
                    {
                        reTryTime--;
                    }
                }
            } while (reTryTime > 0 && !isNotTimeout);
 
            if (isWaitReply)
            {
                replyHandleDict.Remove(msg.ID);
            }
 
            if (!isNotTimeout)
            {
                throw new ProcessException($"{Name}反馈数据超时\r\n" + msg.GetDisplayText());
            }
        }
 
        #region 执行结果属性
        public RobotPoint CurrentPoint { get; set; } = null;
        //public int SlotIndex { get; set; } = 0;
        #endregion
 
        public void Move(RobotPoint point, MoveType isAbs, bool isWaitFinished)
        {
            CurrentPoint = null;
 
            RobotMsg msg = new RobotMsg();
            msg.Type = RobotMsgType.Send;
            msg.ID = SID;
 
            msg.Action = RobotMsgAction.Move;
            msg.Para1 = (int)isAbs;
 
            msg.Point = point ?? new RobotPoint();
 
            SendMsg(msg, true);
 
            TaskTimeoutCheck(isWaitFinished, msg.ID, $"{Name}{(isAbs.GetEnumDescription())}至{point.GetDisplayText()}动作超时");
        }
 
        public void Load(RobotPoint point, TrayType trayType, bool isWaitFinished)
        {
            //SlotIndex = 0;
 
            RobotMsg msg = new RobotMsg();
            msg.Type = RobotMsgType.Send;
            msg.ID = SID;
 
            msg.Action = RobotMsgAction.Load;
            msg.Para1 = (int)trayType;
            msg.Point = point;
 
            SendMsg(msg, true);
 
            TaskTimeoutCheck(isWaitFinished, msg.ID, $"{Name}取{trayType.ToString()}{point.GetDisplayText()}动作超时");
 
            //if (isWaitFinished && SlotIndex <= 0)
            //{
            //    throw new ProcessException($"{Name}没有可用的空白格位,无法放置卷宗");
            //}
        }
 
        public void UnLoad(RobotPoint point, TrayType trayType, bool isWaitFinished)
        {
            RobotMsg msg = new RobotMsg();
            msg.Type = RobotMsgType.Send;
            msg.ID = SID;
 
            msg.Action = RobotMsgAction.Unload;
            msg.Para1 = (int)trayType;
            msg.Point = point;
 
            SendMsg(msg, true);
 
            TaskTimeoutCheck(isWaitFinished, msg.ID, $"{Name}卸{trayType.ToString()}{point.GetDisplayText()}动作超时");
        }
 
        public void GetPosition(bool isWaitFinished)
        {
            CurrentPoint = null;
 
            RobotMsg msg = new RobotMsg();
            msg.Type = RobotMsgType.Send;
            msg.ID = SID;
 
            msg.Action = RobotMsgAction.GetPosition;
 
            SendMsg(msg, true);
 
            TaskTimeoutCheck(isWaitFinished, msg.ID, $"{Name}获取当前坐标超时");
        }
 
        public void SetBasePoint()
        {
            RobotMsg msg = new RobotMsg();
            msg.Type = RobotMsgType.Send;
            msg.ID = SID;
 
            msg.Action = RobotMsgAction.BasePoint;
 
            SendMsg(msg, true);
        }
 
        public void SetIO(int outputIndex, bool isOn)
        {
            RobotMsg msg = new RobotMsg();
            msg.Type = RobotMsgType.Send;
            msg.ID = SID;
 
            msg.Action = RobotMsgAction.IOSet;
            msg.Para1 = outputIndex;
            msg.Para2 = isOn ? 1 : 0;
 
            SendMsg(msg, true);
        }
 
        private void TaskTimeoutCheck(bool isWaitFinished, int msgId, string errorMsg)
        {
            if (isWaitFinished)
            {
                taskHandleDict[msgId] = new ManualResetEvent(false);
                taskHandleDict[msgId].Reset();
                bool isNotTimeout = taskHandleDict[msgId].WaitOne((int)(IConfig.OperationTimeout * 60 * 1000));
 
                taskHandleDict.Remove(msgId);
 
                if (!isNotTimeout)
                {
                    throw new ProcessException(errorMsg);
                }
            }
        }
 
        #region IMonitor
        public event OnMonitorInvokeDelegate OnMonitorInvoke;
        public event OnMonitorAlarmDelegate OnMonitorAlarm;
 
        protected List<int> oldValues = new List<int>();
        List<int> newValues = new List<int>();
        public ManualResetEvent MonitorHandle { get; set; } = new ManualResetEvent(false);
        public List<int> GetIOValues()
        {
            MonitorHandle.Reset();
            scanMsg.ID = SID;
            SendMsg(scanMsg, true, true);
 
            var isNotTimeout = MonitorHandle.WaitOne(IConfig.ReplyTimeout * 3);
 
            if (!isNotTimeout)
                throw new ProcessException($"{Name}监听操作超时");
 
            return newValues;
        }
 
        public virtual void Monitor()
        {
            while (CurrentState != EnumHelper.DeviceState.DSClose && CurrentState != EnumHelper.DeviceState.DSExcept)
            {
                try
                {
                    if (IConfig.IsEnableMonitor)
                    {
                        List<int> newValues = GetIOValues();
 
                        if (newValues == null || newValues.Count == 0)
                            continue;
 
                        if (oldValues.Count == 0)
                        {
                            oldValues = newValues.ConvertAll(s => -1).ToList();
                        }
 
                        if (oldValues.Count == newValues.Count)
                        {
                            var tempNew = new List<int>(newValues);
                            var tempOld = new List<int>(oldValues);
                            MonitorCheckAndInvoke(tempNew, tempOld);
                        }
                        oldValues = new List<int>(newValues);
                    }
 
                    Thread.Sleep(IConfig.ScanInterval);
                }
                catch (Exception ex)
                {
                    LogAsync(DateTime.Now, "监听异常", ex.GetExceptionMessage());
                }
            }
        }
 
        protected virtual void MonitorCheckAndInvoke(List<int> tempNew, List<int> tempOld)
        {
            IConfig.WarningSetCollection.ForEach(w =>
            {
                if (w.WarningIndex_Word < 0 || w.WarningIndex_Word >= tempNew.Count)
                    return;
 
                bool isOn = tempNew[w.WarningIndex_Word] == 1;
                if (w.CurrentStatus != isOn)
                {
                    w.CurrentStatus = isOn;
                    OnMonitorAlarm?.BeginInvoke(DateTime.Now, this, w, null, null);
                }
            });
 
            IConfig.MonitorSetCollection.ForEach(m =>
            {
                if (m.TriggerIndex < 0 || m.TriggerIndex >= tempNew.Count)
                {
                    return;
                }
 
                int newValue = tempNew[m.TriggerIndex];
                int oldValue = tempOld[m.TriggerIndex];
 
                if (newValue != oldValue)
                {
                    if (m.TriggerValue == -999 || newValue == m.TriggerValue)
                    {
                        if (m.OpConfig == null)
                        {
                            m.OpConfig = new OperationConfigBase();
                        }
 
                        m.OpConfig.InputPara = m.InputDataIndex.ConvertAll(index =>
                        {
                            return tempNew[index];
                        }).ToList();
 
                        OnMonitorInvoke?.BeginInvoke(DateTime.Now, this, m, null, null);
                    }
                }
            });
        }
 
        public virtual void ResetAlarm()
        {
            IConfig.WarningSetCollection.ForEach(u => u.CurrentStatus = !u.TriggerValue);
        }
        #endregion
    }
}