forked from smeshlink/CoAP.NET
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathProgram.cs
More file actions
308 lines (257 loc) · 9.93 KB
/
Copy pathProgram.cs
File metadata and controls
308 lines (257 loc) · 9.93 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
using CoAP;
using CoAP.Server.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Concurrent;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
namespace CoAP.Examples.ResourceMvc
{
public static class Program
{
private const int Port = 5683;
public static async Task Main(string[] args)
{
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton<SensorReadingStore>();
builder.Services.AddSingleton<ObserveSequence>();
builder.Services.AddCoapServer(options =>
{
options.ListenAnyIP(Port);
});
builder.Services.AddCoapJsonPayloadBinder(ResourceMvcJsonContext.Default);
builder.Services.AddCoapResources(options => options.AddEndpointFactory(global::MyGeneratedCoapEndpoints.Create));
var app = builder.Build();
app.MapCoapResources();
Console.WriteLine("CoAP.NET Resource/MVC sample is listening on coap://localhost:" + Port);
Console.WriteLine("Discovery: coap://localhost/.well-known/core");
Console.WriteLine("JSON POST: coap://localhost/sensors/demo/readings?point=1");
Console.WriteLine("Binary POST: coap://localhost/sensors/demo/snapshot");
Console.WriteLine("Observe: coap://localhost/sensors/demo/status");
Console.WriteLine("Fault: coap://localhost/sensors/demo/fault");
await app.RunAsync().ConfigureAwait(false);
}
}
[CoapResource]
[CoapRoute("sensors/{sensor}")]
[CoapResourceTitle("Sample sensor")]
[CoapResourceType("sample.sensor")]
[CoapInterfaceDescription("sensor")]
public sealed class SensorCoapResource : CoapResourceBase
{
private readonly SensorReadingStore _readings;
private readonly ObserveSequence _observeSequence;
public SensorCoapResource(SensorReadingStore readings, ObserveSequence observeSequence)
{
_readings = readings;
_observeSequence = observeSequence;
}
[CoapGet("latest")]
[CoapResourceTitle("Latest sensor reading")]
[CoapProduces(MediaType.ApplicationJson)]
public CoapRouteResult GetLatest(string sensor, [CoapFromQuery("unit")] string requestedUnit = null)
{
var reading = _readings.GetLatest(sensor, requestedUnit);
return Json(reading, ResourceMvcJsonContext.Default.ReadingState).WithMaxAge(10);
}
[CoapPost("readings")]
[CoapResourceTitle("Upload JSON sensor reading")]
[CoapConsumes(MediaType.ApplicationJson)]
[CoapProduces(MediaType.ApplicationJson)]
public CoapRouteResult UploadReading(
string sensor,
[CoapFromQuery] int point,
[CoapFromQuery("tag")] string[] tags,
[CoapFromOption(OptionType.ContentFormat)] int contentFormat,
[CoapFromOption(OptionType.Accept)] int accept,
ReadingPayload payload,
CoapRouteContext context,
System.Net.EndPoint remoteEndPoint)
{
var reading = _readings.SaveReading(
sensor,
point,
tags,
contentFormat,
accept,
payload,
remoteEndPoint);
return Json(new UploadReadingResponse
{
Ok = true,
Reading = reading,
Path = string.Join("/", context.PathSegments)
}, ResourceMvcJsonContext.Default.UploadReadingResponse).WithLocationPath("sensors/" + sensor + "/latest");
}
[CoapPost("snapshot")]
[CoapResourceTitle("Upload binary sensor snapshot")]
[CoapConsumes(MediaType.ApplicationOctetStream)]
[CoapProduces(MediaType.ApplicationJson)]
public CoapRouteResult UploadSnapshot(
string sensor,
[CoapFromPayload] ReadOnlyMemory<byte> payload)
{
var receipt = _readings.SaveSnapshot(sensor, payload.Length);
return Json(new UploadSnapshotResponse
{
Ok = true,
Receipt = receipt
}, ResourceMvcJsonContext.Default.UploadSnapshotResponse).WithLocationPath("sensors/" + sensor + "/snapshot");
}
[CoapObserve("status")]
[CoapResourceTitle("Observable sensor status")]
[CoapResourceType("sample.sensor.status")]
[CoapInterfaceDescription("if.s")]
[CoapProduces(MediaType.ApplicationJson)]
public CoapRouteResult ObserveStatus(string sensor)
{
var observe = _observeSequence.Next();
return Json(new SensorStatusResponse
{
Sensor = sensor,
Status = "online",
Observe = observe
}, ResourceMvcJsonContext.Default.SensorStatusResponse).WithObserve(observe).WithMaxAge(5);
}
[CoapGet("fault")]
[CoapResourceTitle("Sample error response")]
[CoapProduces(MediaType.TextPlain)]
public CoapRouteResult Fault(string sensor)
{
return CoapRouteResult.Text(
StatusCode.BadRequest,
"sample error response for sensor '" + sensor + "'");
}
private static CoapRouteResult Json<T>(T value, JsonTypeInfo<T> jsonTypeInfo)
{
return CoapRouteResult.Json(JsonSerializer.SerializeToUtf8Bytes(value, jsonTypeInfo));
}
}
public sealed class SensorReadingStore
{
private readonly ConcurrentDictionary<string, ReadingState> _readings =
new ConcurrentDictionary<string, ReadingState>(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, SnapshotReceipt> _snapshots =
new ConcurrentDictionary<string, SnapshotReceipt>(StringComparer.Ordinal);
public ReadingState GetLatest(string sensor, string requestedUnit)
{
if (_readings.TryGetValue(sensor, out var reading))
{
if (!string.IsNullOrWhiteSpace(requestedUnit))
{
reading.RequestedUnit = requestedUnit;
}
return reading;
}
return new ReadingState
{
Sensor = sensor,
Point = 0,
Unit = requestedUnit ?? "unknown",
Value = 0,
Timestamp = DateTimeOffset.UtcNow,
Source = "default"
};
}
public ReadingState SaveReading(
string sensor,
int point,
string[] tags,
int contentFormat,
int accept,
ReadingPayload payload,
System.Net.EndPoint remoteEndPoint)
{
var reading = new ReadingState
{
Sensor = sensor,
Point = point,
Tags = tags ?? Array.Empty<string>(),
Unit = payload?.Unit ?? "unknown",
Value = payload?.Value ?? 0,
Timestamp = DateTimeOffset.UtcNow,
ContentFormat = MediaType.ToString(contentFormat),
Accept = MediaType.ToString(accept),
RemoteEndPoint = remoteEndPoint?.ToString(),
Source = "json"
};
_readings[sensor] = reading;
return reading;
}
public SnapshotReceipt SaveSnapshot(string sensor, int byteCount)
{
var receipt = new SnapshotReceipt
{
Sensor = sensor,
ByteCount = byteCount,
Timestamp = DateTimeOffset.UtcNow
};
_snapshots[sensor] = receipt;
return receipt;
}
}
public sealed class ObserveSequence
{
private int _value;
public int Next()
{
return Interlocked.Increment(ref _value) & 0x00FFFFFF;
}
}
public sealed class ReadingPayload
{
public string Unit { get; set; }
public double Value { get; set; }
}
public sealed class ReadingState
{
public string Sensor { get; set; }
public int Point { get; set; }
public string[] Tags { get; set; } = Array.Empty<string>();
public string Unit { get; set; }
public string RequestedUnit { get; set; }
public double Value { get; set; }
public DateTimeOffset Timestamp { get; set; }
public string ContentFormat { get; set; }
public string Accept { get; set; }
public string RemoteEndPoint { get; set; }
public string Source { get; set; }
}
public sealed class SnapshotReceipt
{
public string Sensor { get; set; }
public int ByteCount { get; set; }
public DateTimeOffset Timestamp { get; set; }
}
public sealed class UploadReadingResponse
{
public bool Ok { get; set; }
public ReadingState Reading { get; set; }
public string Path { get; set; }
}
public sealed class UploadSnapshotResponse
{
public bool Ok { get; set; }
public SnapshotReceipt Receipt { get; set; }
}
public sealed class SensorStatusResponse
{
public string Sensor { get; set; }
public string Status { get; set; }
public int Observe { get; set; }
}
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
[JsonSerializable(typeof(ReadingPayload))]
[JsonSerializable(typeof(ReadingState))]
[JsonSerializable(typeof(SnapshotReceipt))]
[JsonSerializable(typeof(UploadReadingResponse))]
[JsonSerializable(typeof(UploadSnapshotResponse))]
[JsonSerializable(typeof(SensorStatusResponse))]
internal sealed partial class ResourceMvcJsonContext : JsonSerializerContext
{
}
}