-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEdgeLinkClient.cs
More file actions
186 lines (165 loc) · 6.55 KB
/
EdgeLinkClient.cs
File metadata and controls
186 lines (165 loc) · 6.55 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
using System;
using System.Collections.Concurrent;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EdgeLink
{
public class EdgeLinkClient : IDisposable
{
public event Action<string>? OnMessage;
public event Action? OnConnected;
public event Action? OnDisconnected;
public event Action<Exception>? OnError;
/// <summary>Fired when an upstream device connects or disconnects from EdgeLink Server.
/// Parameters: isConnected, endpoint (e.g. "TCPServer@192.168.1.50"), deviceId (parsed from message id field, may be empty)</summary>
public event Action<bool, string, string>? OnDeviceStatus;
public bool IsConnected => tcpClient?.Connected == true && !disposed;
public string Host { get; }
public int Port { get; }
private TcpClient? tcpClient;
private NetworkStream? stream;
private CancellationTokenSource cts = new();
private readonly ConcurrentQueue<string> queue = new();
private bool disposed;
private bool autoReconnect = true;
private int reconnectDelayMs = 5000;
public EdgeLinkClient(string host, int port)
{
Host = host;
Port = port;
}
public void SetAutoReconnect(bool enable, int delayMs = 5000)
{
autoReconnect = enable;
reconnectDelayMs = delayMs;
}
public async Task ConnectAsync(CancellationToken cancellationToken = default)
{
if (disposed) throw new ObjectDisposedException(nameof(EdgeLinkClient));
cts.Cancel();
cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
await ConnectCoreAsync(cts.Token);
_ = Task.Run(() => ReadLoopAsync(cts.Token), cts.Token);
}
private async Task ConnectCoreAsync(CancellationToken ct)
{
tcpClient?.Dispose();
tcpClient = new TcpClient { NoDelay = true };
await tcpClient.ConnectAsync(Host, Port, ct);
stream = tcpClient.GetStream();
OnConnected?.Invoke();
}
private async Task ReadLoopAsync(CancellationToken ct)
{
var buf = new byte[4096];
var lineBuf = new StringBuilder();
while (!ct.IsCancellationRequested)
{
try
{
if (stream == null || !IsConnected)
{
OnDisconnected?.Invoke();
if (!autoReconnect) return;
await Task.Delay(reconnectDelayMs, ct);
await ConnectCoreAsync(ct);
lineBuf.Clear();
continue;
}
int read = await stream!.ReadAsync(buf, 0, buf.Length, ct);
if (read == 0)
{
tcpClient?.Dispose();
tcpClient = null;
continue;
}
lineBuf.Append(Encoding.UTF8.GetString(buf, 0, read));
int idx;
while ((idx = FindNewline(lineBuf)) >= 0)
{
string line = lineBuf.ToString(0, idx).Trim();
lineBuf.Remove(0, idx + 1);
if (line.Length > 0) HandleLine(line);
}
}
catch (OperationCanceledException) { return; }
catch (Exception ex)
{
OnError?.Invoke(ex);
tcpClient?.Dispose();
tcpClient = null;
if (!autoReconnect) return;
OnDisconnected?.Invoke();
try { await Task.Delay(reconnectDelayMs, ct); } catch { return; }
try { await ConnectCoreAsync(ct); lineBuf.Clear(); } catch { }
}
}
}
private static int FindNewline(StringBuilder sb)
{
for (int i = 0; i < sb.Length; i++)
if (sb[i] == '\n') return i;
return -1;
}
private void HandleLine(string line)
{
if (line.StartsWith("EDGELINK_PING:", StringComparison.Ordinal))
{
string hex = line[14..];
_ = SendRawAsync($"EDGELINK_PONG:{hex}\n");
return;
}
if (line.StartsWith("EDGELINK_STATUS:", StringComparison.Ordinal))
{
// body: "STATUS:protocol@ip" or "STATUS:protocol@ip:deviceId"
string body = line[16..];
int sep = body.IndexOf(':');
string statusStr = sep >= 0 ? body[..sep] : body;
string rest = sep >= 0 ? body[(sep + 1)..] : "";
bool connected = statusStr.Equals("CONNECTED", StringComparison.OrdinalIgnoreCase);
int devSep = rest.LastIndexOf(':');
string endpoint = devSep >= 0 ? rest[..devSep] : rest;
string deviceId = devSep >= 0 ? rest[(devSep + 1)..] : "";
OnDeviceStatus?.Invoke(connected, endpoint, deviceId);
return;
}
if (line.StartsWith("EDGELINK_", StringComparison.Ordinal)) return;
queue.Enqueue(line);
OnMessage?.Invoke(line);
}
public async Task SendAsync(string message)
{
if (stream == null || !IsConnected)
throw new InvalidOperationException("Not connected to EdgeLink.");
if (!message.EndsWith('\n')) message += "\n";
byte[] bytes = Encoding.UTF8.GetBytes(message);
await stream.WriteAsync(bytes);
}
private async Task SendRawAsync(string raw)
{
try
{
if (stream == null) return;
byte[] b = Encoding.UTF8.GetBytes(raw);
await stream.WriteAsync(b);
}
catch { }
}
public bool TryDequeue(out string message) => queue.TryDequeue(out message!);
public void Disconnect()
{
cts.Cancel();
tcpClient?.Dispose();
tcpClient = null;
}
public void Dispose()
{
if (disposed) return;
disposed = true;
Disconnect();
cts.Dispose();
}
}
}