diff --git a/src/hex_util.js b/src/hex_util.js new file mode 100644 index 0000000..fd48fe0 --- /dev/null +++ b/src/hex_util.js @@ -0,0 +1,11 @@ +class HexUtil { + + static bytesToHex(bytes) { + return Array.from(bytes).map((byte) => { + return byte.toString(16).padStart(2, "0"); + }).join(""); + } + +} + +export default HexUtil; diff --git a/src/index.js b/src/index.js index af95004..03f8c40 100644 --- a/src/index.js +++ b/src/index.js @@ -9,6 +9,7 @@ import Advert from "./advert.js"; import Packet from "./packet.js"; import BufferUtils from "./buffer_utils.js"; import CayenneLpp from "./cayenne_lpp.js"; +import MeshCorePath from "./meshore_path.js"; export { Connection, @@ -22,4 +23,5 @@ export { Packet, BufferUtils, CayenneLpp, + MeshCorePath, }; diff --git a/src/meshore_path.js b/src/meshore_path.js new file mode 100644 index 0000000..5b47794 --- /dev/null +++ b/src/meshore_path.js @@ -0,0 +1,47 @@ +import BufferReader from "./buffer_reader.js"; +import HexUtil from "./hex_util.js"; +import Packet from "./packet.js"; + +class MeshCorePath { + + constructor(pathHashSize, pathHashCount, pathItems) { + this.pathHashSize = pathHashSize; + this.pathHashCount = pathHashCount; + this.pathItems = pathItems; + } + + static fromPathAndLength(path, pathLen) { + + // make sure path is valid + if(pathLen === 0xFF){ + return null; + } + + const pathHashSize = Packet.extractPathHashSize(pathLen); + const pathHashCount = Packet.extractPathHashCount(pathLen); + const pathByteLength = pathHashCount * pathHashSize; + const pathBytes = path.subarray(0, pathByteLength); + if(pathBytes.length < pathByteLength){ + return null; + } + + // convert path to comma delimited hex string + const pathItems = []; + const pathBuffer = new BufferReader(pathBytes); + for(var i = 0; i < pathHashCount; i++){ + pathItems.push(pathBuffer.readBytes(pathHashSize)); + } + + return new MeshCorePath(pathHashSize, pathHashCount, pathItems); + + } + + toHexPathString() { + return this.pathItems.map((pathItem) => { + return HexUtil.bytesToHex(pathItem); + }).join(","); + } + +} + +export default MeshCorePath;