Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: binary data representation when sending data through HTTP & MQTT #690 #725

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES_NEXT_RELEASE
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
- Remove: RPM stuff (no longer used)
- Fix: binary data representation when sending data through HTTP & MQTT #690
7 changes: 6 additions & 1 deletion lib/bindings/HTTPBinding.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,9 @@ function parseData(req, res, next) {
next(error);
} else {
req.jsonPayload = data;

if (req.body !== undefined || req.body === Object || Buffer.isBuffer(req.body)) {
data = data.toString('hex');
}
config.getLogger().debug(context, 'Parsed data: [%j]', data);
next();
}
Expand Down Expand Up @@ -290,6 +292,9 @@ function handleIncomingMeasure(req, res, next) {

if (req.attr && req.jsonPayload) {
config.getLogger().debug(context, 'Parsing attr [%s] with value [%s]', req.attr, req.jsonPayload);
if (req.body !== undefined || req.body === Object || Buffer.isBuffer(req.body)) {
req.jsonPayload = req.jsonPayload.toString('hex');
}
const theAttr = [{ name: req.attr, value: req.jsonPayload, type: 'None' }];
attributeArr.push(theAttr);
} else {
Expand Down
7 changes: 6 additions & 1 deletion lib/commonBindings.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,12 @@ function parseMessage(message) {
try {
parsedMessage = JSON.parse(stringMessage);
} catch (e) {
parsedMessage = message.toString('hex');
parsedMessage = stringMessage.replace(/0x|,/g, '');
var arr = [];
for (var i=0; i<parsedMessage.length; i++) {
arr[i] = parsedMessage.charCodeAt(i).toString(16);
}
parsedMessage = arr.join('');
}
config.getLogger().debug(context, 'stringMessage: [%s] parsedMessage: [%s]', stringMessage, parsedMessage);
messageArray = [];
Expand Down
140 changes: 140 additions & 0 deletions test/unit/ngsiv2/MQTT_receive_measures-test3.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of iotagent-json
*
* iotagent-json is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* iotagent-json is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with iotagent-json.
* If not, seehttp://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with::[contacto@tid.es]
*
* Modified by: Daniel Calvo - ATOS Research & Innovation
*/

/* eslint-disable no-unused-vars */

const iotaJson = require('../../../');
const mqtt = require('mqtt');
const config = require('./config-test.js');
const nock = require('nock');
const iotAgentLib = require('iotagent-node-lib');
const async = require('async');

const utils = require('../../utils');
const request = utils.request;
const groupCreation = {
url: 'http://localhost:' + config.iota.server.port + '/iot/services',
method: 'POST',
json: {
services: [
{
resource: '/iot/json',
apikey: 'KL223HHV8732SFL1',
entity_type: 'TheLightType',
trust: '8970A9078A803H3BL98PINEQRW8342HBAMS',
cbHost: 'http://192.168.1.1:1026',
commands: [],
lazy: [],
attributes: [
{
name: 'status',
type: 'Boolean'
}
],
static_attributes: []
}
]
},
headers: {
'fiware-service': 'smartgondor',
'fiware-servicepath': '/gardens'
}
};
let contextBrokerMock;
let contextBrokerUnprovMock;
let mqttClient;

describe('MQTT: Measure reception ', function () {
beforeEach(function (done) {
const provisionOptions = {
url: 'http://localhost:' + config.iota.server.port + '/iot/devices',
method: 'POST',
json: utils.readExampleFile('./test/unit/ngsiv2/deviceProvisioning/provisionDevice1.json'),
headers: {
'fiware-service': 'smartgondor',
'fiware-servicepath': '/gardens'
}
};

nock.cleanAll();

mqttClient = mqtt.connect('mqtt://' + config.mqtt.host, {
keepalive: 0,
connectTimeout: 60 * 60 * 1000
});

// This mock does not check the payload since the aim of the test is not to verify
// device provisioning functionality. Appropriate verification is done in tests under
// provisioning folder of iotagent-node-lib
contextBrokerMock = nock('http://192.168.1.1:1026')
.matchHeader('fiware-service', 'smartgondor')
.matchHeader('fiware-servicepath', '/gardens')
.post('/v2/entities?options=upsert')
.reply(204);

iotaJson.start(config, function () {
request(provisionOptions, function (error, response, body) {
done();
});
});
});

afterEach(function (done) {
nock.cleanAll();
mqttClient.end();

async.series([iotAgentLib.clearAll, iotaJson.stop], done);
});

describe('When a POST single Raw measure arrives for the HTTP binding', function () {
beforeEach(function () {
contextBrokerMock
.matchHeader('fiware-service', 'smartgondor')
.matchHeader('fiware-servicepath', '/gardens')
.patch(
'/v2/entities/Second%20MQTT%20Device/attrs',
utils.readExampleFile('./test/unit/ngsiv2/contextRequests/singleMeasuresRawTypes1.json')
)
.query({ type: 'AnMQTTDevice' })
.reply(204);
});
it('should send its value to the Context Broker', function (done) {
mqttClient.publish('/1234/MQTT_2/attrs/humidity', '0x4D', null, function (error) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
mqttClient.publish('/1234/MQTT_2/attrs/humidity', '0x4D', null, function (error) {
mqttClient.publish('/1234/MQTT_2/attrs/humidity', '0x4D', null, function (error) {

This case is not totally correct. You are not sending binary data through MQTT here. When sending '0x4D', you are sending a string of ascii chars. In that case, the binary representation (in Hex) is made of 4 bytes:

Hex representation

0x30,0x78,0x34,0x44

Binary representation

00110000 01111000 00110100 01000100

So, the expected value persisted in that case should be:

"value": "30783444"

So, the initial part (0x), should not be removed

In order to don't lead to confusion, I suggest to change the test string without including the initial part 0x.
Additionally, the part of the code that removes 0x should be removed

setTimeout(function () {
contextBrokerMock.done();
done();
}, 100);
});
});
it('should return a 200 OK with no error', function (done) {
mqttClient.publish('/1234/MQTT_2/attrs/humidity', '0x4D', null, function (error) {
setTimeout(function () {
contextBrokerMock.done();
done();
}, 100);
});
});
});
});
8 changes: 1 addition & 7 deletions test/unit/ngsiv2/contextRequests/singleMeasuresRawTypes.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
{
"humidity":{
"type": "degrees",
"value": {
"type": "Buffer",
"data": [
51,
50
]
}
"value": "3332"
}
}
6 changes: 6 additions & 0 deletions test/unit/ngsiv2/contextRequests/singleMeasuresRawTypes1.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"humidity":{
"type": "degrees",
"value": "3444"
}
}