Make ArduinoJSON Array globally available

1k Views Asked by At

I am wrapping my head around this problem quite a long time now. I am opening a websocket Connection from my ESP32 to my NodeJS Backend. When receiving a message, the content gets parsed with ArduinoJSON.

I store the parsed content in global Variables so I can access them in my void loop(). Everytime a new message comes in they are overwritten. Thats how it should be.

The Variable Declaration:

uint8_t  brightness = 10;
uint8_t lastMillis = 0;
int ArrayPointer = 0;
int interval = 2000;
bool immediate = true;
const size_t capacity = JSON_ARRAY_SIZE(32) + JSON_OBJECT_SIZE(1) + 290;

After the void Setup()

void onMessageCallback(WebsocketsMessage message) {
    Serial.print("Got Message: ");
    DynamicJsonBuffer jsonBuffer(capacity);
    JsonObject & JSONResponse = jsonBuffer.parseObject(message);
    JsonArray & PixelArray = JSONResponse["frame"];
    brightness = JSONResponse["brightness"];
    ArrayPointer = 0;
    immediate = true;
}

void loop() {
  client.poll();


  if(millis() - lastMillis >= interval || immediate == true) {
    // Here I would like to access the Variable PixelArray
    lastMillis = millis();
  }
}

Of course I cant access PixelArray in the void loop because its a different scope. Now i Need a way to make PixelArray globally accessible.

What I tried:

  • Declared a global JsonArray before void Setup() but this threw an error ;(.
  • Assigning it to another (global) array didnt work properly because the size of the PixelArray varies.

Hopefully somebody can help me ;)

Thanks in advance ;)

PS: Currently I am using ArduinoJson 5 but an upgrade would be no problem.

1

There are 1 best solutions below

3
On BEST ANSWER

Don't do it that way.

You should use ArduinoJson just to serialize and deserialize JSON objects, not to store program state. Its documentation makes that very clear.

The correct way to do this (the way that the ArduinoJSON package is designed to be used) is to maintain an internal data structure and serialize and deserialize your JSON objects to it.

So you'd have a global variable that would be your internal representation of PixelArray and then copy values from the JsonArray to it when you receive a JSON message. You're using brightness correctly here; you should do the same thing with PixelArray.