-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMonitorApiExtensions.cs
More file actions
417 lines (364 loc) · 13.4 KB
/
MonitorApiExtensions.cs
File metadata and controls
417 lines (364 loc) · 13.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
using System.Net;
using System.Net.Sockets;
using Microsoft.AspNetCore.Mvc;
using MonitorControl.Clients;
using MonitorControl.Internal;
using MonitorControl.Protocol;
using MonitorControl.Transport;
namespace MonitorControl.Web;
internal static class MonitorApiExtensions
{
private static void ApplySdcpUnit(VmcClient vmc, int? sdcpUnitId)
{
if (sdcpUnitId is >= 0 and <= 255)
{
vmc.TcpSingleUnitId = (byte)sdcpUnitId.Value;
}
}
private static void ApplyVmcClientHeaders(VmcClient vmc, string? vmcItem, int? sdcpUnitId)
{
vmc.VmcItemNumber = SdcpMessageBuffer.ParseVmcItemSpecifier(vmcItem);
ApplySdcpUnit(vmc, sdcpUnitId);
}
internal static void MapMonitorControlApi(this WebApplication app)
{
var api = app.MapGroup("/api").WithTags("monitor");
api.MapGet("/health", () => Results.Ok(new { status = "ok", service = "MonitorControl.Web" }))
.WithName("Health");
api.MapGet("/sdap/discover", async (
IConfiguration config,
int? durationMs,
string? bind,
CancellationToken cancellationToken) =>
{
int ms = Math.Clamp(durationMs ?? 3000, 200, 60_000);
using var discovery = new SdapDiscovery();
try
{
if (!string.IsNullOrWhiteSpace(bind) && IPAddress.TryParse(bind, out var bindIp))
{
discovery.StartListen(bindIp);
}
else
{
discovery.StartListen();
}
}
catch (SocketException ex)
{
return Results.Problem(
title: "SDAP bind failed",
detail: ex.Message,
statusCode: StatusCodes.Status409Conflict);
}
var deadline = DateTime.UtcNow.AddMilliseconds(ms);
var items = new List<DiscoverItem>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
while (DateTime.UtcNow < deadline && !cancellationToken.IsCancellationRequested)
{
TimeSpan remaining = deadline - DateTime.UtcNow;
if (remaining <= TimeSpan.Zero)
{
break;
}
using var packetCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
packetCts.CancelAfter(remaining);
try
{
(SdapAdvertisementPacket packet, string? matched)? read =
await discovery.ReadAsync(null, packetCts.Token).ConfigureAwait(false);
if (read is null)
{
continue;
}
SdapAdvertisementPacket p = read.Value.packet;
string key = $"{p.SourceIp}|{p.SerialNumber}";
if (seen.Add(key))
{
items.Add(new DiscoverItem(
p.SourceIp?.ToString(),
p.ProductName,
p.SerialNumber,
p.ConnectionIp,
p.RecommendedControlIPv4,
p.GroupId,
p.UnitId,
p.Version,
p.Category));
}
}
catch (OperationCanceledException)
{
break;
}
}
return Results.Ok(new DiscoverResponse(ms, items));
})
.WithName("SdapDiscover");
api.MapPost("/vmc/get", (IConfiguration config, [FromBody] VmcGetBody body) =>
{
if (string.IsNullOrWhiteSpace(body.Host) || string.IsNullOrWhiteSpace(body.Field))
{
return Results.BadRequest(new { error = "host and field are required." });
}
int timeout = body.TimeoutMs ?? config.GetValue("MonitorControl:DefaultSdcpTimeoutMs", 10_000);
try
{
using var tcp = new SdcpConnection(body.Host.Trim())
{
ReceiveTimeoutMs = timeout,
SendTimeoutMs = timeout,
};
tcp.Open();
var vmc = new VmcClient(tcp);
ApplyVmcClientHeaders(vmc, body.VmcItem, body.SdcpUnitId);
string? value = vmc.GetStatString(body.Field.Trim());
return Results.Ok(new VmcGetResponse(value));
}
catch (Exception ex)
{
return Results.Problem(title: "SDCP failed", detail: ex.Message, statusCode: 502);
}
})
.WithName("VmcGet");
api.MapPost("/vmc/set", (IConfiguration config, [FromBody] VmcSetBody body) =>
{
if (string.IsNullOrWhiteSpace(body.Host) || body.Args is null || body.Args.Count == 0)
{
return Results.BadRequest(new { error = "host and args (STATset tail) are required." });
}
int timeout = body.TimeoutMs ?? config.GetValue("MonitorControl:DefaultSdcpTimeoutMs", 10_000);
try
{
using var tcp = new SdcpConnection(body.Host.Trim())
{
ReceiveTimeoutMs = timeout,
SendTimeoutMs = timeout,
};
tcp.Open();
var vmc = new VmcClient(tcp);
ApplyVmcClientHeaders(vmc, body.VmcItem, body.SdcpUnitId);
LegacyVmcContainer? r = vmc.Send("STATset", body.Args.ToArray());
if (r is null)
{
return Results.Ok(new VmcSetResponse(null, "no response container"));
}
_ = r.parse(out string[]? tokens);
return Results.Ok(new VmcSetResponse(tokens, null));
}
catch (Exception ex)
{
return Results.Problem(title: "SDCP failed", detail: ex.Message, statusCode: 502);
}
})
.WithName("VmcSet");
api.MapPost("/vmc/broadcast", ([FromBody] VmcBroadcastBody body) =>
{
if (body.Tokens is null || body.Tokens.Count < 1)
{
return Results.BadRequest(new { error = "tokens must include at least the VMC category (e.g. STATset)." });
}
IPAddress destIp = IPAddress.Broadcast;
if (!string.IsNullOrWhiteSpace(body.BroadcastAddress))
{
if (!IPAddress.TryParse(body.BroadcastAddress.Trim(), out IPAddress? parsed))
{
return Results.BadRequest(new { error = "invalid broadcastAddress." });
}
destIp = parsed;
}
int port = body.Port is > 0 and < 65536 ? body.Port.Value : SdcpConnection.DefaultPort;
IPEndPoint? localEp = null;
if (!string.IsNullOrWhiteSpace(body.LocalBind) && IPAddress.TryParse(body.LocalBind.Trim(), out IPAddress? lb))
{
localEp = new IPEndPoint(lb, 0);
}
var dest = new IPEndPoint(destIp, port);
var scope = string.Equals(body.Scope, "group", StringComparison.OrdinalIgnoreCase)
? VmcUdpBroadcastScope.Group
: VmcUdpBroadcastScope.AllMonitors;
int gid = Math.Clamp(body.GroupId ?? 1, 1, 99);
try
{
using var client = new VmcUdpBroadcastClient(dest, localEp)
{
VmcItemNumber = SdcpMessageBuffer.ParseVmcItemSpecifier(body.VmcItem),
};
string category = body.Tokens[0];
string[] tail = body.Tokens.Count > 1
? body.Tokens.GetRange(1, body.Tokens.Count - 1).ToArray()
: Array.Empty<string>();
bool ok = client.TrySend(scope, (byte)gid, category, tail);
return Results.Ok(new VmcBroadcastResponse(ok, destIp.ToString(), port, body.Scope));
}
catch (Exception ex)
{
return Results.Problem(title: "UDP VMC broadcast failed", detail: ex.Message, statusCode: 502);
}
})
.WithName("VmcBroadcast");
api.MapPost("/vms/product-info", (IConfiguration config, [FromBody] HostBody body) =>
{
if (string.IsNullOrWhiteSpace(body.Host))
{
return Results.BadRequest(new { error = "host is required." });
}
int timeout = body.TimeoutMs ?? config.GetValue("MonitorControl:DefaultSdcpTimeoutMs", 10_000);
try
{
using var tcp = new SdcpConnection(body.Host.Trim())
{
ReceiveTimeoutMs = timeout,
SendTimeoutMs = timeout,
};
tcp.Open();
var vms = new VmsClient(tcp);
var buf = new SdcpMessageBuffer();
int send = vms.SendGetProductInformation(buf);
if (send != MonitorProtocolCodes.Ok)
{
return Results.Ok(new VmsProductInfoResponse(false, send, 0, null, "send failed"));
}
int recv = vms.ReceiveVmsPacket(buf);
if (recv != MonitorProtocolCodes.Ok)
{
return Results.Ok(new VmsProductInfoResponse(false, recv, 0, null, "receive failed"));
}
if (!vms.CheckVmsRecvOk(buf))
{
return Results.Ok(new VmsProductInfoResponse(false, recv, buf.dataLengthV4, null, "device NAK in payload"));
}
int len = Math.Min(buf.dataLengthV4, buf.data.Length);
string hex = WireFormat.ToHex(buf.data.AsSpan(0, len));
return Results.Ok(new VmsProductInfoResponse(true, MonitorProtocolCodes.Ok, buf.dataLengthV4, hex, null));
}
catch (Exception ex)
{
return Results.Problem(title: "VMS failed", detail: ex.Message, statusCode: 502);
}
})
.WithName("VmsProductInfo");
api.MapPost("/vma/control-software-version", (IConfiguration config, [FromBody] HostBody body) =>
VmaRead(config, body, static (v, p) => v.SendGetControlSoftwareVersion(p)));
api.MapPost("/vma/kernel-version", (IConfiguration config, [FromBody] HostBody body) =>
VmaRead(config, body, static (v, p) => v.SendGetKernelVersion(p)));
api.MapPost("/vma/rtc", (IConfiguration config, [FromBody] HostBody body) =>
VmaRead(config, body, static (v, p) => v.SendGetRtc(p)));
api.MapPost("/vma/fpga1-version", (IConfiguration config, [FromBody] HostBody body) =>
VmaRead(config, body, static (v, p) => v.SendGetFpga1Version(p)));
api.MapPost("/vma/fpga2-version", (IConfiguration config, [FromBody] HostBody body) =>
VmaRead(config, body, static (v, p) => v.SendGetFpga2Version(p)));
api.MapPost("/vma/fpga-core-version", (IConfiguration config, [FromBody] HostBody body) =>
VmaRead(config, body, static (v, p) => v.SendGetFpgaCoreVersion(p)));
api.MapPost("/vma/firmware/upgrade-kernel-size", (IConfiguration config, HttpContext http, [FromBody] FirmwareSizeBody body) =>
FirmwareAct(config, http, body, static (v, p, b) => v.SendFirmwareUpgradeKernel(b.SizeBytes, p)));
api.MapPost("/vma/firmware/upgrade-fpga-size", (IConfiguration config, HttpContext http, [FromBody] FirmwareSizeBody body) =>
FirmwareAct(config, http, body, static (v, p, b) => v.SendFirmwareUpgradeFpga(b.SizeBytes, p)));
api.MapPost("/vma/firmware/upgrade-chunk", (IConfiguration config, HttpContext http, [FromBody] FirmwareChunkBody body) =>
FirmwareAct(config, http, body, static (v, p, b) => v.SendFirmwareUpgradeChunk(b.ChunkIndex, p)));
api.MapPost("/vma/firmware/upgrade-restart", (IConfiguration config, HttpContext http, [FromBody] HostBody body) =>
FirmwareAct(config, http, body, static (v, p, _) => v.SendFirmwareUpgradeRestart(p)));
}
private static IResult VmaRead(
IConfiguration config,
HostBody body,
Func<VmaClient, SdcpMessageBuffer, int> act)
{
if (string.IsNullOrWhiteSpace(body.Host))
{
return Results.BadRequest(new { error = "host is required." });
}
int timeout = body.TimeoutMs ?? config.GetValue("MonitorControl:DefaultSdcpTimeoutMs", 10_000);
try
{
using var tcp = new SdcpConnection(body.Host.Trim())
{
ReceiveTimeoutMs = timeout,
SendTimeoutMs = timeout,
};
tcp.Open();
var vma = new VmaClient(tcp);
var packet = new SdcpMessageBuffer();
int code = act(vma, packet);
_ = packet.packet;
int len = Math.Min(packet.dataLength, packet.data.Length);
string hex = WireFormat.ToHex(packet.data.AsSpan(0, len), maxBytes: 512);
return Results.Ok(new VmaReadResponse(code == MonitorProtocolCodes.Ok, code, packet.dataLength, hex));
}
catch (Exception ex)
{
return Results.Problem(title: "VMA failed", detail: ex.Message, statusCode: 502);
}
}
private static IResult FirmwareAct<TBody>(
IConfiguration config,
HttpContext http,
TBody body,
Func<VmaClient, SdcpMessageBuffer, TBody, int> act)
where TBody : HostBody
{
if (!WireFormat.FirmwareGate(config, http.Request.Headers))
{
return Results.Problem(
title: "Firmware actions disabled",
detail: "Set MonitorControl:AllowDangerousFirmware=true or MONITOR_CONTROL_ALLOW_DANGEROUS_FIRMWARE=1 and send header X-Firmware-Ack: CONFIRM",
statusCode: StatusCodes.Status403Forbidden);
}
if (string.IsNullOrWhiteSpace(body.Host))
{
return Results.BadRequest(new { error = "host is required." });
}
int timeout = body.TimeoutMs ?? config.GetValue("MonitorControl:DefaultSdcpTimeoutMs", 10_000);
try
{
using var tcp = new SdcpConnection(body.Host.Trim())
{
ReceiveTimeoutMs = timeout,
SendTimeoutMs = timeout,
};
tcp.Open();
var vma = new VmaClient(tcp);
var packet = new SdcpMessageBuffer();
int code = act(vma, packet, body);
_ = packet.packet;
int len = Math.Min(packet.dataLength, packet.data.Length);
string hex = WireFormat.ToHex(packet.data.AsSpan(0, len), maxBytes: 512);
return Results.Ok(new VmaReadResponse(code == MonitorProtocolCodes.Ok, code, packet.dataLength, hex));
}
catch (Exception ex)
{
return Results.Problem(title: "VMA firmware failed", detail: ex.Message, statusCode: 502);
}
}
}
internal sealed record DiscoverItem(
string? SourceIp,
string ProductName,
string SerialNumber,
string ConnectionIp,
string? RecommendedControlIPv4,
byte GroupId,
byte UnitId,
byte Version,
byte Category);
internal sealed record DiscoverResponse(int ListenDurationMs, IReadOnlyList<DiscoverItem> Items);
internal record HostBody(string Host, int? TimeoutMs, int? SdcpUnitId);
internal sealed record VmcGetBody(string Host, string Field, int? TimeoutMs, int? SdcpUnitId, string? VmcItem);
internal sealed record VmcGetResponse(string? Value);
internal sealed record VmcSetBody(string Host, List<string> Args, int? TimeoutMs, int? SdcpUnitId, string? VmcItem);
internal sealed record VmcSetResponse(string[]? ResponseTokens, string? Error);
internal sealed record VmcBroadcastBody(
string? Scope,
int? GroupId,
string? BroadcastAddress,
int? Port,
string? LocalBind,
List<string>? Tokens,
string? VmcItem);
internal sealed record VmcBroadcastResponse(bool Ok, string DestinationIp, int Port, string? Scope);
internal sealed record VmsProductInfoResponse(bool Ok, int ProtocolCode, int DataLengthV4, string? PayloadHex, string? Message);
internal sealed record VmaReadResponse(bool Ok, int ProtocolCode, int DataLength, string PayloadHex);
internal sealed record FirmwareSizeBody(string Host, int SizeBytes, int? TimeoutMs)
: HostBody(Host, TimeoutMs, null);
internal sealed record FirmwareChunkBody(string Host, int ChunkIndex, int? TimeoutMs)
: HostBody(Host, TimeoutMs, null);