OldClient.cs
17.7 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
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
612
613
614
615
616
617
618
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Asa
{
/// <summary>
/// AGV客户端-旧协议
/// </summary>
public class AgvClient
{
private bool loop;
private string _ip; //远程IP地址
private Socket client; //客户端
private Thread tSend; //发送
private Thread tListen; //监听网络
private Thread tReceive; //接收事件
private int countRecon;
private bool loopRecon;
private Thread tRecon;
private List<ClientNode> _node;
private System.Collections.Concurrent.ConcurrentQueue<ClientNode> _receive;
private const int PORT = 12000; //端口
/// <summary>
/// 小车动作事件
/// </summary>
public delegate void ActionEvent(string name, string rfid);
/// <summary>
/// 日志事件
/// </summary>
/// <param name="s"></param>
public delegate void LogEvent(string s);
/// <summary>
/// 小车到达,仅包装料仓
/// </summary>
public event ActionEvent Arrive;
/// <summary>
/// 小车已准备,对接完成
/// </summary>
public event ActionEvent Ready;
/// <summary>
/// 关门,仅包装料仓
/// </summary>
public event ActionEvent CloseDoor;
/// <summary>
/// 日志
/// </summary>
public event LogEvent Log;
/// <summary>
/// AGV客户端
/// </summary>
/// <param name="serverIP">服务器IP地址</param>
public AgvClient(string serverIP)
{
_ip = serverIP;
_node = new List<ClientNode>();
_receive = new System.Collections.Concurrent.ConcurrentQueue<ClientNode>();
}
/// <summary>
/// 是否连接服务器
/// </summary>
public bool IsConn { private set; get; } = false;
/// <summary>
/// 发送命令的日志是否打印,不影响其他日志
/// </summary>
public bool SendLog { set; get; } = false;
/// <summary>
/// 发送命令的时间间隔,不能大于10s(单位:秒)
/// </summary>
public int SendSleep { set; get; } = 3;
/// <summary>
/// 取消状态,true发送none,false发送实际状态
/// </summary>
public bool CancelState { set; get; } = false;
/// <summary>
/// 连接
/// </summary>
public void Connect()
{
countRecon = 0;
loopRecon = true;
IsConn = false;
tRecon = new Thread(new ThreadStart(Reconnect));
tRecon.Start();
}
/// <summary>
/// 关闭
/// </summary>
public void Close()
{
loop = false;
loopRecon = false;
if (client != null)
{
client.Close();
client = null;
}
Log?.Invoke("客户端关闭");
}
/// <summary>
/// 设置状态
/// </summary>
/// <param name="name">节点名称</param>
/// <param name="mark">节点标记</param>
/// <param name="rfid">架子RFID</param>
/// <param name="action"></param>
/// <param name="level"></param>
public void SetStatus(string name, string mark = "", string rfid = "", ClientAction action = ClientAction.None, ClientLevel level = ClientLevel.Low)
{
int idx = _node.FindIndex(s => s.Name.Equals(name));
if (idx == -1)
{
ClientNode node = new ClientNode(name, mark, rfid, action, level);
_node.Add(node);
Log?.Invoke("SetStatus " + node.ToText());
}
else
{
_node[idx].Mark = mark;
_node[idx].RFID = rfid;
_node[idx].Action = action;
_node[idx].Level = level;
Log?.Invoke("SetStatus " + _node[idx].ToText());
}
}
/// <summary>
/// 重连线程
/// </summary>
private void Reconnect()
{
while (loopRecon)
{
if (!IsConn)
{
Open();
if (IsConn)
{
countRecon = 0;
Log?.Invoke("连接服务器成功");
}
else
{
Log?.Invoke("连接服务器失败" + ++countRecon + "次");
}
}
Thread.Sleep(5000);
}
}
/// <summary>
/// 打开,连接到服务器
/// </summary>
private void Open()
{
try
{
if (CheckIP(_ip))
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 2000);
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 2000);
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
client.Connect(IPAddress.Parse(_ip), PORT);
if (!loopRecon) return;
IsConn = true;
loop = true;
tListen = new Thread(new ThreadStart(ListenNet));
tListen.Start();
tReceive = new Thread(new ThreadStart(Resolve));
tReceive.Start();
tSend = new Thread(new ThreadStart(SendStatus));
tSend.Start();
}
}
catch (Exception ex)
{
IsConn = false;
Log?.Invoke(ex.Message);
}
}
/// <summary>
/// 监听线程
/// </summary>
private void ListenNet()
{
byte[] temp = new byte[200];
int time = 100;
while (loop)
{
try
{
if (client.Available > 0)
{
int count = client.Receive(temp);
byte[] _buffer = new byte[count];
Array.Copy(temp, 0, _buffer, 0, count);
ClientNode node = Decode(_buffer);
if (node == null)
{
Log?.Invoke("命令解析失败: " + HexBuff(_buffer));
}
else
{
_receive.Enqueue(node);
Log?.Invoke("From Server: " + node.ToText());
}
}
}
catch (Exception ex)
{
IsConn = false;
Log?.Invoke(ex.Message);
}
Thread.Sleep(time);
}
}
/// <summary>
/// 分析数据包
/// </summary>
private void Resolve()
{
int time = 100;
while (loop)
{
Thread.Sleep(time);
try
{
if (!_receive.TryDequeue(out ClientNode result))
continue;
switch (result.Action)
{
case ClientAction.Arrive:
Log?.Invoke("触发Arrive事件");
Arrive?.Invoke(result.Name, result.RFID);
break;
case ClientAction.Ready:
Log?.Invoke("触发Ready事件");
Ready?.Invoke(result.Name, result.RFID);
break;
case ClientAction.CloseDoor:
Log?.Invoke("触发CloseDoor事件");
CloseDoor?.Invoke(result.Name, result.RFID);
break;
}
}
catch (Exception ex)
{
Log?.Invoke(ex.Message);
}
}
}
/// <summary>
/// 连续发送状态线程
/// </summary>
private void SendStatus()
{
while (loop)
{
//Socket没有建立连接
if (!IsConn)
{
Thread.Sleep(1000);
continue;
}
if (_node.Count == 0)
{
Thread.Sleep(5000);
continue;
}
for (int i = 0; i < _node.Count; i++)
{
if (!loop) break;
Thread.Sleep(100);
byte[] buff = Encode(_node[i]);
bool bln = Send(buff);
if (!bln)
{
IsConn = false;
loop = false;
break;
}
}
Thread.Sleep(SendSleep * 1000);
}
}
/// <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;
if (CancelState)
buff[idx++] = (byte)ClientAction.None;
else
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 bool Send(byte[] buff)
{
if (!IsConn)
{
Log?.Invoke("Send 服务器没有连接");
return false;
}
try
{
if (!loopRecon) return false;
if (SendLog) Log?.Invoke("Send: " + HexBuff(buff));
client.Send(buff);
return true;
}
catch (Exception ex)
{
Log?.Invoke(ex.Message);
IsConn = false;
return false;
}
}
/// <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, rfid, action, level);
if (buff[idx] != 0xBA)
return null;
return node;
}
/// <summary>
/// 16进制
/// </summary>
/// <param name="buff"></param>
/// <returns></returns>
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>
/// 检查IP地址
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
private bool CheckIP(string ip)
{
//IP合法
string pattern = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
bool rtn = System.Text.RegularExpressions.Regex.IsMatch(ip, pattern);
if (!rtn)
{
Log?.Invoke("非法的IP地址" + ip);
return false;
}
//Ping服务端
try
{
System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply result = ping.Send(ip, 2000);
ping.Dispose();
if (result.Status != System.Net.NetworkInformation.IPStatus.Success)
{
Log?.Invoke("Ping " + ip + " 请求没有响应");
return false;
}
return true;
}
catch (Exception ex)
{
Log?.Invoke(ex.Message);
return false;
}
}
}
/// <summary>
/// 客户端的节点
/// </summary>
public class ClientNode
{
/// <summary>
/// 节点名称
/// </summary>
public string Name { set; get; }
/// <summary>
/// 标记,用于包装料仓
/// </summary>
public string Mark { set; get; }
/// <summary>
/// 当前架子的RFID
/// </summary>
public string RFID { set; get; }
/// <summary>
/// 动作
/// </summary>
public ClientAction Action { set; get; }
/// <summary>
/// 优先级
/// </summary>
public ClientLevel Level { set; get; }
/// <summary>
/// 客户端节点
/// </summary>
/// <param name="name"></param>
/// <param name="mark"></param>
/// <param name="rfid"></param>
/// <param name="action"></param>
/// <param name="level"></param>
public ClientNode(string name, string mark, string rfid, ClientAction action, ClientLevel level)
{
Name = name;
Mark = mark;
RFID = rfid;
Action = action;
Level = level;
}
/// <summary>
/// 所有属性的文本形式
/// </summary>
/// <returns></returns>
public string ToText()
{
string s = string.Format("Name={0}, Action={1}, Level={2}, Mark={3}, RFID={4}", Name, Action, Level, Mark, RFID);
return s;
}
/// <summary>
/// 服务端的命令
/// </summary>
/// <returns></returns>
public string ToServerText()
{
string s = string.Format("Name={0}, Action={1}, RFID={2}", Name, Action, RFID);
return s;
}
}
/// <summary>
/// 客户端的动作
/// </summary>
public enum ClientAction : byte
{
/// <summary>
/// 没有动作
/// </summary>
None = 0,
/// <summary>
/// 包装料仓关门
/// </summary>
CloseDoor = 1,
/// <summary>
/// 可以进入料架,Arrive事件使用,让小车开始对接
/// </summary>
MayEnter = 2,
/// <summary>
/// 可以出去料架,Arrive事件使用,让小车开始对接
/// </summary>
MayLeave = 3,
/// <summary>
/// 需要进入料架
/// </summary>
NeedEnter = 4,
/// <summary>
/// 需要出去料架
/// </summary>
NeedLeave = 5,
/// <summary>
/// 完成进入料架
/// </summary>
FinishEnter = 6,
/// <summary>
/// 完成出去料架
/// </summary>
FinishLeave = 7,
/// <summary>
/// 小车到达,到达包装料仓门口,等待开门
/// </summary>
Arrive = 8,
/// <summary>
/// 小车已准备,已对接上流水线
/// </summary>
Ready = 9,
/// <summary>
/// 包装料仓只能入料不能出料
/// </summary>
EnterShelf = 10,
/// <summary>
/// 不允许
/// </summary>
MayNot = 11
}
/// <summary>
/// 客户端的优先级
/// </summary>
public enum ClientLevel : byte
{
/// <summary>
/// 低
/// </summary>
Low = 0,
/// <summary>
/// 中等
/// </summary>
Middle = 1,
/// <summary>
/// 高
/// </summary>
High = 2
}
}