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. //
  8. // https://arduinojson.org/v6/example/msgpack-parser/
  9. #include <ArduinoJson.h>
  10. void setup() {
  11. // Initialize serial port
  12. Serial.begin(9600);
  13. while (!Serial) continue;
  14. // Allocate the JSON document
  15. //
  16. // Inside the brackets, 200 is the capacity of the memory pool in bytes.
  17. // Don't forget to change this value to match your JSON document.
  18. // Use arduinojson.org/v6/assistant to compute the capacity.
  19. StaticJsonDocument<200> doc;
  20. // StaticJsonObject allocates memory on the stack, it can be
  21. // replaced by DynamicJsonObject which allocates in the heap.
  22. //
  23. // DynamicJsonObject doc(200);
  24. // MessagePack input string.
  25. //
  26. // Using a char[], as shown here, enables the "zero-copy" mode. This mode uses
  27. // the minimal amount of memory because the JsonDocument stores pointers to
  28. // the input buffer.
  29. // If you use another type of input, ArduinoJson must copy the strings from
  30. // the input to the JsonDocument, so you need to increase the capacity of the
  31. // JsonDocument.
  32. uint8_t input[] = {131, 166, 115, 101, 110, 115, 111, 114, 163, 103, 112, 115,
  33. 164, 116, 105, 109, 101, 206, 80, 147, 50, 248, 164, 100,
  34. 97, 116, 97, 146, 203, 64, 72, 96, 199, 58, 188, 148,
  35. 112, 203, 64, 2, 106, 146, 230, 33, 49, 169};
  36. // This MessagePack document contains:
  37. // {
  38. // "sensor": "gps",
  39. // "time": 1351824120,
  40. // "data": [48.75608, 2.302038]
  41. // }
  42. DeserializationError error = deserializeMsgPack(doc, input);
  43. // Test if parsing succeeded.
  44. if (error) {
  45. Serial.print("deserializeMsgPack() failed: ");
  46. Serial.println(error.c_str());
  47. return;
  48. }
  49. // Fetch values.
  50. //
  51. // Most of the time, you can rely on the implicit casts.
  52. // In other case, you can do doc["time"].as<long>();
  53. const char* sensor = doc["sensor"];
  54. long time = doc["time"];
  55. double latitude = doc["data"][0];
  56. double longitude = doc["data"][1];
  57. // Print values.
  58. Serial.println(sensor);
  59. Serial.println(time);
  60. Serial.println(latitude, 6);
  61. Serial.println(longitude, 6);
  62. }
  63. void loop() {
  64. // not used in this example
  65. }