From aeaa6901f76490d3dd0614e3ded2e8b8ad3676b1 Mon Sep 17 00:00:00 2001 From: Adam Nielsen Date: Tue, 12 Feb 2019 16:00:08 +1000 Subject: [PATCH] feature(client): Add helper function to convert enum into string --- lib/asn1.js | 4 +++- lib/enum.js | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/lib/asn1.js b/lib/asn1.js index a1c3d286..a1772b4c 100644 --- a/lib/asn1.js +++ b/lib/asn1.js @@ -484,8 +484,10 @@ const bacappEncodeApplicationData = module.exports.bacappEncodeApplicationData = case baEnum.ApplicationTags.READ_ACCESS_SPECIFICATION: encodeReadAccessSpecification(buffer, value.value); break; + case undefined: + throw new Error('Cannot encode a value if the type has not been specified'); default: - throw 'Unknown type'; + throw 'Unknown ApplicationTags type: ' + baEnum.getEnumName(baEnum.ApplicationTags, value.type); } }; diff --git a/lib/enum.js b/lib/enum.js index 842b5702..6846fa1c 100644 --- a/lib/enum.js +++ b/lib/enum.js @@ -1,5 +1,29 @@ 'use strict'; +/** + * Turn an enum into a string suitable for debugging. + * + * @param object group + * Enum group, e.g. bacnet.enum.ConfirmedServiceChoice. + * + * @param Number value + * Enum value, e.g. 1. Note that this *must* be an integer value, so you may + * need to use parseInt(). Non-integer values will result in an exception. + * + * @example + * const s = bacnet.enum.getEnumName( + * bacnet.enum.PropertyIdentifier, + * bacnet.enum.PropertyIdentifier.PRESENT_VALUE + * ); + * console.log(s); // "PRESENT_VALUE(85)" + */ +module.exports.getEnumName = function(group, value) { + if (!Number.isInteger(value)) { + throw new Error('getEnumName() can only be passed an integer value, was given "' + value + '"'); + } + return Object.keys(group).find(key => group[key] === value) + '(' + value + ')'; +} + module.exports.PDU_TYPE_MASK = 0xF0; module.exports.ASN1_MAX_OBJECT = 0x3FF; module.exports.ASN1_INSTANCE_BITS = 22;