AgvServer.cs
19.1 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Agv
{
public class Server
{
private bool loop;
private Socket _server; //服务端
Dictionary<string, Client> dictClient = new Dictionary<string, Client>(); //所有客户端
private Thread tListenClient; //监听客户端连接
private Dictionary<string, bool> nodeOnline = new Dictionary<string, bool>();
public delegate void NodeChangedEvent(Node clientNode);
public delegate void NodeOnlineEvent(string nodeName, bool online);
public event NodeChangedEvent NodeChanged;
public event NodeOnlineEvent NodeOnline;
private string serverIp;
private int serverPort;
private bool _IsdecodeSingleNode = false;
private Dictionary<string, Node> nodeMap = new Dictionary<string, Node>();
/// <summary>
///
/// </summary>
/// <param name="_IsdecodeSingleNode">解码方式,默认解码多个节点</param>
public Server(bool _IsdecodeSingleNode=false)
{
this._IsdecodeSingleNode = _IsdecodeSingleNode;
}
/// <summary>
/// 服务端信息
/// </summary>
public string ServerInfo
{
get
{
return string.Format("{0}:{1}", serverIp, serverPort.ToString());
}
}
/// <summary>
/// 开启服务
/// </summary>
public void Start(string ip = "127.0.0.1", int port = 12000)
{
try
{
log.info("AGVServer服务启动");
serverIp = ip;
serverPort = port;
IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);
_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_server.Bind(localEP);
_server.Listen(100);
loop = true;
//_client = new List<Client>();
tListenClient = new Thread(new ThreadStart(ListenClient));
tListenClient.Start();
}
catch (Exception ex)
{
log.error("AGVServer服务启动", ex);
}
}
/// <summary>
/// 停止服务
/// </summary>
public void Stop()
{
try
{
loop = false;
foreach (string c in dictClient.Keys)
{
try
{
dictClient[c].ListenNet.Abort();
}
catch (Exception ex)
{
log.error(string.Format("关闭连接客户端[{0}]线程失败", c), ex);
}
try
{
dictClient[c].Socket.Close();
}
catch (Exception ex)
{
log.error(string.Format("关闭连接客户端[{0}]Socket失败", c), ex);
}
}
if (dictClient.Count > 0) dictClient.Clear();
if (nodeMap.Count > 0)
nodeMap.Clear();
log.info("AGVServer服务关闭");
}
catch (Exception ex)
{
log.error("AGVServer服务关闭", ex);
}
}
/// <summary>
/// 向服务端发送命令
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public bool SendToClient(string nodeName, string RFID, ClientAction action)
{
string tar = "";
int n = 0;
do
{
tar = FindClient(nodeName);
if (tar.Equals(""))
{
log.error("没有找到" + nodeName);
Thread.Sleep(500);
n++;
}
else
{
n = 10;
}
} while (n < 4);
if (tar.Equals("")) return false;
Node node = new Node(nodeName, RFID, action);
log.info("SendTo " + nodeName + " RFID=" + RFID + " " + action);
byte[] buff = Common.Encode(node);
return Send(tar, buff);
}
/// <summary>
/// 小车到达
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public bool Arrive(string nodeName, string RFID = "")
{
string tar = "";
int n = 0;
do
{
tar = FindClient(nodeName);
if (tar.Equals(""))
{
log.error("Arrive: 没有找到" + nodeName);
Thread.Sleep(500);
n++;
}
else
{
n = 10;
}
} while (n < 4);
if (tar.Equals("")) return false;
Node node = new Node(nodeName, RFID, ClientAction.Arrive);
log.info("SendTo " + nodeName + " RFID=" + RFID + " " + ClientAction.Arrive);
byte[] buff = Common.Encode(node);
return Send(tar, buff);
}
/// <summary>
/// 小车已准备好
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public bool Ready(string nodeName, string RFID = "")
{
string tar = "";
int n = 0;
do
{
tar = FindClient(nodeName);
if (tar.Equals(""))
{
log.error("Ready: 没有找到" + nodeName);
Thread.Sleep(500);
n++;
}
else
{
n = 10;
}
} while (n < 4);
if (tar.Equals("")) return false;
Node node = new Node(nodeName, RFID, ClientAction.Ready);
log.info("SendTo " + nodeName + " RFID=" + RFID + " " + ClientAction.Ready);
byte[] buff = Common.Encode(node);
return Send(tar, buff);
}
/// <summary>
/// 关门
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public bool CloseDoor(string nodeName, string RFID = "")
{
string tar = "";
int n = 0;
do
{
tar = FindClient(nodeName);
if (tar.Equals(""))
{
log.debug("CloseDoor: 没有找到" + nodeName);
Thread.Sleep(500);
n++;
}
else
{
n = 10;
}
} while (n < 4);
if (tar.Equals("")) return false;
Node node = new Node(nodeName, RFID, ClientAction.CloseDoor);
log.info("SendTo " + nodeName + " RFID=" + RFID + " " + ClientAction.CloseDoor);
byte[] buff = Common.Encode(node);
return Send(tar, buff);
}
/// <summary>
/// 监听客户端连接
/// </summary>
private void ListenClient()
{
while (loop)
{
try
{
// 开始监听客户端连接请求,Accept方法会阻断当前的线程;
Socket sokConnection = _server.Accept(); // 一旦监听到一个客户端的请求,就返回一个与该客户端通信的 套接字;
log.info(string.Format("客户端[{0}]连接服务端[{1}]成功", sokConnection.RemoteEndPoint.ToString(), ServerInfo));
Thread thr = new Thread(ListenNet);
Client client = new Client(sokConnection, thr, sokConnection.RemoteEndPoint.ToString());
thr.IsBackground = true;
thr.Start(client);
dictClient.Add(sokConnection.RemoteEndPoint.ToString(), client);
}
catch (SocketException)
{
//关闭连接,退出阻塞Accept
}
catch (Exception ex)
{
log.error("ListenClient", ex);
}
}
}
/// <summary>
/// 客户端数据接收
/// </summary>
/// <param name="obj">索引</param>
private void ListenNet(object obj)
{
Client client = obj as Client;
Socket sokClient = client.Socket;
while (client.Loop)
{
// Thread.Sleep(sleep);
try
{
// 定义一个缓存区;
byte[] arrMsgRec = new byte[1024];
// 将接收到的数据存入到输入 arrMsgRec中;
int length = -1;
if (sokClient.Poll(-1, SelectMode.SelectRead))
{
try
{
length = sokClient.Receive(arrMsgRec); // 接收数据,并返回数据的长度;
if (length == 0)//连接正常断开
{
Offline(client);
log.debug(string.Format("客户端[{0}]断开与服务端[{1}]的连接", sokClient.RemoteEndPoint.ToString(), ServerInfo));
return;
}
}
catch (SocketException se)
{
Offline(client);
log.error(string.Format("客户端[{0}]接收服务端[{1}]的消息出现异常", sokClient.RemoteEndPoint.ToString(), ServerInfo), se);
return;
}
catch (Exception e)
{
Offline(client);
log.error(string.Format("客户端[{0}]接收服务端[{1}]的消息出现异常", sokClient.RemoteEndPoint.ToString(), ServerInfo), e);
return;
}
}
if (length > 0)
{
byte[] buff = new byte[length];
Array.Copy(arrMsgRec, 0, buff, 0, length);
//解码单个节点
if(_IsdecodeSingleNode)
{
Node node = Common.Decode(buff);
if (node == null)
{
log.error("命令解析失败: " + HexBuff(buff));
}
else
{
//CommonVar.LogUtil.info("Receive[" + client.IP + "] " + node.ToText());
int idx = client.nodeName.FindIndex(s => s == node.Name);
if (idx == -1) client.nodeName.Add(node.Name);
UpdateNode(node);
}
}
else
{
//解码多个节点
List<Node> nodes = Common.DecodeNodes(buff);
if (nodes == null)
{
log.error("命令解析失败: " + HexBuff(buff));
}
else
{
int idx = -1;
foreach (var node in nodes)
{
idx = client.nodeName.FindIndex(s => s == node.Name);
if (idx == -1) client.nodeName.Add(node.Name);
}
UpdateNodes(nodes);
}
}
}
}
catch (Exception ex)
{
log.error("ListenNet", ex);
}
}
}
private string FindClient(string nodeName)
{
foreach (string item in dictClient.Keys)
{
if (dictClient[item].nodeName.Contains(nodeName))
return item;
}
return "";
}
private void UpdateNode(Node node)
{
if(!nodeOnline.Keys.Contains(node.Name))
{
nodeOnline.Add(node.Name,true);
NodeOnline?.Invoke(node.Name, true);
}
else if(nodeOnline[node.Name].Equals(false))
{
nodeOnline[node.Name] = true;
NodeOnline?.Invoke(node.Name, true);
}
if (!nodeMap.Keys.Contains(node.Name))
{
nodeMap.Add(node.Name, node);
NodeChanged?.Invoke(node);
log.info(string.Format("节点添加并状态更新[{0}]", node.ToText()));
}
else if (!nodeMap[node.Name].Equals(node))
{
nodeMap[node.Name]= node;
NodeChanged?.Invoke(node);
log.info(string.Format("节点状态更新[{0}]", node.ToText()));
}
}
private void UpdateNodes(List<Node> nodes)
{
foreach (var node in nodes)
{
UpdateNode(node);
}
}
private void Offline(Client client)
{
client.Loop = false;
client.Socket.Close();
for (int i = 0; i < client.nodeName.Count; i++)
{
if (!nodeOnline.Keys.Contains(client.nodeName[i]))
{
nodeOnline.Add(client.nodeName[i], false);
NodeOnline?.Invoke(client.nodeName[i], false);
}
else if (nodeOnline[client.nodeName[i]].Equals(true))
{
nodeOnline[client.nodeName[i]] = false;
NodeOnline?.Invoke(client.nodeName[i], false);
}
}
client.nodeName.Clear();
client.ListenNet.Abort();
client.Socket = null;
dictClient.Remove(client.IP);
}
private void Offline(string clientKey)
{
if (!dictClient.Keys.Contains(clientKey))
return;
Client client = dictClient[clientKey];
client.Loop = false;
client.Socket.Close();
for (int i = 0; i < client.nodeName.Count; i++)
{
if (!nodeOnline.Keys.Contains(client.nodeName[i]))
{
nodeOnline.Add(client.nodeName[i], false);
NodeOnline?.Invoke(client.nodeName[i], false);
}
else if (nodeOnline[client.nodeName[i]].Equals(true))
{
nodeOnline[client.nodeName[i]] = false;
NodeOnline?.Invoke(client.nodeName[i], false);
}
}
client.nodeName.Clear();
client.ListenNet.Abort();
client.Socket = null;
dictClient.Remove(client.IP);
}
private string HexBuff(byte[] buff)
{
string s = "";
if (buff == null) return s;
for (int i = 0; i < buff.Length; i++)
s += buff[i].ToString("X2") + " ";
return s;
}
/// <summary>
/// 发送命令
/// </summary>
/// <param name="idx"></param>
/// <param name="buff"></param>
/// <returns></returns>
private bool Send(string clientKey, byte[] buff)
{
for (int i = 1; i <= 3; i++)
{
try
{
dictClient[clientKey].Socket.Send(buff);
log.debug(string.Format("服务端[{0}]向客户端[{1}]发送消息:[{2}]", ServerInfo, clientKey, HexBuff(buff)));
return true;
}
catch (Exception ex)
{
log.error("发送失败" + i + "次:" + ex.Message);
}
Thread.Sleep(100);
}
Offline(clientKey);
return false;
}
private class Client
{
public bool Loop;
public string IP;
public List<string> nodeName;
public Socket Socket;
public Thread ListenNet;
public Client(Socket socket,Thread thread,string IP)
{
Socket = socket;
ListenNet = thread;
Loop = true;
this.IP = IP;
nodeName = new List<string>();
}
}
}
/// <summary>
/// 客户端的节点
/// </summary>
public class ClientNode : Node
{
/// <summary>
/// 在线状态
/// </summary>
public bool Online { get; set; }
/// <summary>
/// 是否可调用
/// </summary>
public bool IsUse { set; get; }
/// <summary>
/// 线体名
/// </summary>
public string LineName { set; get; }
public string AliceName { get; set; }
/// <summary>
/// 客户端的节点
/// </summary>
public ClientNode() : base()
{
}
public ClientNode(string nodeName, string rfid, ClientAction clientAction) : base(nodeName)
{
RFID = rfid;
Action = clientAction;
}
/// <summary>
/// 客户端节点
/// </summary>
/// <param name="name"></param>
/// <param name="ip"></param>
/// <param name="isUse"></param>
public ClientNode(string name, string aliceName, string lineName, bool isUse) : base(name)
{
LineName = lineName;
AliceName = aliceName;
Online = false;
IsUse = isUse;
}
/// <summary>
/// 客户端节点
/// </summary>
/// <param name="name"></param>
/// <param name="rfid"></param>
/// <param name="action"></param>
/// <param name="level"></param>
public ClientNode(string name, string rfid = "", string mark = "", ClientAction action = ClientAction.None, Agv.ClientLevel level = Agv.ClientLevel.Low) : base(name)
{
RFID = rfid;
Mark = mark;
Level = level;
Action = action;
}
/// <summary>
/// 脱机
/// </summary>
public void Offline()
{
RFID = "";
Action = ClientAction.None;
Online = false;
}
}
}