# Auto Reconnect

Demonstrates setting a reconnection callback and limited retry attempts on the device. The example opens a simple camera preview;
unplug the device briefly to see reconnection attempts reported via the callback.

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

## Pipeline

### examples/auto_reconnect.pipeline.json

```json
{
  "pipeline": {
    "connections": [],
    "globalProperties": {
      "calibData": null,
      "cameraTuningBlobSize": null,
      "cameraTuningBlobUri": "",
      "eepromId": 0,
      "leonCssFrequencyHz": 700000000.0,
      "leonMssFrequencyHz": 700000000.0,
      "pipelineName": null,
      "pipelineVersion": null,
      "sippBufferSize": 18432,
      "sippDmaBufferSize": 16384,
      "xlinkChunkSize": -1
    },
    "nodes": [
      [
        0,
        {
          "alias": "",
          "id": 0,
          "ioInfo": [
            [
              [
                "",
                "inputControl"
              ],
              {
                "blocking": true,
                "group": "",
                "id": 0,
                "name": "inputControl",
                "queueSize": 3,
                "type": 3,
                "waitForMessage": false
              }
            ],
            [
              [
                "dynamicOutputs",
                "0"
              ],
              {
                "blocking": false,
                "group": "dynamicOutputs",
                "id": 3,
                "name": "0",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ],
            [
              [
                "",
                "mockIsp"
              ],
              {
                "blocking": true,
                "group": "",
                "id": 1,
                "name": "mockIsp",
                "queueSize": 8,
                "type": 3,
                "waitForMessage": false
              }
            ],
            [
              [
                "",
                "raw"
              ],
              {
                "blocking": false,
                "group": "",
                "id": 2,
                "name": "raw",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ]
          ],
          "logLevel": 3,
          "name": "Camera",
          "parentId": -1,
          "properties": {
            "boardSocket": 0,
            "cameraName": "",
            "fps": -1.0,
            "imageOrientation": -1,
            "initialControl": {
              "aeLockMode": false,
              "aeMaxExposureTimeUs": 740756976,
              "aeRegion": {
                "height": 0,
                "priority": 740757104,
                "width": 489,
                "x": 35376,
                "y": 11305
              },
              "afRegion": {
                "height": 11298,
                "priority": 489,
                "width": 31728,
                "x": 489,
                "y": 0
              },
              "antiBandingMode": 167,
              "autoFocusMode": 3,
              "awbLockMode": false,
              "awbMode": 112,
              "brightness": 0,
              "captureIntent": 77,
              "chromaDenoise": 233,
              "cmdMask": 0,
              "contrast": 112,
              "controlMode": 233,
              "effectMode": 1,
              "enableHdr": false,
              "expCompensation": 0,
              "expManual": {
                "exposureTimeUs": 489,
                "frameDurationUs": 489,
                "sensitivityIso": 1302823424
              },
              "frameSyncMode": 0,
              "lensPosAutoInfinity": 112,
              "lensPosAutoMacro": 18,
              "lensPosition": 0,
              "lensPositionRaw": 0.0,
              "lowPowerNumFramesBurst": 112,
              "lowPowerNumFramesDiscard": 157,
              "lumaDenoise": 44,
              "miscControls": [],
              "saturation": 16,
              "sceneMode": 130,
              "sharpness": 39,
              "strobeConfig": {
                "activeLevel": 240,
                "enable": 0,
                "gpioNumber": 0
              },
              "strobeTimings": {
                "durationUs": 489,
                "exposureBeginOffsetUs": 489,
                "exposureEndOffsetUs": 740754288
              },
              "wbColorTemp": 0
            },
            "isp3aFps": 0,
            "mockIspHeight": -1,
            "mockIspWidth": -1,
            "numFramesPoolIsp": 3,
            "numFramesPoolPreview": 4,
            "numFramesPoolRaw": 3,
            "numFramesPoolStill": 4,
            "numFramesPoolVideo": 4,
            "outputRequests": [
              {
                "enableUndistortion": null,
                "fps": {
                  "value": null
                },
                "resizeMode": 0,
                "size": {
                  "value": {
                    "index": 0,
                    "value": [
                      640,
                      400
                    ]
                  }
                },
                "type": null
              }
            ],
            "resolutionHeight": -1,
            "resolutionWidth": -1,
            "sensorType": -1
          }
        }
      ]
    ]
  }
}
```

## Source code

#### Python

```python
#!/usr/bin/env python3

import cv2
import depthai as dai

def callback(x: dai.Device.ReconnectionStatus):
    print(f"Reconnecting state {x}")

# Create pipeline
device = dai.Device()
device.setMaxReconnectionAttempts(3, callback)

# You can try unplugging the camera to see the reconnection in action
with dai.Pipeline(device) as pipeline:
    # Define source and output
    cam = pipeline.create(dai.node.Camera).build()
    videoQueue = cam.requestOutput((640,400)).createOutputQueue()

    # Connect to device and start pipeline
    pipeline.start()
    while pipeline.isRunning():
        videoIn = videoQueue.get()
        assert isinstance(videoIn, dai.ImgFrame)
        cv2.imshow("video", videoIn.getCvFrame())

        if cv2.waitKey(1) == ord("q"):
            break
```

#### C++

```cpp
#include <atomic>
#include <csignal>
#include <iostream>
#include <memory>
#include <opencv2/opencv.hpp>

#include "depthai/depthai.hpp"

// Global flag for graceful shutdown
std::atomic<bool> quitEvent(false);

// Signal handler
void signalHandler(int signum) {
    quitEvent = true;
}

// Reconnection callback function
void reconnectionCallback(dai::Device::ReconnectionStatus status) {
    std::cout << "Reconnecting state " << static_cast<int>(status) << std::endl;
}

int main() {
    // Set up signal handlers
    signal(SIGTERM, signalHandler);
    signal(SIGINT, signalHandler);

    try {
        // Create device with reconnection settings
        auto device = std::make_shared<dai::Device>();
        device->setMaxReconnectionAttempts(3, reconnectionCallback);

        // Create pipeline
        dai::Pipeline pipeline(device);

        // Define source and output
        auto cam = pipeline.create<dai::node::Camera>()->build();
        auto output = cam->requestOutput(std::make_pair(640, 400));
        auto videoQueue = output->createOutputQueue();

        // Start pipeline
        pipeline.start();
        std::cout << "Pipeline started. Try unplugging the camera to see reconnection in action." << std::endl;
        std::cout << "Press 'q' to quit." << std::endl;

        while(pipeline.isRunning() && !quitEvent) {
            auto videoIn = videoQueue->get<dai::ImgFrame>();
            if(videoIn == nullptr) continue;

            cv::imshow("video", videoIn->getCvFrame());

            int key = cv::waitKey(1);
            if(key == 'q') {
                break;
            }
        }

        // Cleanup
        pipeline.stop();
        pipeline.wait();

    } catch(const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}
```

### Need assistance?

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