Particle.variable & JSON

I’m still learning what are the best practices for good code but can someone tell me if this is a good approach or not. I currently have multiple variables returning a single value and I want combine them to a JSON format and just have one Particle.variable that would return all the data.
Sample code below is.

String Data;
char buf[256];

int a 
int b 

void setup()
{
  Particle.variable("JSON", Data);
}


void loop()
{  

JSONBufferWriter writer(buf, sizeof(buf));
writer.beginObject();
    writer.name("a").value(A);
    writer.name("b").value(B);
writer.endObject();
writer.buffer()[std::min(writer.bufferSize(), writer.dataSize())] = 0;

 Data = buf;
 
 }
 
 
 int enableAlerts(String command)
{

    if (command.equalsIgnoreCase("1"))
    {
        A = 1;
     
        EEPROM.put(setAlertEEPROMLocation, A);

        return 1;
    }
    else
    {

        A = 0;
       
        EEPROM.put(setAlertEEPROMLocation, A);

        return 0;
    }
}


int enablePhonePowerAlerts(String command)
{

    if (command.equalsIgnoreCase("1"))
    {
        B = 1;
   
        EEPROM.put(setAlertPhonePowerEEPROMLocation, B);

        return 1;
    }
    else
    {

        B = 0;
       
        EEPROM.put(setAlertPhonePowerEEPROMLocation, B);

        return 0;
    }
}

I don’t think you need your String Data variable, you can just use bufas the base variable for your Particle.variable().

You are also using variables A & B but you only seem to have a & b defined. C/C++ is case sensitive.

While your use of JSONBufferWriter() seems OK, I’d find it overkill for only a variable list that short.
Alternatively you could it do in a one-liner like this

  snprintf(buf, sizeof(buf), " \"a\":%d, \"b\":%d ", a, b);

You’d also only need to update buf when a or b actually have changed.

Thanks @ScruffR

Yes, that was a typo.

I do have more variables that are in the JSON return. I included just two as a example but I’ll see how snprintf works too.

Is it ok to place the JSONBufferWriter code in the loop section or could that be a concern? A or b values do currently update anytime there is a change

You can use JSONBufferWriter inside loop() but as for this

Even in that case you wouldn't need to update the JSON on each iteration of loop() but you could add a "dirty" flag that is set whenever one of the "monitored" variable gets changed and then update the JSON depending on that flag.

Cool. That makes sense. Thanks again!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.