# 脚本 JSON 通信

本示例展示了 Script 节点如何通过发送 [Buffer](https://docs.luxonis.com/software/depthai-components/messages/buffer.md) 消息来与外部世界（主机）进行 JSON
序列化通信。类似地，您也可以使用 [SPIIn](https://docs.luxonis.com/software/depthai-components/nodes/spi_in.md) 和
[SPIOut](https://docs.luxonis.com/software/depthai-components/nodes/spi_out.md) 在 MCU 与 Script 节点之间通过 SPI 发送 JSON。

这有什么用：

Script 节点与主机/MCU 之间的双向通信可用于修改应用程序的流程。

例如，我们可能想在设备上使用两种不同的 NN 模型，中午之前用其中一个，中午到午夜用另一个。主机（例如 RPi）可以检查当前时间，当到中午时，它向 Script 节点发送一条简单消息，Script 节点就会将所有帧转发到另一个 NeuralNetwork
节点（该节点使用不同的 NN 模型）。

它的作用：

主机创建一个字典，序列化后发送给 Script 节点。Script 节点接收 Buffer 消息，反序列化字典，稍微修改一些值，然后再次序列化字典并将其发送回主机，主机反序列化修改后的字典并打印新值。

## 演示

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

## 配置

请运行[安装脚本](https://github.com/luxonis/depthai-python/blob/main/examples/install_requirements.py)以下载所有必需的依赖项。请注意，此脚本必须在 git
上下文中运行，因此您需要先下载 [depthai-python](https://github.com/luxonis/depthai-python) 仓库，然后运行该脚本。

```bash
git clone https://github.com/luxonis/depthai-python.git
cd depthai-python/examples
python3 install_requirements.py
```

更多信息，请参考[安装指南](https://docs.luxonis.com/software/depthai/manual-install.md)。

## 源代码

#### Python

```python
#!/usr/bin/env python3
import depthai as dai
import json

pipeline = dai.Pipeline()

xin = pipeline.create(dai.node.XLinkIn)
xin.setStreamName('in')

script = pipeline.create(dai.node.Script)
xin.out.link(script.inputs['in'])
script.setScript("""
    import json

    # Receive bytes from the host
    data = node.io['in'].get().getData()
    jsonStr = str(data, 'utf-8')
    dict = json.loads(jsonStr)

    # Change initial dictionary a bit
    dict['one'] += 1
    dict['foo'] = "baz"

    b = Buffer(30)
    b.setData(json.dumps(dict).encode('utf-8'))
    node.io['out'].send(b)
""")

xout = pipeline.create(dai.node.XLinkOut)
xout.setStreamName('out')
script.outputs['out'].link(xout.input)

# Connect to device with pipeline
with dai.Device(pipeline) as device:
    # This dict will be serialized (JSON), sent to device (Script node),
    # edited a bit and sent back to the host
    dict = {'one':1, 'foo': 'bar'}
    print('dict', dict)
    data = json.dumps(dict).encode('utf-8')
    buffer = dai.Buffer()
    buffer.setData(list(data))
    device.getInputQueue("in").send(buffer)

    # Wait for the script to send the changed dictionary back
    jsonData = device.getOutputQueue("out").get()
    jsonText = str(jsonData.getData(), 'utf-8')
    changedDict = json.loads(jsonText)
    print('changedDict', changedDict)
```

#### C++

```cpp
#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

        # Receive bytes from the host
        data = node.io['in'].get().getData()
        jsonStr = str(data, 'utf-8')
        dict = json.loads(jsonStr)

        # Change initial dictionary a bit
        dict['one'] += 1
        dict['foo'] = "baz"

        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);

    // This dict will be serialized (JSON), sent to device (Script node),
    // edited a bit and sent back to the host
    nlohmann::json dict{{"one", 1}, {"foo", "bar"}};
    cout << "dict: " << dict << "\n";
    auto buffer = dai::Buffer();
    auto data = dict.dump();
    buffer.setData({data.begin(), data.end()});
    device.getInputQueue("in")->send(buffer);

    // Wait for the script to send the changed dictionary back
    auto jsonData = device.getOutputQueue("out")->get<dai::Buffer>();
    auto changedDict = nlohmann::json::parse(jsonData->getData());
    cout << "changedDict: " << changedDict << "\n";
    const nlohmann::json expectedDict{{"one", 2}, {"foo", "baz"}};
    if(expectedDict != changedDict) return 1;
    return 0;
}
```

## 管道

### examples/script_json_communication.pipeline.json

```json
{
  "pipeline": {
    "connections": [
      {
        "node1Id": 0,
        "node1Output": "out",
        "node1OutputGroup": "",
        "node2Id": 1,
        "node2Input": "in",
        "node2InputGroup": "io"
      },
      {
        "node1Id": 1,
        "node1Output": "out",
        "node1OutputGroup": "io",
        "node2Id": 2,
        "node2Input": "in",
        "node2InputGroup": ""
      }
    ],
    "globalProperties": {
      "calibData": null,
      "cameraTuningBlobSize": null,
      "cameraTuningBlobUri": "",
      "leonCssFrequencyHz": 700000000.0,
      "leonMssFrequencyHz": 700000000.0,
      "pipelineName": null,
      "pipelineVersion": null,
      "sippBufferSize": 18432,
      "sippDmaBufferSize": 16384,
      "xlinkChunkSize": -1
    },
    "nodes": [
      [
        0,
        {
          "id": 0,
          "ioInfo": [
            [
              [
                "",
                "out"
              ],
              {
                "blocking": false,
                "group": "",
                "id": 1,
                "name": "out",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ]
          ],
          "name": "XLinkIn",
          "properties": {
            "maxDataSize": 5242880,
            "numFrames": 8,
            "streamName": "in"
          }
        }
      ],
      [
        1,
        {
          "id": 1,
          "ioInfo": [
            [
              [
                "io",
                "in"
              ],
              {
                "blocking": true,
                "group": "io",
                "id": 2,
                "name": "in",
                "queueSize": 8,
                "type": 3,
                "waitForMessage": false
              }
            ],
            [
              [
                "io",
                "out"
              ],
              {
                "blocking": false,
                "group": "io",
                "id": 3,
                "name": "out",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ]
          ],
          "name": "Script",
          "properties": {
            "processor": 1,
            "scriptName": "<script>",
            "scriptUri": "asset:__script"
          }
        }
      ],
      [
        2,
        {
          "id": 2,
          "ioInfo": [
            [
              [
                "",
                "in"
              ],
              {
                "blocking": true,
                "group": "",
                "id": 4,
                "name": "in",
                "queueSize": 8,
                "type": 3,
                "waitForMessage": true
              }
            ]
          ],
          "name": "XLinkOut",
          "properties": {
            "maxFpsLimit": -1.0,
            "metadataOnly": false,
            "streamName": "out"
          }
        }
      ]
    ]
  }
}
```

### 需要帮助？

请前往 [OAKChina 官网](https://www.oakchina.cn/) 获取技术支持或解答您的任何疑问。
