Skip to content

Latest commit

 

History

History
338 lines (239 loc) · 7.71 KB

File metadata and controls

338 lines (239 loc) · 7.71 KB

PyDIPLink API Reference

Complete API documentation for PyDIPLink library.

Table of Contents


Core Functions

safe_read(ser, num_bytes, timeout=0.5)

Safely read a specific number of bytes from UART with timeout.

Parameters:

  • ser (serial.Serial): Open serial port connection
  • num_bytes (int): Number of bytes to read
  • timeout (float, optional): Timeout in seconds (default: 0.5)

Returns:

  • bytes: The read data

Raises:

  • TimeoutError: If data cannot be read within timeout period

Example:

import serial
from pydiplink import safe_read

ser = serial.Serial('/dev/ttyUSB0', 500000)
data = safe_read(ser, 100, timeout=1.0)

send_image_data(ser, image_path, width, height, image_format)

Send an image to the device via UART.

Parameters:

  • ser (serial.Serial): Open serial port connection
  • image_path (str): Path to image file
  • width (int): Target width in pixels
  • height (int): Target height in pixels
  • image_format (int): Image format constant (see Constants)

Returns:

  • None

Raises:

  • FileNotFoundError: If image file doesn't exist or path is invalid
  • ValueError: If image format is unsupported

Example:

from pydiplink import send_image_data, IMAGE_FORMAT_RGB888

send_image_data(ser, "photo.jpg", 320, 240, IMAGE_FORMAT_RGB888)

Security:

  • Automatically sanitizes file paths to prevent directory traversal
  • Validates image format before processing

capture_image_and_show(ser, save_dir="received_images")

Receive and save a raw image from the device.

Parameters:

  • ser (serial.Serial): Open serial port connection
  • save_dir (str, optional): Directory to save images (default: "received_images")

Returns:

  • None

Raises:

  • TimeoutError: If UART communication times out
  • ValueError: If image dimensions exceed security limits

Example:

from pydiplink import capture_image_and_show

capture_image_and_show(ser, save_dir="my_images")

Security Limits:

  • MAX_IMAGE_WIDTH: 4096 pixels
  • MAX_IMAGE_HEIGHT: 4096 pixels
  • MAX_IMAGE_DEPTH: 4 channels
  • MAX_TOTAL_BYTES: 50 MB

receive_and_show_jpeg(ser, save_path="output.avi", fps=15, resolution=(160, 120))

Receive and display a single JPEG frame from UART.

Parameters:

  • ser (serial.Serial): Open serial port connection
  • save_path (str, optional): Video output path (deprecated, use JpegVideoWriter)
  • fps (int, optional): Frames per second (deprecated)
  • resolution (tuple, optional): Video resolution (deprecated)

Returns:

  • np.ndarray: Decoded BGR image frame

Raises:

  • TimeoutError: If UART communication times out
  • IOError/OSError: If JPEG decoding fails

Example:

from pydiplink import receive_and_show_jpeg

frame = receive_and_show_jpeg(ser)
print(f"Frame shape: {frame.shape}")

Note: For video recording, use JpegVideoWriter context manager instead.


receive_1d_signal(ser, expected_length=None, plot=True, save_path=None)

Receive a 1D signal (e.g., histogram) over UART.

Parameters:

  • ser (serial.Serial): Open serial port connection
  • expected_length (int, optional): Expected number of data points
  • plot (bool, optional): Whether to plot the signal (default: True)
  • save_path (str, optional): Path to save plot and CSV (without extension)

Returns:

  • np.ndarray: 1D numpy array of signal data

Example:

from pydiplink import receive_1d_signal

histogram = receive_1d_signal(ser, plot=True, save_path="histogram")
# Creates histogram.png and histogram.csv
print(f"Histogram bins: {len(histogram)}")

Classes

JpegVideoWriter

Context manager for JPEG video writing with proper resource cleanup.

Constructor:

JpegVideoWriter(save_path="output.avi", fps=15, resolution=(160, 120))

Parameters:

  • save_path (str): Output video file path
  • fps (int): Frames per second
  • resolution (tuple): Video resolution (width, height)

Methods:

write_frame(img_bgr)

Write a single frame to the video.

Parameters:

  • img_bgr (np.ndarray): BGR image array

Raises:

  • RuntimeError: If called outside context manager

Example:

from pydiplink import JpegVideoWriter, receive_and_show_jpeg

with JpegVideoWriter("output.avi", fps=30, resolution=(640, 480)) as writer:
    for i in range(100):
        frame = receive_and_show_jpeg(ser)
        writer.write_frame(frame)
# Video automatically closed and saved

Constants

Image Format Constants

Constant Value Description Bytes/Pixel
IMAGE_FORMAT_GRAYSCALE 0 8-bit grayscale 1
IMAGE_FORMAT_RGB888 1 24-bit true color 3
IMAGE_FORMAT_RGB565 2 16-bit color 2
IMAGE_FORMAT_YUV 3 YUV color space 3
IMAGE_FORMAT_HSV 4 HSV color space 3

Example:

from pydiplink import IMAGE_FORMAT_RGB888, IMAGE_FORMAT_GRAYSCALE

# Send RGB888 image
send_image_data(ser, "color.jpg", 320, 240, IMAGE_FORMAT_RGB888)

# Send grayscale image
send_image_data(ser, "gray.jpg", 160, 120, IMAGE_FORMAT_GRAYSCALE)

Security Limit Constants

Constant Value Description
MAX_IMAGE_WIDTH 4096 Maximum image width in pixels
MAX_IMAGE_HEIGHT 4096 Maximum image height in pixels
MAX_IMAGE_DEPTH 4 Maximum image depth (channels)
MAX_TOTAL_BYTES 52428800 Maximum total image size (50 MB)
UART_BLOCK_SIZE_MAX 65535 Maximum UART block size

Exceptions

TimeoutError

Raised when UART communication times out.

Message Format:

UART read timeout: received X/Y bytes after Z.Zs. Connection may be unstable or device not responding.

Handling:

try:
    data = safe_read(ser, 100)
except TimeoutError as e:
    print(f"Communication timeout: {e}")
    # Retry or abort

FileNotFoundError

Raised when image file is not found or path is invalid.

Handling:

try:
    send_image_data(ser, "missing.jpg", 320, 240, IMAGE_FORMAT_RGB888)
except FileNotFoundError as e:
    print(f"File error: {e}")

ValueError

Raised for invalid parameters or security limit violations.

Common Causes:

  • Unsupported image format
  • Image dimensions exceed MAX_IMAGE_WIDTH or MAX_IMAGE_HEIGHT
  • Image depth exceeds MAX_IMAGE_DEPTH
  • Total image size exceeds MAX_TOTAL_BYTES

Handling:

try:
    capture_image_and_show(ser)
except ValueError as e:
    print(f"Validation error: {e}")

Module Information

import pydiplink

print(pydiplink.__version__)  # "0.2.0"
print(pydiplink.__author__)   # "Ozan Durgut"
print(pydiplink.__license__)  # "MIT"

Protocol Specification

PyDIPLink uses a command-based protocol over UART:

Command Structure

All commands start with a 3-byte header:

Command Bytes Purpose
STR 0x53 0x54 0x52 Send image to device
STW 0x53 0x54 0x57 Receive image from device
STJ 0x53 0x54 0x4A Receive JPEG frame
ST1 0x53 0x54 0x31 Receive 1D signal

Data Format

All multi-byte values use little-endian byte order.

STR (Send Image):

Device → PC: [STR][width:2][height:2][format:2][depth:2]
PC → Device: [image_data]

STW (Receive Image):

Device → PC: [STW][width:2][height:2][format:2][depth:2][image_data]

STJ (Receive JPEG):

Device → PC: [STJ][jpeg_size:4][jpeg_data]

ST1 (Receive Signal):

Device → PC: [ST1][length:4][float32_data...]

For more examples, see the examples/ directory.