Copyright © https://mongoose-os.com

Mongoose OS Forum

frame

MQTT.pub does not publish when called from event callback

I am trying to publish messages to Google Cloud IoT Core based on events that are being triggered when the ADC of the ESP32 measures a certain value. When I call MQTT.pub from within a Timer callback the data is published to my Google Cloud IoT registry and I can pull it from my subscription. However, moving the publishData function within the callback of an event cause the data to not being published anymore, although MQTT.pub returns true.

function publishData() {
    let msg = JSON.stringify({
        current: mean,
        timestamp: Timer.now()
    });
    let ok = MQTT.pub(topic, msg, 1);
    if (ok) {
        print('Data published: ', ok ? 'yes' : 'no');
    } else {
        print('Error while publishing data!');
    }
    return ok;
}

Event.addHandler(
    ADC_DONE,
    function(ev, evdata, ud) {
        // feed watchdog timer to avoid reset of the system
        Sys.wdt_feed();
        if (measurementsCounter<nMeasurements) {
            sampleADC();
        } else {
            GPIO.write(ledPin, 0);
            if (isConnected) {
                let ok = publishData();
            }
        }
    },
    null
);

If anyone has an idea what could be wrong with my code or has ever experienced the same issue, I'd be really grateful for your answers.

Sign In or Register to comment.