MsgPackParser.ino 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2019
  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 capacity of the memory pool in bytes.
  15. // Don't forget to change this value to match your JSON document.
  16. // Use arduinojson.org/v6/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. // Using a char[], as shown here, enables the "zero-copy" mode. This mode uses
  25. // the minimal amount of memory because the JsonDocument stores pointers to
  26. // the input buffer.
  27. // If you use another type of input, ArduinoJson must copy the strings from
  28. // the input to the JsonDocument, so you need to increase the capacity of the
  29. // JsonDocument.
  30. uint8_t input[] = {131, 166, 115, 101, 110, 115, 111, 114, 163, 103, 112, 115,
  31. 164, 116, 105, 109, 101, 206, 80, 147, 50, 248, 164, 100,
  32. 97, 116, 97, 146, 203, 64, 72, 96, 199, 58, 188, 148,
  33. 112, 203, 64, 2, 106, 146, 230, 33, 49, 169};
  34. // This MessagePack document contains:
  35. // {
  36. // "sensor": "gps",
  37. // "time": 1351824120,
  38. // "data": [48.75608, 2.302038]
  39. // }
  40. DeserializationError error = deserializeMsgPack(doc, input);
  41. // Test if parsing succeeded.
  42. if (error) {
  43. Serial.print("deserializeMsgPack() failed: ");
  44. Serial.println(error.c_str());
  45. return;
  46. }
  47. // Fetch values.
  48. //
  49. // Most of the time, you can rely on the implicit casts.
  50. // In other case, you can do doc["time"].as<long>();
  51. const char* sensor = doc["sensor"];
  52. long time = doc["time"];
  53. double latitude = doc["data"][0];
  54. double longitude = doc["data"][1];
  55. // Print values.
  56. Serial.println(sensor);
  57. Serial.println(time);
  58. Serial.println(latitude, 6);
  59. Serial.println(longitude, 6);
  60. }
  61. void loop() {
  62. // not used in this example
  63. }
  64. // Visit https://arduinojson.org/v6/example/msgpack-parser/ for more.