device-os icon indicating copy to clipboard operation
device-os copied to clipboard

Encode/decode event data as a Variant

Open sergeuz opened this issue 1 year ago • 0 comments

Note: This PR is targeting typed-publish/sc-129495 for review purposes.

Description

This PR introduces the following changes:

  • Promote the internal Buffer class to a public API.
  • Extend Variant to support Buffer as one of its alternative types.
  • Extend Particle.publish() to support publishing event data as a variant.
  • Extend Particle.subscribe() to support a new callback type that takes event data as a variant.

Buffer is a general purpose class for storing arbitrary data in a dynamically allocated buffer. Note that one implication of supporting it as one of the Variant's alternative types is that it makes it possible to store binary data in a ledger so this PR enables that as well.

When an event is published as a variant, it's serialized as CBOR and the content type of the event message is set accordingly. In the opposite direction, from the server to device, a conversion to CBOR is performed if necessary (see the examples below).

Examples

Sending event data as a variant:

Variant data;
data["a"] = 123;
data["b"] = 456;
Particle.publish("devout", data);

For non-device subscribers, the event data is encoded as a data URI as usual:

particle subscribe devout

{"name":"devout","data":"data:application/cbor;base64,omFhGHthYhkByA==",...}

Receiving event data as a variant:

void eventHandler(const char* name, Variant data) {
    Log.info("Received event: %s", name);
    Log.print(data.toJSON());
    Log.print("\r\n");
}

void setup() {
    Particle.subscribe("devin", eventHandler);
}

When sending an event to the device, the content type of the event data can be arbitrary. On the wire, the data is converted to a CBOR which is then parsed by Device OS as a variant:

particle publish devin abc
particle publish devin 'data:application/json,[1,2,3,"abc"]'
particle publish devin 'data:application/cbor;base64,oWNhYmMYew=='

Device output:

0000368773 [app] INFO: Received event: devin
"abc"
0000377012 [app] INFO: Received event: devin
[1,2,3,"abc"]
0000398583 [app] INFO: Received event: devin
{"abc":123}

sergeuz avatar Aug 26 '24 12:08 sergeuz