That certainly does work. You can create a global char array that's bigger than any name you will ever use, but you will only write the number of bytes (plus 1 for the terminating 0) that actually are in your name if you do it this way,
char deviceName[50];
const int nameLoc = 24;
void setup() {
// Particle.subscribe("spark/device/name", handler);
Serial.begin();
// Particle.publish("spark/device/name");
EEPROM.get(nameLoc, deviceName);
Serial.printlnf("deviceName is: %s", deviceName);
for (int i=nameLoc; i<nameLoc + 50; i++) {
Serial.printf("%d ", EEPROM.read(i));
}
Serial.printlnf("deviceName from get is: %s", EEPROM.get(nameLoc, deviceName));
}
void loop() {}
void handler(const char *topic, const char *data) { // to get the Hardware name of the Photon
int len = strlen(data) +1 ;
strncpy(deviceName, data, len);
EEPROM.put(nameLoc, deviceName);
}
So, this was run once with the publish and subscribe lines un-commentd. When I comment them out, and run again, I get this from the print statements:
deviceName is: Knut
75, 110, 117, 116, 0, 255, 255, 255, ... 255
deviceName from get is: knut
As you can see, the EEPROM.put only wrote the 4 letters of the name plus the terminating 0.
You should only call Particle.subscribe once, so putting it in loop() is not a good idea, and there's no need for it. You can call it in setup() even if you're not connected to the cloud. From the docs:
Particle.subscribe() returns a bool indicating success. It is ok to register a subscription when the device is not connected to the cloud - the subscription is automatically registered with the cloud next time the device connects.