forked from TrakHound/MTConnect.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMTConnectHttpSampleClient.cs
More file actions
464 lines (401 loc) · 19.5 KB
/
Copy pathMTConnectHttpSampleClient.cs
File metadata and controls
464 lines (401 loc) · 19.5 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
// Copyright (c) 2024 TrakHound Inc., All Rights Reserved.
// TrakHound Inc. licenses this file to you under the MIT license.
using MTConnect.Errors;
using MTConnect.Formatters;
using MTConnect.Http;
using MTConnect.Streams;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace MTConnect.Clients
{
/// <summary>
/// Client that is used to perform a Sample request from an MTConnect Agent using the MTConnect HTTP REST Api protocol
/// </summary>
public class MTConnectHttpSampleClient : IMTConnectSampleClient
{
private const int DefaultTimeout = 15000;
private static readonly HttpClient _httpClient;
static MTConnectHttpSampleClient()
{
_httpClient = new HttpClient();
_httpClient.Timeout = TimeSpan.FromMilliseconds(DefaultTimeout);
}
/// <summary>
/// Initializes a new instance of the MTConnectSampleClient class that is used to perform
/// a Sample request from an MTConnect Agent using the MTConnect HTTP REST Api protocol
/// </summary>
/// <param name="authority">
/// The authority portion consists of the DNS name or IP address associated with an Agent and an optional
/// TCP port number[:port] that the Agent is listening to for incoming Requests from client software applications.
/// If the port number is the default Port 80, port is not required.
/// </param>
/// <param name="device">
/// If present, specifies that only the Equipment Metadata for the piece of equipment represented by the name or uuid will be published.
/// If not present, Metadata for all pieces of equipment associated with the Agent will be published.
/// </param>
/// <param name="path">The XPath expression specifying the components and/or data items to include</param>
/// <param name="from">The sequence to retrieve the sample data from</param>
/// <param name="to">The sequence to retrieve the sample data to</param>
/// <param name="count">The number of sequences to include in the sample data</param>
/// <param name="documentFormat">Gets or Sets the Document Format to return</param>
public MTConnectHttpSampleClient(string authority, string device = null, string path = null, long from = -1, long to = -1, long count = -1, string documentFormat = MTConnect.DocumentFormat.XML)
{
Authority = authority;
Device = device;
Path = path;
From = from;
To = to;
Count = count;
DocumentFormat = documentFormat;
Timeout = DefaultTimeout;
ContentEncodings = HttpContentEncodings.DefaultAccept;
ContentType = MimeTypes.Get(documentFormat);
}
/// <summary>
/// Initializes a new instance of the MTConnectSampleClient class that is used to perform
/// a Sample request from an MTConnect Agent using the MTConnect HTTP REST Api protocol
/// </summary>
/// <param name="hostname">
/// The Hostname of the MTConnect Agent
/// </param>
/// <param name="port">
/// The Port of the MTConnect Agent
/// </param>
/// <param name="device">
/// If present, specifies that only the Equipment Metadata for the piece of equipment represented by the name or uuid will be published.
/// If not present, Metadata for all pieces of equipment associated with the Agent will be published.
/// </param>
/// <param name="path">The XPath expression specifying the components and/or data items to include</param>
/// <param name="from">The sequence to retrieve the sample data from</param>
/// <param name="to">The sequence to retrieve the sample data to</param>
/// <param name="count">The number of sequences to include in the sample data</param>
/// <param name="documentFormat">Gets or Sets the Document Format to return</param>
public MTConnectHttpSampleClient(string hostname, int port, string device = null, string path = null, long from = -1, long to = -1, long count = -1, string documentFormat = MTConnect.DocumentFormat.XML)
{
Authority = CreateUri(hostname, port).ToString();
Device = device;
Path = path;
From = from;
To = to;
Count = count;
DocumentFormat = documentFormat;
Timeout = DefaultTimeout;
ContentEncodings = HttpContentEncodings.DefaultAccept;
ContentType = MimeTypes.Get(documentFormat);
}
/// <summary>
/// The authority portion consists of the DNS name or IP address associated with an Agent and an optional
/// TCP port number[:port] that the Agent is listening to for incoming Requests from client software applications.
/// If the port number is the default Port 80, port is not required.
/// </summary>
public string Authority { get; }
/// <summary>
/// If present, specifies that only the Equipment Metadata for the piece of equipment represented by the name or uuid will be published.
/// If not present, Metadata for all pieces of equipment associated with the Agent will be published.
/// </summary>
public string Device { get; set; }
/// <summary>
/// Gets or Sets the Document Format to use
/// </summary>
public string DocumentFormat { get; set; }
/// <summary>
/// (Optional) The sequence to retrieve the sample data from
/// </summary>
public long From { get; set; }
/// <summary>
/// (Optional) The sequence to retrieve the sample data to
/// </summary>
public long To { get; set; }
/// <summary>
/// (Optional) The number of sequences to include in the sample data
/// </summary>
public long Count { get; set; }
/// <summary>
/// (Optional) The XPath expression specifying the components and/or data items to include
/// </summary>
public string Path { get; set; }
/// <summary>
/// Gets of Sets the connection timeout for the request
/// </summary>
public int Timeout { get; set; }
/// <summary>
/// Gets or Sets the List of Encodings (ex. gzip, br, deflate) to pass to the Accept-Encoding HTTP Header
/// </summary>
public IEnumerable<HttpContentEncoding> ContentEncodings { get; set; }
/// <summary>
/// Gets or Sets the Content-type (or MIME-type) to pass to the Accept HTTP Header
/// </summary>
public string ContentType { get; set; }
/// <summary>
/// Raised when an MTConnectError Document is received
/// </summary>
public event EventHandler<IErrorResponseDocument> MTConnectError;
/// <summary>
/// Raised when a Document Formatting Error is received
/// </summary>
public event EventHandler<IFormatReadResult> FormatError;
/// <summary>
/// Raised when an Connection Error occurs
/// </summary>
public event EventHandler<Exception> ConnectionError;
/// <summary>
/// Raised when an Internal Error occurs
/// </summary>
public event EventHandler<Exception> InternalError;
/// <summary>
/// Execute the Samples Request
/// </summary>
public IStreamsResponseDocument Get()
{
try
{
// Create Http Request
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Get;
request.RequestUri = CreateUri();
// Add 'Accept' HTTP Header
var contentType = ResponseDocumentFormatter.GetContentType(DocumentFormat);
if (!string.IsNullOrEmpty(contentType))
{
request.Headers.Add(HttpHeaders.Accept, contentType);
}
// Add 'Accept-Encoding' HTTP Header
if (!ContentEncodings.IsNullOrEmpty())
{
foreach (var contentEncoding in ContentEncodings)
{
request.Headers.Add(HttpHeaders.AcceptEncoding, contentEncoding.ToString().ToLower());
}
}
// Create Uri and Send Request
#if NET5_0_OR_GREATER
using (var response = _httpClient.Send(request))
#else
using (var response = _httpClient.SendAsync(request).Result)
#endif
{
response.EnsureSuccessStatusCode();
return HandleResponse(response);
}
}
}
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
{
ConnectionError?.Invoke(this, ex);
}
catch (TaskCanceledException) { /* Ignore Task Cancelled */ }
catch (HttpRequestException ex)
{
ConnectionError?.Invoke(this, ex);
}
catch (Exception ex)
{
InternalError?.Invoke(this, ex);
}
return null;
}
/// <summary>
/// Asyncronously execute the Samples Request
/// </summary>
public async Task<IStreamsResponseDocument> GetAsync(CancellationToken cancel)
{
try
{
// Create Http Request
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Get;
request.RequestUri = CreateUri();
// Add 'Accept' HTTP Header
var contentType = ResponseDocumentFormatter.GetContentType(DocumentFormat);
if (!string.IsNullOrEmpty(contentType))
{
request.Headers.Add(HttpHeaders.Accept, contentType);
}
// Add 'Accept-Encoding' HTTP Header
if (!ContentEncodings.IsNullOrEmpty())
{
foreach (var contentEncoding in ContentEncodings)
{
request.Headers.Add(HttpHeaders.AcceptEncoding, contentEncoding.ToString().ToLower());
}
}
// Create Uri and Send Request
using (var response = await _httpClient.SendAsync(request, cancel))
{
response.EnsureSuccessStatusCode();
return await HandleResponseAsync(response, cancel);
}
}
}
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
{
ConnectionError?.Invoke(this, ex);
}
catch (TaskCanceledException) { /* Ignore Task Cancelled */ }
catch (HttpRequestException ex)
{
ConnectionError?.Invoke(this, ex);
}
catch (Exception ex)
{
InternalError?.Invoke(this, ex);
}
return null;
}
/// <summary>Builds the <c>sample</c> request URI from the client's own <see cref="Authority"/>, <see cref="Device"/>, <see cref="Path"/>, <see cref="From"/>, <see cref="To"/>, <see cref="Count"/>, and <see cref="DocumentFormat"/>.</summary>
public Uri CreateUri() => CreateUri(Authority, Device, Path, From, To, Count, DocumentFormat);
/// <summary>Convenience overload that passes <c>0</c> for <paramref name="port"/>, so the port is taken from <paramref name="hostname"/> if it carries one.</summary>
/// <param name="hostname">Agent base URL or hostname.</param>
/// <param name="device">Optional device key; null requests an agent-scoped sample.</param>
/// <param name="path">Optional XPath/JSONPath filter (becomes the <c>path</c> query parameter).</param>
/// <param name="from">The starting sequence number (<c>from</c> query parameter); <c>0</c> means unset.</param>
/// <param name="to">The ending sequence number (<c>to</c> query parameter); <c>0</c> means unset.</param>
/// <param name="count">The maximum number of observations (<c>count</c> query parameter); <c>0</c> means unset.</param>
/// <param name="documentFormat">Optional document format (<c>documentFormat</c> query parameter).</param>
public static Uri CreateUri(string hostname, string device = null, string path = null, long from = 0, long to = 0, long count = 0, string documentFormat = null) => CreateUri(hostname, 0, device, path, from, to, count, documentFormat);
/// <summary>
/// Builds the absolute <c>sample</c> request URI. Combines <paramref name="hostname"/>
/// (with <paramref name="port"/> appended if positive) and the <paramref name="device"/>
/// segment, then adds <c>/sample</c> together with the standard MTConnect query
/// parameters <c>path</c>, <c>from</c>, <c>to</c>, <c>count</c>, and <c>documentFormat</c>
/// for the supplied non-default values.
/// </summary>
public static Uri CreateUri(string hostname, int port, string device = null, string path = null, long from = 0, long to = 0, long count = 0, string documentFormat = null)
{
if (!string.IsNullOrEmpty(hostname))
{
var url = hostname;
// Add Port
url = Url.AddPort(url, port);
var builder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(builder.Query);
if (query.HasKeys())
{
// From
var s = query.Get("from");
if (from < 0 && s != null && long.TryParse(s, out var l)) from = l;
// To
s = query.Get("to"); ;
if (to < 0 && s != null && long.TryParse(s, out l)) to = l;
// Count
s = query.Get("count"); ;
if (count <= 0 && s != null && long.TryParse(s, out l)) count = l;
builder.Query = null;
url = builder.Uri.ToString();
}
// Remove Sample command from URL
var cmd = "sample";
if (url.EndsWith(cmd) && url.Length > cmd.Length)
url = url.Substring(0, url.Length - cmd.Length);
// Check for Trailing Forward Slash
if (!url.EndsWith("/")) url += "/";
if (!string.IsNullOrEmpty(device)) url += device + "/";
// Add Command
url += cmd;
// Replace 'localhost' with '127.0.0.1' (This is due to a performance issue with .NET Core's System.Net.Http.HttpClient)
if (url.Contains("localhost")) url = url.Replace("localhost", "127.0.0.1");
// Check for http
if (!url.StartsWith("http://") && !url.StartsWith("https://")) url = "http://" + url;
// Add 'From' parameter
if (from > 0) url = Url.AddQueryParameter(url, "from", from);
// Add 'To' parameter
if (to > 0) url = Url.AddQueryParameter(url, "to", to);
// Add 'Count' parameter
if (count > 0) url = Url.AddQueryParameter(url, "count", count);
// Add 'Path' parameter
if (!string.IsNullOrEmpty(path)) url = Url.AddQueryParameter(url, "path", path);
// Add 'DocumentFormat' parameter
if (!string.IsNullOrEmpty(documentFormat) && documentFormat != MTConnect.DocumentFormat.XML)
{
url = Url.AddQueryParameter(url, "documentFormat", documentFormat.ToLower());
}
return new Uri(url);
}
return null;
}
private IStreamsResponseDocument HandleResponse(HttpResponseMessage response)
{
if (response != null)
{
if (!response.IsSuccessStatusCode)
{
ConnectionError?.Invoke(this, new Exception(response.ReasonPhrase));
}
else if (response.Content != null)
{
var documentStream = response.Content.ReadAsStreamAsync().Result;
return ReadDocument(response, documentStream);
}
}
return null;
}
private async Task<IStreamsResponseDocument> HandleResponseAsync(HttpResponseMessage response, CancellationToken cancel)
{
if (response != null)
{
if (!response.IsSuccessStatusCode)
{
ConnectionError?.Invoke(this, new Exception(response.ReasonPhrase));
}
else if (response.Content != null)
{
#if NET5_0_OR_GREATER
var documentStream = await response.Content.ReadAsStreamAsync(cancel);
#else
var documentStream = await response.Content.ReadAsStreamAsync();
#endif
return ReadDocument(response, documentStream);
}
}
return null;
}
private IStreamsResponseDocument ReadDocument(HttpResponseMessage response, Stream documentStream)
{
if (documentStream != null && documentStream.Length > 0)
{
// Handle Compression Encoding
var contentEncoding = MTConnectHttpResponse.GetContentHeaderValue(response, HttpHeaders.ContentEncoding);
var stream = MTConnectHttpResponse.HandleContentEncoding(contentEncoding, documentStream);
if (stream != null && stream.Position > 0) stream.Seek(0, SeekOrigin.Begin);
var formatResult = ResponseDocumentFormatter.CreateStreamsResponseDocument(DocumentFormat, stream);
if (formatResult.Success)
{
// Process MTConnectDevices Document
var document = formatResult.Content;
if (document != null)
{
return document;
}
else
{
// Process MTConnectError Document (if MTConnectStreams fails)
var errorFormatResult = ResponseDocumentFormatter.CreateErrorResponseDocument(DocumentFormat, stream);
if (errorFormatResult.Success)
{
var errorDocument = errorFormatResult.Content;
if (errorDocument != null) MTConnectError?.Invoke(this, errorDocument);
}
else
{
// Raise Format Error
if (FormatError != null) FormatError.Invoke(this, errorFormatResult);
}
}
}
else
{
// Raise Format Error
if (FormatError != null) FormatError.Invoke(this, formatResult);
}
}
return null;
}
}
}