Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added json communication example #308

Merged
merged 1 commit into from
Dec 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
55 changes: 55 additions & 0 deletions examples/Script/script_json_communication.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#include <chrono>
#include <iostream>
#include <thread>

// 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<dai::node::XLinkIn>();
xin->setStreamName("in");

auto script = pipeline.create<dai::node::Script>();
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<dai::node::XLinkOut>();
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<dai::Buffer>();
auto changedDict = nlohmann::json::parse(jsonData->getData());
cout << "changedDict: " << changedDict << "\n";

return 0;
}