Last active
February 22, 2018 12:31
-
-
Save felixerdy/362d4f4ee6b13c99f4635e7d6aec4d5f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Decoder(bytes, port) { | |
var result = decode(bytes, [latLng, temperature, temperature], ['latLng', 'alt', 'hdop']) | |
return { | |
latitude: result.latLng[0], | |
longitude: result.latLng[1], | |
altitude: result.alt, | |
hdop: result.hdop | |
} | |
} | |
var bytesToInt = function(bytes) { | |
var i = 0; | |
for (var x = 0; x < bytes.length; x++) { | |
i |= +(bytes[x] << (x * 8)); | |
} | |
return i; | |
}; | |
var latLng = function(bytes) { | |
if (bytes.length !== latLng.BYTES) { | |
throw new Error('Lat/Long must have exactly 8 bytes'); | |
} | |
var lat = bytesToInt(bytes.slice(0, latLng.BYTES / 2)); | |
var lng = bytesToInt(bytes.slice(latLng.BYTES / 2, latLng.BYTES)); | |
return [lat / 1e6, lng / 1e6]; | |
}; | |
latLng.BYTES = 8; | |
var temperature = function(bytes) { | |
if (bytes.length !== temperature.BYTES) { | |
throw new Error('Temperature must have exactly 2 bytes'); | |
} | |
var isNegative = bytes[0] & 0x80; | |
var b = ('00000000' + Number(bytes[0]).toString(2)).slice(-8) | |
+ ('00000000' + Number(bytes[1]).toString(2)).slice(-8); | |
if (isNegative) { | |
var arr = b.split('').map(function(x) { return !Number(x); }); | |
for (var i = arr.length - 1; i > 0; i--) { | |
arr[i] = !arr[i]; | |
if (arr[i]) { | |
break; | |
} | |
} | |
b = arr.map(Number).join(''); | |
} | |
var t = parseInt(b, 2); | |
if (isNegative) { | |
t = -t; | |
} | |
return t / 1e2; | |
}; | |
temperature.BYTES = 2; | |
var decode = function(bytes, mask, names) { | |
var maskLength = mask.reduce(function(prev, cur) { | |
return prev + cur.BYTES; | |
}, 0); | |
if (bytes.length < maskLength) { | |
throw new Error('Mask length is ' + maskLength + ' whereas input is ' + bytes.length); | |
} | |
names = names || []; | |
var offset = 0; | |
return mask | |
.map(function(decodeFn) { | |
var current = bytes.slice(offset, offset += decodeFn.BYTES); | |
return decodeFn(current); | |
}) | |
.reduce(function(prev, cur, idx) { | |
prev[names[idx] || idx] = cur; | |
return prev; | |
}, {}); | |
}; | |
if (typeof module === 'object' && typeof module.exports !== 'undefined') { | |
module.exports = { | |
temperature: temperature, | |
latLng: latLng, | |
decode: decode | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment