# Multiple Scripts Sync

This example illustrates the use of the DepthAI Sync node to synchronize outputs from two separate script nodes. Each script
generates and sends data buffers at different intervals, and the Sync node aligns these outputs based on their timestamps.

### Similar samples:

 * [Depth and Video Sync](https://docs.luxonis.com/software-v3/depthai/examples/depth_video_sync.md)
 * [IMU and Video Sync](https://docs.luxonis.com/software-v3/depthai/examples/imu_video_sync.md)

## Demo

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

This example requires the DepthAI v3 API, see [installation instructions](https://docs.luxonis.com/software-v3/depthai.md).

## Source code

#### 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));
    }
}
```

### How it Works

 * Initialize a DepthAI pipeline.
 * Create two Script nodes, each generating and sending data buffers at different intervals.
 * Set up a Sync node with a synchronization threshold.
 * Link the outputs of the Script nodes to the Sync node.
 * Start the pipeline and continuously receive synchronized data from the Script nodes.
 * Print the received data along with timestamps and the interval between messages.

### Need assistance?

Head over to [Discussion Forum](https://discuss.luxonis.com/) for technical support or any other questions you might have.
