uhppoted
Version:
NodeJS module wrapper for the interface to UHPPOTE TCP/IP Wiegand Access Controllers
142 lines (123 loc) • 4.26 kB
JavaScript
/**
* Encodes and decodes binary UHPPOTE controller messages.
*
* @module codec
* @private
*/
const opcodes = require('./opcodes.js')
const errors = require('./errors.js')
const encoder = require('./encoder.js')
const decoder = require('./decoder.js')
const { Buffer } = require('node:buffer')
/**
* 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
*/
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 errors.InvalidFunctionCode(code)
},
/**
* Decodes a 64 byte received message into the corresponding object.
*
* @param {buffer} buffer 64 byte NodeJS buffer
*
* @param {object} Decoded object (or null)
*/
decode: function (buffer) {
// NOTE: v6.62 firmware sends events with SOM code 0x19
// Ref. https://github.com/uhppoted/node-red-contrib-uhppoted/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)
}
return null
},
}