Skip to content

Commit 2f15fcd

Browse files
authored
Merge pull request #40 from id-studiolab/test
mqtt wrapper capable of handling M4 and pico2w
2 parents 6558f5f + 0acd9e9 commit 2f15fcd

2 files changed

Lines changed: 55 additions & 21 deletions

File tree

Lines changed: 55 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,69 @@
11
import time
2-
import ssl
32
import os
4-
import wifi
5-
import socketpool
6-
73
import adafruit_minimqtt.adafruit_minimqtt as MQTT
84

5+
# --- DYNAMIC HARDWARE DETECTION ---
6+
try:
7+
import wifi
8+
import socketpool
9+
import ssl
10+
HAS_NATIVE_WIFI = True
11+
except ImportError:
12+
# We are on the ItsyBitsy M4 (or similar) without native WiFi/SSL
13+
HAS_NATIVE_WIFI = False
14+
import board
15+
import busio
16+
from digitalio import DigitalInOut
17+
from adafruit_esp32spi import adafruit_esp32spi
18+
import adafruit_esp32spi.adafruit_esp32spi_socket as esp32spi_socket
19+
20+
# Global for the ESP32 interface if using the SPI co-processor
21+
esp32_interface = None
22+
923

1024
def connected(client, userdata, flags, rc):
1125
print("Connected to the mqtt broker.")
1226

13-
1427
def disconnected(client, userdata, rc):
1528
print("Disconnected from the mqtt broker.")
1629

17-
1830
def message(client, topic, m):
1931
print("New message on topic {0}: {1}".format(topic, m))
2032

21-
2233
def _require_env(keys):
2334
missing = [k for k in keys if os.getenv(k) is None]
2435
if missing:
2536
raise RuntimeError("settings.toml is missing required keys: " + ", ".join(missing))
2637

2738

2839
def _connect_wifi():
40+
global esp32_interface
2941
_require_env(["CIRCUITPY_WIFI_SSID", "CIRCUITPY_WIFI_PASSWORD"])
42+
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
43+
password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
3044
print("Connecting to WiFi...")
31-
wifi.radio.connect(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD"))
32-
print("Connected! IP:", wifi.radio.ipv4_address)
45+
46+
if HAS_NATIVE_WIFI:
47+
# --- PICO 2 W SETUP ---
48+
wifi.radio.connect(ssid, password)
49+
print("Connected! IP:", wifi.radio.ipv4_address)
50+
else:
51+
# --- ITSYBITSY M4 + ESP32 SPI SETUP ---
52+
# IMPORTANT: Update these pins to match your actual physical wiring!
53+
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
54+
esp32_cs = DigitalInOut(board.D9)
55+
esp32_ready = DigitalInOut(board.D11)
56+
esp32_reset = DigitalInOut(board.D12)
57+
58+
esp32_interface = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
59+
60+
while not esp32_interface.is_connected:
61+
try:
62+
esp32_interface.connect_AP(ssid, password)
63+
except RuntimeError as e:
64+
print("Could not connect to AP, retrying: ", e)
65+
continue
66+
print("Connected! IP:", esp32_interface.pretty_ip(esp32_interface.ip_address))
3367

3468

3569
def Create_MQTT(
@@ -41,21 +75,23 @@ def Create_MQTT(
4175
_require_env(["MQTT_BROKER"])
4276
_connect_wifi()
4377

44-
pool = socketpool.SocketPool(wifi.radio)
45-
4678
broker = os.getenv("MQTT_BROKER")
4779
port = int(os.getenv("MQTT_PORT", "1883"))
48-
49-
# FIX: use MQTT_USERNAME, not MQTT_CLIENT_ID
5080
username = os.getenv("MQTT_USERNAME") or None
5181
password = os.getenv("MQTT_PASSWORD") or None
52-
5382
use_tls = os.getenv("MQTT_USE_TLS", "false").lower() == "true"
54-
55-
# Use a realistic default for cloud brokers
5683
socket_timeout = float(os.getenv("MQTT_SOCKET_TIMEOUT", "0.11"))
5784

58-
ssl_context = ssl.create_default_context() if use_tls else None
85+
# --- DYNAMIC SOCKET AND SSL SETUP ---
86+
if HAS_NATIVE_WIFI:
87+
pool = socketpool.SocketPool(wifi.radio)
88+
ssl_context = ssl.create_default_context() if use_tls else None
89+
is_ssl = False # Native networking relies on ssl_context
90+
else:
91+
esp32spi_socket.set_interface(esp32_interface)
92+
pool = esp32spi_socket
93+
ssl_context = None # ESP32 handles TLS internally, no context needed
94+
is_ssl = use_tls # Tell MiniMQTT to instruct the ESP32 to use TLS
5995

6096
mqtt_client = MQTT.MQTT(
6197
client_id=client_id,
@@ -65,6 +101,7 @@ def Create_MQTT(
65101
password=password,
66102
socket_pool=pool,
67103
ssl_context=ssl_context,
104+
is_ssl=is_ssl, # Required for ESP32 SPI co-processors
68105
socket_timeout=socket_timeout,
69106
)
70107

@@ -74,10 +111,7 @@ def Create_MQTT(
74111

75112
print(f"Connecting to mqtt broker {broker}:{port} (TLS={use_tls})")
76113
mqtt_client.connect()
77-
78-
#mqtt_client.publish("debug/presence", "online")
79-
#mqtt_client.subscribe("debug/presence")
80114

81115
# Return a loop timeout that satisfies MiniMQTT: loop_timeout > socket_timeout
82116
loop_timeout = max(0.050, socket_timeout + 0.01)
83-
return mqtt_client, loop_timeout
117+
return mqtt_client, loop_timeout
567 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)