Skip to content

Instantly share code, notes, and snippets.

@rom1504
Created March 12, 2017 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rom1504/5b12318a66cc4723085151593e00d1d3 to your computer and use it in GitHub Desktop.
Save rom1504/5b12318a66cc4723085151593e00d1d3 to your computer and use it in GitHub Desktop.
manual code idea
const manuals=[
{
"type":"switch",
"subtypes":[
{
"description": "container including a switch going to u8, u16 or u32",
"encoder":(value,buffer,offset) => {
const {action,result}=value;
offset+=buffer.writeUInt8(action,offset);
switch(action) {
case 0:
offset+=buffer.writeUInt8(result,offset);
break;
case 1:
offset+=buffer.writeUInt16BE(result,offset);
break;
case 2:
offset+=buffer.writeUInt32BE(result,offset);
break;
}
return offset;
},
"decoder":(buffer,offset) => {
const action=buffer.readUInt8(offset);
offset+=1;
let result;
switch(action) {
case 0:
result=buffer.readUInt8(offset);
offset+=1;
break;
case 1:
result=buffer.readUInt16BE(offset);
offset+=2;
break;
case 2:
result=buffer.readUInt32BE(offset);
offset+=4;
break;
}
const value={action,result};
return {value,offset};
},
"type": ["container",
[
{
"name":"action",
"type":"u8"
},
{
"name":"result",
"type":["switch",
{
"compareTo":"action",
"fields":{
"0":"u8",
"1":"u16",
"2":"u32"
}
}
]
}
]
],
"values":[
{
"description":"u8",
"value":{
"action":0,
"result":3
},
"buffer":["0x00","0x03"]
},
{
"description":"u32",
"value":{
"action":2,
"result":4294966272
},
"buffer":["0x02","0xff","0xff","0xfc","0x00"]
}
]
}
]
}
];
function arrayToBuffer(arr)
{
return new Buffer(arr.map(e => parseInt(e)));
}
function transformValues(type,values)
{
return values.map(value => ({
buffer: arrayToBuffer(value.buffer),
value: type.indexOf("buffer") == 0 ? arrayToBuffer(value.value) : value.value,
description: value.description
}));
}
console.log(manuals[0]["subtypes"][0]["decoder"](transformValues(manuals[0]["type"],manuals[0]["subtypes"][0]["values"])[0]["buffer"],0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment