Mqtt addon connects but most of the time don't receive or send messages

Hello,

I’m trying to build a tiny HA add-on that’d rely on MQTT to communicate with HA and for example being triggered by some automation sending an MQTT message.

I’ve put it into my addons folder and I’m able to install it directly from HA.

Here are the files I’ve got:

addonds/mqtt-test/config.yaml:

name: "MQTT test"
description: "MQTT basic test"
version: "0.0.0"
slug: "mqtt_test"
arch:
  - aarch64
  - amd64
  - armhf
  - armv7
  - i386
startup: "services"
boot: "auto"

addonds/mqtt-test/Dockerfile:

ARG BUILD_FROM
FROM $BUILD_FROM

ENV LANG C.UTF-8
SHELL ["/bin/bash", "-o", "pipefail", "-c"]

RUN apk add --no-cache \
    nodejs \
    npm \
    git

COPY package.json /
COPY index.js /

RUN cd / && npm install

COPY run.sh /
RUN chmod a+x /run.sh

CMD [ "/run.sh" ]

addonds/mqtt-test/run.sh:

#!/usr/bin/with-contenv bashio

set +u

npm run start

addonds/mqtt-test/package.json:

{
  "name": "mqtt_test",
  "version": "0.0.0",
  "description": "MQTT basic test",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "mqtt": "4.3.6"
  }
}

addonds/mqtt-test/index.js:

const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://core-mosquitto', {
  protocolId: 'MQIsdp',
  protocolVersion: 3,
});

client.on('connect', function () {
  console.log('[debug] Connected');

  client.subscribe('mqtt-test/some-topic', function (err) {
    console.log('[debug] Subscribe...');

    if (!err) {
      console.log('[debug] Subscribed to the topic');
    } else {
      console.log(`[debug] Couldn't subscribe to the topic`, err);
    }

    // setInterval(() => {
    //   client.publish(`mqtt-test/response`,`Emission test`);
    //   console.log('[debug] Publishing...')
    // }, 1000)
  });
});

client.on('message', function (topic, message) {
  console.log('[debug] message received');
  console.log({ topic, message: message.toString() });
});

client.on('error', function (error) {
  console.log('[debug] ERROR: ', error);
});

client.on('offline', function () {
  console.log('[debug] offline');
});

client.on('reconnect', function () {
  console.log('[debug] reconnect');
});

Now, I’ve got this to work a few times. A few times, I’ve received messages in the add-on and I’ve been able to get within HA the mqtt message sent by the add-on by listening to mqtt-test/response. But what is really odd is that most of the time it doesn’t work?

The connection is always successful, but sometimes when I try to send a message so it’d be displayed in the add-on logs, nothing shows up. Same if I listen to mqtt-test/response, nothing happens.

I think I’ve noticed a pattern where if I uncomment the block of code

    // setInterval(() => {
    //   client.publish(`mqtt-test/response`,`Emission test`);
    //   console.log('[debug] Publishing...')
    // }, 1000)

Then I have slightly more chances to have it receiving and emitting messages correctly. But most of the time only the connection is successful and I get no messages.

This project looks quite simple to me and I’ve followed mqtt.js doc from here: https://github.com/mqttjs/MQTT.js#example

So I’m really unsure what isn’t done well.

Can anyone spot what I’m doing wrong? It’s my first time playing with mqtt so I might be missing something obvious.

Thanks a lot for any help.

Regards,

Maxime

Alright so I’ve got a working solution. Pardon the fact that I’m a newbie in HA and MQTT… I was just missing the username and password :see_no_evil:.

That said, I’m pretty sure it’s the first time I’m passing it and that I’ve had it working at least 3 times :man_shrugging: So I was either really not paying attention and used the username/password before or I don’t know what happened…