DepthAI v2 has been superseded by DepthAI v3. You are viewing legacy documentation.
此页面由 AI 自动翻译。查看英文原版
DepthAI 教程
DepthAI API 参考

本页目录

  • 演示
  • 设置
  • 源代码
  • 管道

Script JSON 通信

此示例演示了 Script 节点如何通过发送 Buffer 消息与外部世界(主机计算机)进行通信,并使用 JSON 序列化。同样,您可以使用 SPIInSPIOut 通过 SPI 在 MCU 和 Script 节点之间发送 JSON。这有什么用:Script 节点和主机/MCU 之间的双向通信可用于例如更改应用程序的流程。例如,我们可能希望在设备上使用 2 种不同的 NN 模型,一种在中午之前使用,另一种在中午到午夜之间使用。主机(例如 RPi)可以检查当前时间,当是中午时,它会向 Script 节点发送一条简单消息,该消息将开始将所有帧转发到另一个 NeuralNetwork 节点(该节点具有不同的 NN 模型)。它的作用:主机创建一个字典,将其序列化,然后将其发送到 Script 节点。Script 节点接收 Buffer 消息,反序列化字典,稍微更改值,再次序列化字典,然后将其发送到主机,主机反序列化更改后的字典并打印新值。

演示

Command Line
1~/depthai-python/examples/Script$ python3 script_json_communication.py
2dict {'one': 1, 'foo': 'bar'}
3[14442C1041B7EFD000] [3.496] [Script(1)] [warning] Original: {'one': 1, 'foo': 'bar'}
4[14442C1041B7EFD000] [3.496] [Script(1)] [warning] Changed: {'one': 2, 'foo': 'baz'}
5changedDict {'one': 2, 'foo': 'baz'}

设置

请运行 安装脚本 以下载所有必需的依赖项。请注意,此脚本必须在 git 上下文中运行,因此您必须先下载 depthai-python 存储库,然后运行脚本
Command Line
1git clone https://github.com/luxonis/depthai-python.git
2cd depthai-python/examples
3python3 install_requirements.py
有关更多信息,请遵循 安装指南

源代码

Python

Python
GitHub
1#!/usr/bin/env python3
2import depthai as dai
3import json
4
5pipeline = dai.Pipeline()
6
7xin = pipeline.create(dai.node.XLinkIn)
8xin.setStreamName('in')
9
10script = pipeline.create(dai.node.Script)
11xin.out.link(script.inputs['in'])
12script.setScript("""
13    import json
14
15    # Receive bytes from the host
16    data = node.io['in'].get().getData()
17    jsonStr = str(data, 'utf-8')
18    dict = json.loads(jsonStr)
19
20    # Change initial dictionary a bit
21    dict['one'] += 1
22    dict['foo'] = "baz"
23
24    b = Buffer(30)
25    b.setData(json.dumps(dict).encode('utf-8'))
26    node.io['out'].send(b)
27""")
28
29xout = pipeline.create(dai.node.XLinkOut)
30xout.setStreamName('out')
31script.outputs['out'].link(xout.input)
32
33# Connect to device with pipeline
34with dai.Device(pipeline) as device:
35    # This dict will be serialized (JSON), sent to device (Script node),
36    # edited a bit and sent back to the host
37    dict = {'one':1, 'foo': 'bar'}
38    print('dict', dict)
39    data = json.dumps(dict).encode('utf-8')
40    buffer = dai.Buffer()
41    buffer.setData(list(data))
42    device.getInputQueue("in").send(buffer)
43
44    # Wait for the script to send the changed dictionary back
45    jsonData = device.getOutputQueue("out").get()
46    jsonText = str(jsonData.getData(), 'utf-8')
47    changedDict = json.loads(jsonText)
48    print('changedDict', changedDict)

C++

1#include <chrono>
2#include <iostream>
3#include <thread>
4
5// Includes common necessary includes for development using depthai library
6#include "depthai/depthai.hpp"
7
8// Include nlohmann json
9#include "nlohmann/json.hpp"
10
11int main() {
12    using namespace std;
13
14    dai::Pipeline pipeline;
15
16    auto xin = pipeline.create<dai::node::XLinkIn>();
17    xin->setStreamName("in");
18
19    auto script = pipeline.create<dai::node::Script>();
20    xin->out.link(script->inputs["in"]);
21    script->setScript(R"(
22        import json
23
24        # Receive bytes from the host
25        data = node.io['in'].get().getData()
26        jsonStr = str(data, 'utf-8')
27        dict = json.loads(jsonStr)
28
29        # Change initial dictionary a bit
30        dict['one'] += 1
31        dict['foo'] = "baz"
32
33        b = Buffer(30)
34        b.setData(json.dumps(dict).encode('utf-8'))
35        node.io['out'].send(b)
36    )");
37
38    auto xout = pipeline.create<dai::node::XLinkOut>();
39    xout->setStreamName("out");
40    script->outputs["out"].link(xout->input);
41
42    // Connect to device with pipeline
43    dai::Device device(pipeline);
44
45    // This dict will be serialized (JSON), sent to device (Script node),
46    // edited a bit and sent back to the host
47    nlohmann::json dict{{"one", 1}, {"foo", "bar"}};
48    cout << "dict: " << dict << "\n";
49    auto buffer = dai::Buffer();
50    auto data = dict.dump();
51    buffer.setData({data.begin(), data.end()});
52    device.getInputQueue("in")->send(buffer);
53
54    // Wait for the script to send the changed dictionary back
55    auto jsonData = device.getOutputQueue("out")->get<dai::Buffer>();
56    auto changedDict = nlohmann::json::parse(jsonData->getData());
57    cout << "changedDict: " << changedDict << "\n";
58    const nlohmann::json expectedDict{{"one", 2}, {"foo", "baz"}};
59    if(expectedDict != changedDict) return 1;
60    return 0;
61}

管道

需要帮助?

请前往 Discussion Forum 获取技术支持或提出您可能有的任何其他问题。