From e666817a9b95fc5dcb6fc216c0063436706cc64a Mon Sep 17 00:00:00 2001 From: TheMarpe Date: Thu, 23 Dec 2021 02:16:03 +0100 Subject: [PATCH] Added json communication example --- examples/CMakeLists.txt | 1 + examples/Script/script_json_communication.cpp | 55 +++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 examples/Script/script_json_communication.cpp diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index fce516908..f37446415 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -236,6 +236,7 @@ dai_add_example(script_http_client Script/script_http_client.cpp OFF) dai_add_example(script_http_server Script/script_http_server.cpp OFF) dai_add_example(script_mjpeg_server Script/script_mjpeg_server.cpp OFF) dai_add_example(script_nndata_example Script/script_nndata_example.cpp ON) +dai_add_example(script_json_communication Script/script_json_communication.cpp ON) # SpatialDetection dai_add_example(spatial_location_calculator SpatialDetection/spatial_location_calculator.cpp ON) diff --git a/examples/Script/script_json_communication.cpp b/examples/Script/script_json_communication.cpp new file mode 100644 index 000000000..835ba92a4 --- /dev/null +++ b/examples/Script/script_json_communication.cpp @@ -0,0 +1,55 @@ +#include +#include +#include + +// Includes common necessary includes for development using depthai library +#include "depthai/depthai.hpp" + +// Include nlohmann json +#include "nlohmann/json.hpp" + +int main() { + using namespace std; + + dai::Pipeline pipeline; + + auto xin = pipeline.create(); + xin->setStreamName("in"); + + auto script = pipeline.create(); + xin->out.link(script->inputs["in"]); + script->setScript(R"( + import json + # Recieve bytes from the host + data = node.io['in'].get().getData() + jsonStr = str(data, 'utf-8') + dict = json.loads(jsonStr) + # Change initial dictionary a bit + node.warn('Original: ' + str(dict)) + dict['one'] += 1 + dict['foo'] = "baz" + node.warn('Changed: ' + str(dict)) + b = Buffer(30) + b.setData(json.dumps(dict).encode('utf-8')) + node.io['out'].send(b) + )"); + + auto xout = pipeline.create(); + xout->setStreamName("out"); + script->outputs["out"].link(xout->input); + + // Connect to device with pipeline + dai::Device device(pipeline); + + nlohmann::json dict{{"one", 1}, {"foo", "bar"}}; + auto buffer = dai::Buffer(); + auto data = dict.dump(); + buffer.setData({data.begin(), data.end()}); + device.getInputQueue("in")->send(buffer); + + auto jsonData = device.getOutputQueue("out")->get(); + auto changedDict = nlohmann::json::parse(jsonData->getData()); + cout << "changedDict: " << changedDict << "\n"; + + return 0; +}