Particle.variable with an array of hex values

Hi!,
i need to share a variable from a Photon device through the cloud in order to get it from a node.js server and store it in a DB. The variable is defined as an array of hex values: char sample_data2 [] = {0x00, 0x00, 0x01, 0x00, …} … how could i share it with Particle.variable()?
thanks

Here’s some code that translates an array of bytes into a sequence of hex digits in a string. This will work up to about 310 or so bytes of data, based on the limit of the string size for a particle variable.

#include "Particle.h"

void updateHexData(const byte *data, size_t dataLength); // forward declaration

const byte testData[] = {0x00, 0x00, 0x01, 0x00, 0xff, 0x65, 0x66, 0x67, 0x31, 0x32};


String sensorData;

void setup() {
	// Register the variable once in setup
	Particle.variable("sensordata", sensorData);

	// This just updates the data once. Normally, you'd periodically call this when you
	// read the sensor. Updating this changes the data locally so when it's requested,
	// fresh data is returned. It's OK to call this frequently as it doesn't cause
	// data to be pushed to the cloud.
	updateHexData(testData, sizeof(testData));
}

void loop() {

}

void updateHexData(const byte *data, size_t dataLength) {
	// Reserve buffer space so we only need to do one memory allocation when appending to sensorData
	// Note that Particle.variable has a limit of 622 bytes, so the maximum dataLength is 310 or so bytes.
	sensorData.reserve(dataLength * 2 + 1);

	// This is where we store the one byte of hex data (two bytes of ASCII 0-9 and a-f).
	char hexBuf[4];

	// Convert the input data to hex
	for(size_t ii = 0; ii < dataLength; ii++) {
		snprintf(hexBuf, sizeof(hexBuf), "%02x", data[ii]);
		if (ii == 0) {
			sensorData = hexBuf;
		}
		else {
			sensorData += hexBuf;
		}
	}
}

And here’s what the value looks like in the variable

$ particle get test4 sensorData
00000100ff6566673132
3 Likes

Thanks @rickkas7! … i will try that way.
best regards

The reason I selected hex format is that you mentioned using node.js, and it’s really easy to convert from a hex string into a node Buffer object, which will allow you to access the underlying binary data easily.

var buf = new Buffer(hexVariableString, "hex")