Unable to store device name as variable

Could anyone enlighten me as to why the following code result in a blank for the device name? I’ve followed the example in the reference documentation, which worked so the subscribing process works fine. When I save the name as a variable however and publish it, it only returns blanks, i.e.

{ “deviceName”: “” }


EDIT: Oh of course…The particle.publish is neccessary because that’s how it fetches its name.

So it works now?

Yep. Simply adding:


before it works. Apologies for the beginner drama.

Seeing as you placed the subscription in the loop, and not in the setup (where it’s supposed to be):

NOTE 1: A device can register up to 4 event handlers. This means you can call Particle.subscribe() a maximum of 4 times; after that it will return false.

    case PUBLISH: {
	    if (Particle.connected()) {
	        Particle.subscribe("particle/device/name", handler);
	        char data[256];
	        float soc = batteryMonitor.getSoC();
	        snprintf(data, sizeof(data), "{ \"deviceName\": \"%s\", \"soc\": \"%.02f\", \"sta\": \"%s\",  \"latitude\": \"%.04f\",  \"longitude\": \"%.04f\" }", deviceName, soc, sta, latitude, longitude);
	        stateTime = millis();
	        state = CONFIG;

The ‘if’ statement checks if you’re connected, which you then check for again after the subscription. Shouldn’t really be necessary, as far as I’m concerned.
Then you subscribe to the ‘particle’ handler, yet publish under the ‘Spark’ one.
Though the delay could work and return your name in time, it doesn’t have to do so. Try setting a flag in the subscription handler, and checking that before continuing?

Disregarding that, it seems as though you’ve got a bunch of inconsistent brackets/breaks in your switches, which you should probably check and correct, since those are bound to cause troubles.


Interesting. I did in fact try the subscription in void setup() before but it wasn’t working, so thinking it might conflict with all the other subscriptions I moved it to Publish. I will move it back to void setup() again, have a good look at the code again tomorrow, see if I can figure it out. Thanks for the assistance.

Thanks, I’m not really sure where the ‘Spark’ publish came from. I’ve been relying on many tutorials/guides posted here and elsewhere as I don’t have any coding or electronics background, and I assume along the way they changed it from spark to particle (I guess, as it was the first released product if Im not mistaken) so I must picked up on some outdated code.

So again thanks, everything works correctly now.