diff --git a/src/escpos/capabilities.py b/src/escpos/capabilities.py index 1a253da..ce67682 100644 --- a/src/escpos/capabilities.py +++ b/src/escpos/capabilities.py @@ -77,11 +77,13 @@ class BaseProfile(object): profile_data: Dict[str, Any] = {} def __getattr__(self, name): + """Get a data element from the profile.""" return self.profile_data[name] def get_font(self, font) -> int: - """Return the escpos index for `font`. Makes sure that - the requested `font` is valid. + """Return the escpos index for `font`. + + Makes sure that the requested `font` is valid. """ font = {"a": 0, "b": 1}.get(font, font) if not six.text_type(font) in self.fonts: @@ -105,8 +107,9 @@ class BaseProfile(object): def get_profile(name: str = None, **kwargs): - """Get the profile by name; if no name is given, return the - default profile. + """Get a profile by name. + + If no name is given, return the default profile. """ if isinstance(name, Profile): return name @@ -119,7 +122,9 @@ CLASS_CACHE = {} def get_profile_class(name: str): - """For the given profile name, load the data from the external + """Load a profile class. + + For the given profile name, load the data from the external database, then generate dynamically a class. """ if name not in CLASS_CACHE: @@ -133,6 +138,7 @@ def get_profile_class(name: str): def clean(s): + """Clean profile name.""" # Remove invalid characters s = re.sub("[^0-9a-zA-Z_]", "", s) # Remove leading characters until we find a letter or underscore @@ -141,17 +147,20 @@ def clean(s): class Profile(get_profile_class("default")): - """ - For users, who want to provide their profile + """Profile class for user usage. + + For users, who want to provide their own profile. """ def __init__(self, columns=None, features=None): + """Initialize profile.""" super(Profile, self).__init__() self.columns = columns self.features = features or {} def get_columns(self, font): + """Get column count of printer.""" if self.columns is not None: return self.columns diff --git a/src/escpos/cli.py b/src/escpos/cli.py index 01049bf..321fa01 100644 --- a/src/escpos/cli.py +++ b/src/escpos/cli.py @@ -26,8 +26,10 @@ from . import config, version # Must be defined before it's used in DEMO_FUNCTIONS def str_to_bool(string): - """Used as a type in argparse so that we get back a proper - bool instead of always True + """Convert string to Bool. + + Used as a type in argparse so that we get back a proper + bool instead of always True. """ return string.lower() in ("y", "yes", "1", "true") @@ -453,13 +455,11 @@ ESCPOS_COMMANDS = [ def main(): - """ + """Handle main entry point of CLI script. Handles loading of configuration and creating and processing of command line arguments. Called when run from a CLI. - """ - parser = argparse.ArgumentParser( description="CLI for python-escpos", epilog="Printer configuration is defined in the python-escpos config" @@ -570,8 +570,9 @@ def main(): def demo(printer, **kwargs): - """ - Prints demos. Called when CLI is passed `demo`. This function + """Print demos. + + Called when CLI is passed `demo`. This function uses the DEMO_FUNCTIONS dictionary. :param printer: A printer from escpos.printer diff --git a/src/escpos/codepages.py b/src/escpos/codepages.py index b3f7720..90acd62 100644 --- a/src/escpos/codepages.py +++ b/src/escpos/codepages.py @@ -1,25 +1,31 @@ +"""Helper module for codepage handling.""" from .capabilities import CAPABILITIES class CodePageManager: - """Holds information about all the code pages (as defined - in escpos-printer-db). + """Holds information about all the code pages. + + Information as defined in escpos-printer-db. """ def __init__(self, data): + """Initialize codepage manager.""" self.data = data def get_all(self): + """Get list of all codepages.""" return self.data.values() @staticmethod def get_encoding_name(encoding): """Get encoding name. - .. todo:: Resolve the encoding alias.""" + .. todo:: Resolve the encoding alias. + """ return encoding.upper() def get_encoding(self, encoding): + """Return the endocing data.""" return self.data[encoding] diff --git a/src/escpos/config.py b/src/escpos/config.py index 380c956..8649dae 100644 --- a/src/escpos/config.py +++ b/src/escpos/config.py @@ -1,10 +1,7 @@ -""" ESC/POS configuration manager. +"""ESC/POS configuration manager. This module contains the implementations of abstract base class :py:class:`Config`. - """ - - import os import appdirs @@ -48,13 +45,11 @@ class Config(object): self._printer_config = None def load(self, config_path=None): - """Load and parse the configuration file using pyyaml + """Load and parse the configuration file using pyyaml. :param config_path: An optional file path, file handle, or byte string for the configuration file. - """ - self._reset_config() if not config_path: @@ -96,8 +91,9 @@ class Config(object): self._has_loaded = True def printer(self): - """Returns a printer that was defined in the config, or throws an - exception. + """Return a printer that was defined in the config. + + Throw an exception on error. This method loads the default config if one hasn't beeen already loaded. diff --git a/src/escpos/escpos.py b/src/escpos/escpos.py index 7e07420..cb1427d 100644 --- a/src/escpos/escpos.py +++ b/src/escpos/escpos.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -*- coding: utf-8 -*- -"""Main class +"""Main class. This module contains the abstract base class :py:class:`Escpos`. @@ -107,7 +107,7 @@ SW_BARCODE_NAMES = { @six.add_metaclass(ABCMeta) class Escpos(object): - """ESC/POS Printer object + """ESC/POS Printer object. This class is the abstract base class for an esc/pos-printer. The printer implementations are children of this class. @@ -116,19 +116,20 @@ class Escpos(object): device = None def __init__(self, profile=None, magic_encode_args=None, **kwargs): - """Initialize ESCPOS Printer + """Initialize ESCPOS Printer. - :param profile: Printer profile""" + :param profile: Printer profile + """ self.profile = get_profile(profile) self.magic = MagicEncode(self, **(magic_encode_args or {})) def __del__(self): - """call self.close upon deletion""" + """Call self.close upon deletion.""" self.close() @abstractmethod def _raw(self, msg): - """Sends raw data to the printer + """Send raw data to the printer. This function has to be individually implemented by the implementations. @@ -138,7 +139,9 @@ class Escpos(object): pass def _read(self): - """Returns a NotImplementedError if the instance of the class doesn't override this method. + """Read from printer. + + Returns a NotImplementedError if the instance of the class doesn't override this method. :raises NotImplementedError """ raise NotImplementedError() @@ -152,7 +155,7 @@ class Escpos(object): fragment_height=960, center=False, ): - """Print an image + """Print an image. You can select whether the printer should print in high density or not. The default value is high density. When printing in low density, the image will be stretched. @@ -259,8 +262,7 @@ class Escpos(object): self._raw(b"".join(outp)) def _image_send_graphics_data(self, m, fn, data): - """ - Wrapper for GS ( L, to calculate and send correct data length. + """Calculate and send correct data length for `GS ( L`. :param m: Modifier//variant for function. Usually '0' :param fn: Function number to use, as byte @@ -279,7 +281,7 @@ class Escpos(object): center=False, impl="bitImageRaster", ): - """Print QR Code for the provided string + """Print QR Code for the provided string. :param content: The content of the code. Numeric data will be more efficiently compacted. :param ec: Error-correction level to use. One of QR_ECLEVEL_L (default), QR_ECLEVEL_M, QR_ECLEVEL_Q or @@ -352,7 +354,7 @@ class Escpos(object): self._send_2d_code_data(six.int2byte(81), cn, b"", b"0") def _send_2d_code_data(self, fn, cn, data, m=b""): - """Wrapper for GS ( k, to calculate and send correct data length. + """Calculate and send correct data length for`GS ( k`. :param fn: Function to use. :param cn: Output code type. Affects available data. @@ -387,7 +389,7 @@ class Escpos(object): return outp def charcode(self, code="AUTO"): - """Set Character Code Table + """Set Character Code Table. Sets the control sequence from ``CHARCODE`` in :py:mod:`escpos.constants` as active. It will be sent with the next text sequence. If you set the variable code to ``AUTO`` it will try to automatically guess the @@ -741,7 +743,7 @@ class Escpos(object): font_size=10, center=True, ): - """Print Barcode + """Print Barcode. This method allows to print barcodes. The rendering of the barcode is done by the `barcode` library and sent to the printer as image through one of the @@ -825,7 +827,7 @@ class Escpos(object): self.image(image, impl=impl, center=center) def text(self, txt): - """Print alpha-numeric text + """Print alpha-numeric text. The text has to be encoded in the currently selected codepage. The input text has to be encoded in unicode. @@ -837,7 +839,7 @@ class Escpos(object): self.magic.write(txt) def textln(self, txt=""): - """Print alpha-numeric text with a newline + """Print alpha-numeric text with a newline. The text has to be encoded in the currently selected codepage. The input text has to be encoded in unicode. @@ -848,7 +850,7 @@ class Escpos(object): self.text("{}\n".format(txt)) def ln(self, count=1): - """Print a newline or more + """Print a newline or more. :param count: number of newlines to print :raises: :py:exc:`ValueError` if count < 0 @@ -859,7 +861,7 @@ class Escpos(object): self.text("\n" * count) def block_text(self, txt, font="0", columns=None): - """Text is printed wrapped to specified columns + """Print text wrapped to specifiec columns. Text has to be encoded in unicode. @@ -926,7 +928,6 @@ class Escpos(object): :type height: int :type density: int """ - if custom_size: if ( 1 <= width <= 8 @@ -1004,7 +1005,6 @@ class Escpos(object): :param feed: print and feed before cutting. default: true :raises ValueError: if mode not in ('FULL', 'PART') """ - if not feed: self._raw(GS + b"V" + six.int2byte(66) + b"\x00") return @@ -1027,7 +1027,7 @@ class Escpos(object): self._raw(PAPER_PART_CUT) def cashdraw(self, pin): - """Send pulse to kick the cash drawer + """Send pulse to kick the cash drawer. Kick cash drawer on pin 2 (:py:const:`~escpos.constants.CD_KICK_2`) or pin 5 (:py:const:`~escpos.constants.CD_KICK_5`) @@ -1049,7 +1049,7 @@ class Escpos(object): raise CashDrawerError(err) def linedisplay_select(self, select_display=False): - """Selects the line display or the printer + """Select the line display or the printer. This method is used for line displays that are daisy-chained between your computer and printer. If you set `select_display` to true, only the display is selected and if you set it to false, @@ -1064,15 +1064,14 @@ class Escpos(object): self._raw(LINE_DISPLAY_CLOSE) def linedisplay_clear(self): - """Clears the line display and resets the cursor + """Clear the line display and resets the . This method is used for line displays that are daisy-chained between your computer and printer. """ self._raw(LINE_DISPLAY_CLEAR) def linedisplay(self, text): - """ - Display text on a line display connected to your printer + """Display text on a line display connected to your printer. You should connect a line display to your printer. You can do this by daisy-chaining the display between your computer and printer. @@ -1085,7 +1084,7 @@ class Escpos(object): self.linedisplay_select(select_display=False) def hw(self, hw): - """Hardware operations + """Hardware operations. :param hw: hardware action, may be: @@ -1103,7 +1102,7 @@ class Escpos(object): pass def print_and_feed(self, n=1): - """Print data in print buffer and feed *n* lines + """Print data in print buffer and feed *n* lines. If n not in range (0, 255) then a ValueError will be raised. @@ -1117,7 +1116,7 @@ class Escpos(object): raise ValueError("n must be betwen 0 and 255") def control(self, ctl, count=5, tab_size=8): - """Feed control sequences + """Feed control sequences. :param ctl: string for the following control sequences: @@ -1153,7 +1152,7 @@ class Escpos(object): self._raw(CTL_VT) def panel_buttons(self, enable=True): - """Controls the panel buttons on the printer (e.g. FEED) + """Control the panel buttons on the printer (e.g. FEED). When enable is set to False the panel buttons on the printer will be disabled. @@ -1183,9 +1182,9 @@ class Escpos(object): self._raw(PANEL_BUTTON_OFF) def query_status(self, mode): - """ - Queries the printer for its status, and returns an array - of integers containing it. + """Query the printer for its status. + + Returns an array of integers containing it. :param mode: Integer that sets the status mode queried to the printer. - RT_STATUS_ONLINE: Printer status. @@ -1197,8 +1196,7 @@ class Escpos(object): return status def is_online(self): - """ - Queries the online status of the printer. + """Query the online status of the printer. :returns: When online, returns ``True``; ``False`` otherwise. :rtype: bool @@ -1209,8 +1207,7 @@ class Escpos(object): return not (status[0] & RT_MASK_ONLINE) def paper_status(self): - """ - Queries the paper status of the printer. + """Query the paper status of the printer. Returns 2 if there is plenty of paper, 1 if the paper has arrived to the near-end sensor and 0 if there is no paper. @@ -1229,7 +1226,7 @@ class Escpos(object): return 2 def target(self, type="ROLL"): - """Select where to print to + """Select where to print to. Print to the thermal printer by default (ROLL) or print to the slip dot matrix printer if supported (SLIP) @@ -1242,11 +1239,11 @@ class Escpos(object): raise ValueError("Unsupported target") def eject_slip(self): - """Eject the slip/cheque""" + """Eject the slip/cheque.""" self._raw(SLIP_EJECT) def print_and_eject_slip(self): - """Print and eject + """Print and eject. Prints data from the buffer to the slip station and if the paper sensor is covered, reverses the slip out the front of the printer @@ -1256,7 +1253,7 @@ class Escpos(object): self._raw(SLIP_PRINT_AND_EJECT) def use_slip_only(self): - """Selects the Slip Station for all functions. + """Select the Slip Station for all functions. The receipt station is the default setting after the printer is initialized or the Clear Printer (0x10) command is received @@ -1264,7 +1261,7 @@ class Escpos(object): self._raw(SLIP_SELECT) def buzzer(self, times=2, duration=4): - """Activate the internal printer buzzer (only supported printers). + """Activate the internal printer buzzer on supported printers. The 'times' parameter refers to the 'n' escpos command parameter, which means how many times the buzzer will be 'beeped'. @@ -1273,7 +1270,6 @@ class Escpos(object): :param duration: Integer between 1 and 9, indicates the beep duration. :returns: None """ - if not 1 <= times <= 9: raise ValueError("times must be between 1 and 9") if not 1 <= duration <= 9: @@ -1283,7 +1279,7 @@ class Escpos(object): class EscposIO(object): - """ESC/POS Printer IO object + r"""ESC/POS Printer IO object. Allows the class to be used together with the `with`-statement. You have to define a printer instance and assign it to the EscposIO class. @@ -1303,7 +1299,8 @@ class EscposIO(object): """ def __init__(self, printer, autocut=True, autoclose=True, **kwargs): - """ + """Initialize object. + :param printer: An EscPos-printer object :type printer: escpos.Escpos :param autocut: If True, paper is automatically cut after the `with`-statement *default*: True @@ -1315,7 +1312,7 @@ class EscposIO(object): self.autoclose = autoclose def set(self, **kwargs): - """Set the printer-parameters + """Set the printer-parameters. Controls which parameters will be passed to :py:meth:`Escpos.set() `. For more information on the parameters see the :py:meth:`set() `-methods @@ -1327,6 +1324,7 @@ class EscposIO(object): self.params.update(kwargs) def writelines(self, text, **kwargs): + """Print text.""" params = dict(self.params) params.update(kwargs) @@ -1349,14 +1347,18 @@ class EscposIO(object): self.printer.text("{0}\n".format(line)) def close(self): - """called upon closing the `with`-statement""" + """Close printer. + + Called upon closing the `with`-statement. + """ self.printer.close() def __enter__(self, **kwargs): + """Enter context.""" return self def __exit__(self, type, value, traceback): - """ + """Cut and close if configured. If :py:attr:`autocut ` is `True` (set by this class' constructor), then :py:meth:`printer.cut() ` will be called here. diff --git a/src/escpos/exceptions.py b/src/escpos/exceptions.py index 5be8eef..8a357d5 100644 --- a/src/escpos/exceptions.py +++ b/src/escpos/exceptions.py @@ -27,9 +27,10 @@ Result/Exit codes: class Error(Exception): - """Base class for ESC/POS errors""" + """Base class for ESC/POS errors.""" def __init__(self, msg, status=None): + """Initialize Error object.""" Exception.__init__(self) self.msg = msg self.resultcode = 1 @@ -37,6 +38,7 @@ class Error(Exception): self.resultcode = status def __str__(self): + """Return string representation of Error.""" return self.msg @@ -49,11 +51,13 @@ class BarcodeTypeError(Error): """ def __init__(self, msg=""): + """Initialize BarcodeTypeError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 10 def __str__(self): + """Return string representation of BarcodeTypeError.""" return "No Barcode type is defined ({msg})".format(msg=self.msg) @@ -66,11 +70,13 @@ class BarcodeSizeError(Error): """ def __init__(self, msg=""): + """Initialize BarcodeSizeError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 20 def __str__(self): + """Return string representation of BarcodeSizeError.""" return "Barcode size is out of range ({msg})".format(msg=self.msg) @@ -83,11 +89,13 @@ class BarcodeCodeError(Error): """ def __init__(self, msg=""): + """Initialize BarcodeCodeError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 30 def __str__(self): + """Return string representation of BarcodeCodeError.""" return "No Barcode code was supplied ({msg})".format(msg=self.msg) @@ -98,11 +106,13 @@ class ImageSizeError(Error): """ def __init__(self, msg=""): + """Initialize ImageSizeError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 40 def __str__(self): + """Return string representation of ImageSizeError.""" return "Image height is longer than 255px and can't be printed ({msg})".format( msg=self.msg ) @@ -115,11 +125,13 @@ class ImageWidthError(Error): """ def __init__(self, msg=""): + """Initialize ImageWidthError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 41 def __str__(self): + """Return string representation of ImageWidthError.""" return "Image width is too large ({msg})".format(msg=self.msg) @@ -131,11 +143,13 @@ class TextError(Error): """ def __init__(self, msg=""): + """Initialize TextError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 50 def __str__(self): + """Return string representation of TextError.""" return "Text string must be supplied to the text() method ({msg})".format( msg=self.msg ) @@ -149,16 +163,20 @@ class CashDrawerError(Error): """ def __init__(self, msg=""): + """Initialize CashDrawerError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 60 def __str__(self): + """Return string representation of CashDrawerError.""" return "Valid pin must be set to send pulse ({msg})".format(msg=self.msg) class TabPosError(Error): - """Valid tab positions must be set by using from 1 to 32 tabs, and between 1 and 255 tab size values. + """Tab position is invalid. + + Valid tab positions must be set by using from 1 to 32 tabs, and between 1 and 255 tab size values. Both values multiplied must not exceed 255, since it is the maximum tab value. This exception is raised by :py:meth:`escpos.escpos.Escpos.control`. @@ -166,11 +184,13 @@ class TabPosError(Error): """ def __init__(self, msg=""): + """Initialize TabPosError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 70 def __str__(self): + """Return string representation of TabPosError.""" return "Valid tab positions must be in the range 0 to 16 ({msg})".format( msg=self.msg ) @@ -184,43 +204,49 @@ class CharCodeError(Error): """ def __init__(self, msg=""): + """Initialize CharCodeError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 80 def __str__(self): + """Return string representation of CharCodeError.""" return "Valid char code must be set ({msg})".format(msg=self.msg) class USBNotFoundError(Error): - """Device wasn't found (probably not plugged in) + """Device wasn't found (probably not plugged in). The USB device seems to be not plugged in. Ths returncode for this exception is `90`. """ def __init__(self, msg=""): + """Initialize USBNotFoundError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 90 def __str__(self): + """Return string representation of USBNotFoundError.""" return "USB device not found ({msg})".format(msg=self.msg) class SetVariableError(Error): - """A set method variable was out of range + """A set method variable was out of range. Check set variables against minimum and maximum values Ths returncode for this exception is `100`. """ def __init__(self, msg=""): + """Initialize SetVariableError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 100 def __str__(self): + """Return string representation of SetVariableError.""" return "Set variable out of range ({msg})".format(msg=self.msg) @@ -228,48 +254,54 @@ class SetVariableError(Error): class ConfigNotFoundError(Error): - """The configuration file was not found + """The configuration file was not found. The default or passed configuration file could not be read Ths returncode for this exception is `200`. """ def __init__(self, msg=""): + """Initialize ConfigNotFoundError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 200 def __str__(self): + """Return string representation of ConfigNotFoundError.""" return "Configuration not found ({msg})".format(msg=self.msg) class ConfigSyntaxError(Error): - """The configuration file is invalid + """The configuration file is invalid. The syntax is incorrect Ths returncode for this exception is `210`. """ def __init__(self, msg=""): + """Initialize ConfigSyntaxError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 210 def __str__(self): + """Return string representation of ConfigSyntaxError.""" return "Configuration syntax is invalid ({msg})".format(msg=self.msg) class ConfigSectionMissingError(Error): - """The configuration file is missing a section + """The configuration file is missing a section. The part of the config asked for doesn't exist in the loaded configuration Ths returncode for this exception is `220`. """ def __init__(self, msg=""): + """Initialize ConfigSectionMissingError object.""" Error.__init__(self, msg) self.msg = msg self.resultcode = 220 def __str__(self): + """Return string representation of ConfigSectionMissingError.""" return "Configuration section is missing ({msg})".format(msg=self.msg)