-
Notifications
You must be signed in to change notification settings - Fork 0
/
aws_iot_shadow.py
135 lines (119 loc) · 4.55 KB
/
aws_iot_shadow.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
'''
Guy Shiff - 308577469
Nadav Lotan - 312346406
'''
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
import logging
import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import Adafruit_DHT
import argparse
import json
# Change according to your configuration
host = 'a1rpddawph4ysg-ats.iot.eu-west-1.amazonaws.com'
rootCA = './root-CA.crt'
privateKey = './56075c5af2-private.pem.key'
cert = './56075c5af2-certificate.pem.crt'
thingName = 'Guy_nadav-Voldemort'
deviceId = thingName
telemetry = None
topic = thingName + '/Potentiometer'
interval = 1
CLK = 18
MISO = 23
MOSI = 24
CS = 25
mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
# 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 interval
# payload is a JSON string ready to be parsed using json.loads(...)
# in both Py2.x and Py3.x
payloadDict = json.loads(payload)
if 'delta' in payloadDict['state']:
newpayload = {
'state': payloadDict['state']['delta']
}
customShadowCallback_Delta(json.dumps(newpayload), None, None)
return
print("++++++++GET++++++++++")
if 'interval' in payloadDict['state']['desired']:
interval = int(payloadDict['state']['desired']['interval'])
def customShadowCallback_Delta(payload, responseStatus, token):
global interval
# payload is a JSON string ready to be parsed using json.loads(...)
# in both Py2.x and Py3.x
payloadDict = json.loads(payload)
print("++++++++DELTA++++++++++")
print(payloadDict)
print("++++++++DELTA++++++++++")
if 'interval' in payloadDict['state']:
interval = int(payloadDict['state']['interval'])
newPayload = '{"state":{"reported":' + json.dumps(payloadDict['state']) + '}}'
print("++++++++NEW_REPORTED++++++++++")
print(newPayload)
print("++++++++NEW_REPORTED++++++++++")
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 = 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:
potentiometer = mcp.read_adc(0)
payload = {
'Potentiometer': potentiometer,
}
print(topic)
print(json.dumps(payload))
myMQTTClient.publish(topic,json.dumps(payload),1)
time.sleep(interval)