This repository has been archived by the owner on Jul 25, 2024. It is now read-only.
forked from Azure-Samples/azure-iot-samples-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdevice.py
130 lines (104 loc) · 4.41 KB
/
device.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
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
import AWSIoTPythonSDK.MQTTLib as AWSIoTPyMQTT
import logging
import time
import json
import sys
device_id = sys.argv[1]
host = "a3mfkf3z93nqt8.iot.us-west-2.amazonaws.com"
rootCAPath = "certs/root-CA.crt"
certificatePath = "certs/team55device%s.cert.pem" % device_id
privateKeyPath = "certs/team55device%s.private.key" % device_id
clientId = "team55"
thingName = "team55device%s" % device_id
# logging
logger = logging.getLogger("AWSIoTPythonSDK.core")
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)
# the client
myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
myAWSIoTMQTTClient.configureEndpoint(host, 8883)
myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec
# Init AWSIoTMQTTShadowClient
myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883)
myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
# AWSIoTMQTTShadowClient configuration
myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10) # 10 sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) # 5 sec
myAWSIoTMQTTShadowClient.connect()
N = 1000000
deviceState = {}
def median_counts(device_seq, median):
print("median_counts", device_seq, median)
with open('vibrations-m%d.txt' % (int(device_seq) - 1), 'r') as f:
low, high, eq = 0, 0, 0
for line in f.readlines():
if not line.startswith('vibration'):
n = int(line)
if n < median:
low += 1
if n > median:
high += 1
if n == median:
eq += 1
return low, eq, high
def do_median(median):
low, eq, high = median_counts(device_id, median)
message = {"msg": "counts", "median": median, "counts": [low, eq, high], "state": deviceState}
messageJson = json.dumps({'message': message, 'device': device_id})
print(topic, messageJson)
myAWSIoTMQTTClient.publish(topic, messageJson, 1)
def customShadowCallback_Delta(payload, responseStatus, token):
# payload is a JSON string ready to be parsed using json.loads(...)
# in both Py2.x and Py3.x
print(responseStatus)
try:
payloadDict = json.loads(payload)
print("++++++++DELTA++++++++++")
print("state: " + str(payloadDict["state"]))
print("version: " + str(payloadDict["version"]))
print("+++++++++++++++++++++++\n\n")
deviceState.update(payloadDict["state"]["delta"])
print(deviceState)
if "median" in deviceState:
do_median(int(deviceState["median"]))
except Exception as e:
print(str(e))
def customShadowCallback_Get(payload, responseStatus, token):
# payload is a JSON string ready to be parsed using json.loads(...)
# in both Py2.x and Py3.x
print(payload)
print(responseStatus)
print("++++++++GET++++++++++")
try:
payloadDict = json.loads(payload)
print("state: " + str(payloadDict["state"]))
print("version: " + str(payloadDict["version"]))
print("+++++++++++++++++++++++\n\n")
deviceState.update(payloadDict["state"]["delta"])
if "median" in deviceState:
do_median(int(deviceState["median"]))
except Exception as e:
print(str(e))
# Create a deviceShadow with persistent subscription
deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(thingName, True)
# Listen on deltas
# deviceShadowHandler.shadowRegisterDeltaCallback(customShadowCallback_Delta)
deviceShadowHandler.shadowGet(customShadowCallback_Get, 5)
myAWSIoTMQTTClient.connect()
topic = "sdk/test/team55"
loopCount = 0
# Loop forever to react to device state delta requests
while True:
time.sleep(5)