/
Lwm2mObjectInstance.cs
465 lines (407 loc) · 11.1 KB
/
Lwm2mObjectInstance.cs
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
465
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using Waher.Events;
using Waher.Persistence.Attributes;
using Waher.Networking.CoAP;
using Waher.Networking.CoAP.Options;
using Waher.Networking.LWM2M.ContentFormats;
namespace Waher.Networking.LWM2M
{
/// <summary>
/// Base class for all LWM2M object instances.
/// </summary>
[CollectionName("Lwm2mObjectInstances")]
[TypeName(TypeNameSerialization.FullName)]
[Index("Id", "InstanceId")]
public abstract class Lwm2mObjectInstance : CoapResource, ICoapGetMethod, ICoapPutMethod, ICoapPostMethod
{
private readonly SortedDictionary<int, Lwm2mResource> resources = new SortedDictionary<int, Lwm2mResource>();
private Lwm2mObject obj = null;
private string objectId = null;
private ushort id;
private ushort instanceId;
/// <summary>
/// Base class for all LWM2M objects.
/// </summary>
/// <param name="Id">ID of object.</param>
/// <param name="InstanceId">ID of object instance.</param>
/// <param name="Resources">Resources.</param>
public Lwm2mObjectInstance(ushort Id, ushort InstanceId, params Lwm2mResource[] Resources)
: base("/" + Id.ToString() + "/" + InstanceId.ToString())
{
this.id = Id;
this.instanceId = InstanceId;
foreach (Lwm2mResource Resource in Resources)
this.Add(Resource);
}
/// <summary>
/// Object ID in database.
/// </summary>
[ObjectId]
public string ObjectId
{
get => this.objectId;
set => this.objectId = value;
}
/// <summary>
/// LWM2M object.
/// </summary>
public Lwm2mObject Object
{
get => this.obj;
internal set => this.obj = value;
}
/// <summary>
/// ID of object.
/// </summary>
public ushort Id
{
get => this.id;
set
{
if (this.id != value)
{
this.id = value;
this.Path = "/" + this.id.ToString() + "/" + this.instanceId.ToString();
}
}
}
/// <summary>
/// ID of Object Instance.
/// </summary>
public ushort InstanceId
{
get => this.instanceId;
set
{
if (this.instanceId != value)
{
this.instanceId = value;
this.Path = "/" + this.id.ToString() + "/" + this.instanceId.ToString();
}
}
}
/// <summary>
/// Registered resources.
/// </summary>
public Lwm2mResource[] Resources
{
get
{
Lwm2mResource[] Result;
lock (this.resources)
{
Result = new Lwm2mResource[this.resources.Count];
this.resources.Values.CopyTo(Result, 0);
}
return Result;
}
}
/// <summary>
/// If the object instance has resources registered on it.
/// </summary>
public bool HasResources
{
get
{
lock (this.resources)
{
return this.resources.Count > 0;
}
}
}
/// <summary>
/// How notifications are sent, if at all.
/// </summary>
public override Notifications Notifications => Notifications.Acknowledged;
/// <summary>
/// Adds a resource.
/// </summary>
/// <param name="Resource">Resource.</param>
public void Add(Lwm2mResource Resource)
{
lock (this.resources)
{
if (Resource.ResourceId < 0)
throw new ArgumentException("Invalid resource ID.", nameof(Resource));
if (this.resources.ContainsKey(Resource.ResourceId))
{
throw new ArgumentException("A resource with ID " + Resource.ResourceId +
" is already registered.", nameof(Resource));
}
this.resources[Resource.ResourceId] = Resource;
Resource.ObjectInstance = this;
}
}
/// <summary>
/// Removes all resources.
/// </summary>
protected void ClearResources()
{
Lwm2mResource[] Resources;
lock (this.resources)
{
Resources = new Lwm2mResource[this.resources.Count];
this.resources.Values.CopyTo(Resources, 0);
this.resources.Clear();
}
foreach (Lwm2mResource Resource in Resources)
this.obj?.Client?.CoapEndpoint.Unregister(Resource);
}
/// <summary>
/// Loads any Bootstrap information.
/// </summary>
public virtual async Task LoadBootstrapInfo()
{
foreach (Lwm2mResource Resource in this.Resources)
{
if (Resource.CanWrite && Resource.Persist)
await Resource.ReadPersistedValue();
}
}
/// <summary>
/// Deletes any Bootstrap information.
/// </summary>
public virtual Task DeleteBootstrapInfo()
{
return Task.CompletedTask;
}
/// <summary>
/// Applies any Bootstrap information.
/// </summary>
public virtual Task ApplyBootstrapInfo()
{
return Task.CompletedTask;
}
/// <summary>
/// Method called when the resource value has been updated.
/// </summary>
/// <param name="Resource">Resource reporting an updated value.</param>
public virtual Task ValueUpdated(Lwm2mResource Resource)
{
return Task.CompletedTask;
}
/// <summary>
/// Encodes available object links.
/// </summary>
/// <param name="IncludeSecurity">If security objects are to be included.</param>
/// <param name="Output">Link output.</param>
public void EncodeObjectLinks(bool IncludeSecurity, StringBuilder Output)
{
if (this.id > 0 || IncludeSecurity)
{
Output.Append(',');
Output.Append("</");
Output.Append(this.id.ToString());
Output.Append('/');
Output.Append(this.instanceId.ToString());
Output.Append('>');
this.EncodeLinkParameters(Output);
}
}
/// <summary>
/// Encodes any link parameters to the object link.
/// </summary>
/// <param name="Output">Link output.</param>
public virtual void EncodeLinkParameters(StringBuilder Output)
{
}
/// <inheritdoc/>
public override string ToString()
{
return this.Path + ": " + this.GetType().FullName;
}
/// <summary>
/// If the GET method is allowed.
/// </summary>
public bool AllowsGET => true;
/// <summary>
/// Executes the GET method on the resource.
/// </summary>
/// <param name="Request">CoAP Request</param>
/// <param name="Response">CoAP Response</param>
/// <exception cref="CoapException">If an error occurred when processing the method.</exception>
public virtual Task GET(CoapMessage Request, CoapResponse Response)
{
ILwm2mWriter Writer;
bool FromBootstrapServer = this.obj.Client.IsFromBootstrapServer(Request);
if (this.id == 0 && !FromBootstrapServer)
{
Response.RST(CoapCode.Unauthorized);
return Task.CompletedTask;
}
if (!string.IsNullOrEmpty(Request.SubPath))
{
Response.RST(CoapCode.NotFound);
return Task.CompletedTask;
}
if (Request.IsAcceptable(Tlv.ContentFormatCode))
Writer = new TlvWriter();
else if (Request.IsAcceptable(Json.ContentFormatCode))
Writer = new JsonWriter(this.Path + "/");
else if (Request.IsAcceptable(CoAP.ContentFormats.CoreLinkFormat.ContentFormatCode))
{
StringBuilder Output = new StringBuilder();
this.EncodeObjectLinks(FromBootstrapServer, Output);
Response.Respond(CoapCode.Content, Encoding.UTF8.GetBytes(Output.ToString()), 64,
new CoapOptionContentFormat(CoAP.ContentFormats.CoreLinkFormat.ContentFormatCode));
return Task.CompletedTask;
}
else
{
Response.RST(CoapCode.NotAcceptable);
return Task.CompletedTask;
}
this.Export(Writer);
byte[] Payload = Writer.ToArray();
if (Payload.Length == 0)
Response.RST(CoapCode.NotFound);
else
{
Response.Respond(CoapCode.Content, Payload, 64,
new CoapOptionContentFormat(Writer.ContentFormat));
}
return Task.CompletedTask;
}
/// <summary>
/// Exports all resources.
/// </summary>
/// <param name="Writer">Output</param>
public virtual void Export(ILwm2mWriter Writer)
{
foreach (Lwm2mResource Resource in this.Resources)
Resource.Write(Writer);
}
/// <summary>
/// Event raised after the resource has been registered
/// </summary>
public event EventHandler OnAfterRegister = null;
/// <summary>
/// Called after the resource has been registered on a CoAP Endpoint.
/// </summary>
/// <param name="Client">LWM2M Client</param>
public virtual void AfterRegister(Lwm2mClient Client)
{
foreach (Lwm2mResource Resource in this.Resources)
{
Client.CoapEndpoint.Register(Resource);
Resource.AfterRegister();
}
try
{
this.OnAfterRegister?.Invoke(this, EventArgs.Empty);
}
catch (Exception ex)
{
Log.Critical(ex);
}
}
/// <summary>
/// If the POST method is allowed.
/// </summary>
public bool AllowsPOST => this.AllowsPUT;
/// <summary>
/// Executes the POST method on the resource.
/// </summary>
/// <param name="Request">CoAP Request</param>
/// <param name="Response">CoAP Response</param>
/// <exception cref="CoapException">If an error occurred when processing the method.</exception>
public Task POST(CoapMessage Request, CoapResponse Response)
{
return this.PUT(Request, Response);
}
/// <summary>
/// If the PUT method is allowed.
/// </summary>
public virtual bool AllowsPUT => true;
/// <summary>
/// Executes the PUT method on the resource.
/// </summary>
/// <param name="Request">CoAP Request</param>
/// <param name="Response">CoAP Response</param>
/// <exception cref="CoapException">If an error occurred when processing the method.</exception>
public virtual async Task PUT(CoapMessage Request, CoapResponse Response)
{
bool FromBootstrapServer = this.obj.Client.IsFromBootstrapServer(Request);
if (this.id == 0 && !FromBootstrapServer)
{
Response.RST(CoapCode.Unauthorized);
return;
}
if (!(Request.UriQuery is null) && Request.UriQuery.Count > 0) // Write attributes
{
if (!FromBootstrapServer)
{
Response.RST(CoapCode.Unauthorized);
return;
}
foreach (KeyValuePair<string, string> P in Request.UriQuery)
{
switch (P.Key)
{
case "pmin":
case "pmax":
case "gt":
case "lt":
case "st":
// TODO: Implement support
break;
default:
Response.RST(CoapCode.BadRequest);
return;
}
}
}
if (!(Request.ContentFormat is null)) // Write operation
{
object Decoded = await Request.DecodeAsync();
if (Decoded is TlvRecord[] Records)
{
LinkedList<KeyValuePair<Lwm2mResource, TlvRecord>> ToWrite =
new LinkedList<KeyValuePair<Lwm2mResource, TlvRecord>>();
lock (this.resources)
{
foreach (TlvRecord Rec in Records)
{
if (!this.resources.TryGetValue(Rec.Identifier, out Lwm2mResource Resource) ||
(!Resource.CanWrite && !FromBootstrapServer))
{
ToWrite = null;
break;
}
ToWrite.AddLast(new KeyValuePair<Lwm2mResource, TlvRecord>(Resource, Rec));
}
}
if (ToWrite is null)
{
Response.Respond(CoapCode.BadRequest);
return;
}
if (Request.Code == CoapCode.PUT) // POST updates, PUT recreates
{
foreach (Lwm2mResource Resource in this.Resources)
Resource.Reset();
}
foreach (KeyValuePair<Lwm2mResource, TlvRecord> Rec in ToWrite)
{
await Rec.Key.Read(Rec.Value);
Rec.Key.RemoteUpdate(Request);
}
}
else
{
Response.Respond(CoapCode.NotAcceptable);
return;
}
}
else
{
Response.Respond(CoapCode.BadRequest);
return;
}
Response.Respond(CoapCode.Changed);
}
}
}