-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSendCloudToDeviceMessage.py
50 lines (39 loc) · 1.65 KB
/
SendCloudToDeviceMessage.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
import random
import sys
from azure.iot.hub import IoTHubRegistryManager
MESSAGE_COUNT = 2
AVG_WIND_SPEED = 10.0
MSG_TXT = "{\"service client sent a message\": %.2f}"
CONNECTION_STRING = "HostName=IoTBITS.azure-devices.net;SharedAccessKeyName=mypolicy;SharedAccessKey=NsVnJ1UIFfiRiG2XIafklXKrQhb7xJd6HAIoTAvkcYM="
DEVICE_ID = "ROAD1"
def iothub_messaging_sample_run():
try:
# Create IoTHubRegistryManager
registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
for i in range(0, MESSAGE_COUNT):
print ( 'Sending message: {0}'.format(i) )
data = MSG_TXT % (AVG_WIND_SPEED + (random.random() * 4 + 2))
props={}
# optional: assign system properties
props.update(messageId = "message_%d" % i)
props.update(correlationId = "correlation_%d" % i)
props.update(contentType = "application/json")
# optional: assign application properties
prop_text = "PropMsg_%d" % i
props.update(testProperty = prop_text)
registry_manager.send_c2d_message(DEVICE_ID, data, properties=props)
try:
# Try Python 2.xx first
input("Press Enter to continue...\n")
except:
pass
# Use Python 3.xx in the case of exception
input("Press Enter to continue...\n")
except Exception as ex:
print (f"Unexpected error {ex}")
return
except KeyboardInterrupt:
print ( "IoT Hub C2D Messaging service sample stopped" )
if __name__ == '__main__':
print ( "Starting the Python IoT Hub C2D Messaging service sample..." )
iothub_messaging_sample_run()