Connection Module

The connection module provides connection implementations for USB and network communication with Brother P-touch printers.

Connection classes for Brother P-touch printers.

ptouch.connection.parse_usb_uri(uri)[source]

Parse a USB device URI into vendor_id, product_id, and serial.

Supported formats: - usb://0x04f9:0x2086 - vendor:product - usb://0x04f9:0x2086/serial - vendor:product/serial - usb://:0x2086 - product only (uses default vendor) - usb://:0x2086/serial - product/serial (uses default vendor)

Parameters:

uri (str) – USB URI string to parse.

Returns:

Tuple of (vendor_id, product_id, serial). Values may be None if not specified.

Return type:

tuple[int | None, int | None, str | None]

Raises:

ValueError – If the URI format is invalid.

Examples

>>> parse_usb_uri("usb://0x04f9:0x2086")
(0x04f9, 0x2086, None)
>>> parse_usb_uri("usb://:0x2086/A1B2C3D4E5")
(None, 0x2086, 'A1B2C3D4E5')
exception ptouch.connection.PrinterConnectionError(message, original_error=None)[source]

Bases: Exception

Base exception for all printer connection errors.

Parameters:
  • message (str) – Human-readable error message.

  • original_error (Exception | None) – The underlying exception that caused this error.

__init__(message, original_error=None)[source]
exception ptouch.connection.PrinterNotFoundError(message, original_error=None)[source]

Bases: PrinterConnectionError

Printer device not found or not accessible.

Raised when: - USB device with specified product ID is not detected - USB endpoints are not found on the device

exception ptouch.connection.PrinterPermissionError(message, original_error=None)[source]

Bases: PrinterConnectionError

Insufficient permissions to access printer.

Raised when: - USB device requires elevated permissions (EACCES) - Typically resolved by running with sudo or configuring udev rules

exception ptouch.connection.PrinterNetworkError(message, original_error=None)[source]

Bases: PrinterConnectionError

Network-specific connection errors.

Raised when: - Connection is refused by the printer - Hostname cannot be resolved - Network connection is lost (BrokenPipe, ConnectionReset) - Generic network connection failures

exception ptouch.connection.PrinterTimeoutError(message, original_error=None)[source]

Bases: PrinterConnectionError

Connection or operation timeout.

Raised when: - Network connection attempt times out - Write operation times out after retries - Read operation times out

exception ptouch.connection.PrinterWriteError(message, original_error=None)[source]

Bases: PrinterConnectionError

Failed to write data to printer.

Raised when: - Incomplete write (not all bytes written) - Write operation fails after retry attempts - USB or network write encounters non-recoverable error

class ptouch.connection.Connection[source]

Bases: ABC

Abstract base class for printer connections.

abstractmethod connect(printer)[source]

Establish the connection to the printer.

Parameters:

printer (LabelPrinter) – The printer instance that will use this connection.

Return type:

None

abstractmethod write(payload)[source]

Write data to the printer.

Parameters:

payload (bytes) – Bytes to send to the printer.

Return type:

None

abstractmethod close()[source]

Close the connection and release resources.

Return type:

None

read(num_bytes=1024)[source]

Read data from the printer (optional, not all connections support this).

Parameters:

num_bytes (int) – Maximum number of bytes to read.

Returns:

Bytes received from the printer.

Return type:

bytes

Raises:

NotImplementedError – If the connection does not support reading.

__del__()[source]

Clean up connection on garbage collection.

Return type:

None

class ptouch.connection.ConnectionUSB(vendor_id=None, product_id=None, serial=None)[source]

Bases: Connection

USB connection for Brother label printers.

The actual USB connection is established when connect() is called by the printer. The printer class must define a USB_PRODUCT_ID class attribute unless vendor_id and product_id are provided explicitly.

Parameters:
  • vendor_id (int | None) – USB vendor ID. Defaults to Brother (0x04F9) if not specified.

  • product_id (int | None) – USB product ID. If not specified, uses the printer’s USB_PRODUCT_ID.

  • serial (str | None) – USB serial number to match a specific device when multiple are connected.

Raises:

PrinterConnectionError – If the printer device is not found, endpoints are missing, or USB access fails.

Examples

Basic connection (uses printer’s USB_PRODUCT_ID):

>>> connection = ConnectionUSB()

Specific device by product ID:

>>> connection = ConnectionUSB(product_id=0x2086)

Specific device by serial number:

>>> connection = ConnectionUSB(product_id=0x2086, serial="A1B2C3D4E5")
__init__(vendor_id=None, product_id=None, serial=None)[source]
connect(printer)[source]

Establish USB connection to the printer.

Parameters:

printer (LabelPrinter) – The printer instance. Must have USB_PRODUCT_ID class attribute unless product_id was provided to the constructor.

Raises:
Return type:

None

write(payload, retries=3)[source]

Write data to the printer via USB with retry logic.

Parameters:

retries (int) – Number of retry attempts for transient failures.

Raises:

PrinterWriteError – If not all bytes were written successfully after retries.

Return type:

None

close()[source]

Close USB connection and reattach kernel driver if needed.

Return type:

None

class ptouch.connection.ConnectionNetwork(host, port=9100, timeout=5.0)[source]

Bases: Connection

Network (TCP/IP) connection for Brother label printers.

The actual socket connection is established when connect() is called by the printer.

Parameters:
  • host (str) – Hostname or IP address of the printer.

  • port (int) – TCP port number for raw printing.

  • timeout (float) – Connection timeout in seconds. Also used for read/write operations.

__init__(host, port=9100, timeout=5.0)[source]
connect(printer)[source]

Establish network connection to the printer.

Parameters:

printer (LabelPrinter) – The printer instance (not used for network connections).

Raises:
Return type:

None

write(payload, retries=3)[source]

Write data to the printer via network with retry logic.

Parameters:

retries (int) – Number of retry attempts for transient failures (timeout only).

Raises:
Return type:

None

read(num_bytes=1024)[source]

Read data from the printer via network.

Raises:
Return type:

bytes

close()[source]

Close the network connection.

Return type:

None

USB Device Selection

When multiple USB printers are connected, you can select a specific device using:

  • product_id - USB product ID to match a specific printer model

  • serial - USB serial number to match a specific device

Example:

from ptouch import ConnectionUSB

# Connect to specific device by serial number
connection = ConnectionUSB(product_id=0x2086, serial="A1B2C3D4E5")

USB URI Format

The parse_usb_uri function parses USB device URIs for CLI usage:

from ptouch import parse_usb_uri

# Parse various URI formats
vendor, product, serial = parse_usb_uri("usb://0x04f9:0x2086/A1B2C3D4E5")
vendor, product, serial = parse_usb_uri("usb://:0x2086/A1B2C3D4E5")
vendor, product, serial = parse_usb_uri("usb://:0x2086")

Supported formats:

  • usb://vendor:product - Vendor and product ID

  • usb://vendor:product/serial - With serial number

  • usb://:product - Product ID only (default vendor)

  • usb://:product/serial - Product and serial (default vendor)

Exception Classes

The module defines a hierarchy of exception classes for connection errors:

  • PrinterConnectionError - Base exception for all connection errors

  • PrinterNotFoundError - Printer device not found

  • PrinterPermissionError - Permission denied (USB requires sudo/udev rules)

  • PrinterNetworkError - Network connection/communication errors

  • PrinterTimeoutError - Connection or operation timeout

  • PrinterWriteError - Failed to write data to printer

All specific exceptions inherit from PrinterConnectionError, allowing you to catch all connection-related errors with a single except clause.

See Also