-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy paththing.py
More file actions
467 lines (365 loc) · 12.9 KB
/
thing.py
File metadata and controls
467 lines (365 loc) · 12.9 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
465
466
467
"""High-level Thing base class implementation."""
from jsonschema import validate
from jsonschema.exceptions import ValidationError
class Thing:
"""A Web Thing."""
def __init__(self, id_, title, type_=[], description=''):
"""
Initialize the object.
id_ -- the thing's unique ID - must be a URI
title -- the thing's title
type_ -- the thing's type(s)
description -- description of the thing
"""
if not isinstance(type_, list):
type_ = [type_]
self.id = id_
self.context = ['https://www.w3.org/ns/wot-next/td', 'https://webthings.io/schemas']
self.profiles = ["https://www.w3.org/2022/wot/profile/http-basic/v1"]
self.type = type_
self.title = title
self.description = description
self.properties = {}
self.available_actions = {}
self.available_events = {}
self.actions = {}
self.events = []
self.subscribers = set()
self.href_prefix = ''
self.ui_href = None
self.securityDefinitions = { "nosec_sc": { "scheme": "nosec" }}
self.security = "nosec_sc"
def as_thing_description(self):
"""
Return the thing state as a Thing Description.
Returns the state as a dictionary.
"""
thing = {
'id': self.id,
'title': self.title,
'@context': self.context,
'profile': self.profiles,
'properties': self.get_property_descriptions(),
'actions': {},
'events': {},
'forms': [
{
'op': "readallproperties",
'href': '{}/properties'.format(self.href_prefix),
'contentType': 'application/json',
},
{
'op': "writemultipleproperties",
'href': '{}/properties'.format(self.href_prefix),
'contentType': 'application/json',
}
],
'securityDefinitions': self.securityDefinitions,
'security': self.security
}
for name, action in self.available_actions.items():
thing['actions'][name] = action['metadata']
thing['actions'][name]['synchronous'] = True
thing['actions'][name]['forms'] = [
{
'op': ['invokeaction'],
'href': '{}/actions/{}'.format(self.href_prefix, name),
},
]
for name, event in self.available_events.items():
thing['events'][name] = event['metadata']
thing['events'][name]['forms'] = [
{
'op': ['subscribeevent', 'unsubscribeevent'],
'href': '{}/events/{}'.format(self.href_prefix, name),
},
]
if self.ui_href is not None:
thing['forms'].append({
'rel': 'alternate',
'type': 'text/html',
'href': self.ui_href,
})
if self.description:
thing['description'] = self.description
if self.type:
thing['@type'] = self.type
return thing
def get_href(self):
"""Get this thing's href."""
if self.href_prefix:
return self.href_prefix
return '/'
def get_ui_href(self):
"""Get the UI href."""
return self.ui_href
def set_href_prefix(self, prefix):
"""
Set the prefix of any hrefs associated with this thing.
prefix -- the prefix
"""
self.href_prefix = prefix
for property_ in self.properties.values():
property_.set_href_prefix(prefix)
for action_name in self.actions.keys():
for action in self.actions[action_name]:
action.set_href_prefix(prefix)
def set_ui_href(self, href):
"""
Set the href of this thing's custom UI.
href -- the href
"""
self.ui_href = href
def get_id(self):
"""
Get the ID of the thing.
Returns the ID as a string.
"""
return self.id
def get_title(self):
"""
Get the title of the thing.
Returns the title as a string.
"""
return self.title
def get_context(self):
"""
Get the type context of the thing.
Returns the context as a string.
"""
return self.context
def get_type(self):
"""
Get the type(s) of the thing.
Returns the list of types.
"""
return self.type
def get_description(self):
"""
Get the description of the thing.
Returns the description as a string.
"""
return self.description
def get_property_descriptions(self):
"""
Get the thing's properties as a dictionary.
Returns the properties as a dictionary, i.e. name -> description.
"""
return {k: v.as_property_description()
for k, v in self.properties.items()}
def get_action_descriptions(self, action_name=None):
"""
Get the thing's actions as an array.
action_name -- Optional action name to get descriptions for
Returns the action descriptions.
"""
descriptions = []
if action_name is None:
for name in self.actions:
for action in self.actions[name]:
descriptions.append(action.as_action_description())
elif action_name in self.actions:
for action in self.actions[action_name]:
descriptions.append(action.as_action_description())
return descriptions
def get_event_descriptions(self, event_name=None):
"""
Get the thing's events as an array.
event_name -- Optional event name to get descriptions for
Returns the event descriptions.
"""
if event_name is None:
return [e.as_event_description() for e in self.events]
else:
return [e.as_event_description()
for e in self.events if e.get_name() == event_name]
def add_property(self, property_):
"""
Add a property to this thing.
property_ -- property to add
"""
property_.set_href_prefix(self.href_prefix)
self.properties[property_.name] = property_
def remove_property(self, property_):
"""
Remove a property from this thing.
property_ -- property to remove
"""
if property_.name in self.properties:
del self.properties[property_.name]
def find_property(self, property_name):
"""
Find a property by name.
property_name -- the property to find
Returns a Property object, if found, else None.
"""
return self.properties.get(property_name, None)
def get_property(self, property_name):
"""
Get a property's value.
property_name -- the property to get the value of
Returns the properties value, if found, else None.
"""
prop = self.find_property(property_name)
if prop:
return prop.get_value()
return None
def get_properties(self):
"""
Get a mapping of all properties and their values.
Returns a dictionary of property_name -> value.
"""
return {prop.get_name(): prop.get_value()
for prop in self.properties.values()}
def has_property(self, property_name):
"""
Determine whether or not this thing has a given property.
property_name -- the property to look for
Returns a boolean, indicating whether or not the thing has the
property.
"""
return property_name in self.properties
def set_property(self, property_name, value):
"""
Set a property value.
property_name -- name of the property to set
value -- value to set
"""
prop = self.find_property(property_name)
if not prop:
return
prop.set_value(value)
def get_action(self, action_name, action_id):
"""
Get an action.
action_name -- name of the action
action_id -- ID of the action
Returns the requested action if found, else None.
"""
if action_name not in self.actions:
return None
for action in self.actions[action_name]:
if action.id == action_id:
return action
return None
def add_event(self, event):
"""
Add a new event and notify subscribers.
event -- the event that occurred
"""
self.events.append(event)
self.event_notify(event)
def add_available_event(self, name, metadata):
"""
Add an available event.
name -- name of the event
metadata -- event metadata, i.e. type, description, etc., as a dict
"""
if metadata is None:
metadata = {}
self.available_events[name] = {
'metadata': metadata,
'subscribers': set(),
}
def perform_action(self, action_name, input_=None):
"""
Perform an action on the thing.
action_name -- name of the action
input_ -- any action inputs
Returns the action that was created.
"""
if action_name not in self.available_actions:
return None
action_type = self.available_actions[action_name]
if 'input' in action_type['metadata']:
try:
validate(input_, action_type['metadata']['input'])
except ValidationError:
return None
action = action_type['class'](self, input_=input_)
action.set_href_prefix(self.href_prefix)
self.action_notify(action)
self.actions[action_name].append(action)
return action
def remove_action(self, action_name, action_id):
"""
Remove an existing action.
action_name -- name of the action
action_id -- ID of the action
Returns a boolean indicating the presence of the action.
"""
action = self.get_action(action_name, action_id)
if action is None:
return False
action.cancel()
self.actions[action_name].remove(action)
return True
def add_available_action(self, name, metadata, cls):
"""
Add an available action.
name -- name of the action
metadata -- action metadata, i.e. type, description, etc., as a dict
cls -- class to instantiate for this action
"""
if metadata is None:
metadata = {}
self.available_actions[name] = {
'metadata': metadata,
'class': cls,
}
self.actions[name] = []
def add_subscriber(self, subscriber):
"""
Add a new websocket subscriber.
:param subscriber: Subscriber
"""
self.subscribers.add(subscriber)
def remove_subscriber(self, subscriber):
"""
Remove a websocket subscriber.
:param subscriber: Subscriber
"""
if subscriber in self.subscribers:
self.subscribers.remove(subscriber)
for name in self.available_events:
self.remove_event_subscriber(name, subscriber)
def add_event_subscriber(self, name, subscriber):
"""
Add a new websocket subscriber to an event.
:param name: Name of the event
:param subscriber: Subscriber
"""
if name in self.available_events:
self.available_events[name]['subscribers'].add(subscriber)
def remove_event_subscriber(self, name, subscriber):
"""
Remove a websocket subscriber from an event.
:param name: Name of the event
:param subscriber: Subscriber
"""
if name in self.available_events and \
subscriber in self.available_events[name]['subscribers']:
self.available_events[name]['subscribers'].remove(subscriber)
def property_notify(self, property_):
"""
Notify all subscribers of a property change.
:param property_: the property that changed
"""
for subscriber in list(self.subscribers):
subscriber.update_property(property_)
def action_notify(self, action):
"""
Notify all subscribers of an action status change.
:param action: The action whose status changed
"""
for subscriber in list(self.subscribers):
subscriber.update_action(action)
def event_notify(self, event):
"""
Notify all subscribers of an event.
:param event: The event that occurred
"""
if event.name not in self.available_events:
return
for subscriber in self.available_events[event.name]['subscribers']:
subscriber.update_event(event)