- Notifications
You must be signed in to change notification settings - Fork 384
/
Copy pathtemp_controller_with_thermostats.py
419 lines (334 loc) · 14.6 KB
/
temp_controller_with_thermostats.py
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
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
importos
importasyncio
importrandom
importlogging
fromazure.iot.device.aioimportIoTHubDeviceClient
fromazure.iot.device.aioimportProvisioningDeviceClient
fromazure.iot.deviceimportMethodResponse
fromdatetimeimporttimedelta, datetime
importpnp_helper
logging.basicConfig(level=logging.ERROR)
# the interfaces that are pulled in to implement the device.
# User has to know these values as these may change and user can
# choose to implement different interfaces.
thermostat_digital_twin_model_identifier="dtmi:com:example:Thermostat;1"
device_info_digital_twin_model_identifier="dtmi:azure:DeviceManagement:DeviceInformation;1"
# The device "TemperatureController" that is getting implemented using the above interfaces.
# This id can change according to the company the user is from
# and the name user wants to call this Plug and Play device
model_id="dtmi:com:example:TemperatureController;2"
# the components inside this Plug and Play device.
# there can be multiple components from 1 interface
# component names according to interfaces following pascal case.
device_information_component_name="deviceInformation"
thermostat_1_component_name="thermostat1"
thermostat_2_component_name="thermostat2"
serial_number="some_serial_number"
#####################################################
# COMMAND HANDLERS : User will define these handlers
# depending on what commands the component defines
#####################################################
# GLOBAL VARIABLES
THERMOSTAT_1=None
THERMOSTAT_2=None
classThermostat(object):
def__init__(self, name, moving_win=10):
self.moving_window=moving_win
self.records= [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
self.index=0
self.cur=0
self.max=0
self.min=0
self.avg=0
self.name=name
defrecord(self, current_temp):
self.cur=current_temp
self.records[self.index] =current_temp
self.max=self.calculate_max(current_temp)
self.min=self.calculate_min(current_temp)
self.avg=self.calculate_average()
self.index= (self.index+1) %self.moving_window
defcalculate_max(self, current_temp):
ifnotself.max:
returncurrent_temp
elifcurrent_temp>self.max:
returnself.max
defcalculate_min(self, current_temp):
ifnotself.min:
returncurrent_temp
elifcurrent_temp<self.min:
returnself.min
defcalculate_average(self):
returnsum(self.records) /self.moving_window
defcreate_report(self):
response_dict= {}
response_dict["maxTemp"] =self.max
response_dict["minTemp"] =self.min
response_dict["avgTemp"] =self.avg
response_dict["startTime"] = (
(datetime.now() -timedelta(0, self.moving_window*8)).astimezone().isoformat()
)
response_dict["endTime"] =datetime.now().astimezone().isoformat()
returnresponse_dict
asyncdefreboot_handler(values):
ifvalues:
print("Rebooting after delay of {delay} secs".format(delay=values))
print("Done rebooting")
asyncdefmax_min_handler(values):
ifvalues:
print(
"Will return the max, min and average temperature from the specified time {since} to the current time".format(
since=values
)
)
print("Done generating")
# END COMMAND HANDLERS
#####################################################
#####################################################
# CREATE RESPONSES TO COMMANDS
defcreate_max_min_report_response(thermostat_name):
"""
An example function that can create a response to the "getMaxMinReport" command request the way the user wants it.
Most of the times response is created by a helper function which follows a generic pattern.
This should be only used when the user wants to give a detailed response back to the Hub.
:param values: The values that were received as part of the request.
"""
if"Thermostat;1"inthermostat_nameandTHERMOSTAT_1:
response_dict=THERMOSTAT_1.create_report()
elifTHERMOSTAT_2:
response_dict=THERMOSTAT_2.create_report()
else: # This is done to pass certification.
response_dict= {}
response_dict["maxTemp"] =0
response_dict["minTemp"] =0
response_dict["avgTemp"] =0
response_dict["startTime"] =datetime.now().astimezone().isoformat()
response_dict["endTime"] =datetime.now().astimezone().isoformat()
print(response_dict)
returnresponse_dict
# END CREATE RESPONSES TO COMMANDS
#####################################################
#####################################################
# TELEMETRY TASKS
asyncdefsend_telemetry_from_temp_controller(device_client, telemetry_msg, component_name=None):
msg=pnp_helper.create_telemetry(telemetry_msg, component_name)
awaitdevice_client.send_message(msg)
print("Sent message")
print(msg)
awaitasyncio.sleep(5)
#####################################################
# COMMAND TASKS
asyncdefexecute_command_listener(
device_client,
component_name=None,
method_name=None,
user_command_handler=None,
create_user_response_handler=None,
):
"""
Coroutine for executing listeners. These will listen for command requests.
They will take in a user provided handler and call the user provided handler
according to the command request received.
:param device_client: The device client
:param component_name: The name of the device like "sensor"
:param method_name: (optional) The specific method name to listen for. Eg could be "blink", "turnon" etc.
If not provided the listener will listen for all methods.
:param user_command_handler: (optional) The user provided handler that needs to be executed after receiving "command requests".
If not provided nothing will be executed on receiving command.
:param create_user_response_handler: (optional) The user provided handler that will create a response.
If not provided a generic response will be created.
:return:
"""
whileTrue:
ifcomponent_nameandmethod_name:
command_name=component_name+"*"+method_name
elifmethod_name:
command_name=method_name
else:
command_name=None
command_request=awaitdevice_client.receive_method_request(command_name)
print("Command request received with payload")
values=command_request.payload
print(values)
ifuser_command_handler:
awaituser_command_handler(values)
else:
print("No handler provided to execute")
(response_status, response_payload) =pnp_helper.create_response_payload_with_status(
command_request, method_name, create_user_response=create_user_response_handler
)
command_response=MethodResponse.create_from_method_request(
command_request, response_status, response_payload
)
try:
awaitdevice_client.send_method_response(command_response)
exceptException:
print("responding to the {command} command failed".format(command=method_name))
#####################################################
# PROPERTY TASKS
asyncdefexecute_property_listener(device_client):
whileTrue:
patch=awaitdevice_client.receive_twin_desired_properties_patch() # blocking call
print(patch)
properties_dict=pnp_helper.create_reported_properties_from_desired(patch)
awaitdevice_client.patch_twin_reported_properties(properties_dict)
#####################################################
# An # END KEYBOARD INPUT LISTENER to quit application
defstdin_listener():
"""
Listener for quitting the sample
"""
whileTrue:
selection=input("Press Q to quit\n")
ifselection=="Q"orselection=="q":
print("Quitting...")
break
# END KEYBOARD INPUT LISTENER
#####################################################
#####################################################
# MAIN STARTS
asyncdefprovision_device(provisioning_host, id_scope, registration_id, symmetric_key, model_id):
provisioning_device_client=ProvisioningDeviceClient.create_from_symmetric_key(
provisioning_host=provisioning_host,
registration_id=registration_id,
id_scope=id_scope,
symmetric_key=symmetric_key,
)
provisioning_device_client.provisioning_payload= {"modelId": model_id}
returnawaitprovisioning_device_client.register()
asyncdefmain():
switch=os.getenv("IOTHUB_DEVICE_SECURITY_TYPE")
ifswitch=="DPS":
provisioning_host= (
os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT")
ifos.getenv("IOTHUB_DEVICE_DPS_ENDPOINT")
else"global.azure-devices-provisioning.net"
)
id_scope=os.getenv("IOTHUB_DEVICE_DPS_ID_SCOPE")
registration_id=os.getenv("IOTHUB_DEVICE_DPS_DEVICE_ID")
symmetric_key=os.getenv("IOTHUB_DEVICE_DPS_DEVICE_KEY")
registration_result=awaitprovision_device(
provisioning_host, id_scope, registration_id, symmetric_key, model_id
)
ifregistration_result.status=="assigned":
print("Device was assigned")
print(registration_result.registration_state.assigned_hub)
print(registration_result.registration_state.device_id)
device_client=IoTHubDeviceClient.create_from_symmetric_key(
symmetric_key=symmetric_key,
hostname=registration_result.registration_state.assigned_hub,
device_id=registration_result.registration_state.device_id,
product_info=model_id,
)
else:
raiseRuntimeError(
"Could not provision device. Aborting Plug and Play device connection."
)
elifswitch=="connectionString":
conn_str=os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
print("Connecting using Connection String "+conn_str)
device_client=IoTHubDeviceClient.create_from_connection_string(
conn_str, product_info=model_id
)
else:
raiseRuntimeError(
"At least one choice needs to be made for complete functioning of this sample."
)
# Connect the client.
awaitdevice_client.connect()
################################################
# Update readable properties from various components
properties_root=pnp_helper.create_reported_properties(serialNumber=serial_number)
properties_thermostat1=pnp_helper.create_reported_properties(
thermostat_1_component_name, maxTempSinceLastReboot=98.34
)
properties_thermostat2=pnp_helper.create_reported_properties(
thermostat_2_component_name, maxTempSinceLastReboot=48.92
)
properties_device_info=pnp_helper.create_reported_properties(
device_information_component_name,
swVersion="5.5",
manufacturer="Contoso Device Corporation",
model="Contoso 4762B-turbo",
osName="Mac Os",
processorArchitecture="x86-64",
processorManufacturer="Intel",
totalStorage=1024,
totalMemory=32,
)
property_updates=asyncio.gather(
device_client.patch_twin_reported_properties(properties_root),
device_client.patch_twin_reported_properties(properties_thermostat1),
device_client.patch_twin_reported_properties(properties_thermostat2),
device_client.patch_twin_reported_properties(properties_device_info),
)
################################################
# Get all the listeners running
print("Listening for command requests and property updates")
globalTHERMOSTAT_1
globalTHERMOSTAT_2
THERMOSTAT_1=Thermostat(thermostat_1_component_name, 10)
THERMOSTAT_2=Thermostat(thermostat_2_component_name, 10)
listeners=asyncio.gather(
execute_command_listener(
device_client, method_name="reboot", user_command_handler=reboot_handler
),
execute_command_listener(
device_client,
thermostat_1_component_name,
method_name="getMaxMinReport",
user_command_handler=max_min_handler,
create_user_response_handler=create_max_min_report_response,
),
execute_command_listener(
device_client,
thermostat_2_component_name,
method_name="getMaxMinReport",
user_command_handler=max_min_handler,
create_user_response_handler=create_max_min_report_response,
),
execute_property_listener(device_client),
)
################################################
# Function to send telemetry every 8 seconds
asyncdefsend_telemetry():
print("Sending telemetry from various components")
whileTrue:
curr_temp_ext=random.randrange(10, 50)
THERMOSTAT_1.record(curr_temp_ext)
temperature_msg1= {"temperature": curr_temp_ext}
awaitsend_telemetry_from_temp_controller(
device_client, temperature_msg1, thermostat_1_component_name
)
curr_temp_int=random.randrange(10, 50) # Current temperature in Celsius
THERMOSTAT_2.record(curr_temp_int)
temperature_msg2= {"temperature": curr_temp_int}
awaitsend_telemetry_from_temp_controller(
device_client, temperature_msg2, thermostat_2_component_name
)
workingset_msg3= {"workingSet": random.randrange(1, 100)}
awaitsend_telemetry_from_temp_controller(device_client, workingset_msg3)
send_telemetry_task=asyncio.ensure_future(send_telemetry())
# Run the stdin listener in the event loop
loop=asyncio.get_running_loop()
user_finished=loop.run_in_executor(None, stdin_listener)
# # Wait for user to indicate they are done listening for method calls
awaituser_finished
ifnotlisteners.done():
listeners.set_result("DONE")
ifnotproperty_updates.done():
property_updates.set_result("DONE")
listeners.cancel()
property_updates.cancel()
send_telemetry_task.cancel()
# Finally, shut down the client
awaitdevice_client.shutdown()
#####################################################
# EXECUTE MAIN
if__name__=="__main__":
asyncio.run(main())