-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathmultiple-things.py
More file actions
180 lines (152 loc) · 5.7 KB
/
multiple-things.py
File metadata and controls
180 lines (152 loc) · 5.7 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
from __future__ import division, print_function
from webthing import (Action, Event, MultipleThings, Property, Thing, Value,
WebThingServer)
import logging
import random
import time
import tornado.ioloop
import uuid
class OverheatedEvent(Event):
def __init__(self, thing, data):
Event.__init__(self, thing, 'overheated', data=data)
class FadeAction(Action):
def __init__(self, thing, input_):
Action.__init__(self, uuid.uuid4().hex, thing, 'fade', input_=input_)
def perform_action(self):
time.sleep(self.input['duration'] / 1000)
self.thing.set_property('brightness', self.input['brightness'])
self.thing.add_event(OverheatedEvent(self.thing, 102))
class ExampleDimmableLight(Thing):
"""A dimmable light that logs received commands to stdout."""
def __init__(self):
Thing.__init__(
self,
'urn:dev:ops:my-lamp-1234',
'My Lamp',
['OnOffSwitch', 'Light'],
'A web connected lamp'
)
self.add_property(
Property(self,
'on',
Value(True, lambda v: print('On-State is now', v)),
metadata={
'@type': 'OnOffProperty',
'title': 'On/Off',
'type': 'boolean',
'description': 'Whether the lamp is turned on',
}))
self.add_property(
Property(self,
'brightness',
Value(50, lambda v: print('Brightness is now', v)),
metadata={
'@type': 'BrightnessProperty',
'title': 'Brightness',
'type': 'integer',
'description': 'The level of light from 0-100',
'minimum': 0,
'maximum': 100,
'unit': 'percent',
}))
self.add_available_action(
'fade',
{
'title': 'Fade',
'description': 'Fade the lamp to a given level',
'input': {
'type': 'object',
'required': [
'brightness',
'duration',
],
'properties': {
'brightness': {
'type': 'integer',
'minimum': 0,
'maximum': 100,
'unit': 'percent',
},
'duration': {
'type': 'integer',
'minimum': 1,
'unit': 'milliseconds',
},
},
},
},
FadeAction)
self.add_available_event(
'overheated',
{
'description':
'The lamp has exceeded its safe operating temperature',
'type': 'number',
'unit': 'degree celsius',
})
class FakeGpioHumiditySensor(Thing):
"""A humidity sensor which updates its measurement every few seconds."""
def __init__(self):
Thing.__init__(
self,
'urn:dev:ops:my-humidity-sensor-1234',
'My Humidity Sensor',
['MultiLevelSensor'],
'A web connected humidity sensor'
)
self.level = Value(0.0)
self.add_property(
Property(self,
'level',
self.level,
metadata={
'@type': 'LevelProperty',
'title': 'Humidity',
'type': 'number',
'description': 'The current humidity in %',
'minimum': 0,
'maximum': 100,
'unit': 'percent',
'readOnly': True,
}))
logging.debug('starting the sensor update looping task')
self.timer = tornado.ioloop.PeriodicCallback(
self.update_level,
3000
)
self.timer.start()
def update_level(self):
new_level = self.read_from_gpio()
logging.debug('setting new humidity level: %s', new_level)
self.level.notify_of_external_update(new_level)
def cancel_update_level_task(self):
self.timer.stop()
@staticmethod
def read_from_gpio():
"""Mimic an actual sensor updating its reading every couple seconds."""
return abs(70.0 * random.random() * (-0.5 + random.random()))
def run_server():
# Create a thing that represents a dimmable light
light = ExampleDimmableLight()
# Create a thing that represents a humidity sensor
sensor = FakeGpioHumiditySensor()
# If adding more than one thing, use MultipleThings() with a name.
# In the single thing case, the thing's name will be broadcast.
server = WebThingServer(MultipleThings([light, sensor],
'LightAndTempDevice'),
port=8888)
try:
logging.info('starting the server')
server.start()
except KeyboardInterrupt:
logging.debug('canceling the sensor update looping task')
sensor.cancel_update_level_task()
logging.info('stopping the server')
server.stop()
logging.info('done')
if __name__ == '__main__':
logging.basicConfig(
level=10,
format="%(asctime)s %(filename)s:%(lineno)s %(levelname)s %(message)s"
)
run_server()