11import time
22from adafruit_esp32spi import adafruit_esp32spi_wifimanager
33import adafruit_esp32spi .adafruit_esp32spi_socket as socket
4- from adafruit_minimqtt import MQTT
4+ import adafruit_minimqtt as MQTT
55import adafruit_pyportal
66
77pyportal = adafruit_pyportal .PyPortal ()
8-
8+
99### WiFi ###
10-
10+
1111# Get wifi details and more from a secrets.py file
1212try :
1313 from secrets import secrets
1414except ImportError :
1515 print ("WiFi secrets are kept in secrets.py, please add them there!" )
1616 raise
1717
18- wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(pyportal._esp,
18+ # pylint: disable=protected-access
19+ wifi = adafruit_esp32spi_wifimanager .ESPSPI_WiFiManager (pyportal ._esp ,
1920 secrets , None )
20-
21+
2122# ------------- MQTT Topic Setup ------------- #
2223mqtt_topic = 'test/topic'
23-
24+
2425### Code ###
2526# Define callback methods which are called when events occur
2627# pylint: disable=unused-argument, redefined-outer-name
@@ -29,43 +30,47 @@ def connected(client, userdata, flags, rc):
2930 # successfully to the broker.
3031 print ('Subscribing to %s' % (mqtt_topic ))
3132 client .subscribe (mqtt_topic )
32-
33+
3334def disconnected (client , userdata , rc ):
3435 # This method is called when the client is disconnected
3536 print ('Disconnected from MQTT Broker!' )
36-
37+
3738def message (client , topic , message ):
3839 """Method callled when a client's subscribed feed has a new
3940 value.
4041 :param str topic: The topic of the feed with a new value.
4142 :param str message: The new value
4243 """
4344 print ('New message on topic {0}: {1}' .format (topic , message ))
44-
45+
4546# Connect to WiFi
47+ print ("Connecting to WiFi..." )
4648wifi .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+
4855# 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+
5661# Setup the callback methods above
5762mqtt_client .on_connect = connected
5863mqtt_client .on_disconnect = disconnected
5964mqtt_client .on_message = message
60-
65+
6166# Connect the client to the MQTT broker.
6267mqtt_client .connect ()
63-
68+
6469photocell_val = 0
6570while True :
6671 # Poll the message queue
6772 mqtt_client .loop ()
68-
73+
6974 # Send a new message
7075 print ('Sending photocell value: %d' % photocell_val )
7176 mqtt_client .publish (mqtt_topic , photocell_val )
0 commit comments