Skip to content

Commit b79e782

Browse files
author
Luca Barbetti
authored
Merge pull request #73 from ilcato/multi-value-properties
Multi value properties decode management
2 parents b5e70ed + 6613ce6 commit b79e782

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

src/index.js

+28-6
Original file line numberDiff line numberDiff line change
@@ -121,29 +121,51 @@ const connect = options => new Promise((resolve, reject) => {
121121
}
122122

123123
const propertyValue = CBOR.decode(buf);
124+
const propertyNameId = 0;
125+
const attributeNameId = 1;
126+
127+
let valueToSend = {};
128+
let propertyNameKeyPrevious = '';
124129
propertyValue.forEach((p) => {
125130
// Support cbor labels
126-
const propertyNameKey = p.n !== undefined ? p.n : p['0'];
131+
let propertyNameKey = p.n !== undefined ? p.n : p['0'];
132+
const propertyNameKeySplit = propertyNameKey.split(':');
133+
127134
const valueKey = p.v !== undefined ? 'v' : '2';
128135
const valueStringKey = p.vs !== undefined ? 'vs' : '3';
129136
const valueBooleanKey = p.vb !== undefined ? 'vb' : '4';
137+
let value;
138+
propertyNameKey = propertyNameKeySplit[propertyNameId];
130139
if (propertyCallback[msg.topic][propertyNameKey]) {
131-
let value = null;
132-
133140
if (!(p[valueKey] === undefined)) {
134141
value = p[valueKey];
135142
} else if (!(p[valueStringKey] === undefined)) {
136143
value = p[valueStringKey];
137144
} else if (!(p[valueBooleanKey] === undefined)) {
138145
value = p[valueBooleanKey];
139146
}
140-
141-
propertyCallback[msg.topic][propertyNameKey](value);
147+
}
148+
if (propertyNameKeyPrevious === '') {
149+
propertyNameKeyPrevious = propertyNameKeySplit[propertyNameId];
150+
}
151+
if (propertyNameKeyPrevious !== propertyNameKey) {
152+
propertyCallback[msg.topic][propertyNameKeyPrevious](valueToSend);
153+
propertyNameKeyPrevious = propertyNameKey;
154+
valueToSend = {};
155+
}
156+
if (propertyNameKeySplit.length === 1) {
157+
valueToSend = value;
158+
} else {
159+
const attributeName = propertyNameKeySplit[attributeNameId];
160+
valueToSend[attributeName] = value;
142161
}
143162
});
163+
if (valueToSend !== {}) {
164+
propertyCallback[msg.topic][propertyNameKeyPrevious](valueToSend);
165+
}
144166
}
145167
};
146-
168+
147169
client.onConnected = (reconnect) => {
148170
if (reconnect === true) {
149171
// This is a re-connection: re-subscribe to all topics subscribed before the

0 commit comments

Comments
 (0)