randdusing/ng-cordova-bluetoothle, parsing ble advertisement ionic - angularjs

using the randdusing bluetoothle plugin for ionic app, need to read the advertisement.
The ble scan returns with Start Scan Success :
{"address":"14::30:c6:60:e8;9f","name":null,"rssi":-50,"advertisement":"AgEGG/9SVgIADSw5YTNlMTQAAAJlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA;=","status":"scanResult"}
query: need to decipher this json data and convert this advertisement data into array containing hex values of advertisement data? The advertisement data seems to be base64 encoded. Please advice.

I made for this purpose a little helper function as shown below. The key is the $cordovaBluetoothLE.encodedStringToBytes as you can see in docs https://github.com/randdusing/ng-cordova-bluetoothle.
var encodedToByteString = function encodedToByteString(input) {
var val = $cordovaBluetoothLE.encodedStringToBytes(input);
var byteStr = "";
for (var i = 0; i < val.length; i++) {
var byte = val[i].toString(16);
if (byte.length == 1) byte = "0" + byte;
byteStr += byte;
}
return byteStr;
};
The same goes for the opposite operation - that is sending data. You first need to get your hex-string into an array of bytes and then encode it via $cordovaBluetoothLE.bytesToEncodedString(value).

Related

Using 'repeated' inside 'repeated' data in Nanopb

How to properly encode data with NanoPB when having several nested 'repeated' fields?
This is my schema:
message Report {
message SensorData {
required uint32 sensorid = 1;
required uint32 sample = 2;
}
message DeviceData {
required uint32 devid = 1;
repeated SensorData sensor_data = 2;
}
required uint32 reportnum = 1;
repeated DeviceData dev_data = 2;
}
I have already made a working version in which SensorData fields are embedded inside DeviceData message based on the server.c example from the NanoPB source. This way I have only one repeated field and everything works fine. However this way I have to repeat the 'devid' field for every sensorid and every 'sample', instead of giving it just one time and then loop through an array of SensorData messages. However I am struggling to encode this with NanoPB, the decoding part is in Python. Can someone give me an example how to properly encode data in this case?
For me the simplest way to do this was by statically defining the size of the array's using a nanopb options file. After that you can access each element just like an array.
report.dev_data[i].devid[j] = 1234;
report.dev_data[i].sensor_data[j] = 9876;

Extracting Array inside a Property in Azure Stream Analytics

I have had no luck so far extracting certain values in a wide format out of a JSON string via a stream analytics job.
The JSON has the following format:
{"devicename":"demo","msgtime":"2018-04-13T11:00:00.0000000Z",
"payload":[{"Sensor":"one","Value":1.817,"Unit":"W"},
{"Sensor":"two","Value":0.481,"Unit":"W"},
{"Sensor":"three","Value":0.153,"Unit":"W"}]}}
I am trying to get it in the following format:
name one two three
demo 1.817 0.481 0.153
… … … …
I tried getting the values with "Cross APPLY GetPropertyValues(input)", but I can't get them in a wide format.
try code like below
SELECT
localInput.devicename,
udf.getValue('one', localInput.payload) as One,
udf.getValue('two', localInput.payload) as Two,
udf.getValue('three', localInput.payload) as Three
FROM localInput;
function main(identifier, arr) {
var result = null;
if (Object.prototype.toString.call(arr) == "[object Array]") {
for (i = 0; i < arr.length; i++) {
if (arr[i].type == identifier) {
result = arr[i].value;
}
}
}
return result;
}

What is a compact way to save a float32array to disk on node.js?

JSON.stringify is obviously not space-efficient. What is the most elegant way to serialize and store a float32array using Node.js?
EDIT: People are closing the question for reasons such as being "opinion based" and "lack of an understanding of the problem". I seriously believe the first one was a missclick. For the second one, maybe this makes it more clear:
var fs = require("fs");
var len = 1000*1000*10;
var big_array = new Float32Array(len);
for (var i=0; i<len; ++i)
big_array[i] = Math.random();
// OBVIOUSLY NOT SPACE EFFICIENT \/
fs.writeFileSync("big_array.json",JSON.stringify(big_array));
It is not space efficient because you are representing numbers as strings, so an 8 bytes float will be using as much as ~20 utf8 chars, which is a waste. The question is: how to store the array in a space-efficient manner?
Finally I managed to write float32array to disk with nodejs and retrieve them on the browser, and I hope it will help you.
Write Float32Array to binary file in NodeJS
var fs = require('fs');
var wstream = fs.createWriteStream('data.dat');
var data = new Float32Array([1.1,2.2,3.3,4.4,5.5]);
//prepare the length of the buffer to 4 bytes per float
var buffer = new Buffer(data.length*4);
for(var i = 0; i < data.length; i++){
//write the float in Little-Endian and move the offset
buffer.writeFloatLE(data[i], i*4);
}
wstream.write(buffer);
wstream.end();
Read the file and convert it to a Float32Array on a Browser
var urlToFloatFile = 'data.dat';
var request = new XMLHttpRequest();
request.open('GET', urlToFloatFile, true);
//specify the response type as arraybuffer
request.responseType = 'arraybuffer';
request.onload = function (msg) {
var yourFloatData = new Float32Array(this.response);
console.log(yourFloatData);
};
request.send();
Thanks to #ben_a_adams from WebGL Dev List GGroup https://groups.google.com/forum/#!topic/webgl-dev-list/EbGUi_iSEx8 for the client side code
I've create a simple test to test roughly how much space a JSON serialization of a float array differs from a binary representation and the results are:
2.000.000 floating point values
7.8MB on a binary file
38.5MB on a JSON file
17.5 on a Gzipped JSON file
There is actually a much simpler version possible
let fs = require('fs')
let data = [150, 180]
fs.writeFileSync('mydata', new Buffer(new Uint32Array(data).buffer))
fs.readFile('mydata', (err, buf) => {
let restoredData = new Uint32Array(buf.buffer, buf.offset, buf.byteLength/4)
console.log(data[1])
console.log(restoredData[1])
});
Easy, clean way to do it:
const float32Array = new Float32Array([.69,.420])
const buffer = Buffer.from(float32Array.buffer)
fs.writeFileSync(filePath, buffer)
const loadedBuffer = fs.readFileSync(filePath)
const newFloat32Array = new Float32Array(loadedBuffer.buffer)
I believe you could use Meteor's EJSON:
http://docs.meteor.com/#ejson
https://npmjs.org/package/meteor-ejson
EJSON is an extension of JSON to support more types. It supports all
JSON-safe types, as well as:
Date (JavaScript Date)
Binary (JavaScript Uint8Array or the result of EJSON.newBinary)
User-defined types (see EJSON.addType. For example, Meteor.Collection.ObjectID is implemented this way.)

put live audio input data into array

Hey I am using GetUserMedia() to capture audio input from user's microphone. Meanwhile I want to put captured values into an array so I can manipulate with them. I am using the following code but the problem is that my array gets filled with value 128 all the time (I print the results in console for now), and I can't find my mistake. Can someone help me find my mistake?
//create a new context for audio input
context = new webkitAudioContext();
var analyser = null;
var dataarray = [];
getLiveInput = function() {
navigator.webkitGetUserMedia({audio: true},onStream,onStreamError);
};
function onStream(stream)
{
var input = context.createMediaStreamSource(stream);
analyser = context.createAnalyser();
var str = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteTimeDomainData(str);
for (var i = 0; i < str.length; i++) {
var value = str[i];
dataarray.push(value);
console.log(dataarray)
}//end for loop
}//end function
function onStreamError(e) {
console.error('Streaming failed: ', e);
};
The values returned from getByteTimeDomainData are 8 bit integers, from 0 to 255. 128, which is half way, basically means "no signal". It is the equivalent of 0 in PCM audio data from -1 to 1.
But ANYWAY - there are a couple problems:
First, you're never connecting the input to the analyser. You need input.connect(analyser) before you call analyser.getByteTimeDomainData().
The second problem isn't with your code so much as it's just an implementation issue.
Basically, the gotStream function only gets called once - and getByteTimeDomainData only returns data for 1024 samples worth of audio (a tiny fraction of a second). The problem is, this all happens so quickly and for such a short period of time after the stream gets created, that there's no real input yet. Try wrapping the analyser.getByteTimeDomainData() call and the loop that follows it in a 1000ms setTimeout and then whistle into your microphone as soon as you give the browser permission to record. You should see some values other than 128.
Here's an example: http://jsbin.com/avasav/5/edit

raw sound byteArray to float Array

I'm trying to convert the byteArray of a Sound Object to an array with floats. The Sound Object plays back fine & at full length, but the float Array i get from it is cut off (but sounds correct), so i must be doing something wrong in the conversion:
var s:Sound = mySound;
s.play(); // plays fine
var bytes:ByteArray = new ByteArray();
bytes.endian = Endian.LITTLE_ENDIAN;
s.extract(bytes, s.bytesTotal, 0);
var leftChannel:Array = new Array();
var rightChannel:Array = new Array();
bytes.position = 0;
while (bytes.bytesAvailable)
{
leftChannel.push(bytes.readFloat());
rightChannel.push(bytes.readFloat());
}
and this is what i get:
The top two channels are the original Sound Object.
The lower two is the float Array Data. I aligned them so you can see that the beginning is cut off and obviously the length is incorrect.
Thanks for any answers...
ok there were two problems:
the mp3 file i was importing was somehow corrupt, that caused the beginning to be cut off
the length i defined to extract was not correct, to find the full sound length use
var numTotalSamples:Number = int(s.length * 44.1); //assuming 44.1kHz sample rate
then:
s.extract(bytes, numTotalSamples, 0);

Resources