AutoConnectJsonDefs.h 2.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
 * Wrapping definition to ensure version compatibility of ArduinoJson.
 * @file AutoConnectJsonDefs.h
 * @author hieromon@gmail.com
 * @version  1.0.0
 * @date 2019-04-25
 * @copyright  MIT license.
 */

#ifndef _AUTOCONNECTJSONDEFS_H_
#define _AUTOCONNECTJSONDEFS_H_

#include <ArduinoJson.h>

/**
 * Make the Json types and functions consistent with the ArduinoJson
 * version. These declarations share the following type definitions:
 * - Difference between reference and proxy of JsonObject and JsonArray.
 * - Difference of check whether the parsing succeeded or not.
 * - The print function name difference.
 * - The buffer class difference.
 * - When PSRAM present, enables the buffer allocation it with ESP32 and
 *   supported version.
 */
#if ARDUINOJSON_VERSION_MAJOR<=5
#define ArduinoJsonStaticBuffer           StaticJsonBuffer
#define ARDUINOJSON_CREATEOBJECT(doc)     doc.createObject()
#define ARDUINOJSON_CREATEARRAY(doc)      doc.createArray()
#define ARDUINOJSON_PRETTYPRINT(doc, out) ({ size_t s = doc.prettyPrintTo(out); s; })
#define ARDUINOJSON_PRINT(doc, out)       ({ size_t s = doc.printTo(out); s; })
using ArduinoJsonObject = JsonObject&;
using ArduinoJsonArray = JsonArray&;
using ArduinoJsonBuffer = DynamicJsonBuffer;
#define AUTOCONNECT_JSONBUFFER_PRIMITIVE_SIZE AUTOCONNECT_JSONBUFFER_SIZE
#else
#define ArduinoJsonStaticBuffer           StaticJsonDocument
#define ARDUINOJSON_CREATEOBJECT(doc)     doc.to<JsonObject>()
#define ARDUINOJSON_CREATEARRAY(doc)      doc.to<JsonArray>()
#define ARDUINOJSON_PRETTYPRINT(doc, out) ({ size_t s = serializeJsonPretty(doc, out); s; })
#define ARDUINOJSON_PRINT(doc, out)       ({ size_t s = serializeJson(doc, out); s; })
using ArduinoJsonObject = JsonObject;
using ArduinoJsonArray = JsonArray;
#if defined(BOARD_HAS_PSRAM) && ((ARDUINOJSON_VERSION_MAJOR==6 && ARDUINOJSON_VERSION_MINOR>=10) || ARDUINOJSON_VERSION_MAJOR>6)
// JsonDocument is assigned to PSRAM by ArduinoJson's custom allocator.
struct SpiRamAllocatorST {
  void* allocate(size_t size) {
    uint32_t  caps;
    if (psramFound())
      caps = MALLOC_CAP_SPIRAM;
    else {
      caps = MALLOC_CAP_8BIT;
      AC_DBG("PSRAM not found, JSON buffer allocates to the heap.\n");
    } 
    return heap_caps_malloc(size, caps);
  }
  void  deallocate(void* pointer) {
    heap_caps_free(pointer);
  }
};
#define AUTOCONNECT_JSONBUFFER_PRIMITIVE_SIZE AUTOCONNECT_JSONPSRAM_SIZE
using ArduinoJsonBuffer = BasicJsonDocument<SpiRamAllocatorST>;
#else
#define AUTOCONNECT_JSONBUFFER_PRIMITIVE_SIZE AUTOCONNECT_JSONDOCUMENT_SIZE
using ArduinoJsonBuffer = DynamicJsonDocument;
#endif
#endif

#endif // _AUTOCONNECTJSONDEFS_H_