63 lines
2.3 KiB
JavaScript
63 lines
2.3 KiB
JavaScript
|
|
/**
|
|
* SystaComfort II node implementation
|
|
*
|
|
* @param {*} RED
|
|
*/
|
|
const PARADIGMA_UDP_PORT_DEFAULT = 22460
|
|
const dgram = require('node:dgram')
|
|
const dataParser = require('./dataparser')
|
|
|
|
module.exports = function(RED) {
|
|
|
|
/**
|
|
* Node object function
|
|
* @param {*} config
|
|
*/
|
|
function systaComfort2(config) {
|
|
RED.nodes.createNode(this, config)
|
|
const node = this
|
|
const udpServer = dgram.createSocket('udp4')
|
|
// Handle exceptions on server
|
|
udpServer.on('error', (err) => {
|
|
node.error(`SystaComfort II: Error on udp server connection: ${err.stack}`)
|
|
node.status({ fill: 'red', shape: 'ring', text: 'Error on udp server connection' })
|
|
udpServer.close()
|
|
})
|
|
// Handle messages
|
|
udpServer.on('message', (data, rinfo) => {
|
|
node.log(`Recieved message from ${rinfo.address}:${rinfo.port} at ${new Date().toLocaleString()}`)
|
|
node.status({ fill: 'green', shape: 'dot', text: `Recieved message from ${rinfo.address}:${rinfo.port} at ${new Date().toLocaleString()}` })
|
|
// Create response and send back to client
|
|
let responseData = dataParser.createResponse(data)
|
|
const client = dgram.createSocket('udp4')
|
|
client.send(responseData, rinfo.port, rinfo.address, (err) => {
|
|
client.close()
|
|
})
|
|
// Parse data receieved from systa comfort device
|
|
let msgData = dataParser.parseData(data, config.topicPrefix)
|
|
if ( msgData ) {
|
|
msgData.deviceIP = rinfo.address
|
|
msgData.devicePort = rinfo.port
|
|
node.send(msgData)
|
|
}
|
|
})
|
|
// Handle listen state
|
|
udpServer.on('listening', () => {
|
|
const address = udpServer.address()
|
|
node.status({ fill: 'green', shape: 'dot', text: `Server is listening: ${address.address}:${address.port}` })
|
|
})
|
|
udpServer.bind(config.listenPort || PARADIGMA_UDP_PORT_DEFAULT)
|
|
// Cleanup hooks
|
|
node.on('close', () => {
|
|
if ( udpServer ) {
|
|
udpServer.close()
|
|
}
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Register node object to Node-RED instance
|
|
*/
|
|
RED.nodes.registerType('systacomfort2', systaComfort2)
|
|
} |