-
Notifications
You must be signed in to change notification settings - Fork 0
/
IDC_Shadow_Demo.py
139 lines (124 loc) · 4.77 KB
/
IDC_Shadow_Demo.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
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
import logging
import time
import argparse
import json
from sense_hat import SenseHat
# Change according to your configuration
host = 'a3l4eg6ieh6np6-ats.iot.eu-west-1.amazonaws.com'
rootCA = './root-CA.crt'
privateKey = './Thing.private.key'
cert = './Thing.cert.pem'
thingName = 'Thing'
deviceId = thingName
telemetry = None
topic = 'telemetry/' + thingName
# SendHat configuration
sense = SenseHat()
color = {}
color['yellow'] = (255, 255, 0)
color['red'] = (255, 0, 0)
color['green'] = (0, 255, 0)
# Custom MQTT message callback
def customCallback(client, userdata, message):
print("Received a new message: ")
print(message.payload)
print("from topic: ")
print(message.topic)
print("--------------\n\n")
# Custom Shadow callbacks
def customShadowCallback_Update(payload, responseStatus, token):
# payload is a JSON string ready to be parsed using json.loads(...)
# in both Py2.x and Py3.x
if responseStatus == "timeout":
print("Update request " + token + " time out!")
if responseStatus == "accepted":
payloadDict = json.loads(payload)
print("~~~~~~~~~~~~~~~~~~~~~~~")
print("Update request with token: " + token + " accepted!")
print("property: " + str(payloadDict["state"]))
print("~~~~~~~~~~~~~~~~~~~~~~~\n\n")
if responseStatus == "rejected":
print("Update request " + token + " rejected!")
def customShadowCallback_Get(payload, responseStatus, token):
global telemetry
# payload is a JSON string ready to be parsed using json.loads(...)
# in both Py2.x and Py3.x
payloadDict = json.loads(payload)
print("++++++++GET++++++++++")
reportedColor = str(payloadDict['state']['reported']['color']).lower()
print("reported color: " + reportedColor)
print("version: " + str(payloadDict["version"]))
print("+++++++++++++++++++++++\n\n")
if reportedColor in ['red', 'green', 'yellow']:
sense.clear(color[reportedColor])
else:
sense.clear()
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
payloadDict = json.loads(payload)
print(payloadDict)
print("++++++++DELTA++++++++++")
reportedColor = str(payloadDict['state']['color']).lower()
print("color: " + reportedColor)
print("version: " + str(payloadDict["version"]))
print("+++++++++++++++++++++++\n\n")
if reportedColor in ['red', 'green', 'yellow']:
sense.clear(color[reportedColor])
else:
sense.clear()
newPayload = '{"state":{"reported":' + json.dumps(payloadDict['state']) + '}}'
deviceShadowHandler.shadowUpdate(newPayload, customShadowCallback_Update, 5)
# Configure logging
logger = logging.getLogger("AWSIoTPythonSDK.core")
logger.setLevel(logging.WARNING)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)
# Init AWSIoTMQTTClient
myAWSIoTMQTTShadowClient = None
myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(deviceId)
myAWSIoTMQTTShadowClient.configureEndpoint(host, 8883)
myAWSIoTMQTTShadowClient.configureCredentials(rootCA, privateKey, cert)
# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10) # 10 sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5) # 5 sec
# Connect and subscribe to AWS IoT
myAWSIoTMQTTShadowClient.connect()
# Create a deviceShadow with persistent subscription
deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(
thingName, True)
# Listen on deltas
deviceShadowHandler.shadowRegisterDeltaCallback(customShadowCallback_Delta)
deviceShadowHandler.shadowGet(customShadowCallback_Get,5)
myMQTTClient = myAWSIoTMQTTShadowClient.getMQTTConnection()
# Infinite offline Publish queueing
myMQTTClient.configureOfflinePublishQueueing(-1)
myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz
myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec
myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec
# Loop forever and wait for joystic
# Use the sensehat module
time.sleep(2)
while True:
temp = sense.get_temperature()
humidity = sense.get_humidity()
accel = sense.get_accelerometer()
payload = {
'Temperature': temp,
'Humidity': humidity,
'Accelerometer':
{
'Pitch': accel['pitch'],
'Roll' : accel['roll'],
'Yaw' : accel['yaw']
}
}
print(topic)
print(json.dumps(payload))
myMQTTClient.publish(topic,json.dumps(payload),1)
time.sleep(2)