won't run in a fork.
Yardie- opened this issue · 2 comments
Yardie- commented
Hi I have observed that this code will not run in a fork.
I have a web server that works fine however this library blocks.
below is the modified to show the behaviour
simply uncomment the #define USE_FORK to run the code in a fork on the esp32
#include <WiFi.h>
#include <MQTTPubSubClient.h>
//#define USE_FORK
const char* ssid = "your-ssid";
const char* pass = "your-password";
const char* broker = "public.cloud.shiftr.io";
WiFiClient client;
MQTTPubSubClient mqtt;
void mqtt_loop() {
while(1)
{
mqtt.update(); // should be called
// publish message
static uint32_t prev_ms = millis();
if (millis() > prev_ms + 1000) {
prev_ms = millis();
mqtt.publish("/hello", "world");
}
}
}
void mqtt_setup()
{
Serial.begin(115200);
WiFi.begin(ssid, pass);
Serial.print("connecting to wifi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.println(" connected!");
Serial.print("connecting to host...");
while (!client.connect(broker, 1883)) {
Serial.print(".");
delay(1000);
}
Serial.println(" connected!");
// initialize mqtt client
mqtt.begin(client);
Serial.print("connecting to mqtt broker...");
while (!mqtt.connect("arduino", "public", "public")) {
Serial.print(".");
delay(1000);
}
Serial.println(" connected!");
// subscribe callback which is called when every packet has come
mqtt.subscribe([](const String& topic, const String& payload, const size_t size) {
Serial.println("mqtt received: " + topic + " - " + payload);
});
// subscribe topic and callback which is called when /hello has come
mqtt.subscribe("/hello", [](const String& payload, const size_t size) {
Serial.print("/hello ");
Serial.println(payload);
});
// this should never return either way
mqtt_loop();
}
#ifdef USE_FORK
TaskHandle_t mqtt_forked; // Task handle to keep track of created task. Allows vTaskDelete(sensor_watch);
void fork_mqtt(void * pvParameters )
{
mqtt_setup();
}
void setup() {
uint8_t core = 1;
uint8_t priority = 0;
xTaskCreatePinnedToCore(
fork_mqtt, // Function to implement the task */
"forked mqtt client", // Name of the task
10000, // Stack size in bytes ( vanilla FreeRTOS uses words! https://www.freertos.org/a00125.html )
NULL, // Task input parameter
priority, // Create as a low priority task
&mqtt_forked, // Task handle to keep track of created task.
core); // Core where the task should run
delay(500); // needed to start-up task
}
#else
void setup() {
mqtt_setup();
}
#endif
void loop() {
// only gets here if forked where this runs normally
}
hideakitai commented
@Yardie- Hi, this library does not block the program. delay()
blocks your task. Please set the priority higher than 0.
Yardie- commented
Yep I missed that.
Thanks