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
using Bro.Common.Base;
using Bro.Common.Helper;
using Bro.Common.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
 
namespace Bro.Device.AuboRobot
{
    [Device("AuboRobot", "奥博机器人", EnumHelper.DeviceAttributeType.Device)]
    public class AuboRobotDriver : DeviceBase
    {
        public Action<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()
        {
            if (string.IsNullOrWhiteSpace(IConfig.EndChar))
            {
                throw new ProcessException("协议文本的结束字符不可为空,请检查配置", null);
            }
 
            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);
        }
 
        protected override void Pause()
        {
        }
 
        protected override void Resume()
        {
        }
 
        protected override void Start()
        {
            //Query Robot IOs
            //SendMsg(RobotMsgType.Send, 0, true, RobotMsgAction.IO, RobotMsgParas.Query, new List<string>());
        }
 
        protected override void Stop()
        {
            client.Close();
        }
        #endregion
 
        TcpClient client = new TcpClient();
        byte[] buffer = new byte[1024];
 
        private void OnConnect(IAsyncResult ar)
        {
            try
            {
                client.EndConnect(ar);
                client.GetStream().BeginRead(buffer, 0, buffer.Length, OnDateReceived, null);
            }
            catch (Exception ex)
            {
                OnLog?.Invoke(DateTime.Now, this, ex.GetExceptionMessage());
 
                client.BeginConnect(IPAddress.Parse(IConfig.RobotIP), IConfig.RobotPort, OnConnect, null);
            }
        }
 
        private void OnDateReceived(IAsyncResult ar)
        {
            int dataLength = client.GetStream().EndRead(ar);
 
            if (dataLength > 0)
            {
                byte[] data = buffer.Take(dataLength).ToArray();
 
                string dataStr = System.Text.Encoding.ASCII.GetString(data).Trim();
                AnalyzeData(dataStr);
 
                client.GetStream().BeginRead(buffer, 0, buffer.Length, OnDateReceived, null);
            }
            else
            {
                if (!client.Connected)
                {
                    OnLog?.Invoke(DateTime.Now, this, "返回空数据,连接中断");
                    client.BeginConnect(IPAddress.Parse(IConfig.RobotIP), IConfig.RobotPort, OnConnect, null);
                }
            }
        }
 
        string msg = "";
        static 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)
                     {
                         if (replyHandleDict.ContainsKey(msg.ID))
                         {
                             replyHandleList.Remove(msg.ID);
 
                             replyHandleDict[msg.ID].Set();
                             replyHandleDict.Remove(msg.ID);
                         }
                     }
                     else
                     {
                         SendMsg(RobotMsgType.Rec, msg.ID, false);
                         OnMsgReceived?.Invoke(msg);                         
                     }
                 });
            });
        }
 
        int sid = 1;
        int SID
        {
            get
            {
                if (sid > 999)
                {
                    sid = 1;
                }
 
                return sid++;
            }
        }
 
        List<int> replyHandleList = new List<int>();
        Dictionary<int, AutoResetEvent> replyHandleDict = new Dictionary<int, AutoResetEvent>();
 
        public void SendMsg(RobotMsgType type, int replyId, bool isWaitReply = true, RobotMsgAction action = RobotMsgAction.Move, RobotMsgParas para1 = RobotMsgParas.None, List<string> paras = null)
        {
            RobotMsg msg = new RobotMsg();
 
            msg.Type = type;
            if (msg.Type == RobotMsgType.Send)
            {
                msg.ID = SID;
            }
            else
            {
                msg.ID = replyId;
            }
 
            msg.Para1 = para1;
            msg.Paras = new List<string>(paras ?? new List<string>());
 
            SendMsg(msg, isWaitReply);
        }
 
        public void SendMsg(RobotMsg msg, bool isWaitReply = true)
        {
            if (isWaitReply)
            {
                replyHandleList.Add(msg.ID);
                replyHandleDict[msg.ID] = new AutoResetEvent(false);
            }
 
            byte[] bytes = msg.GetMsgBytes(IConfig.Seperator, IConfig.EndChar);
            client.GetStream().Write(bytes, 0, bytes.Length);
 
            if (isWaitReply)
            {
                replyHandleDict[msg.ID].WaitOne(IConfig.ReplyTimeout);
 
                if (replyHandleList.Contains(msg.ID))
                {
                    throw new ProcessException("反馈数据超时\r\n" + msg.GetDisplayText(), null);
                }
            }
        }
    }
}