1
0
mirror of https://github.com/python-escpos/python-escpos synced 2025-09-13 09:09:58 +00:00

Separate method open() and constructor, enhance consistency between connectors. (#584)

* Add self-open mechanism
* self-open mechanism through the 'device' property
* Separate open() and store connection in 'device'
* Restore device status to False on close()
* Add default value to all params + type annotations
* Add generic DeviceNotFoundError exception
* Update USBNotFoundError return code
* Enhance connectors consistency
* Fix LP printer stall
* Fix LP waste of paper due to auto-flush + flush on close
* Move platform dependent printers' guard to init

---------

Co-authored-by: Patrick Kanzler <4189642+patkan@users.noreply.github.com>
This commit is contained in:
Benito López
2023-10-16 11:36:07 +02:00
committed by GitHub
parent 3a8af8a6f5
commit a00b98937b
10 changed files with 537 additions and 179 deletions

View File

@@ -14,7 +14,7 @@ This module contains the abstract base class :py:class:`Escpos`.
import textwrap
from abc import ABCMeta, abstractmethod # abstract base class support
from re import match as re_match
from typing import List, Optional, Union
from typing import List, Literal, Optional, Union
import barcode
import qrcode
@@ -114,7 +114,11 @@ class Escpos(object):
class.
"""
device = None
# device status:
# False -> Not initialized
# None -> Initialized but not connected
# object -> The connection object (Usb(), Serial(), Network(), etc.)
_device: Union[Literal[False], Literal[None], object] = False
def __init__(self, profile=None, magic_encode_args=None, **kwargs) -> None:
"""Initialize ESCPOS Printer.
@@ -128,6 +132,27 @@ class Escpos(object):
"""Call self.close upon deletion."""
self.close()
@property
def device(self) -> Union[Literal[None], object]:
"""Implements a self-open mechanism.
An attempt to get the property before open the connection
will cause the connection to open.
"""
if self._device is False:
# Open device if not previously opened
self._device = None # None -> Initialized
self.open()
return self._device
@device.setter
def device(self, new_device: Union[Literal[False], Literal[None], object]):
self._device = new_device
def open(self):
"""Open a printer device/connection."""
pass
@abstractmethod
def _raw(self, msg: bytes) -> None:
"""Send raw data to the printer.