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