-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
411 lines (327 loc) · 14.3 KB
/
Program.cs
File metadata and controls
411 lines (327 loc) · 14.3 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
////////////////////////////////////////////////////////////////
// //
// IoniConnect.UsageExample //
// ------------------------ //
// //
// Showcase, demonstration and documentation by example //
// of the Ionicon AME HTTP-API. //
// //
// You should have received a copy of the IoniConnect.nupgk //
// NuGet-package together with this source code. //
// This requires the IoniConnect.API to run on port 5066. //
// The API version is displayed in the example /api/status //
// below and should conform to the NuGet package version. //
// //
// Author: //
// moritz.koenemann@ionicon.com //
// software@ionicon.com //
// //
// Version history: //
// //
// v5 - 9.Dez 2025 //
// * changed: api.GetFile() / .SendFile() takes 'query' //
// as *last* argument, consistent with all other API calls //
// * update IoniConnect.nupgk v1.0.9 //
// //
// v4 - 7.Oct 2025 //
// * changed: use a PATCH request to stop a measurement //
// //
// v3 - 28.Aug 2025 //
// * add example 'download the result files and report' //
// * update IoniConnect.nupgk v1.0.7 //
// //
////////////////////////////////////////////////////////////////
using IoniConnect;
using IoniConnect.Models;
Console.WriteLine(@"
=========== checking the connection/status ============
connect the API and print some infos...
");
// first, let's use this helper class to start making our HTTP-requests.
// Note: there is also an `async` variant for this (`APIConnectorAsync`)
// that provides the same methods as described here, but with an -Async suffix
var api = new IoniConnect.Http.APIConnector("http://localhost:5066");
// just a placeholders for later use...
HttpResponseMessage r;
Newtonsoft.Json.Linq.JObject jObject;
string href = "";
// check an endpoint that's always available to see if we're connected:
var status = api.GetJson("/api/status");
// Note: all methods of the `APIConnector` swallow most Exceptions that occur
// on connection problems and instead return an empty object as default:
if (!status.HasValues)
{
Console.WriteLine("error: no connection to API");
Thread.Sleep(3 * 1000);
return;
}
Console.WriteLine(new
{
SerialNr = status["instrumentSerialNr"].ToObject<string>(),
Version = status["version"].ToObject<string>(),
});
/////////////////////////////////////////////////////////
Console.WriteLine(@"
=========== getting a list of actions ============
this is an example of getting any kind of collection
within the API and here we list the (predefined) actions.
");
// let's have a look at a collection of elements...
jObject = api.GetJson("/api/actions");
var count = jObject["count"].ToObject<int>();
Console.WriteLine($"we are counting ({count}) actions");
if (count > 0)
{
// ...that is always organized underneath an `_embedded` object:
// this contains in most cases an object of the same name as
// requested in the endpoint, which is a JSON array of objects.
var jArray = jObject["_embedded"]["actions"];
var element = jArray[0];
var action = element.ToObject<IoniConnect.Models.Action>();
href = element["_links"]["self"]["href"].ToObject<string>();
Console.WriteLine($"found '{action.Name}' with endpoint '{href}'...");
}
// One common data-structure is this kind of collection within an "_embedded" element.
// We provide an adapter that implements an `ICollection` to simplify the C-R-U-D protocol.
// Let's use the same endpoint as above, but with our collection-helper.
// The type of the `generic` must of course match the type provided by the endpoint.
// All neccessary types can be found in the `IoniConnect.Models` namespace:
var actions = new IoniConnect.ReadOnlyEmbeddedCollection<IoniConnect.Models.Action>(api, "/api/actions");
// now, we can iterate over the elements
foreach (var action in actions)
{
Console.WriteLine(new
{
action.Name,
action.Duration_Runs,
action.AME_ActionNumber,
});
}
#region +++ [advanced] modifying lists using an EmbeddedCollection +++
// not for `IoniConnect.ReadOnlyEmbeddedCollection` !!
/*
// add some elements:
if (actions.Count == 0)
{
actions.Add(new IoniConnect.Models.Action
{
Name = "Last Action Hero",
AME_ActionNumber = 1,
Duration_Runs = 17,
});
actions.Add(new IoniConnect.Models.Action
{
Name = "The Red Tide",
PostActionNumber = 1,
});
}
// to modify an element, we can use a common pattern...
// EXTRACT
var firstAction = actions[0];
// TRANSFORM
firstAction.Name = "Django Unchained";
// LOAD (note, that only the item-setter emulates a PUT-request)
actions[0] = firstAction;
// although this is implemented for the `ICollection` interface, it is not allowed to delete actions:
//actions.RemoveAt(0); // DON't ~> will throw with `405: method not allowed`
*/
#endregion
/////////////////////////////////////////////////////////
Console.WriteLine(@"
=========== setting up a server-sent-event listener ============
This lets us follow the events of the AME-system during the measurement.
Especially useful for fetching the current (component-)data during the
run, which is exemplified below.
");
// no need to worry about thread-safety in this simple example,
// but one would normally use something like a ConcurrentQueue here:
var events = new List<string>();
var componentData = new List<IReadOnlyCollection<IoniConnect.Json.Models.Quantity>>();
void Sse_MessageHandler(object? sender, string href)
{
if (sender is IoniConnect.ServerSentEventListener sse)
{
// collect all occurring events in this list:
events.Add(sse.Topic);
// we can always follow the link passed as event-data:
var j = api.GetJson(href);
if (sse.Topic == IoniConnect.TopicString.POST_average_components)
{
// for this special event, we can download the current trace-data
// ("component" data), which resolves again to a well-known collection:
var embedded = new IoniConnect.ReadOnlyEmbeddedCollection<IoniConnect.Json.Models.Quantity>(api, href, collectionName: "quantities");
componentData.Add(embedded.ToList());
}
}
}
// get a token, otherwise it would truely 'ListenForever()'...
var cts = new CancellationTokenSource();
// ...and spawn a thread, because our listener blocks (an async-method *is*
// available, but I would not trust my own implementation of that!)
var t = new Thread(() =>
{
var sse = new IoniConnect.ServerSentEventListener(new UriBuilder(api.Uri) { Path = "/api/events" }.Uri);
sse.MessageHandler += Sse_MessageHandler;
sse.ListenForever(cts.Token);
});
t.Start();
/////////////////////////////////////////////////////////
Console.WriteLine(@"
=========== how to START a measurement ============
we POST a new element in the list of measurements, which points to
a 'RecipeDirectory' containing the configuration. They are exclusively
found in 'C:/Ionicon/AME/Recipes/' and must contain a 'Composition[.json]'
file and a '*.ionipt' peaktable.
Let's ask the API for a list of valid paths:
");
var recipeCollection = new ReadOnlyEmbeddedCollection<IndexedFile>(api, "/api/recipes");
foreach (var choice in recipeCollection.Select((file, i) => $"[{i}]: " + file.Path))
{
Console.WriteLine(choice);
}
Console.WriteLine("\nselect a recipe by entering a number: ");
int recipeIndex = int.Parse(Console.ReadKey(false).KeyChar.ToString());
Console.WriteLine();
string recipe = recipeCollection.ElementAt(recipeIndex).Path;
// first, check what's going on...
jObject = api.GetJson("/api/measurements/current");
// this call does not communicate errors and instead just gives us
// a default object, when encountering an HTTP-error. This is just
// what we would expect, when there is no 'current' measurement!
// Testing for '.HasValues' is a good way to check this:
if (!jObject.HasValues)
{
// so, the `GET /api/measurements/current` is [410: Gone]...
Console.WriteLine("no measurement is currently running");
// ...and we can create a new measurement to start:
r = api.SendJson(HttpMethod.Post, "/api/measurements", new
{
RecipeDirectory = recipe,
});
Console.WriteLine($"`POST /api/measurements` returned [{r.StatusCode}]");
// the API will check if the 'recipeDirectory' is valid:
if (!r.IsSuccessStatusCode)
{
Console.WriteLine("\nthis didn't work... are you sure the recipe-directory exists?");
}
}
// ...then wait for the measurement to start:
while (!jObject.HasValues)
{
jObject = api.GetJson("/api/measurements/current");
Console.WriteLine(" -- still waiting for measurement to start -- ");
Thread.Sleep(1000);
}
var meas = jObject.ToObject<IoniConnect.Models.Measurement>() !;
Console.WriteLine($"currently running recipe from '{meas.RecipeDirectory}'");
/////////////////////////////////////////////////////////
Console.WriteLine(@"
=========== how to schedule an action ============
we are sending a LINK request to `/api/actions/pending` which links
this placeholder with the hyper-reference to the desired action.
(that sounds more complicated than it is...)
Note (DEMO): This WILL NOT work as intended on the DEMO configuration!!
let's wait a couple of seconds for the measurement to initialize...
Note the green status information on the bottom of the AME_launcher!
");
Console.WriteLine("Press any key for the program to continue!");
Console.ReadKey(true);
// Note: this is not strictly neccessary, because it would be
// done by the AME-system, but if the "/pending" slot is occupied,
// the following request will fail with a [409: Conflict]:
r = api.Request(HttpMethod.Delete, "/api/actions/pending", "");
// the endpoint "/api/actions/1" must of course exist and point
// to the action we want to trigger (see examples above):
r = api.LinkLocation("/api/actions/pending", "/api/actions/1");
Console.WriteLine($"`LINK /api/actions/pending` returned [{r.StatusCode}]");
/////////////////////////////////////////////////////////
Console.WriteLine(@"
=========== how to STOP a measurement ============
we GET the current measurement and PUT the 'isRunning' property to false.
let's wait a couple of seconds for the measurement...
");
Console.WriteLine("Press any key for the program to continue!");
Console.ReadKey(true);
// again, check what's going on...
jObject = api.GetJson("/api/measurements/current");
if (jObject.HasValues)
{
// we need the link and luckily the hyper-reference to "self",
// meaning the resolved endpoint to our request, is ALWAYS provided:
href = jObject["_links"]["self"]["href"].ToObject<string>();
r = api.SendJson(new HttpMethod("PATCH"), href, new { IsRunning = false });
Console.WriteLine($"`PUT {href}` returned [{r.StatusCode}]");
}
while (api.GetJson("/api/measurements/current").HasValues)
{
Console.WriteLine(" -- still waiting for measurement to stop -- ");
Thread.Sleep(1000);
}
/////////////////////////////////////////////////////////
Console.WriteLine(@"
=========== download the result files and report ============
The results of the measurement are saved in directories usually
such as D:\AMEData\<current datetime>, where each new-folder-action
would create a new directory. These are attached as the /results-
endpoint for a given /api/measurement/:id that we just obtained.
We will now navigate to the /api/measurement/X/results/last,
download all files as a ZIP-archive and get a report for the
top 5 TVOCs in XML format...
");
if (string.IsNullOrEmpty(href)) // should have been set to /api/measurement/<current> above...
{
jObject = api.GetJson("/api/measurements/last");
href = jObject["_links"]["self"]["href"].ToObject<string>();
}
var results = new ReadOnlyEmbeddedCollection<IndexedFile>(api, href + "/results")
.Select(file => file.Name)
.ToList();
jObject = api.GetJson(href + "/results/last"); // href should be "/api/measurements/X"
if (jObject.HasValues)
{
href = jObject["_links"]["self"]["href"].ToObject<string>(); // href should be "/api/measurements/X/results/Y"
api.GetFile(href + "/download", "./result.zip", query: "exclude=*.h5"); // use "exclude=*.h5&exclude=*.tsv" for more exclusions
Console.WriteLine("Result files saved as " + Directory.GetCurrentDirectory() + "\\result.zip");
var xml = api.GetContent(href + "/report");
Console.Write(xml.Substring(0, 200));
Console.WriteLine("...");
}
/////////////////////////////////////////////////////////
Console.WriteLine(@"
=========== observing the AME events ============
let's have a look at the events dispatched along this litte program...
");
foreach (var e in events)
{
Console.WriteLine(e);
}
if (componentData.Count == 0)
{
Console.WriteLine("\nno components have been collected :/");
}
else
{
Console.WriteLine($"\nwe collected the component-data for ({componentData.Count}) averages, nice!");
var data = componentData.Last();
foreach (var x in data)
{
jObject = api.GetJson("/api/components/" + x.Id.ToString());
Console.WriteLine(new
{
Name = jObject["shortName"].ToObject<string>(),
x.Id,
x.Value,
x.Error,
});
}
}
/////////////////////////////////////////////////////////
Console.WriteLine("\nDone. Press the 'any' key to quit!");
if (new ConsoleKeyInfo[] { Console.ReadKey(true) }.Any())
{
Console.WriteLine("\n...but there is no 'any' key ?!?!?");
// we don't need this anymore and it prevents the program from closing:
cts.Cancel();
t.Join();
return;
}