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?

4
  • 1
    I doubt you receive the data in that format. Curly quotes are invalid there. Also in your code... Commented Sep 25, 2019 at 15:10
  • Possible duplicate of Byte array to Hex string conversion in javascript Commented Sep 25, 2019 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)? Commented Sep 25, 2019 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 } Commented Sep 25, 2019 at 16:01

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.