Determine which device sent an event

It’s great how easy particle allows you to publish an event and subscribe to it from other device. What I would like to do is determine which device sent the event. I could send the Device id in the event data, but I was hoping there is another way as I really don’t enjoy parsing strings in C++. I can’t think that this is a unique requirement. A best practice would be appreciated as well.

Brett

If you read the docs on publish() and subscribe() you will see that it may be easier than you fear.

I am not sure if I understand what you mean. A subscriber get’s two pieces of information from an event, the full event name and and data which may have been sent with it. If I need to know the device which sent the event, I guess the only way is to include that information in the data somehow. Any other suggestions?

how about the event name?

thisDevice publishes like this:

Particle.publish("thisDevice", "thisData", 60, PRIVATE);

otherDevice subscribes like this:

Particle.subscribe("thisDevice", webhookHandler, MY_DEVICES);

right from the docs:

A subscription works like a prefix filter. If you subscribe to "foo", you will receive any event whose name begins with "foo", including "foo", "fool", "foobar", and "food/indian/sweet-curry-beans".

@brettski

another hint:

device 42 published here:

Particle.publish("thisEvent_Device_42", "thisData", 60, PRIVATE);

the other device waits for all thisEvent events:

Particle.subscribe("thisEvent", webhookHandler, MY_DEVICES);

and handles them like this:

void webhookHandler(const char *event, const char *data)
{
  if(strstr(event, "Device_42"))
  {
    // do device 42 stuff
  }
  else if (strstr(event, "Device_43"))
  {
    // do device 43 stuff
  }
}
1 Like

This is an interesting approach, thank you.