node-red-contrib-uhppoted
Version:
A set of nodes for the UHPPOTE Wiegand Access Controller
133 lines (121 loc) • 4.53 kB
JavaScript
const { Buffer } = require('node:buffer')
const opcodes = require('../nodes/opcodes.js')
const encoder = require('../nodes/encoder.js')
const decoder = require('../nodes/decoder.js')
/**
* Lookup table that maps op codes to the equivalent encoder function.
*/
const enc = new Map([
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
])
/**
* Lookup table that maps message codes to the equivalent decoder function.
*/
const dec = new Map([
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
])
module.exports = {
/**
* Encodes a request as a 64 byte UDP message.
*
* @param {opcode} code Function opcode, translated into message function byte
* @param {number} deviceId The serial number for the target access controller
* @param {object} object Additional request specific information.
*
* @param {buffer} 64 byte NodeJS Buffer
*
* @exports
*/
encode: function (code, deviceId, object) {
const request = Buffer.alloc(64)
request.writeUInt8(0x17, 0)
if (enc.has(code)) {
const f = enc.get(code)
return f(deviceId, object)
}
throw new Error(`invalid protocol function code ${code}`)
},
/**
* Decodes a 64 byte received message into the corresponding object.
*
* @param {buffer} buffer 64 byte NodeJS buffer
* @param {function} translator (optional) function to internationalise the text in a decoded object
*
* @param {object} Decoded object (or null)
*
* @exports
*/
decode: function (buffer, translator) {
// NOTE: v6.62 firmware sends events with SOM code 0x19
// Ref. https://github.com/uhppoted/uhppoted-lib-node-red/issues/3
if (buffer.length === 64 && (buffer[0] === 0x17 || (buffer[0] === 0x19 && buffer[1] === 0x20)) && dec.has(buffer[1])) {
const f = dec.get(buffer[1])
const bytes = new DataView(buffer.buffer)
return f(bytes, translator)
}
return null
},
}