Skip to content

Commit a3c6f48

Browse files
committed
feat(client): Add helper function for constructing a bit string
1 parent c52c5d4 commit a3c6f48

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

lib/client.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1189,5 +1189,43 @@ class Client extends EventEmitter {
11891189
close() {
11901190
this._transport.close();
11911191
}
1192+
1193+
/**
1194+
* Helper function to take an array of enums and produce a bitstring suitable
1195+
* for inclusion as a property.
1196+
*
1197+
* @example
1198+
* [bacnet.enum.PropertyIdentifier.PROTOCOL_OBJECT_TYPES_SUPPORTED]: [
1199+
* {value: bacnet.createBitstring([
1200+
* bacnet.enum.ObjectTypesSupported.ANALOG_INPUT,
1201+
* bacnet.enum.ObjectTypesSupported.ANALOG_OUTPUT,
1202+
* ]),
1203+
* type: bacnet.enum.ApplicationTags.BIT_STRING},
1204+
* ],
1205+
*/
1206+
static createBitstring(items) {
1207+
let offset = 0;
1208+
let bytes = [];
1209+
let bitsUsed = 0;
1210+
while (items.length) {
1211+
// Find any values between offset and offset+8, for the next byte
1212+
let value = 0;
1213+
items = items.filter(i => {
1214+
if (i >= offset + 8) return true; // leave for future iteration
1215+
value |= 1 << (i - offset);
1216+
bitsUsed = Math.max(bitsUsed, i);
1217+
return false; // remove from list
1218+
});
1219+
bytes.push(value);
1220+
offset += 8;
1221+
}
1222+
bitsUsed++;
1223+
1224+
return {
1225+
value: bytes,
1226+
bitsUsed: bitsUsed,
1227+
};
1228+
}
1229+
11921230
}
11931231
module.exports = Client;

test/unit/client.spec.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'use strict';
2+
3+
const expect = require('chai').expect;
4+
const utils = require('./utils');
5+
const baEnum = require('../../lib/enum');
6+
const client = require('../../lib/client');
7+
8+
describe('bacstack - client', () => {
9+
it('should successfuly encode a bitstring > 32 bits', () => {
10+
const result = client.createBitstring([
11+
baEnum.ServicesSupported.CONFIRMED_COV_NOTIFICATION,
12+
baEnum.ServicesSupported.READ_PROPERTY,
13+
baEnum.ServicesSupported.WHO_IS,
14+
]);
15+
expect(result).to.deep.equal({
16+
value: [2, 16, 0, 0, 4],
17+
bitsUsed: 35,
18+
});
19+
});
20+
it('should successfuly encode a bitstring < 8 bits', () => {
21+
const result = client.createBitstring([
22+
baEnum.ServicesSupported.GET_ALARM_SUMMARY,
23+
]);
24+
expect(result).to.deep.equal({
25+
value: [8],
26+
bitsUsed: 4,
27+
});
28+
});
29+
it('should successfuly encode a bitstring of only one bit', () => {
30+
const result = client.createBitstring([
31+
baEnum.ServicesSupported.ACKNOWLEDGE_ALARM,
32+
]);
33+
expect(result).to.deep.equal({
34+
value: [1],
35+
bitsUsed: 1,
36+
});
37+
});
38+
});

0 commit comments

Comments
 (0)