Last active
July 18, 2017 09:50
-
-
Save noerw/96712a854f496ee8dd8386fde526fe93 to your computer and use it in GitHub Desktop.
TTN payload function for lora-serialization -> openSenseMap.org JSON profile
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) { | |
'use strict'; | |
let boxes = []; | |
// maps LoRa ports to openSenseMap configurations | |
// should contain | |
// [ | |
// TEMPSENSOR_ID, | |
// HUMISENSOR_ID | |
// ] | |
boxes[1] = [ | |
tempsensor_id, | |
humisensor_id, | |
]; | |
boxes[2] = [ | |
tempsensor_id, | |
humisensor_id, | |
]; | |
boxes[3] = [ | |
tempsensor_id, | |
humisensor_id, | |
]; | |
boxes[4] = [ | |
tempsensor_id, | |
humisensor_id, | |
]; | |
let bytesToInt = function (bytes) { | |
let i = 0; | |
for (let x = 0; x < bytes.length; x++) { | |
i = i | +(bytes[x] << (x * 8)); | |
} | |
return i; | |
}; | |
var uint16 = function (bytes) { | |
if (bytes.length !== uint16.BYTES) { | |
throw new Error('int must have exactly 2 bytes'); | |
} | |
return bytesToInt(bytes); | |
}; | |
uint16.BYTES = 2; | |
var humidity = function (bytes) { | |
if (bytes.length !== humidity.BYTES) { | |
throw new Error('Humidity must have exactly 2 bytes'); | |
} | |
let h = bytesToInt(bytes); | |
return h / 1e2; | |
}; | |
humidity.BYTES = 2; | |
let decode = function (bytes, mask, names) { | |
let 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 || []; | |
let offset = 0; | |
return mask | |
.map(function (decodeFn) { | |
let current = bytes.slice(offset, offset = offset + decodeFn.BYTES); | |
return decodeFn(current); | |
}) | |
.reduce(function (prev, cur, idx) { | |
prev[names[idx] || idx] = cur; | |
return prev; | |
}, {}); | |
}; | |
let bytesToSenseBoxJson = function (bytes) { | |
let json; | |
try { | |
json = decode(bytes, | |
[ | |
uint16, | |
humidity | |
], | |
boxes[port] | |
); | |
//temp | |
json[boxes[port][0]] = parseFloat(((json[boxes[port][0]] / 771) - 18).toFixed(1)); | |
//hum | |
json[boxes[port][1]] = parseFloat(json[boxes[port][1]].toFixed(1)); | |
} catch (e) { | |
json = { payload: bytes }; | |
} | |
return json; | |
}; | |
return bytesToSenseBoxJson(bytes); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment