Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Receipt logos: add support for black-and-white binary netpbm images. #282

Merged
merged 32 commits into from
May 9, 2024
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
b2bb96a
Receipt logos: initial draft implementation.
jayaddison May 4, 2024
bce2bdb
Dependencies: add 'imagesize' Python package dependency.
jayaddison May 4, 2024
ea9bb87
Fix PBM image header parsing:
jayaddison May 4, 2024
0dcc0cf
Refactor / fixup: don't octuplicate the data.
jayaddison May 4, 2024
d72f0ee
Linting: fit within flake8-suggested line length limits.
jayaddison May 4, 2024
c837eba
Fixup: assertion expectation should use an f-string for variable subs…
jayaddison May 4, 2024
5da27b9
Fixup: check for ASCII-encoded hash-symbol ('#') as bytestring, not u…
jayaddison May 4, 2024
3808a1e
Cleanup: remove half-dot-feed command.
jayaddison May 5, 2024
1f26bde
Fixup: re-use existing logic to correctly construct image width_info.
jayaddison May 5, 2024
81de564
Refactor: rename 'bits' variable to 'line'.
jayaddison May 5, 2024
b09578a
Fixup: include the padding bits when determining the bitimage command…
jayaddison May 5, 2024
4ce2d19
Refactor: use Python int.to_bytes function to prepare width_info data.
jayaddison May 6, 2024
02b01a2
Refactor: perform calculation of padding before row-partitioning the …
jayaddison May 6, 2024
bf55022
Refactor: rectify some variable names.
jayaddison May 6, 2024
a7e8902
Printing: group and transmit eight-line groups to the receipt printer.
jayaddison May 6, 2024
9e335cc
Padding: expand each pad-bit to a pad-byte.
jayaddison May 7, 2024
87eca3b
Revert "Padding: expand each pad-bit to a pad-byte."
jayaddison May 7, 2024
6cca49c
Printing: use double-density horizontal printing, and read 24-bits of…
jayaddison May 8, 2024
1f41665
Fixup: include any incomplete 24-line chunk found at end of image dat…
jayaddison May 8, 2024
e5d8cbb
Printing: set zero line-spacing for duration of image output, then re…
jayaddison May 8, 2024
2ffafaf
Printing: process a carriage-return after each image line is printed.
jayaddison May 8, 2024
e55f5fa
Printing: add a carriage-return plus line-feed after each bitimage is…
jayaddison May 8, 2024
080c53c
Fixup: append LF instead of CR after each row of image data.
jayaddison May 8, 2024
10b0a17
Refactor / cleanup: use [more_]itertools.batched to read up-to-24-lin…
jayaddison May 8, 2024
71a8cb4
Config: correction for logo-config-existence check.
jayaddison May 8, 2024
225edf6
Refactor: use [more_]itertools.batched to read image data line-by-line.
jayaddison May 8, 2024
46e97df
Linting: declare long config description using shorter concatenated s…
jayaddison May 8, 2024
6e086e7
Continuous integration: add newly-introduced dependencies.
jayaddison May 8, 2024
027b00b
Continuous integration: remove python3-more-itertools
jayaddison May 8, 2024
e4634c5
Refactor: use local implementation of iterable-chunking.
jayaddison May 8, 2024
d47cc3c
Dependencies: remove more-itertools dependency.
jayaddison May 8, 2024
136c5b9
Nitpick: cleanup: remove redundant iter(...) function call.
jayaddison May 8, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added examples/data/cc.pbm
Binary file not shown.
62 changes: 61 additions & 1 deletion quicktill/pdrivers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
_qrcode_supported = True
except ImportError:
_qrcode_supported = False
import imagesize

from reportlab.pdfgen import canvas
from reportlab.lib.units import toLength
Expand Down Expand Up @@ -110,7 +111,18 @@ def __str__(self):

class ImageElement(ReceiptElement):
def __init__(self, image):
self.image_data = image
assert image.startswith(b"P4") # only B&W PBM format supported
width, height = imagesize.get(io.BytesIO(image))
data_lines = [
line
for line in image.splitlines()
if not line.startswith(b"#")
]
assert data_lines[0] == b"P4"
assert data_lines[1] == f"{width} {height}".encode("ascii")
self.image_data = bytes().join(data_lines[2:])
self.image_width = width
self.image_height = height

def __str__(self):
return "Image"
Expand Down Expand Up @@ -592,6 +604,7 @@ class escpos:
ep_unidirectional_off = bytes([27, 85, 0])
# follow ep_bitimage_sd with 16-bit little-endian data length
ep_bitimage_sd = bytes([27, 42, 0])
ep_bitimage_dd_v24 = bytes([27, 42, 33]) # double-density, 24-dot vertical
ep_short_feed = bytes([27, 74, 5])
ep_half_dot_feed = bytes([27, 74, 1])

Expand Down Expand Up @@ -689,6 +702,9 @@ def process_canvas(self, canvas, f):
("%s%s%s%s%s\n" % (
left, ' ' * padl, center, ' ' * padr, right))
.encode(self.coding))
elif hasattr(i, 'image_data'):
assert 8 * len(i.image_data) == i.image_width * i.image_height
self._image(i.image_data, i.image_width, i.image_height, f)
elif hasattr(i, 'qrcode_data'):
self._qrcode(i.qrcode_data, f)
else:
Expand All @@ -701,6 +717,50 @@ def process_canvas(self, canvas, f):
f.write(escpos.ep_fullcut)
f.flush()

def _image(self, data, width, height, f):
# Print a PBM bit-image
if width > self.dpl:
# Image too wide for paper
return

# Calculate padding required to center the image
padding = (self.dpl - width) // 2
padchars = [False] * padding

# Partition the bitmap into lines
lines = []
for line in range(height):
start = line * (width // 8)
end = start + (width // 8)
line = padchars.copy()
jayaddison marked this conversation as resolved.
Show resolved Hide resolved
for byte in data[start:end]:
for bit in f"{int(byte):08b}":
line.append(bool(int(bit)))
lines.append(line)

# Compact up to twenty-four bit-lines into each row
rows = []
for chunk in range(height // 24):
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note-to-self: this division should be adjusted to use a math ceiling-function; there could (and in the case of 512h, is) be trailing line data otherwise.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A more Pythonic way to do this would be to iterate over a generator that returns (up-to) 24 row chunks.

Eg.

for chunk in itertools.batched(lines, 24):
    ...
    for column in zip(*chunk):
        ...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Much better 👍

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the Python version support policy for the application? I see Py3.8+ mentioned in setup.cfg; itertools.batched seems to be from Py3.12+ (still possible that a cleanup similar to this is possible using more backwards-compatible functions, though).

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, good point. Yes, itertools.batched is still too new to use. You could include a generator that does something suitable, and which also pads to a multiple of 24 rows?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(And to answer your question directly: I'm still officially supporting Python 3.8 [it's in Ubuntu 20.04 which I still use in a couple of places], but I expect I'll drop that for the next major release and require a minimum of Python 3.10.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aha: more-itertools provides batched, and in fact may even be the origin of the Py3.12 implementation (although I'm not certain of that).

It's Py3.8+ compatible, and using a similar implementation would make it easier to drop that dependency when the baseline here becomes Py3.12+ at a later date.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately the version of more-itertools in Ubuntu 22.04 (which the tills run on in my pub company) doesn't include batched. I think you're going to have to include the text of the function in this project. (It's very small.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

D'oh, that's frustrating. I noticed this comment after adding the dependency to the GitHub Workflows definition.. clearing that out in a moment.

group_start = chunk * 24
group_end = group_start + 24
row = []
for column in zip(*lines[group_start:group_end]):
segments = column[0:8], column[8:16], column[16:24]
for segment in segments:
binary = str().join("1" if bit else "0" for bit in segment)
row.append(int(binary, base=2))
rows.append(bytes(row))

# Write the commands to render the padded image
f.write(escpos.ep_unidirectional_on)
for row in rows:
width_info = (len(row) // 3).to_bytes(length=2, byteorder="little")
f.write(escpos.ep_bitimage_dd_v24 + width_info + row)
f.write(escpos.ep_unidirectional_off)

# Clear the line for subsequent content
f.write(escpos.ep_short_feed)
jayaddison marked this conversation as resolved.
Show resolved Hide resolved

def _qrcode_native(self, data, f):
# Set the size of a "module", in dots. The default is apparently
# 3 (which is also the lowest). The maximum is 16.
Expand Down
5 changes: 5 additions & 0 deletions quicktill/printer.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import base64

from . import td, ui, tillconfig, payment
from decimal import Decimal
from .models import Delivery, VatBand, Business, Transaction, PayType
Expand Down Expand Up @@ -25,6 +27,9 @@ def print_receipt(printer, transid):
if not trans.lines:
return
with printer as d:
if tillconfig.publogo:
image = base64.b64decode(f"{tillconfig.publogo}")
jayaddison marked this conversation as resolved.
Show resolved Hide resolved
d.printimage(image)
d.printline(f"\t{tillconfig.pubname}", emph=1)
for i in tillconfig.pubaddr().splitlines():
d.printline(f"\t{i}", colour=1)
Expand Down
3 changes: 3 additions & 0 deletions quicktill/tillconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
label_printers = []
cash_drawer = None

publogo = config.ConfigItem(
'core:sitelogo', None, display_name="Site logo",
description="Logo image to be printed on receipts. To update it, use 'base64 logo.pbm | runtill config -s core:sitelogo'")
pubname = config.ConfigItem(
'core:sitename', "Default site name", display_name="Site name",
description="Site name to be printed on receipts")
Expand Down
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ install_requires =
pycups
python-dateutil
cryptography
imagesize ~= 1.4
python_requires = >=3.8

[options.extras_require]
Expand Down