Skip to content

Commit

Permalink
Merge branch 'Ozzard-fix-#19-combine-tcp-segments'
Browse files Browse the repository at this point in the history
  • Loading branch information
eelcocramer committed Sep 28, 2022
2 parents 0fa03cc + 4fc473b commit b763ac5
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 21 deletions.
61 changes: 41 additions & 20 deletions lib/gpsd.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,30 +31,51 @@ function createServiceSocket(self) {
sock.on('connect', function (socket) {
self.logger.info('Socket connected.');
self.connected = true;
self.partialMessages = [];
self.emit('connected');
});

sock.on("data", function (payload) {
payload = payload.replace(/\}\{/g, '}\n{');
var info = payload.split('\n'), data;

for (var index = 0; index < info.length; index++) {
if (info[index]) {
if (!self.parse) {
self.emit('raw', info[index]);
} else {
try {
data = JSON.parse(info[index]);
self.emit(data.class, data);
} catch (error) {
self.logger.error("Bad message format", info[index], error);
self.emit('error', {
message : "Bad message format",
cause : info[index],
error : error
});

continue;
if (payload[payload.length - 1] === '\n') {
// End of a possible sequence of messages. Squish all the messages together if necessary, then parse.
if (self.partialMessages.length === 0) {
// Short-circuit: there's no prior bytes.
parseOneOrMoreCompleteMessages(payload);
} else {
// There are prior bytes.
self.partialMessages.push(payload);
parseOneOrMoreCompleteMessages(Buffer.concat(self.partialMessages));
self.partialMessages = [];
}
} else {
// Not a complete message. Push the buffer until we know more.
self.partialMessages.push(payload);
}

function parseOneOrMoreCompleteMessages(completeMessages) {
// Payload is a Buffer, and we ideally want to do some string-splitting on it. Convert to string, therefore.
var completeMessagesString = completeMessages.toString('ascii');
var stringPayload = completeMessagesString.replace(/\}\{/g, '}\n{');
var info = stringPayload.split('\n');

for (var index = 0; index < info.length; index++) {
if (info[index]) {
if (!self.parse) {
self.emit('raw', info[index]);
} else {
try {
var data = JSON.parse(info[index]);
self.emit(data.class, data);
} catch (error) {
self.logger.error("Bad message format", info[index], error);
self.emit('error', {
message : "Bad message format",
cause : info[index],
error : error
});

continue;
}
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "node-gpsd",
"description": "Node.js gpsd client for GPS tracking device.",
"version": "0.3.2",
"version": "0.3.3",
"keywords": ["gps", "gpsd", "location", "tracking", "position"],
"repository": {
"type": "git",
Expand Down

0 comments on commit b763ac5

Please sign in to comment.