Skip to content

Commit

Permalink
feat(client): Add helper function for constructing a bit string
Browse files Browse the repository at this point in the history
  • Loading branch information
adam-nielsen committed Feb 27, 2019
1 parent c52c5d4 commit a3c6f48
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
38 changes: 38 additions & 0 deletions lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -1189,5 +1189,43 @@ class Client extends EventEmitter {
close() {
this._transport.close();
}

/**
* Helper function to take an array of enums and produce a bitstring suitable
* for inclusion as a property.
*
* @example
* [bacnet.enum.PropertyIdentifier.PROTOCOL_OBJECT_TYPES_SUPPORTED]: [
* {value: bacnet.createBitstring([
* bacnet.enum.ObjectTypesSupported.ANALOG_INPUT,
* bacnet.enum.ObjectTypesSupported.ANALOG_OUTPUT,
* ]),
* type: bacnet.enum.ApplicationTags.BIT_STRING},
* ],
*/
static createBitstring(items) {
let offset = 0;
let bytes = [];
let bitsUsed = 0;
while (items.length) {
// Find any values between offset and offset+8, for the next byte
let value = 0;
items = items.filter(i => {
if (i >= offset + 8) return true; // leave for future iteration
value |= 1 << (i - offset);
bitsUsed = Math.max(bitsUsed, i);
return false; // remove from list
});
bytes.push(value);
offset += 8;
}
bitsUsed++;

return {
value: bytes,
bitsUsed: bitsUsed,
};
}

}
module.exports = Client;
38 changes: 38 additions & 0 deletions test/unit/client.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
'use strict';

const expect = require('chai').expect;
const utils = require('./utils');
const baEnum = require('../../lib/enum');
const client = require('../../lib/client');

describe('bacstack - client', () => {
it('should successfuly encode a bitstring > 32 bits', () => {
const result = client.createBitstring([
baEnum.ServicesSupported.CONFIRMED_COV_NOTIFICATION,
baEnum.ServicesSupported.READ_PROPERTY,
baEnum.ServicesSupported.WHO_IS,
]);
expect(result).to.deep.equal({
value: [2, 16, 0, 0, 4],
bitsUsed: 35,
});
});
it('should successfuly encode a bitstring < 8 bits', () => {
const result = client.createBitstring([
baEnum.ServicesSupported.GET_ALARM_SUMMARY,
]);
expect(result).to.deep.equal({
value: [8],
bitsUsed: 4,
});
});
it('should successfuly encode a bitstring of only one bit', () => {
const result = client.createBitstring([
baEnum.ServicesSupported.ACKNOWLEDGE_ALARM,
]);
expect(result).to.deep.equal({
value: [1],
bitsUsed: 1,
});
});
});

0 comments on commit a3c6f48

Please sign in to comment.