MsgPackParser.ino 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2018
  3. // MIT License
  4. //
  5. // This example shows how to deserialize a MessagePack document with
  6. // ArduinoJson.
  7. #include <ArduinoJson.h>
  8. void setup() {
  9. // Initialize serial port
  10. Serial.begin(9600);
  11. while (!Serial) continue;
  12. // Allocate the JSON document
  13. //
  14. // Inside the brackets, 200 is the size of the memory pool in bytes.
  15. // Don't forget to change this value to match your JSON document.
  16. // Use arduinojson.org/assistant to compute the capacity.
  17. StaticJsonDocument<200> doc;
  18. // StaticJsonObject allocates memory on the stack, it can be
  19. // replaced by DynamicJsonObject which allocates in the heap.
  20. //
  21. // DynamicJsonObject doc(200);
  22. // MessagePack input string.
  23. //
  24. // It's better to use a char[] as shown here.
  25. // If you use a const char* or a String, ArduinoJson will
  26. // have to make a copy of the input in the JsonBuffer.
  27. uint8_t input[] = {131, 166, 115, 101, 110, 115, 111, 114, 163, 103, 112, 115,
  28. 164, 116, 105, 109, 101, 206, 80, 147, 50, 248, 164, 100,
  29. 97, 116, 97, 146, 203, 64, 72, 96, 199, 58, 188, 148,
  30. 112, 203, 64, 2, 106, 146, 230, 33, 49, 169};
  31. // This MessagePack document contains:
  32. // {
  33. // "sensor": "gps",
  34. // "time": 1351824120,
  35. // "data": [48.75608, 2.302038]
  36. // }
  37. // doc of the object tree.
  38. //
  39. // It's a reference to the JsonObject, the actual bytes are inside the
  40. // JsonBuffer with all the other nodes of the object tree.
  41. // Memory is freed when jsonBuffer goes out of scope.
  42. DeserializationError error = deserializeMsgPack(doc, input);
  43. // Test if parsing succeeds.
  44. if (error) {
  45. Serial.print("deserializeMsgPack() failed: ");
  46. Serial.println(error.c_str());
  47. return;
  48. }
  49. // Get the root object in the document
  50. JsonObject root = doc.as<JsonObject>();
  51. // Fetch values.
  52. //
  53. // Most of the time, you can rely on the implicit casts.
  54. // In other case, you can do root["time"].as<long>();
  55. const char* sensor = root["sensor"];
  56. long time = root["time"];
  57. double latitude = root["data"][0];
  58. double longitude = root["data"][1];
  59. // Print values.
  60. Serial.println(sensor);
  61. Serial.println(time);
  62. Serial.println(latitude, 6);
  63. Serial.println(longitude, 6);
  64. }
  65. void loop() {
  66. // not used in this example
  67. }
  68. // Visit https://arduinojson.org/v6/example/msgpack-parser/ for more.