Skip to content

Commit

Permalink
Merge pull request #308 from luxonis/json_comm_example
Browse files Browse the repository at this point in the history
Added json communication example
  • Loading branch information
Erol444 committed Dec 26, 2021
2 parents 62e9f8c + e666817 commit 29e2a54
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
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;
}

0 comments on commit 29e2a54

Please sign in to comment.