Files
dispatcher_ng/src/RelayBox.ts

83 lines
3.5 KiB
TypeScript

import * as logger from './log'
import { mqttHandler } from './MqttDispatcher'
import { AItem } from './AItem'
import { RelayBoxExport, ExportType } from './Export'
export class RelayBoxThing extends AItem {
private itemNames: string[]
private readonly deviceCommandTopic: string
private readonly deviceStatusTopic: string
private readonly stateTopicPre: string
private readonly feedbackTopicPre: string
private readonly conflictTopicPre: string
private status : any
private switchStates : string
private oldSwitchStates : string
constructor(floor: string, room: string, item: string, deviceCommandTopic: string,
deviceStatusTopic: string, itemNames: string[]) {
super(floor, room, item, '')
this.itemNames = itemNames
this.deviceCommandTopic = deviceCommandTopic
this.deviceStatusTopic = deviceStatusTopic
this.stateTopicPre = `${this.topicFirstPart}/state`
this.feedbackTopicPre = `${this.topicFirstPart}/feedback`
this.conflictTopicPre = `${this.topicFirstPart}/conflict`
this.subscribeTopics = [
`${this.deviceStatusTopic}`,
`${this.stateTopicPre}/#`
]
this.oldSwitchStates = ''
}
exportItem() : ExportType|null {
return RelayBoxExport(this.itemId, this.stateTopicPre, this.feedbackTopicPre, this.conflictTopicPre, this.itemNames)
}
processMessage(topic: string, payload: string) {
// logger.info(`RT: ${topic}, ${payload}`)
if (topic == this.deviceStatusTopic) {
// logger.info(`RT: status received`)
this.status = JSON.parse(payload)
let statusParsed = JSON.stringify(this.status)
this.switchStates = JSON.stringify(this.status.data.switchStates)
if (this.switchStates != this.oldSwitchStates) {
this.oldSwitchStates = this.switchStates
logger.info(`RT: status parsed: ${statusParsed}`)
logger.info(`RT: device: ${this.status.metadata.device}`)
logger.info(`RT: uptime: ${this.status.data.uptime}`)
for (let i : number = 0; i < this.itemNames.length; i ++) {
if (this.status.data.switchStates[i].feedbackState == '0') {
mqttHandler.send(`${this.feedbackTopicPre}/${i}`, 'OFF')
} else {
mqttHandler.send(`${this.feedbackTopicPre}/${i}`, 'ON')
}
if (this.status.data.switchStates[i].stateConflict == '0') {
mqttHandler.send(`${this.conflictTopicPre}/${i}`, 'CLEAR')
} else {
mqttHandler.send(`${this.conflictTopicPre}/${i}`, 'CONFLICT')
}
}
}
} else {
logger.info(`RT: ${topic}, ${payload}`)
let thingRelatedPart = topic.substring(this.stateTopicPre.length+1)
let itemIdx = parseInt(thingRelatedPart)
logger.info(`RT: pre: ${this.stateTopicPre}, thingRelatedPart: ${thingRelatedPart}, itemIdx: ${itemIdx}`)
if (itemIdx >= 0 && itemIdx < this.itemNames.length) {
if (payload == 'ON') {
mqttHandler.send(this.deviceCommandTopic, `switch ${itemIdx} on`)
} else {
mqttHandler.send(this.deviceCommandTopic, `switch ${itemIdx} off`)
}
} else {
logger.warn(`RT: no handling available for ${topic}`)
}
}
}
}