Multiple Particle.subscribes strange behavior

So I’ve got 2 publish events that i’m trying to get the response from. With a single Particle.subscribe(), I can catch one of the 2 published responses, without a problem. They both work, as long as I only use 1. As soon as I try and use 2 Particle.subscribes, things get weird. It seems to run both handler events for whichever comes back last.

Here is the relevant code:

void setup() {
    currentTask = 1;
    Particle.publish("getEvent",(String)currentTask,PRIVATE);
    Particle.publish("getLog1",(String)1,PRIVATE);
    
    Particle.subscribe("log1", myHandler, MY_DEVICES);
    Particle.subscribe("getEvent", myHandler, MY_DEVICES);
}

void myHandler(const char *event, const char *data) {
    if(strstr(event, "getEvent")){
        eventName = (char*)data;
    }else if(strstr(event, "log1")){
        strLog1 = (char*)data;
    }
}

The result is that both eventName AND strLog1 get set to whichever response comes back last.
What can I do to make them only run their respective code?

i’d have named this better, but i really just don’t know what to.

Your "log1" handler won’t trigger for "getLog1" - subscribe filters for the prefix not a suffix and they are case sensitiv log1 is not Log1

BTW, you’d usually subscribe before publishing the event.
Also since you are only “copying” the pointer (which will always point to the same static buffer) but don’t copy the actual string content the effect you are seeing is to be expected - try strncpy(eventName, data, sizeof(eventName)-1) and strncpy(strLog1, data, sizeof(strLog1)-1) instead :wink:
(assuming you have declared them as char eventName[len] and strLog1[len] and not String)

1 Like

I thought the log1 bit would get mentioned. I changed the Response Topic in my integration to log1, so it does actually work. (I was just trying out some things, and never removed it.)

The particular code you supplied only half works for me as is, but gets me in the right direction (The length of strLog1 isn’t defined). Thanks!

edit: I hadn’t realized the full scope of what subscribe did. I’ve got it listening for webhooks, but added the response topics. not realizing it would subscribe to both the output event AND the response. I’ve got it all sorted out now though.

Does this mean strLog1 is only a char pointer? If so, you cannot copy data there unless you have allocated memory to hold that data.

When I have to base my suggestions on half the info that’d required to provide a full one :wink:

1 Like