uci-base/examples/ha-mqtt.js

42 lines
1.4 KiB
JavaScript

///***************** HOME ASSISTANT ************************
// for use with four in one example
// reformats incoming and outgoing topic/payload from HA from/to a UCI json packet
// import this function then call it binding your instance of uci/base
// passing the name of the mqtt socket which will be getting packets from HA
// NOTE: using @uci/ha one can communicate with HA directly not via mqtt
const STATUS_TOPIC = 'fio/switch/status'
export default function register(socketname) {
this.beforeProcessHook(async (packet) => {
console.log('incoming mqtt packet to modify')
console.dir(packet)
let modified = Object.assign({},packet)
let cmd = packet.cmd.split('/')
modified.cmd = `${cmd[1]}/${packet.data.toLowerCase()}`
modified.id = cmd[3]
delete modified.data
console.log('translated to uci packet')
console.dir(modified)
return modified
// return packet
},
{name:socketname})
// will cover push sends which is how HA will know state changed
this.beforeSendHook(async (packet) => {
console.log('beforeSendHook', packet)
if (packet.cmd === 'switch/status') {
packet.cmd = `${STATUS_TOPIC}/${packet.id}`
packet.payload = packet.state
console.log('=============modified packet sent to broker================')
console.dir(packet)
console.log('================')
}
return packet
},
{name:socketname})
}