1
1
import time
2
2
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
3
3
import adafruit_esp32spi .adafruit_esp32spi_socket as socket
4
- from adafruit_minimqtt import MQTT
4
+ import adafruit_minimqtt as MQTT
5
5
import adafruit_pyportal
6
6
7
7
pyportal = adafruit_pyportal .PyPortal ()
8
-
8
+
9
9
### WiFi ###
10
-
10
+
11
11
# Get wifi details and more from a secrets.py file
12
12
try :
13
13
from secrets import secrets
14
14
except ImportError :
15
15
print ("WiFi secrets are kept in secrets.py, please add them there!" )
16
16
raise
17
17
18
- wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(pyportal._esp,
18
+ # pylint: disable=protected-access
19
+ wifi = adafruit_esp32spi_wifimanager .ESPSPI_WiFiManager (pyportal ._esp ,
19
20
secrets , None )
20
-
21
+
21
22
# ------------- MQTT Topic Setup ------------- #
22
23
mqtt_topic = 'test/topic'
23
-
24
+
24
25
### Code ###
25
26
# Define callback methods which are called when events occur
26
27
# pylint: disable=unused-argument, redefined-outer-name
@@ -29,43 +30,47 @@ def connected(client, userdata, flags, rc):
29
30
# successfully to the broker.
30
31
print ('Subscribing to %s' % (mqtt_topic ))
31
32
client .subscribe (mqtt_topic )
32
-
33
+
33
34
def disconnected (client , userdata , rc ):
34
35
# This method is called when the client is disconnected
35
36
print ('Disconnected from MQTT Broker!' )
36
-
37
+
37
38
def message (client , topic , message ):
38
39
"""Method callled when a client's subscribed feed has a new
39
40
value.
40
41
:param str topic: The topic of the feed with a new value.
41
42
:param str message: The new value
42
43
"""
43
44
print ('New message on topic {0}: {1}' .format (topic , message ))
44
-
45
+
45
46
# Connect to WiFi
47
+ print ("Connecting to WiFi..." )
46
48
wifi .connect ()
47
-
49
+ print ("Connected!" )
50
+
51
+ # Initialize MQTT interface with the esp interface
52
+ # pylint: disable=protected-access
53
+ MQTT .set_socket (socket , pyportal ._esp )
54
+
48
55
# Set up a MiniMQTT Client
49
- mqtt_client = MQTT(socket,
50
- broker=secrets['broker'],
51
- username=secrets['user'],
52
- password=secrets['pass'],
53
- is_ssl=False,
54
- network_manager=wifi)
55
-
56
+ mqtt_client = MQTT .MQTT (broker = secrets ['broker' ],
57
+ username = secrets ['user' ],
58
+ password = secrets ['pass' ],
59
+ is_ssl = False )
60
+
56
61
# Setup the callback methods above
57
62
mqtt_client .on_connect = connected
58
63
mqtt_client .on_disconnect = disconnected
59
64
mqtt_client .on_message = message
60
-
65
+
61
66
# Connect the client to the MQTT broker.
62
67
mqtt_client .connect ()
63
-
68
+
64
69
photocell_val = 0
65
70
while True :
66
71
# Poll the message queue
67
72
mqtt_client .loop ()
68
-
73
+
69
74
# Send a new message
70
75
print ('Sending photocell value: %d' % photocell_val )
71
76
mqtt_client .publish (mqtt_topic , photocell_val )
0 commit comments