0

I am working on an encoder for LoRaWAN with JavaScript. I receive this field of data:

{“header”: 6,“sunrise”: -30,“sunset”: 30,“lat”: 65.500226,“long”: 24.833547}

And I need to encode in an hex message, my code is:

var header = byteToHex(object.header);
var sunrise =byteToHex(object.sunrise);
var sunset = byteToHex(object.sunset);
var la = parseInt(object.lat100,10);
var lat = swap16(la);
var lo = parseInt(object.long100,10);
var lon = swap16(lo);
var message={};
if (object.header === 6){
    message = (lon)|(lat<<8);
    bytes = message;
}
return hexToBytes(bytes.toString(16));

Functions byteToHex / swap16 defined as:

function byteToHex(byte) {
    var unsignedByte = byte & 0xff;
    if (unsignedByte < 16) {
        return ‘0’ + unsignedByte.toString(16);
    } else {
        return unsignedByte.toString(16);
    }
}

function swap16(val) {
    return ((val & 0xFF) << 8) | ((val >> 8) & 0xFF);
}

Testing it with return message = lon produces B3 09 in hex. Testing it with message = lon | lat <<8 return 96 BB 09 but result I am looking for is 96 19 B3 09 (composing lon + lat ).

Any tips? What I am doing wrong?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
RobMBSos
  • 55
  • 7
  • 1
    I doubt you receive the data in that format. Curly quotes are invalid there. Also in your code... – trincot Sep 25 '19 at 15:10
  • Possible duplicate of [Byte array to Hex string conversion in javascript](https://stackoverflow.com/questions/34309988/byte-array-to-hex-string-conversion-in-javascript) – VirxEC Sep 25 '19 at 15:10
  • Since `lon` and `lat` are 16 bit numbers, you will lose information with `(lon)|(lat<<8)`. Did you mean `lon|(lat<<16)`? – trincot Sep 25 '19 at 15:13
  • @trincot copied from backend and it modified my response; fields are { "header": 6, "sunrise": -30, "sunset": 30, "lat": 65.500226, "long": 24.833547 } – RobMBSos Sep 25 '19 at 16:01

1 Answers1

0

I solved this problem using this code:

    var long = object.long;
    var lat = object.lat;
    lat = parseInt(lat*100,10);
    var la = swap16(lat);
    la = la.toString(16);
    long = parseInt(long*100,10);
    var lon = swap16(long);
    lon = lon.toString(16);
    var header = object.header;
    var result= la;
    result+= lon;
    result= result.toString(16);
    bytes = hexToBytes(result);
  }
  }
  return bytes;

Now response is:

// encoded payload:
96 19 B3 09
RobMBSos
  • 55
  • 7