### Example: Get Printer Info with CLI
Source: https://github.com/labbots/niimprintx/blob/main/README.md
An example command to retrieve information about a printer model using the NiimPrintX CLI.
```shell
python -m NiimPrintX.cli info -m d110
```
--------------------------------
### Install NiimPrintX
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/getting-started.md
Clone the repository, set up a virtual environment, and install dependencies using Poetry.
```bash
git clone https://github.com/labbots/NiimPrintX.git
cd NiimPrintX
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
poetry install
```
--------------------------------
### Printer Connection Example
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/README.md
Shows how to find a device, instantiate the PrinterClient, and establish a connection.
```python
device = await find_device("model")
printer = PrinterClient(device)
await printer.connect()
# ... use printer ...
await printer.disconnect()
```
--------------------------------
### START_PRINT Command Example
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/protocol-reference.md
An example of a START_PRINT command packet, illustrating the byte values for markers, type, length, data, and checksum.
```text
0x55 0x55 Start marker
0x01 Type (START_PRINT)
0x01 Length (1 byte)
0x01 Data (parameter: 1)
0x01 Checksum (0x01 ^ 0x01 ^ 0x01 = 0x01)
0xAA 0xAA End marker
```
--------------------------------
### Start Bluetooth Notification Handler
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/module-overview.md
Example of setting up a handler for incoming Bluetooth notifications. The handler function will be invoked for each notification received.
```python
transport.start_notification(char_uuid, handler)
# handler called for each incoming notification
```
--------------------------------
### macOS Development Setup
Source: https://github.com/labbots/niimprintx/blob/main/README.md
Specific setup commands for macOS local development, including installing libraries and setting environment variables.
```shell
brew install libffi
brew install glib gobject-introspection cairo pkg-config
export PKG_CONFIG_PATH="/usr/local/opt/libffi/lib/pkgconfig"
export LDFLAGS="-L/usr/local/opt/libffi/lib"
export CFLAGS="-I/usr/local/opt/libffi/include"
```
--------------------------------
### Print Image Example
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/README.md
Demonstrates how to open an image file and send it to the printer with specified parameters.
```python
from PIL import Image
image = Image.open("file.png")
await printer.print_image(image, density=3, quantity=1, vertical_offset=0, horizontal_offset=0)
```
--------------------------------
### CLI Print Command Example
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/configuration.md
Demonstrates how to use the command-line interface to print a label. This example specifies the printer model, density, quantity, rotation, and image file.
```bash
python -m NiimPrintX.cli print -m d110 -d 3 -n 2 -r 90 -i label.png
```
--------------------------------
### Example: Print Image with CLI
Source: https://github.com/labbots/niimprintx/blob/main/README.md
An example command to print an image using the NiimPrintX CLI with specified options.
```shell
python -m NiimPrintX.cli print -m d110 -d 3 -n 1 -r 90 -i path/to/image.png
```
--------------------------------
### Install Dependencies with Poetry
Source: https://github.com/labbots/niimprintx/blob/main/README.md
Install project dependencies using Poetry after cloning the repository.
```shell
python -m venv venv
poetry install
```
--------------------------------
### Get Device Information
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/README.md
Provides examples for retrieving specific device information, such as serial number and software version.
```python
serial = await printer.get_info(InfoEnum.DEVICESERIAL)
version = await printer.get_info(InfoEnum.SOFTVERSION)
```
--------------------------------
### Global CLI Options Example
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/cli_interface.md
Demonstrates how to use global CLI options such as verbosity flags and the help command. The verbose flag can be repeated for increased logging detail.
```bash
python -m NiimPrintX.cli -vv print -m d110 -i label.png
```
```bash
python -m NiimPrintX.cli -h
```
--------------------------------
### CLI Usage Examples
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/logger.md
Demonstrates how to invoke the NiimPrintX CLI with different verbosity flags to control log output.
```bash
python -m NiimPrintX.cli print -i label.png # INFO
python -m NiimPrintX.cli -v print -i label.png # INFO
python -m NiimPrintX.cli -vv print -i label.png # DEBUG
python -m NiimPrintX.cli -vvv print -i label.png # TRACE
```
--------------------------------
### Initiate Print Job
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/printer_client.md
Starts a new print job on the printer. Returns True if the printer acknowledges the request.
```python
await printer.start_print()
```
--------------------------------
### Integrating NiimPrintX with Application Logging
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/advanced-usage.md
Integrate NiimPrintX operations with your application's logging framework. This example shows how to set up both application-level and NiimPrintX-specific logging for comprehensive event tracking.
```python
import asyncio
import logging
from NiimPrintX.nimmy.logger_config import setup_logger, get_logger
from NiimPrintX.nimmy.bluetooth import find_device
from NiimPrintX.nimmy.printer import PrinterClient
# Setup application logging
logging.basicConfig(level=logging.INFO)
app_logger = logging.getLogger(__name__)
# Setup NiimPrintX logging
setup_logger()
nimmy_logger = get_logger()
async def print_with_logging(image_path, model="d110"):
"""Print with integrated logging."""
app_logger.info(f"Starting print job: {image_path}")
try:
device = await find_device(model)
app_logger.debug(f"Found device: {device.name}")
printer = PrinterClient(device)
await printer.connect()
app_logger.info("Connected to printer")
# Perform print...
app_logger.info("Print completed successfully")
except Exception as e:
app_logger.error(f"Print failed: {e}", exc_info=True)
raise
# Usage
await print_with_logging("label.png", "d110")
```
--------------------------------
### Start a New Page
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/printer_client.md
Begins a new page or label within the current print job. Returns True if the printer acknowledged the request.
```python
async def start_page_print() -> bool
```
--------------------------------
### Catch BLEException
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/errors.md
Example of catching BLEException when a device is not found during discovery. Ensure to import the exception and the relevant function.
```python
from NiimPrintX.nimmy.exception import BLEException
from NiimPrintX.nimmy.bluetooth import find_device
try:
device = await find_device("d110")
except BLEException as e:
print(f"Device not found: {e}")
```
--------------------------------
### Get RFID Metadata Example
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/types.md
Retrieve and print RFID metadata, including UUID and capacity, using PrinterClient.get_rfid().
```python
rfid = await printer.get_rfid()
if rfid:
print(f"UUID: {rfid['uuid']}")
print(f"Capacity: {rfid['used_len']}/{rfid['total_len']} bytes")
```
--------------------------------
### start_print
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/printer_client.md
Initiates a new print job on the printer. Returns true if the printer acknowledges the start of the print job.
```APIDOC
## start_print
### Description
Initiates a print job.
### Method
`async def start_print() -> bool`
### Parameters
None
### Request Example
```python
if await printer.start_print():
print("Print job started")
```
### Response
#### Success Response (200)
- **Return Value** (bool) - `True` if the printer acknowledged the start of the print job.
#### Response Example
```json
{
"example": "true | false"
}
```
```
--------------------------------
### Logging Example: DEBUG Level
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/cli_interface.md
Shows how to invoke a CLI command to trigger DEBUG level logging using the -vv flag. Output is directed to stdout and the log file.
```bash
python -m NiimPrintX.cli -vv print -i label.png
```
--------------------------------
### Send Command with Request Code Example
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/types.md
Send a command, such as a heartbeat, using RequestCodeEnum with PrinterClient.send_command().
```python
response = await printer.send_command(RequestCodeEnum.HEARTBEAT, b"\x01")
```
--------------------------------
### Batch Print Images from Directory
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/getting-started.md
Prints all PNG images found in a specified directory, with a configurable delay between each print job. Ensure the printer is connected before starting.
```python
import asyncio
from pathlib import Path
async def batch_print(image_dir, model="d110"):
device = await find_device(model)
printer = PrinterClient(device)
await printer.connect()
for image_file in Path(image_dir).glob("*.png"):
print(f"Printing {image_file.name}...")
image = Image.open(image_file)
await printer.print_image(image, quantity=1)
await asyncio.sleep(5) # Wait between jobs
await printer.disconnect()
# Usage
await batch_print("./labels")
```
--------------------------------
### start_page_print
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/printer_client.md
Begins a new page/label within the print job. The printer acknowledges the start of a new page.
```APIDOC
## start_page_print
### Description
Begins a new page/label within the print job. The printer acknowledges the start of a new page.
### Method
Asynchronous function call (Python SDK)
### Endpoint
N/A (SDK Method)
### Parameters
None
### Response
#### Success Response
- **acknowledged** (bool) - True if the printer acknowledged the start of the new page.
```
--------------------------------
### Catch PrinterException
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/errors.md
Example of catching PrinterException when required Bluetooth characteristics are not found on the printer device. Import the exception and the PrinterClient.
```python
from NiimPrintX.nimmy.exception import PrinterException
from NiimPrintX.nimmy.printer import PrinterClient
try:
await printer.find_characteristics()
except PrinterException as e:
print(f"Device not compatible: {e}")
```
--------------------------------
### Get NiimPrintX Logger Instance
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/logger.md
Returns the global loguru Logger instance for application-wide use. Allows logging messages at various levels.
```python
from NiimPrintX.nimmy.logger_config import get_logger
logger = get_logger()
logger.info("Application started")
logger.debug("Debug information")
logger.error("Error message")
```
--------------------------------
### Troubleshoot Printer Not Found (CLI)
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/getting-started.md
Uses the Niimprintx CLI to get information about a specific printer model ('b21'). This command helps verify if the printer is discoverable via Bluetooth.
```bash
# Verify device is powered on and nearby
# Check Bluetooth is enabled
# Try specific model name
python -m NiimPrintX.cli info -m b21
```
--------------------------------
### AppConfig Initialization and Usage
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/configuration.md
Demonstrates how to instantiate the AppConfig class and set key configuration properties like the selected device and label size. Ensure the AppConfig class is imported before use.
```python
from NiimPrintX.ui.AppConfig import AppConfig
config = AppConfig()
config.device = "d110"
config.current_label_size = (30, 15) # mm
```
--------------------------------
### Get Heartbeat Status Example
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/types.md
Retrieve and print paper status from the heartbeat response using PrinterClient.heartbeat(). Fields may be None depending on the printer model.
```python
status = await printer.heartbeat()
if status['paper_state'] is not None:
print(f"Paper status: {status['paper_state']}")
```
--------------------------------
### CLI Entry Point
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/module-overview.md
Run the command-line interface for NiimPrintX.
```bash
python -m NiimPrintX.cli
```
--------------------------------
### Main CLI Group Initialization
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/cli_interface.md
Sets up the main entry point for the CLI, including global options like verbosity. Initializes logger configuration and Click context.
```python
import click
@click.group()
@click.option("-v", "--verbose", count=True, default=0)
@click.pass_context
def niimbot_cli(ctx, verbose):
```
--------------------------------
### setup_logger
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/logger.md
Initializes the global logger with default INFO level. It removes existing handlers and configures output to stderr with a colored format and to a rotating file named 'nimmy.log'.
```APIDOC
## setup_logger
### Description
Initializes the global logger with default INFO level. Removes any existing handlers and configures output to stderr and a rotating file.
### Behavior:
- Sets base log level to INFO
- Writes to stderr with colored format
- Writes to `nimmy.log` with file rotation (100MB) and gzip compression
- Format: `{time} | {level} | {message}`
### Returns:
`None`
### Side Effects:
Configures global `logger` object
### Example:
```python
from NiimPrintX.nimmy.logger_config import setup_logger
setup_logger()
```
```
--------------------------------
### Initialize and Configure AppConfig
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/ui_components.md
Instantiate the AppConfig class and set device and label size properties. This is useful for setting up the application's initial state and configuration.
```python
from NiimPrintX.ui.AppConfig import AppConfig
config = AppConfig()
config.device = "d110"
config.current_label_size = config.label_sizes["d110"]["size"]["30mm x 15mm"]
```
--------------------------------
### Initialize PrinterClient
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/printer_client.md
Instantiate the PrinterClient with a discovered Bleak BLE device object. Ensure the device is found using `find_device` before initialization.
```python
from NiimPrintX.nimmy.bluetooth import find_device
from NiimPrintX.nimmy.printer import PrinterClient
import asyncio
async def main():
device = await find_device("d110")
printer = PrinterClient(device)
await printer.connect()
```
--------------------------------
### CLI Integration for Logging
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/logger.md
Shows how the logger is initialized and configured by the CLI, applying verbosity settings from command-line flags.
```python
# cli/command.py
setup_logger() # Initialize with INFO
logger_enable(ctx.obj['VERBOSE']) # Apply verbosity from -v flags
```
--------------------------------
### connect
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/ble_transport.md
Establishes a Bluetooth connection to a device by MAC address. Lazy-initializes the BleakClient on first call.
```APIDOC
## connect
### Description
Establishes a Bluetooth connection to a device by MAC address. Lazy-initializes the `BleakClient` on first call.
### Signature
```python
async def connect(self, address: str) -> bool
```
### Parameters
#### Path Parameters
- **address** (str) - Required - Device MAC address
### Returns
- `bool` - `True` if successfully connected, `False` if already connected or connection failed
### Side Effects
- Sets `self.client` to a `BleakClient` instance (if not already set)
### Example
```python
if await transport.connect("AA:BB:CC:DD:EE:FF"):
print("Connected")
```
```
--------------------------------
### Niimprintx Connection Flow with Bleak
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/protocol-reference.md
Outlines the steps for discovering, connecting to, and communicating with Niimprintx printers using the Bleak library.
```python
Discovery: BleakScanner.discover() → list of BleakDevice
Connect: BleakClient(address).connect()
Discover characteristics:
- Iterate services and characteristics
- Find characteristic with read, write-without-response, notify
- Cache characteristic UUID
Subscribe to notifications:
- client.start_notify(char_uuid, handler)
- Handler invoked for each incoming packet
Send command:
- Encode packet with to_bytes()
- client.write_gatt_char(char_uuid, bytes)
Receive response:
- Notification handler receives bytes
- Decode with NiimbotPacket.from_bytes()
- Validate checksum and markers
Close:
- client.stop_notify(char_uuid)
- client.disconnect()
```
--------------------------------
### Get Print Status
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/types.md
Retrieves the current status of a print job. The status includes the current page and progress indicators.
```python
status = await printer.get_print_status()
print(f"Page {status['page']}: {status['progress1']}% done")
```
--------------------------------
### Get Print Status
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/types.md
Retrieves the current status of the ongoing print job. This includes the current page number and progress indicators.
```APIDOC
## Get Print Status
### Description
Retrieves the current status of the ongoing print job, including the current page number and progress indicators.
### Method
`PrinterClient.get_print_status()`
### Parameters
None
### Response
#### Success Response
A dictionary containing the print status:
- **page** (int) - Current page number being printed.
- **progress1** (int) - Primary progress percentage or step (0-255).
- **progress2** (int) - Secondary progress indicator (0-255).
### Request Example
```python
status = await printer.get_print_status()
print(f"Page {status['page']}: {status['progress1']}% done")
```
### Response Example
```json
{
"page": 5,
"progress1": 128,
"progress2": 64
}
```
```
--------------------------------
### Async/Await for Bluetooth Operations
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/README.md
Demonstrates the asynchronous pattern used for all Bluetooth operations, including device discovery, connection, printing, and disconnection.
```python
async def main():
device = await find_device("d110")
await printer.connect()
await printer.print_image(image)
await printer.disconnect()
asyncio.run(main())
```
--------------------------------
### CLI Options
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt
Documentation covers 8 print-related options and 1 info-related option for the CLI.
```APIDOC
## CLI Options
### Description
Options available for CLI commands.
### Options
- **Print Options**: 8 options documented for the 'print' command.
- **Info Options**: 1 option documented for the 'info' command.
These options are completely documented.
```
--------------------------------
### NiimbotPacket.to_bytes
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/niimbot_packet.md
Serializes the NiimbotPacket instance into a binary format suitable for transmission. The format includes start and end markers, type, length, data, and a checksum.
```APIDOC
## NiimbotPacket.to_bytes
### Description
Serializes the NiimbotPacket instance into a binary format suitable for transmission. The format includes start and end markers, type, length, data, and a checksum.
### Method
```python
def to_bytes(self) -> bytes
```
### Endpoint
N/A (Instance method)
### Response
#### Success Response
- **bytes** - Complete binary packet ready for transmission
### Request Example
```python
pkt = NiimbotPacket(0x40, bytes([1]))
binary = pkt.to_bytes()
# Result: b'\x55\x55\x40\x01\x01\x40\xaa\xaa'
```
```
--------------------------------
### PrinterClient Constructor
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/printer_client.md
Initializes a new PrinterClient instance. It requires a BleakDevice object to establish a connection.
```APIDOC
## PrinterClient Constructor
### Description
Initializes a new `PrinterClient` instance. It requires a `BleakDevice` object to establish a connection.
### Parameters
#### Path Parameters
- **device** (BleakDevice) - Required - A Bleak BLE device object from device discovery
### Request Example
```python
from NiimPrintX.nimmy.bluetooth import find_device
from NiimPrintX.nimmy.printer import PrinterClient
import asyncio
async def main():
device = await find_device("d110")
printer = PrinterClient(device)
await printer.connect()
```
```
--------------------------------
### Start BLE Notifications
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/ble_transport.md
Subscribes to notifications from a GATT characteristic. A handler function is called for each received notification. Requires an active connection and raises BLEException if not connected.
```python
def on_notify(sender, data):
print(f"Received: {data.hex()}")
await transport.start_notification("12345678-1234-1234-1234-123456789012", on_notify)
```
--------------------------------
### Run NiimPrintX GUI Application
Source: https://github.com/labbots/niimprintx/blob/main/README.md
Command to launch the Graphical User Interface (GUI) application for NiimPrintX.
```shell
python -m NiimPrintX.ui
```
--------------------------------
### CLI: Print Image with Default Settings
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/README.md
Prints a label using the default printer and settings. Requires a 'label.png' file.
```bash
# Default settings
python -m NiimPrintX.cli print -i label.png
```
--------------------------------
### Set Label Dimensions
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/printer_client.md
Sets the dimensions of the label to be printed in pixels. Use this before starting a print job to define the label size. Returns True if the printer acknowledged the request.
```python
async def set_dimension(w: int, h: int) -> bool
```
```python
await printer.set_dimension(240, 400)
```
--------------------------------
### Print an Image with Defaults
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/INDEX.md
Connect to a specified printer model, open an image file, and print it with default density and quantity. Ensure to disconnect after the operation.
```python
from NiimPrintX.nimmy.printer import PrinterClient
from NiimPrintX.nimmy.bluetooth import find_device
from PIL import Image
device = await find_device("d110")
printer = PrinterClient(device)
await printer.connect()
image = Image.open("label.png")
await printer.print_image(image, density=3, quantity=1)
await printer.disconnect()
```
--------------------------------
### Get Print Status
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/printer_client.md
Retrieves the current print progress, including the page number and two progress metrics. The return structure is a dictionary containing 'page', 'progress1', and 'progress2'.
```python
async def get_print_status() -> dict
```
```python
{
"page": int, # Current page number
"progress1": int, # Progress metric 1
"progress2": int # Progress metric 2
}
```
```python
status = await printer.get_print_status()
print(f"Page {status['page']} Progress: {status['progress1']}")
```
--------------------------------
### Initialize NiimPrintX Logger
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/logger.md
Initializes the global logger with default INFO level. Removes existing handlers and configures output to stderr and a rotating file.
```python
from NiimPrintX.nimmy.logger_config import setup_logger
setup_logger()
```
--------------------------------
### Print Command with Custom Settings
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/cli_interface.md
Prints a label image with custom settings for model, density, quantity, and image file. Density is capped for certain models.
```bash
python -m NiimPrintX.cli print -m d110 -d 3 -n 2 -i label.png
```
--------------------------------
### heartbeat
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/printer_client.md
Polls the printer to get its current status, including closing state, power level, paper state, and RFID read state. The availability and format of some fields may vary by printer model.
```APIDOC
## heartbeat
### Description
Polls the device for its current status. The response may vary depending on the printer model, and some fields might be null.
### Method
`async def heartbeat() -> dict`
### Parameters
None
### Request Example
```python
status = await printer.heartbeat()
print(f"Power: {status['power_level']}")
print(f"Paper: {status['paper_state']}")
```
### Response
#### Success Response (200)
- **Return Value** (dict) - Dictionary with keys: `closing_state`, `power_level`, `paper_state`, `rfid_read_state`. Values are integers or `None`.
#### Response Example
```json
{
"closing_state": "integer | null",
"power_level": "integer | null",
"paper_state": "integer | null",
"rfid_read_state": "integer | null"
}
```
```
--------------------------------
### Configure Logging Level (Python API)
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/getting-started.md
Sets up and enables detailed logging for the Niimprintx library using its Python API. Use TRACE level (3) for the most verbose output during debugging.
```python
from NiimPrintX.nimmy.logger_config import setup_logger, logger_enable
setup_logger()
logger_enable(3) # TRACE level (most verbose)
# Now run your code
```
--------------------------------
### Get Device Information
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/printer_client.md
Retrieves specific device information based on the provided InfoEnum key. The return type varies depending on the key requested (e.g., string for serial, float for versions, int for others).
```python
from NiimPrintX.nimmy.printer import InfoEnum
serial = await printer.get_info(InfoEnum.DEVICESERIAL)
fw_version = await printer.get_info(InfoEnum.SOFTVERSION)
battery = await printer.get_info(InfoEnum.BATTERY)
print(f"Serial: {serial}")
print(f"Firmware: {fw_version}")
print(f"Battery: {battery}")
```
--------------------------------
### Get Data from Cache or Compute if Missing/Expired
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/ui_components.md
This method efficiently retrieves data by first checking the cache. If the data is not found or has expired, it computes the data using the provided function and then caches it. Useful for data that is expensive to generate.
```python
def scan_fonts():
return get_system_fonts()
fonts = cache_manager.get_data(
"fonts.pkl",
scan_fonts,
expiration_sec=86400 # 24 hours
)
```
--------------------------------
### Info Command with Verbose Logging
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/cli_interface.md
Retrieves device information with high verbosity (TRACE level) using -vvv. This provides detailed logs during the discovery and connection process.
```bash
python -m NiimPrintX.cli -vvv info -m d110
```
--------------------------------
### CLI Commands
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt
The CLI module includes documentation for the 'print' and 'info' commands.
```APIDOC
## CLI Commands
### Description
Provides command-line interface functionalities.
### Commands
- **print**: Command to initiate printing operations.
- **info**: Command to retrieve information about the printer or system.
These commands are completely documented.
```
--------------------------------
### Helper Functions
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt
Utility functions for device discovery and enumeration.
```APIDOC
## Helper Functions
### `find_device(name_or_address)`
**Description:**
Scans for a Bluetooth device by its name or MAC address and returns its details if found.
### `scan_devices()`
**Description:**
Enumerates all available Bluetooth devices within range and returns a list of their details.
```
--------------------------------
### BLETransport Constructor
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/ble_transport.md
Initializes a BLETransport instance. Optionally connects to a device if an address is provided.
```APIDOC
## BLETransport Constructor
### Description
Initializes a BLETransport instance. Optionally connects to a device if an address is provided.
### Signature
```python
def __init__(self, address: str | None = None)
```
### Parameters
#### Path Parameters
- **address** (str) - Optional - Device MAC address for context manager auto-connect
### Returns
- `BLETransport` instance
### Example
```python
from NiimPrintX.nimmy.bluetooth import BLETransport
transport = BLETransport("AA:BB:CC:DD:EE:FF")
```
```
--------------------------------
### Define Device Information Query Keys
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/types.md
Use InfoEnum for device information query keys when calling PrinterClient.get_info().
```python
class InfoEnum(enum.IntEnum):
DENSITY = 1
PRINTSPEED = 2
LABELTYPE = 3
LANGUAGETYPE = 6
AUTOSHUTDOWNTIME = 7
DEVICETYPE = 8
SOFTVERSION = 9
BATTERY = 10
DEVICESERIAL = 11
HARDVERSION = 12
```
--------------------------------
### Handling Bluetooth Exceptions
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/README.md
Demonstrates how to catch and handle BLEException when a device cannot be found. This is useful for gracefully managing connection errors.
```python
from NiimPrintX.nimmy.exception import BLEException, PrinterException
try:
device = await find_device("d110")
except BLEException as e:
print(f"Device not found: {e}")
```
--------------------------------
### Print Workflow - High Level
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/module-overview.md
High-level overview of the print job process from user input to print completion.
```text
User provides image
Image validation & processing
Printer discovery (Bluetooth scan)
Device connection (BLE)
PrinterClient.print_image()
├─ Set print parameters (density, quantity)
├─ Encode image to monochrome
├─ Transform image (rotate, offset)
├─ Transmit image scanlines via NiimbotPacket
├─ Monitor print progress
Close connection
Print job complete
```
--------------------------------
### Configure Label Size
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/module-overview.md
Sets the device and current label size using the AppConfig object. Ensure the specified device and label size exist in the configuration.
```python
config.device = "d110"
config.current_label_size = config.label_sizes[config.device]["size"]["30mm x 15mm"]
```
--------------------------------
### Import PrinterClient
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/module-overview.md
Import the main printer control interface from the nimmy module.
```python
from NiimPrintX.nimmy.printer import PrinterClient
```
--------------------------------
### Connect to BLE Device
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/ble_transport.md
Establishes a Bluetooth connection to a specified device MAC address. This method lazily initializes the BleakClient. Returns True on successful connection, False otherwise.
```python
if await transport.connect("AA:BB:CC:DD:EE:FF"):
print("Connected")
```
--------------------------------
### CLI: Print Image with Custom Parameters
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/README.md
Prints a label using a specified printer model ('b21'), density ('4'), quantity ('2'), rotation ('90'), and image file ('label.png').
```bash
# Custom printer and parameters
python -m NiimPrintX.cli print -m b21 -d 4 -n 2 -r 90 -i label.png
```
--------------------------------
### connect
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/printer_client.md
Establishes a Bluetooth connection to the printer. It automatically discovers device characteristics on the first connection.
```APIDOC
## connect
### Description
Establishes a Bluetooth connection to the printer. Automatically discovers device characteristics on first connection.
### Method
async def connect() -> bool
### Returns
`bool` — `True` if connection successful, `False` otherwise
### Raises
- `PrinterException` — if Bluetooth characteristics cannot be found after connection
### Request Example
```python
printer = PrinterClient(device)
if await printer.connect():
print(f"Connected to {device.name}")
else:
print("Connection failed")
```
```
--------------------------------
### Python API: Basic Print Job
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/module-overview.md
Demonstrates a typical print job using the Python API. This includes discovering a device, connecting, retrieving serial information, printing an image, and disconnecting.
```python
from NiimPrintX.nimmy.bluetooth import find_device
from NiimPrintX.nimmy.printer import PrinterClient, InfoEnum
from PIL import Image
import asyncio
async def main():
# Discover device
device = await find_device("d110")
# Create client and connect
printer = PrinterClient(device)
await printer.connect()
# Get device info
serial = await printer.get_info(InfoEnum.DEVICESERIAL)
print(f"Serial: {serial}")
# Print image
image = Image.open("label.png")
await printer.print_image(image, density=3, quantity=1)
# Cleanup
await printer.disconnect()
asyncio.run(main())
```
--------------------------------
### Batch Printing Multiple Images Sequentially
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/advanced-usage.md
Use this pattern to print a list of images to a single printer, with a delay between each job. Ensure the 'NiimPrintX.nimmy.bluetooth' and 'NiimPrintX.nimmy.printer' modules are imported, along with 'PIL.Image'.
```python
import asyncio
from NiimPrintX.nimmy.bluetooth import find_device
from NiimPrintX.nimmy.printer import PrinterClient
from PIL import Image
async def batch_print(model="d110", images=None):
"""Print multiple images in sequence."""
if not images:
return
device = await find_device(model)
printer = PrinterClient(device)
if not await printer.connect():
raise RuntimeError("Failed to connect")
try:
for image_path, quantity in images:
print(f"Printing {image_path}...")
image = Image.open(image_path)
await printer.print_image(image, quantity=quantity)
await asyncio.sleep(2) # Delay between jobs
finally:
await printer.disconnect()
# Usage
images = [
("label1.png", 1),
("label2.png", 3),
("label3.png", 2),
]
await batch_print("d110", images)
```
--------------------------------
### Initialize BLETransport
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/ble_transport.md
Instantiate the BLETransport class, optionally providing the device MAC address for auto-connection when used as a context manager.
```python
from NiimPrintX.nimmy.bluetooth import BLETransport
transport = BLETransport("AA:BB:CC:DD:EE:FF")
```
--------------------------------
### PrintOption Constructor
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/ui_components.md
Initializes the PrintOption widget, which controls printer operations and displays live connection status. It sets up the UI elements for managing the printer connection and print jobs.
```APIDOC
## PrintOption
### Description
Widget controlling print operations with live connection status.
### Constructor
```python
def __init__(self, root, parent: tk.Widget, config: AppConfig)
```
### Parameters
#### Arguments
- **root** (Tk) - Required - Main application window
- **parent** (tk.Widget) - Required - Parent container
- **config** (AppConfig) - Required - Application config
### Buttons Created
- "Connect/Disconnect" — Toggles printer connection
- "Save Image" — Exports canvas to image file
- "Print" — Sends image to connected printer
### Side Effects
Starts automatic heartbeat polling every 5 seconds
```
--------------------------------
### Clone NiimPrintX Repository
Source: https://github.com/labbots/niimprintx/blob/main/README.md
Clone the NiimPrintX repository to your local machine.
```shell
git clone https://github.com/labbots/NiimPrintX.git
cd NiimPrintX
```
--------------------------------
### NiimPrintX CLI Info Command Usage
Source: https://github.com/labbots/niimprintx/blob/main/README.md
Details the options available for the 'info' command in the NiimPrintX CLI.
```shell
Usage: python -m NiimPrintX.cli info [OPTIONS]
Options:
-m, --model [b1|b18|b21|d11|d110]
Niimbot printer model [default: d110]
-h, --help Show this message and exit.
```
--------------------------------
### Create NiimbotPacket Instance
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/niimbot_packet.md
Instantiates a NiimbotPacket object with a specified type and data payload. Use this to prepare commands or responses for NiimBot devices.
```python
from NiimPrintX.nimmy.packet import NiimbotPacket
pkt = NiimbotPacket(0x01, b"\x01") # START_PRINT command
```
--------------------------------
### Info Command Default Usage
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/cli_interface.md
Retrieves device information from a NiimBot printer using the default 'd110' model. Prints serial, software, and hardware versions to stdout.
```bash
python -m NiimPrintX.cli info
```
--------------------------------
### Connect to Printer
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/printer_client.md
Establishes a Bluetooth connection to the printer. This method automatically discovers necessary device characteristics upon the first connection.
```python
printer = PrinterClient(device)
if await printer.connect():
print(f"Connected to {device.name}")
else:
print("Connection failed")
```
--------------------------------
### Async Context Manager for Printer Connection
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/advanced-usage.md
Use this async context manager to ensure a printer connection is properly established and disconnected, even if errors occur. It simplifies resource management for printer operations.
```python
import asyncio
from contextlib import asynccontextmanager
from NiimPrintX.nimmy.bluetooth import find_device
from NiimPrintX.nimmy.printer import PrinterClient
@asynccontextmanager
async def get_printer(model="d110"):
"""Async context manager for printer connection."""
device = await find_device(model)
printer = PrinterClient(device)
try:
await printer.connect()
yield printer
finally:
await printer.disconnect()
# Usage
async with get_printer("d110") as printer:
# Printer is connected
await printer.print_image(image)
# Automatic cleanup on exit
```
--------------------------------
### Basic Image Printing with PrinterClient
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/README.md
Connects to a printer, prints a specified image with custom density and quantity, and then disconnects. Ensure you have a 'label.png' file in the same directory.
```python
import asyncio
from PIL import Image
from NiimPrintX.nimmy.bluetooth import find_device
from NiimPrintX.nimmy.printer import PrinterClient
async def main():
device = await find_device("d110")
printer = PrinterClient(device)
await printer.connect()
image = Image.open("label.png")
await printer.print_image(image, density=3, quantity=1)
await printer.disconnect()
asyncio.run(main())
```
--------------------------------
### PrinterClient Methods
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt
The PrinterClient class provides a complete interface for interacting with printers, with all 21 methods fully documented.
```APIDOC
## PrinterClient Class
### Description
Provides a complete interface for interacting with printers.
### Methods
All 21 methods are fully documented.
### Example Usage
```python
# Example of how to instantiate and use PrinterClient
from nimmy import PrinterClient
client = PrinterClient()
# ... use client methods ...
```
```
--------------------------------
### Print Command Basic Usage
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/cli_interface.md
Prints a label image using a NiimBot printer. Requires the image file path. Defaults to 'd110' model and density 3.
```bash
python -m NiimPrintX.cli print -i label.png
```
--------------------------------
### AppConfig
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/ui_components.md
Manages configuration and application state for the NiimPrintX GUI. It holds settings related to the operating system, screen DPI, canvas items, device selection, label sizes, and printer connection status.
```APIDOC
## AppConfig
### Description
Configuration and application state container for the GUI.
### Constructor
```python
def __init__(self)
```
### Attributes
- **os_system** (str) - Operating system ("Windows", "Darwin", "Linux")
- **screen_dpi** (int) - Screen DPI (detected from canvas)
- **text_items** (dict) - Text objects on canvas
- **image_items** (dict) - Image objects on canvas
- **current_selected** (object) - Active text item
- **current_selected_image** (object) - Active image item
- **current_dir** (str) - UI module directory path
- **icon_folder** (str) - Icon assets directory
- **canvas** (object) - Canvas widget reference
- **bounding_box** (object) - Selection rectangle
- **device** (str) - Selected printer model (e.g., "d110")
- **label_sizes** (dict) - Model → {size_names, density, print_dpi}
- **current_label_size** (tuple) - (width_mm, height_mm)
- **frames** (dict) - Tkinter Frame references
- **print_job** (bool) - Is print operation active
- **printer_connected** (bool) - Is printer connected
- **cache_dir** (str) - User cache directory for app data
### Example
```python
from NiimPrintX.ui.AppConfig import AppConfig
config = AppConfig()
config.device = "d110"
config.current_label_size = config.label_sizes["d110"]["size"]["30mm x 15mm"]
```
```
--------------------------------
### get_info
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/printer_client.md
Retrieves specific device information based on the provided key. The return type of the information (string, float, or integer) depends on the requested key.
```APIDOC
## get_info
### Description
Retrieves specific device information. The type of the returned value depends on the `key` parameter provided.
### Method
`async def get_info(key: InfoEnum) -> int | float | str`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **key** (InfoEnum) - Required - Information type to retrieve.
### Request Example
```python
from NiimPrintX.nimmy.printer import InfoEnum
serial = await printer.get_info(InfoEnum.DEVICESERIAL)
fw_version = await printer.get_info(InfoEnum.SOFTVERSION)
battery = await printer.get_info(InfoEnum.BATTERY)
print(f"Serial: {serial}")
print(f"Firmware: {fw_version}")
print(f"Battery: {battery}")
```
### Response
#### Success Response (200)
- **Return Value** (int | float | str) - Device information. Returns `str` for `DEVICESERIAL`, `float` for `SOFTVERSION` and `HARDVERSION`, and `int` for all other keys.
#### Response Example
```json
{
"example": "string | float | int"
}
```
### Returns
- `str` for `DEVICESERIAL` (hex-encoded bytes)
- `float` for `SOFTVERSION` and `HARDVERSION` (value divided by 100)
- `int` for all other keys
```
--------------------------------
### Print with Custom Parameters (Python API)
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/getting-started.md
Print an image using the Python API with custom parameters such as density, quantity, and offsets. Ensure the printer is connected before sending the print job.
```python
async def main():
device = await find_device("d110")
printer = PrinterClient(device)
await printer.connect()
image = Image.open("label.png")
await printer.print_image(
image,
density=3, # Print darkness
quantity=2, # Number of copies
vertical_offset=10,
horizontal_offset=5
)
await printer.disconnect()
asyncio.run(main())
```
--------------------------------
### Initialize Print Option Widget
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/ui_components.md
Initializes the PrintOption widget, which controls printer operations and displays live connection status. It requires the root Tk window, a parent widget, and application configuration.
```python
def __init__(self, root, parent: tk.Widget, config: AppConfig)
```
--------------------------------
### Protocol State Machine
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt
The protocol documentation includes a complete description of the state machine.
```APIDOC
## Protocol Specification
### State Machine
### Description
Describes the state machine governing the protocol's operation.
This section is completely documented.
```
--------------------------------
### NiimPrintX CLI Print Command Usage
Source: https://github.com/labbots/niimprintx/blob/main/README.md
Details the options available for the 'print' command in the NiimPrintX CLI.
```shell
Usage: python -m NiimPrintX.cli print [OPTIONS]
Options:
-m, --model [b1|b18|b21|d11|d11_h|d110]
Niimbot printer model [default: d110]
-d, --density INTEGER RANGE Print density [default: 3; 1<=x<=5]
-n, --quantity INTEGER Print quantity [default: 1]
-r, --rotate [0|90|180|270] Image rotation (clockwise) [default: 0]
--vo INTEGER Vertical offset in pixels [default: 0]
--ho INTEGER Horizontal offset in pixels [default: 0]
-i, --image PATH Image path [required]
-h, --help Show this message and exit.
```
--------------------------------
### Dynamic Image Generation for Printing
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/advanced-usage.md
Generate images on-the-fly using PIL (Pillow) before sending them to the printer. This involves creating a function to generate the image content and then using the printer client to print it.
```python
import asyncio
from PIL import Image, ImageDraw, ImageFont
from NiimPrintX.nimmy.bluetooth import find_device
from NiimPrintX.nimmy.printer import PrinterClient
def create_label(text, width=240, height=100):
"""Generate a simple label image."""
img = Image.new("RGB", (width, height), color="white")
draw = ImageDraw.Draw(img)
# Simple text rendering
draw.text((10, 40), text, fill="black")
return img
async def print_generated_label(text, model="d110"):
"""Generate and print a label."""
device = await find_device(model)
printer = PrinterClient(device)
await printer.connect()
try:
image = create_label(text)
await printer.print_image(image)
finally:
await printer.disconnect()
# Usage
await print_generated_label("QR: ABC123", "d110")
```
--------------------------------
### Perform Custom Image Preprocessing for Printing
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/advanced-usage.md
Optimize image quality and compatibility for printing by applying transformations like resizing, grayscale conversion, and contrast enhancement. This function requires `PIL` (Pillow) and `NiimPrintX.nimmy.bluetooth`, `NiimPrintX.nimmy.printer` for the printing process.
```python
import asyncio
from PIL import Image, ImageOps
from NiimPrintX.nimmy.bluetooth import find_device
from NiimPrintX.nimmy.printer import PrinterClient
def preprocess_image(image_path, target_width=240):
"""Preprocess image for printing."""
img = Image.open(image_path)
# Resize to fit printer width
if img.width > target_width:
ratio = target_width / img.width
new_height = int(img.height * ratio)
img = img.resize((target_width, new_height), Image.Resampling.LANCZOS)
# Convert to grayscale for better print quality
img = img.convert("L")
# Enhance contrast
img = ImageOps.autocontrast(img)
return img
async def print_optimized(image_path, model="d110"):
"""Print with optimized preprocessing."""
device = await find_device(model)
printer = PrinterClient(device)
await printer.connect()
try:
image = preprocess_image(image_path)
await printer.print_image(image, density=3)
finally:
await printer.disconnect()
# Usage
await print_optimized("raw_label.jpg", "d110")
```
--------------------------------
### NiimPrintX CLI General Usage
Source: https://github.com/labbots/niimprintx/blob/main/README.md
Displays the general usage information for the NiimPrintX Command-Line Interface (CLI).
```shell
Usage: python -m NiimPrintX.cli [OPTIONS] COMMAND [ARGS]...
Options:
-v, --verbose Enable verbose logging
-h, --help Show this message and exit.
Commands:
info
print
```
--------------------------------
### Protocol Command Codes
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt
Documentation lists and explains 13 distinct command codes used in the protocol.
```APIDOC
## Protocol Specification
### Command Codes
### Description
Lists and explains the 13 command codes utilized within the protocol.
This section is completely documented.
```
--------------------------------
### Bluetooth Helpers
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt
Utility functions for Bluetooth operations, including finding and scanning for devices, are fully documented.
```APIDOC
## Bluetooth Helpers
### Description
Provides utility functions for Bluetooth operations.
### Functions
- **find_device**: Finds a specific Bluetooth device.
- **scan_devices**: Scans the environment for available Bluetooth devices.
These functions are completely documented.
```
--------------------------------
### start_notification
Source: https://github.com/labbots/niimprintx/blob/main/_autodocs/api-reference/ble_transport.md
Subscribes to notifications from a GATT characteristic. Invokes a handler for each notification received.
```APIDOC
## start_notification
### Description
Subscribes to notifications from a GATT characteristic. Invokes `handler` for each notification received.
### Signature
```python
async def start_notification(self, char_uuid: str, handler: Callable[[Any, bytes], None]) -> None
```
### Parameters
#### Path Parameters
- **char_uuid** (str) - Required - GATT characteristic UUID
- **handler** (Callable) - Required - Callback function: `handler(sender, data: bytes)`
### Returns
- `None`
### Raises
- `BLEException` if not connected
### Example
```python
def on_notify(sender, data):
print(f"Received: {data.hex()}")
await transport.start_notification("12345678-1234-1234-1234-123456789012", on_notify)
```
```