got mqtt and wifi connection working reliably

This commit is contained in:
2026-03-27 16:33:49 +01:00
parent 5f49a5c1fe
commit 12873bae43
7 changed files with 139 additions and 30 deletions

View File

@@ -10,6 +10,8 @@
#include <cstdio>
#include <cstring>
static dhcp_server_t dhcp_server{};
void ap_init() {
cyw43_arch_enable_ap_mode("SensorAP", "passwort123", CYW43_AUTH_WPA2_AES_PSK);
@@ -18,7 +20,7 @@ void ap_init() {
IP4_ADDR(&gw, 192, 168, 4, 1);
IP4_ADDR(&mask, 255, 255, 255, 0);
static dhcp_server_t dhcp_server{};
dhcp_server_deinit(&dhcp_server);
dhcp_server_init(&dhcp_server, &gw, &mask);
}
@@ -39,12 +41,14 @@ int connect_to_wifi() {
cyw43_arch_poll();
sleep_ms(100);
}
dhcp_server_deinit(&dhcp_server);
cyw43_arch_disable_ap_mode();
cyw43_arch_disable_sta_mode();
sleep_ms(500);
cyw43_arch_enable_sta_mode();
ret = cyw43_arch_wifi_connect_timeout_ms(saved_ssid, saved_password,
CYW43_AUTH_WPA2_MIXED_PSK, 10000);
CYW43_AUTH_WPA2_MIXED_PSK, 30000);
if (ret == 0) {
return 0;
}
@@ -73,6 +77,7 @@ int connect_to_mqtt() {
info.client_user = saved_mqtt_user;
info.client_pass = saved_mqtt_password;
mqtt_status = -1;
mqtt_client_connect(client, &broker_ip, saved_mqtt_port, mqtt_cb,
&mqtt_status, &info);
while (mqtt_status == -1) {
@@ -82,9 +87,33 @@ int connect_to_mqtt() {
return mqtt_status;
}
BME280_READING_INTERVALS_MS convert_Interval(int interval) {
if (interval < 1 && interval > 0) {
return INTERVAL_0_5MS;
} else if (interval < 20 && interval > 1) {
return INTERVAL_10MS;
} else if (interval < 30 && interval > 10) {
return INTERVAL_20MS;
} else if (interval < 125 && interval > 20) {
return INTERVAL_62_5MS;
} else if (interval < 250 && interval > 62.5) {
return INTERVAL_125MS;
} else if (interval < 500 && interval > 125) {
return INTERVAL_250MS;
} else if (interval < 1000 && interval > 250) {
return INTERVAL_500MS;
} else if (interval > 1000) {
return INTERVAL_1000MS;
} else {
return INTERVAL_500MS;
}
}
int main() {
int mqtt_ret{-1};
int wifi_status{1};
int bme_status{-1};
bme280_handle_t handle{};
stdio_init_all();
sleep_ms(3000);
cyw43_arch_init();
@@ -92,7 +121,10 @@ int main() {
while (wifi_status != 0) {
wifi_status = (connect_to_wifi() == 0) ? 0 : 1;
printf("Wifi status: %d\n", wifi_status);
}
printf("Connected to wifi!\n");
printf("IP: %s\n", ip4addr_ntoa(netif_ip4_addr(netif_default)));
while (true) {
while (saved_mqtt_address[0] == '\0') {
@@ -100,10 +132,23 @@ int main() {
sleep_ms(200);
}
mqtt_ret = connect_to_mqtt();
if (mqtt_ret) {
if (!mqtt_ret) {
printf("Connected to mqtt!\n");
break;
} else {
printf("Mqtt Status: %d\n", mqtt_ret);
reset_mqtt_config();
}
}
bme_status =
bme280_init(&handle, 0x76, convert_Interval(saved_measure_frequency));
if (!bme_status) {
while (true) {
bme280_read_data(handle);
printf("Messwerte: %s\n", bme280_get_json(handle));
// publish_mqtt();
cyw43_arch_poll();
sleep_ms(500);
}
}
}