Complete API documentation for PyDIPLink library.
Safely read a specific number of bytes from UART with timeout.
Parameters:
ser(serial.Serial): Open serial port connectionnum_bytes(int): Number of bytes to readtimeout(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 an image to the device via UART.
Parameters:
ser(serial.Serial): Open serial port connectionimage_path(str): Path to image filewidth(int): Target width in pixelsheight(int): Target height in pixelsimage_format(int): Image format constant (see Constants)
Returns:
None
Raises:
FileNotFoundError: If image file doesn't exist or path is invalidValueError: 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
Receive and save a raw image from the device.
Parameters:
ser(serial.Serial): Open serial port connectionsave_dir(str, optional): Directory to save images (default: "received_images")
Returns:
None
Raises:
TimeoutError: If UART communication times outValueError: 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 display a single JPEG frame from UART.
Parameters:
ser(serial.Serial): Open serial port connectionsave_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 outIOError/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 a 1D signal (e.g., histogram) over UART.
Parameters:
ser(serial.Serial): Open serial port connectionexpected_length(int, optional): Expected number of data pointsplot(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)}")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 pathfps(int): Frames per secondresolution(tuple): Video resolution (width, height)
Methods:
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| 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)| 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 |
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 abortRaised 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}")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}")import pydiplink
print(pydiplink.__version__) # "0.2.0"
print(pydiplink.__author__) # "Ozan Durgut"
print(pydiplink.__license__) # "MIT"PyDIPLink uses a command-based protocol over UART:
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 |
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.