MsgPackParser.ino 2.1 KB

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