# 多个脚本同步

本示例演示了使用 DepthAI Sync 节点来同步两个独立脚本节点的输出。每个脚本以不同的间隔生成并发送数据缓冲区，Sync节点根据时间戳对齐这些输出。

### 类似示例：

 * [深度与视频同步](https://docs.luxonis.com/software-v3/depthai/examples/depth_video_sync.md)
 * [IMU与视频同步](https://docs.luxonis.com/software-v3/depthai/examples/imu_video_sync.md)

## 演示

```bash
~/depthai-python/examples/Sync $ python3 sync_scripts.py
Start
Received s1 with timestamp 0:00:02.420089
Received s2 with timestamp 0:00:02.461076
Time interval between messages: 40.987ms
----------
Received s1 with timestamp 0:00:03.422108
Received s2 with timestamp 0:00:03.367069
Time interval between messages: 55.039ms
----------
Received s1 with timestamp 0:00:05.426088
Received s2 with timestamp 0:00:05.481086
Time interval between messages: 54.998ms
----------
Received s1 with timestamp 0:00:06.428106
Received s2 with timestamp 0:00:06.387129
Time interval between messages: 40.977ms
----------
```

这个示例需要DepthAI v3 API，参见[安装说明](https://docs.luxonis.com/software-v3/depthai.md)。

## 源代码

#### Python

```python
import depthai as dai
import time
from datetime import timedelta

pipeline = dai.Pipeline()

script1 = pipeline.create(dai.node.Script)
script1.setScript("""
from time import sleep

while True:
    sleep(1)
    b = Buffer(512)
    b.setData(bytes(4 * [i for i in range(0, 128)]))
    b.setTimestamp(Clock.now())
    node.io['out'].send(b)
""")

script2 = pipeline.create(dai.node.Script)
script2.setScript("""
from time import sleep

while True:
    sleep(0.3)
    b = Buffer(512)
    b.setData(bytes(4 * [i for i in range(128, 256)]))
    b.setTimestamp(Clock.now())
    node.io['out'].send(b)
""")

sync = pipeline.create(dai.node.Sync)
sync.setSyncThreshold(timedelta(milliseconds=100))

xout = pipeline.create(dai.node.XLinkOut)
xout.setStreamName("xout")

sync.out.link(xout.input)

script1.outputs["out"].link(sync.inputs["s1"])
script2.outputs["out"].link(sync.inputs["s2"])

# script1.outputs["out"].link(xout.input)

with dai.Device(pipeline) as device:
    print("Start")
    q = device.getOutputQueue("xout", maxSize=10, blocking=True)
    while True:
        grp = q.get()
        for name, msg in grp:
            print(f"Received {name} with timestamp {msg.getTimestamp()}")
        print(f"Time interval between messages: {grp.getIntervalNs() / 1e6}ms")
        print("----------")
        time.sleep(0.2)
```

#### C++

```cpp
#include <chrono>
#include <iostream>

#include "depthai/depthai.hpp"

int main() {
    dai::Pipeline pipeline;

    auto script1 = pipeline.create<dai::node::Script>();
    script1->setScript(
        R"SCRPT(
from time import sleep

while True:
    sleep(1)
    b = Buffer(512)
    b.setData(bytes(4 * [i for i in range(0, 128)]))
    b.setTimestamp(Clock.now())
    node.io['out'].send(b)
)SCRPT");

    auto script2 = pipeline.create<dai::node::Script>();
    script2->setScript(
        R"SCRPT(
from time import sleep

while True:
    sleep(0.3)
    b = Buffer(512)
    b.setData(bytes(4 * [i for i in range(128, 256)]))
    b.setTimestamp(Clock.now())
    node.io['out'].send(b)
)SCRPT");

    auto sync = pipeline.create<dai::node::Sync>();
    sync->setSyncThreshold(std::chrono::milliseconds(100));

    auto xout = pipeline.create<dai::node::XLinkOut>();
    xout->setStreamName("xout");

    sync->out.link(xout->input);
    script1->outputs["out"].link(sync->inputs["s1"]);
    script2->outputs["out"].link(sync->inputs["s2"]);

    dai::Device device(pipeline);
    std::cout << "Start" << std::endl;
    auto queue = device.getOutputQueue("xout", 10, true);
    while(true) {
        auto grp = queue->get<dai::MessageGroup>();
        std::cout << "Buffer 1 timestamp: " << grp->get<dai::Buffer>("s1")->getTimestamp().time_since_epoch().count() << std::endl;
        std::cout << "Buffer 2 timestamp: " << grp->get<dai::Buffer>("s2")->getTimestamp().time_since_epoch().count() << std::endl;
        std::cout << "Time interval between messages: " << static_cast<double>(grp->getIntervalNs()) / 1e6 << "ms" << std::endl;
        std::cout << "----------" << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }
}
```

### 工作原理

 * 初始化一个 DepthAI 管道。
 * 创建两个 Script 节点，每个节点以不同的间隔生成并发送数据缓冲区。
 * 设置一个 Sync 节点，并指定同步阈值。
 * 将 Script 节点的输出链接到 Sync 节点。
 * 启动管道并持续接收来自 Script 节点的同步数据。
 * 打印接收到的数据，包括时间戳和消息间隔。

### 需要帮助？

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