AgvServer.cs
15.4 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
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using AGVControl;
namespace BLL
{
public class AgvServer
{
private bool _loop;
private Socket _server; //服务端
private List<Client> _client; //所有客户端
private Thread tListenClient; //监听客户端连接
public delegate void NodeChangedEvent(int nodeIndex);
public event NodeChangedEvent NodeChanged;
public event NodeChangedEvent NodeOnline;
public AgvServer()
{
}
/// <summary>
/// 开启服务
/// </summary>
public void Start()
{
try
{
Common.log.Info("服务启动");
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 12000);
_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)
{
Common.log.Error(ex);
}
}
/// <summary>
/// 停止服务
/// </summary>
public void Stop()
{
_loop = false;
for (int i = 0; i < _client.Count; i++)
{
_client[i].Loop = false;
_client[i].IsConn = false;
_client[i].Socket.Close();
}
_server.Close();
_client = null;
Common.log.Info("服务关闭");
}
/// <summary>
/// 更新节点界面
/// </summary>
/// <param name="nodeIndex"></param>
public void NodeRefresh(int nodeIndex)
{
NodeChanged?.Invoke(nodeIndex);
}
/// <summary>
/// 小车到达
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public bool Arrive(Agv_Info info)
{
int idx;
int n = 0;
do
{
idx = FindClient(info.Place);
if (idx == -1)
{
Common.log.Info("没有找到" + info.Place);
Thread.Sleep(500);
n++;
}
else
{
n = 10;
}
} while (n < 4);
if (idx == -1) return false;
ClientNode node = new ClientNode(info.Place, info.RFID, ClientAction.Arrive);
Common.log.Info("SendTo " + info.Place + " " + ClientAction.Arrive);
byte[] buff = Encode(node);
return Send(idx, buff);
}
/// <summary>
/// 小车已准备好
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public bool Ready(Agv_Info info)
{
int idx;
int n = 0;
do
{
idx = FindClient(info.Place);
if (idx == -1)
{
Common.log.Info("没有找到" + info.Place);
Thread.Sleep(500);
n++;
}
else
{
n = 10;
}
} while (n < 4);
if (idx == -1) return false;
ClientNode node = new ClientNode(info.Place, info.RFID, ClientAction.Ready);
Common.log.Info("SendTo " + info.Place + " " + ClientAction.Ready);
byte[] buff = Encode(node);
return Send(idx, buff);
}
/// <summary>
/// 关门
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public bool CloseDoor(Agv_Info info)
{
int idx;
int n = 0;
do
{
idx = FindClient(info.Place);
if (idx == -1)
{
Common.log.Info("没有找到" + info.Place);
Thread.Sleep(500);
n++;
}
else
{
n = 10;
}
} while (n < 4);
if (idx == -1) return false;
ClientNode node = new ClientNode(info.Place, info.RFID, ClientAction.CloseDoor);
Common.log.Info("SendTo " + info.Place + " " + ClientAction.CloseDoor);
byte[] buff = Encode(node);
return Send(idx, buff);
}
/// <summary>
/// 需要进入料架
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public bool EnterShelf(Agv_Info info)
{
int idx;
int n = 0;
do
{
idx = FindClient(info.Place);
if (idx == -1)
{
Common.log.Info("没有找到" + info.Place);
Thread.Sleep(500);
n++;
}
else
{
n = 10;
}
} while (n < 4);
if (idx == -1) return false;
ClientNode node = new ClientNode(info.Place, info.RFID, ClientAction.EnterShelf);
Common.log.Info("SendTo " + info.Place + " " + ClientAction.EnterShelf);
byte[] buff = Encode(node);
return Send(idx, buff);
}
/// <summary>
/// 监听客户端
/// </summary>
private void ListenClient()
{
while (_loop)
{
try
{
Socket socket = _server.Accept(); //这边会暂停,不需要sleep
IPEndPoint ep = (IPEndPoint)socket.RemoteEndPoint;
Thread listen = new Thread(new ParameterizedThreadStart(ListenNet));
string ip = ep.Address.ToString();
if (ip == System.Configuration.ConfigurationManager.AppSettings["LocalIP"])
ip += ":" + ep.Port;
//新的客户端
Client client = new Client
{
IP = ip,
Loop = true,
IsConn = true,
Socket = socket,
ListenNet = listen,
nodeName = new List<string>(),
};
//重连后关闭旧连接
int idx = _client.FindIndex(s => s.IP.Equals(ip));
if (idx > -1)
{
_client[idx].IsConn = false;
_client[idx].nodeName.Clear();
_client[idx].Loop = false;
_client[idx].Socket.Close();
_client.RemoveAt(idx);
}
_client.Add(client);
listen.Start(_client.Count - 1);
Common.log.Info(string.Format("[{0}] 已连接", client.IP));
}
catch (SocketException)
{
//关闭连接,退出阻塞Accept
}
catch (Exception ex)
{
Common.log.Error(ex);
}
}
}
/// <summary>
/// 客户端数据接收
/// </summary>
/// <param name="obj">索引</param>
private void ListenNet(object obj)
{
int sleep = 10;
Client client = _client[(int)obj];
byte[] temp = new byte[200];
int time = 0;
while (client.Loop)
{
Thread.Sleep(sleep);
try
{
if (!client.Loop) break;
if (client.Socket.Available > 0)
{
time = 0;
int count = client.Socket.Receive(temp);
byte[] buff = new byte[count];
Array.Copy(temp, 0, buff, 0, count);
ClientNode node = Decode(buff);
if (node == null)
{
Common.log.Info("命令解析失败: " + HexBuff(buff));
}
else
{
//Common.log.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
{
time += sleep;
if (time > 10000)
{
Offline(client);
Common.log.Info("[" + client.IP + "] 超过10s没有收到数据,关闭连接");
}
}
}
catch (Exception ex)
{
Common.log.Error(ex);
}
}
}
/// <summary>
/// 编码
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private byte[] Encode(ClientNode node)
{
byte[] name = System.Text.Encoding.UTF8.GetBytes(node.Name);
byte[] mark = System.Text.Encoding.UTF8.GetBytes(node.Mark);
byte[] rfid = System.Text.Encoding.UTF8.GetBytes(node.RFID);
int count = name.Length + mark.Length + rfid.Length + 7;
int idx = 0;
byte[] buff = new byte[count];
buff[idx++] = 0xAB;
buff[idx++] = Convert.ToByte(name.Length);
Array.Copy(name, 0, buff, idx, name.Length);
idx += name.Length;
buff[idx++] = Convert.ToByte(mark.Length);
Array.Copy(mark, 0, buff, idx, mark.Length);
idx += mark.Length;
buff[idx++] = Convert.ToByte(rfid.Length);
Array.Copy(rfid, 0, buff, idx, rfid.Length);
idx += rfid.Length;
buff[idx++] = (byte)node.Action;
buff[idx++] = Convert.ToByte(node.Level);
buff[idx++] = 0xBA;
return buff;
}
/// <summary>
/// 解码
/// </summary>
/// <param name="buff"></param>
/// <returns></returns>
private ClientNode Decode(byte[] buff)
{
int idx = 0;
if (buff[idx++] != 0xAB) return null;
byte[] temp1 = new byte[buff[idx++]];
Array.Copy(buff, idx, temp1, 0, temp1.Length);
string name = System.Text.Encoding.UTF8.GetString(temp1);
idx += temp1.Length;
temp1 = new byte[buff[idx++]];
Array.Copy(buff, idx, temp1, 0, temp1.Length);
string mark = System.Text.Encoding.UTF8.GetString(temp1);
idx += temp1.Length;
temp1 = new byte[buff[idx++]];
Array.Copy(buff, idx, temp1, 0, temp1.Length);
string rfid = System.Text.Encoding.UTF8.GetString(temp1);
idx += temp1.Length;
ClientAction action = (ClientAction)buff[idx++];
ClientLevel level = (ClientLevel)buff[idx++];
ClientNode node = new ClientNode(name)
{
Mark = mark,
RFID = rfid,
Action = action,
Level = level
};
if (buff[idx] != 0xBA)
return null;
return node;
}
private void UpdateNode(ClientNode node)
{
int idx = Common.nodeInfo.FindIndex(s => s.Name == node.Name);
if (idx == -1)
{
Common.log.Info(node.Name + " 不存在");
return;
}
if (!Common.nodeInfo[idx].Online)
{
Common.nodeInfo[idx].Online = true;
NodeOnline?.Invoke(idx);
NodeChanged?.Invoke(idx);
}
if (Common.nodeInfo[idx].Mark != node.Mark ||
Common.nodeInfo[idx].Action != node.Action ||
Common.nodeInfo[idx].Level != node.Level ||
Common.nodeInfo[idx].RFID != node.RFID)
{
Common.nodeInfo[idx].Mark = node.Mark;
Common.nodeInfo[idx].Action = node.Action;
Common.nodeInfo[idx].Level = node.Level;
Common.nodeInfo[idx].RFID = node.RFID;
Common.log.Info(node.Name + "更新 " + node.ToText());
NodeChanged?.Invoke(idx);
}
}
private void Offline(Client client)
{
client.Loop = false;
client.IsConn = false;
client.Socket.Close();
for (int i = 0; i < client.nodeName.Count; i++)
{
int idx = AGVControl.Common.nodeInfo.FindIndex(s => s.Name == client.nodeName[i]);
if (idx == -1) continue;
AGVControl.Common.nodeInfo[idx].Offline();
NodeChanged(idx);
NodeOnline(idx);
}
client.nodeName.Clear();
}
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="name">节点名称</param>
/// <returns></returns>
private int FindClient(string name)
{
int index = -1;
for (int i = 0; i < _client.Count; i++)
{
if (_client[i].IsConn)
{
int idx = _client[i].nodeName.FindIndex(a => a == name);
if (idx != -1)
{
index = i;
break;
}
}
}
return index;
}
/// <summary>
/// 发送命令
/// </summary>
/// <param name="idx"></param>
/// <param name="buff"></param>
/// <returns></returns>
private bool Send(int idx, byte[] buff)
{
for (int i = 1; i <= 3; i++)
{
try
{
_client[idx].Socket.Send(buff);
Common.log.Info("[" + _client[idx].IP + "] " + HexBuff(buff));
return true;
}
catch (Exception ex)
{
Common.log.Info("发送失败" + i + "次:" + ex.Message);
}
Thread.Sleep(100);
}
return false;
}
private class Client
{
public bool Loop;
public string IP;
public bool IsConn;
public List<string> nodeName;
public Socket Socket;
public Thread ListenNet;
}
}
}