Question

G'day peoples,

I'm using MavLink to obtain GPS information. One of the message types is GPS_STATUS which is described by MavLink using a series of uint8_t[20].

If I run the following code:

console.log(' sat prn: ' + message.satellite_prn);
console.log(' sat prn: ' + JSON.stringify(message.satellite_prn));
console.log(' sat prn: ' + JSON.stringify(new Uint8Array(message.satellite_prn)));

I get the following output:

 sat prn: <weird charcaters...>
 sat prn: "\u0002\u0005\n\f\u000f\u0012\u0015\u0019\u001a\u001b\u001d\u001e\u001f\u0000\u0000\u0000\u0000"
 sat prn: {"BYTES_PER_ELEMENT":1,"buffer":{"byteLength":0},"length":0,"byteOffset":0,"byteLength":0}

So obviously it's not working. I need a means to get the int value of each element.

I found this https://developer.mozilla.org/en-US/docs/JavaScript/Typed_arrays?redirectlocale=en-US&redirectslug=JavaScript_typed_arrays

Which made me think I would be able to do the following:

satellite_prn = Array.apply([], new Uint8Array(message.satellite_prn));
satellite_prn.length === 20;
satellite_prn.constructor === Array;

But when I stringify it via JSON it reports [], I presume this is an empty array.

Anyone know how I can do this? I know that the data is an array of 20 unsigned 8 bit integers. I just need to know how to access or parse them.

Note: I'm using node.js, but that shouldn't affect what I'm doing. This is why I'm using console.log, as it's avail in node.js.

Était-ce utile?

La solution

Two issues with your code:

  1. message.satellite_prn is a string not an array
  2. Unit8Array needs to be loaded with .set

To get an array of numbers from message.satellite_prn, do this:

var array = message.satellite_prn.map(function(c) { return c.charCodeAt(0) })

To load an ArrayBuffer, do this:

var buffer = new ArrayBuffer(array.length);
var uint8View = new Uint8Array(buffer);
uint8View.set(array);

Ideally you wouldn't need to go through the string. If you are obtaining the data from an up-to-date implementation of XMLHttpRequest, such as xhr2, you can set:

responseType = "arraybuffer"

Autres conseils

Looks like the problem is my understanding on how to deal with binary data within javascript. I found that I can just do the following to get the data as base 10 via charCodeAt().

The following is the code that allowed me to iterate through the 20 unsigned 8 bit integers and get each value as a decimal:

for(var i = 0, l = message.satellite_prn.length; i < l; i++) {
    console.log(' Satellite ' + i + ', id: ' +
        parseInt(message.satellite_prn.charCodeAt(i), 10)
    );
}

I suspect that there may be a function that allows me to convert the binary data into an array, but for an unknown reason Uint8Array didn't appear to be working for me. However the above does.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top