I’m trying to simulate the MQTT service for a switch. The MQTT client connects to HA, but the
switch is not switched or no message is returned that the switch has been switched.
The log does not see any messages, even if it is set to homeassistant.components.mqtt: debug
.
What can I do ?
Testcase:
### MQTT Broker #########################
mqtt:
broker: !secret mqtt_broker
port: !secret mqtt_port
client_id: ha-system-1
keepalive: 60
username: !secret mqtt_username
password: !secret mqtt_password
protocol: 3.1
### SWITCH ############################
- platform: mqtt
name: "Sonoff power"
state_topic: "stat/switch/POWER"
command_topic: "cmnd/stat/switch/POWER"
qos: 1
payload_on: "ON"
payload_off: "OFF"
retain: true
Javascript
## SIMULATE SWITCH SCRIPT ###########
'use strict';
// call: node mqttswitchtest.js
const mqtt = require('mqtt');
const moment = require('moment');
const broker = 'mqtt://hassbian.local';
const options = {
port: 1883,
username: '******',
password: '******'
};
// MQTT Client
const client = mqtt.connect(broker,options);
const device = 'stat/switch';
let state = 'OFF';
let timer;
client.on('connect', function () {
console.log(`${moment().format("YYYY-MM-DD HH:mm:ss")} Client connected to ${broker}`);
client.subscribe(`stat/${device}/+`);
client.subscribe(`tele/${device}/+`);
client.publish(`cmnd/${device}/status`);
timer = setInterval(loop, 2000);
});
client.on('message', function (topic, message) {
if (topic === `stat/${device}/POWER`) {
state = message.toString();
}
console.log(`${moment().format("YYYY-MM-DD HH:mm:ss")} RX ${topic} ${message}`);
});
function loop() {
if (!client.connected) {
return timer && clearInterval(timer);
}
let newState = state === 'OFF' ? 'ON' : 'OFF';
client.publish(`cmnd/${device}/POWER`, newState);
console.log(`${moment().format("YYYY-MM-DD HH:mm:ss")} TX cmnd/${device}/POWER ${newState}`);
}