-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMQTTsubscribe.py
61 lines (49 loc) · 1.57 KB
/
MQTTsubscribe.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
# Import SDK packages
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import time
import json
import urllib
import lighting
# Custom MQTT message callback
def customCallback(client, userdata, message):
print("Received a new message: ")
print(message.payload)
js = json.loads(message.payload)
if js['on'] == True:
lighting.lightsOn(js['light'])
print("True")
else:
lighting.lightsOff(js['light'])
print("False")
print("from topic: ")
print(message.topic)
print("--------------\n\n")
while True:
try:
file = urllib.urlopen('http://google.com');
print('Connect');
break;
except:
print('No connect');
time.sleep(3);
# For certificate based connection
myMQTTClient = AWSIoTMQTTClient("RaspberryPi")
# For Websocket connection
# myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True)
# Configurations
# For TLS mutual authentication
myMQTTClient.configureEndpoint("rest end point", 8883)
# For Websocket
# myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)
myMQTTClient.configureCredentials("root crt", "private crt", "certificate")
# For Websocket, we only need to configure the root CA
# myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH")
myMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz
myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec
myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec
myMQTTClient.connect()
myMQTTClient.subscribe("PhilipsLight", 1, customCallback)
print("subscribe successful")
while True:
time.sleep(1)