Render QR codes pixel-exact with an own encoder
nxhmi.qr is a dependency-free QR encoder. Measured in the Editor simulator: numeric/alphanumeric/byte mode by content, level L, mask 0, smallest version; scaled to w - 2*dis by width (not clipped to h), last column run one pixel narrower, logo centred, nothing when too small. Basic rendering is now 20/20 pixel-exact. Also: unknown component kinds give a clean CLI error instead of a traceback. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f0bcc608b1
commit
842591a14c
10 files changed
+428
-8
No files matched your search
@@ -42,4 +42,6 @@ Back up the user's file first (copy it) unless they said not to; edits write in
|
|||||||
|
|
||||||
- Writes projects for Nextion Editor 1.68.2; the user still compiles/uploads the `.tft` with the
|
- Writes projects for Nextion Editor 1.68.2; the user still compiles/uploads the `.tft` with the
|
||||||
Editor (or Nexus for uploading). nxhmi cannot compile `.tft` files yet.
|
Editor (or Nexus for uploading). nxhmi cannot compile `.tft` files yet.
|
||||||
- Rendering: QR codes are a placeholder, Intelligent-only components are not drawn.
|
- Rendering: Intelligent-only components are not drawn yet.
|
||||||
|
- QR codes on Basic displays: long texts can exceed the display RAM; the Editor then refuses to
|
||||||
|
compile ("not enough memory ... QR code"). Keep QR texts short there and compile to check.
|
||||||
@@ -30,8 +30,8 @@ Every percentage is a count with a stated basis, so it can be checked (details i
|
|||||||
| Picture formats | **50 %** (1/2) | raw RGB565 (Basic) done; compressed format (Intelligent) not yet |
|
| Picture formats | **50 %** (1/2) | raw RGB565 (Basic) done; compressed format (Intelligent) not yet |
|
||||||
| Font modes | **50 %** (1/2) | black/white done (incl. TrueType import); anti-aliased not yet |
|
| Font modes | **50 %** (1/2) | black/white done (incl. TrueType import); anti-aliased not yet |
|
||||||
| Readable attribute names in JSON | **65 %** (20/31 types) | value lists taken from the Editor for all Basic types; Intelligent-only types still raw numbers |
|
| Readable attribute names in JSON | **65 %** (20/31 types) | value lists taken from the Editor for all Basic types; Intelligent-only types still raw numbers |
|
||||||
| Rendering, Basic components | **95 %** (19/20 pixel-exact) | QR code placeholder |
|
| Rendering, Basic components | **100 %** (20/20 pixel-exact) | incl. gauges and QR codes (own encoder, no dependencies) |
|
||||||
| Rendering, all components | **61 %** (19/31 pixel-exact) | Intelligent-only components not rendered yet |
|
| Rendering, all components | **65 %** (20/31 pixel-exact) | Intelligent-only components not rendered yet |
|
||||||
| `.tft` compilation | **31 %** (2.5/8 milestones) | layout mapped, layout table decoded, trailer checksum (same-length edits only); not usable yet |
|
| `.tft` compilation | **31 %** (2.5/8 milestones) | layout mapped, layout table decoded, trailer checksum (same-length edits only); not usable yet |
|
||||||
|
|
||||||
## Compatibility
|
## Compatibility
|
||||||
|
|||||||
+1
-2
@@ -15,7 +15,7 @@ byte for byte, or a file written by nxhmi was opened in the Editor and showed th
|
|||||||
| Readable JSON (enum names, colours) | done for every value list the Editor documents |
|
| Readable JSON (enum names, colours) | done for every value list the Editor documents |
|
||||||
| Pictures | Basic series **complete**; Intelligent compressed format **missing** |
|
| Pictures | Basic series **complete**; Intelligent compressed format **missing** |
|
||||||
| Fonts | black/white **complete** incl. generation from TrueType; anti-aliased **missing** |
|
| Fonts | black/white **complete** incl. generation from TrueType; anti-aliased **missing** |
|
||||||
| Rendering pages like the Editor | **pixel-identical** for most components incl. picture skins, radios and gauges; QR placeholder |
|
| Rendering pages like the Editor | **pixel-identical** for most components for every Basic component incl. picture skins, radios, gauges and QR codes |
|
||||||
| New projects from scratch | `project.new_project(model)` for 12 Basic/Intelligent models; the generated demo is byte-identical to the Editor's re-save |
|
| New projects from scratch | `project.new_project(model)` for 12 Basic/Intelligent models; the generated demo is byte-identical to the Editor's re-save |
|
||||||
| Compiling `.tft` firmware | **research only** -- not possible yet |
|
| Compiling `.tft` firmware | **research only** -- not possible yet |
|
||||||
|
|
||||||
@@ -98,7 +98,6 @@ byte for byte, or a file written by nxhmi was opened in the Editor and showed th
|
|||||||
### Rendering
|
### Rendering
|
||||||
| Item | Notes |
|
| Item | Notes |
|
||||||
|---|---|
|
|---|---|
|
||||||
| QR code | placeholder; needs the Editor's QR settings |
|
|
||||||
| Pressed / runtime states, Intelligent-only components | not drawn |
|
| Pressed / runtime states, Intelligent-only components | not drawn |
|
||||||
|
|
||||||
### `.tft` compilation (firmware for the display)
|
### `.tft` compilation (firmware for the display)
|
||||||
|
|||||||
+10
-2
@@ -33,7 +33,7 @@ Per component (dedicated test pages):
|
|||||||
| waveform (frame + grid) | 100 % | horizontal grid lines count from the bottom |
|
| waveform (frame + grid) | 100 % | horizontal grid lines count from the bottom |
|
||||||
| gauge (every angle, needle width 1-8, odd/even/non-square sizes) | 100 % | the needle routine, see below |
|
| gauge (every angle, needle width 1-8, odd/even/non-square sizes) | 100 % | the needle routine, see below |
|
||||||
| radio (all sizes, also non-square) | 100 % | the display's own circle routine, see below |
|
| radio (all sizes, also non-square) | 100 % | the display's own circle routine, see below |
|
||||||
| QR code | placeholder only | |
|
| QR code (byte/alphanumeric/numeric text, versions 1-8, margins, colours, logo, Latin-1) | 100 % | own encoder (`nxhmi.qr`), see below |
|
||||||
| hotspot, touch cap, timer, variable | nothing drawn (same as the Editor) | |
|
| hotspot, touch cap, timer, variable | nothing drawn (same as the Editor) | |
|
||||||
|
|
||||||
## Rules learned from the Editor
|
## Rules learned from the Editor
|
||||||
@@ -60,8 +60,16 @@ Per component (dedicated test pages):
|
|||||||
and `24*sin 30` truncates to 11). The line runs from the tip to the centre: step the major
|
and `24*sin 30` truncates to 11). The line runs from the tip to the centre: step the major
|
||||||
axis, minor offset `(k*minor + minor - 1) // major`. Width > 1: every line pixel is stamped
|
axis, minor offset `(k*minor + minor - 1) // major`. Width > 1: every line pixel is stamped
|
||||||
with a `wid` x `wid` square starting at `-(wid//2)`.
|
with a `wid` x `wid` square starting at `-(wid//2)`.
|
||||||
|
- QR code: the text's bytes (iso-8859-1) encoded in numeric mode if all digits, alphanumeric
|
||||||
|
if all in `0-9A-Z $%*+-./:`, else byte mode; error correction **L**, **mask 0** always, the
|
||||||
|
smallest version that fits. Drawn into a square of `w - 2*dis` px at `(dis, dis)` -- sized by
|
||||||
|
the width only and *not* clipped to `h`; pixel `p` shows module `p*N//size`. Dark runs are
|
||||||
|
drawn column by column and the last one (last column, reaching the bottom) is one pixel
|
||||||
|
narrower. Fewer pixels than modules or empty text: only the `bco` background. `sta` 1:
|
||||||
|
picture `pic` pasted centred in the box. Big codes can exceed a Basic display's RAM (the
|
||||||
|
Editor refuses to compile), the canvas still draws them.
|
||||||
- Slider: auto cursor (255) is a square as thick as the slider; position = `int(frac * free)`.
|
- Slider: auto cursor (255) is a square as thick as the slider; position = `int(frac * free)`.
|
||||||
- Waveform: vertical grid lines from the left edge, horizontal ones counted from the bottom.
|
- Waveform: vertical grid lines from the left edge, horizontal ones counted from the bottom.
|
||||||
|
|
||||||
Not covered yet: QR codes, Intelligent-only components (need Intelligent
|
Not covered yet: Intelligent-only components (need Intelligent
|
||||||
picture format 4), anti-aliased fonts, pressed/runtime states.
|
picture format 4), anti-aliased fonts, pressed/runtime states.
|
||||||
@@ -201,7 +201,11 @@ def main(argv=None):
|
|||||||
s = sub.add_parser("dump", help="print pages as JSON"); s.add_argument("hmi"); s.add_argument("--page")
|
s = sub.add_parser("dump", help="print pages as JSON"); s.add_argument("hmi"); s.add_argument("--page")
|
||||||
s.add_argument("--encoding", default="latin-1"); s.add_argument("--raw", action="store_true"); s.set_defaults(f=cmd_dump)
|
s.add_argument("--encoding", default="latin-1"); s.add_argument("--raw", action="store_true"); s.set_defaults(f=cmd_dump)
|
||||||
a = ap.parse_args(argv)
|
a = ap.parse_args(argv)
|
||||||
|
try:
|
||||||
return a.f(a) or 0
|
return a.f(a) or 0
|
||||||
|
except (ValueError, KeyError) as e:
|
||||||
|
print("error:", e.args[0] if e.args else e, file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -186,6 +186,8 @@ def t_verify(path):
|
|||||||
|
|
||||||
|
|
||||||
def t_schema(kind):
|
def t_schema(kind):
|
||||||
|
if kind not in C.KINDS:
|
||||||
|
raise ValueError("unknown component kind %r; known kinds: %s" % (kind, ", ".join(sorted(C.KINDS))))
|
||||||
tpl = C.TYPES[C.KINDS[kind]]
|
tpl = C.TYPES[C.KINDS[kind]]
|
||||||
ctype = C.KINDS[kind]
|
ctype = C.KINDS[kind]
|
||||||
out = []
|
out = []
|
||||||
|
|||||||
+262
@@ -0,0 +1,262 @@
|
|||||||
|
"""Minimal QR code encoder (no dependencies), matching what Nextion draws for the QR code component.
|
||||||
|
|
||||||
|
Measured in Nextion Editor 1.68's simulator: byte mode, error correction level L, mask 0 always
|
||||||
|
(no mask scoring), smallest version that fits. `matrix()` is a plain ISO 18004 encoder; the
|
||||||
|
choices are parameters so other settings can be produced too.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
# error-correction codewords per block and number of blocks, indexed [level][version]
|
||||||
|
_ECC_PER_BLOCK = {
|
||||||
|
"L": [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
|
||||||
|
"M": [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28],
|
||||||
|
"Q": [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
|
||||||
|
"H": [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
|
||||||
|
}
|
||||||
|
_BLOCKS = {
|
||||||
|
"L": [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25],
|
||||||
|
"M": [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49],
|
||||||
|
"Q": [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68],
|
||||||
|
"H": [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81],
|
||||||
|
}
|
||||||
|
_FORMAT_LEVEL = {"L": 1, "M": 0, "Q": 3, "H": 2}
|
||||||
|
_MASKS = [
|
||||||
|
lambda r, c: (r + c) % 2 == 0,
|
||||||
|
lambda r, c: r % 2 == 0,
|
||||||
|
lambda r, c: c % 3 == 0,
|
||||||
|
lambda r, c: (r + c) % 3 == 0,
|
||||||
|
lambda r, c: (r // 2 + c // 3) % 2 == 0,
|
||||||
|
lambda r, c: r * c % 2 + r * c % 3 == 0,
|
||||||
|
lambda r, c: (r * c % 2 + r * c % 3) % 2 == 0,
|
||||||
|
lambda r, c: ((r + c) % 2 + r * c % 3) % 2 == 0,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _raw_modules(ver: int) -> int:
|
||||||
|
n = (16 * ver + 128) * ver + 64
|
||||||
|
if ver >= 2:
|
||||||
|
a = ver // 7 + 2
|
||||||
|
n -= (25 * a - 10) * a - 55
|
||||||
|
if ver >= 7:
|
||||||
|
n -= 36
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
def data_codewords(ver: int, ecc: str = "L") -> int:
|
||||||
|
return _raw_modules(ver) // 8 - _ECC_PER_BLOCK[ecc][ver] * _BLOCKS[ecc][ver]
|
||||||
|
|
||||||
|
|
||||||
|
ALNUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"
|
||||||
|
|
||||||
|
|
||||||
|
def mode_of(data: bytes) -> str:
|
||||||
|
"""Numeric if all digits, alphanumeric if all in the QR alnum set, else byte (as the display does)."""
|
||||||
|
t = data.decode("latin-1")
|
||||||
|
if t and t.isdigit() and t.isascii():
|
||||||
|
return "numeric"
|
||||||
|
if t and all(ch in ALNUM for ch in t):
|
||||||
|
return "alnum"
|
||||||
|
return "byte"
|
||||||
|
|
||||||
|
|
||||||
|
def _count_bits(mode: str, ver: int) -> int:
|
||||||
|
i = 0 if ver < 10 else (1 if ver < 27 else 2)
|
||||||
|
return {"numeric": (10, 12, 14), "alnum": (9, 11, 13), "byte": (8, 16, 16)}[mode][i]
|
||||||
|
|
||||||
|
|
||||||
|
def _data_bits(data: bytes, mode: str):
|
||||||
|
bits = []
|
||||||
|
|
||||||
|
def put(val, n):
|
||||||
|
bits.extend((val >> k) & 1 for k in range(n - 1, -1, -1))
|
||||||
|
t = data.decode("latin-1")
|
||||||
|
if mode == "numeric":
|
||||||
|
for k in range(0, len(t), 3):
|
||||||
|
g = t[k:k + 3]
|
||||||
|
put(int(g), len(g) * 3 + 1)
|
||||||
|
elif mode == "alnum":
|
||||||
|
for k in range(0, len(t) - 1, 2):
|
||||||
|
put(ALNUM.index(t[k]) * 45 + ALNUM.index(t[k + 1]), 11)
|
||||||
|
if len(t) % 2:
|
||||||
|
put(ALNUM.index(t[-1]), 6)
|
||||||
|
else:
|
||||||
|
for b in data:
|
||||||
|
put(b, 8)
|
||||||
|
return bits
|
||||||
|
|
||||||
|
|
||||||
|
def pick_version(data: bytes, ecc: str = "L", mode: str = None) -> int:
|
||||||
|
mode = mode or mode_of(data)
|
||||||
|
n = len(_data_bits(data, mode))
|
||||||
|
for v in range(1, 41):
|
||||||
|
if 4 + _count_bits(mode, v) + n <= data_codewords(v, ecc) * 8:
|
||||||
|
return v
|
||||||
|
raise ValueError("%d bytes do not fit in a QR code" % len(data))
|
||||||
|
|
||||||
|
|
||||||
|
def _gf_mul(x: int, y: int) -> int:
|
||||||
|
z = 0
|
||||||
|
for i in range(7, -1, -1):
|
||||||
|
z = (z << 1) ^ ((z >> 7) * 0x11D)
|
||||||
|
z ^= ((y >> i) & 1) * x
|
||||||
|
return z
|
||||||
|
|
||||||
|
|
||||||
|
def _rs_divisor(degree: int):
|
||||||
|
res = [0] * (degree - 1) + [1]
|
||||||
|
root = 1
|
||||||
|
for _ in range(degree):
|
||||||
|
for j in range(degree):
|
||||||
|
res[j] = _gf_mul(res[j], root)
|
||||||
|
if j + 1 < degree:
|
||||||
|
res[j] ^= res[j + 1]
|
||||||
|
root = _gf_mul(root, 2)
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
def _rs_remainder(data, divisor):
|
||||||
|
res = [0] * len(divisor)
|
||||||
|
for b in data:
|
||||||
|
f = b ^ res.pop(0)
|
||||||
|
res.append(0)
|
||||||
|
for i, coef in enumerate(divisor):
|
||||||
|
res[i] ^= _gf_mul(coef, f)
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
def _codewords(data: bytes, ver: int, ecc: str, mode: str):
|
||||||
|
bits = []
|
||||||
|
|
||||||
|
def put(val, n):
|
||||||
|
bits.extend((val >> i) & 1 for i in range(n - 1, -1, -1))
|
||||||
|
put({"numeric": 1, "alnum": 2, "byte": 4}[mode], 4)
|
||||||
|
put(len(data), _count_bits(mode, ver))
|
||||||
|
bits += _data_bits(data, mode)
|
||||||
|
cap = data_codewords(ver, ecc) * 8
|
||||||
|
put(0, min(4, cap - len(bits)))
|
||||||
|
put(0, -len(bits) % 8)
|
||||||
|
words = [int("".join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8)]
|
||||||
|
pad = 0xEC
|
||||||
|
while len(words) < cap // 8:
|
||||||
|
words.append(pad)
|
||||||
|
pad ^= 0xEC ^ 0x11
|
||||||
|
# split into blocks, add RS codes, interleave
|
||||||
|
nblocks, eccn = _BLOCKS[ecc][ver], _ECC_PER_BLOCK[ecc][ver]
|
||||||
|
raw = _raw_modules(ver) // 8
|
||||||
|
nshort = nblocks - raw % nblocks
|
||||||
|
short_len = raw // nblocks
|
||||||
|
div = _rs_divisor(eccn)
|
||||||
|
blocks, k = [], 0
|
||||||
|
for i in range(nblocks):
|
||||||
|
dlen = short_len - eccn + (0 if i < nshort else 1)
|
||||||
|
d = words[k:k + dlen]
|
||||||
|
k += dlen
|
||||||
|
e = _rs_remainder(d, div)
|
||||||
|
if i < nshort:
|
||||||
|
d = d + [None]
|
||||||
|
blocks.append(d + e)
|
||||||
|
out = []
|
||||||
|
for i in range(len(blocks[0])):
|
||||||
|
for j, b in enumerate(blocks):
|
||||||
|
if b[i] is not None:
|
||||||
|
out.append(b[i])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _align_positions(ver: int):
|
||||||
|
if ver == 1:
|
||||||
|
return []
|
||||||
|
n = ver // 7 + 2
|
||||||
|
step = 26 if ver == 32 else (ver * 4 + n * 2 + 1) // (n * 2 - 2) * 2
|
||||||
|
size = ver * 4 + 17
|
||||||
|
return [6] + sorted(size - 7 - i * step for i in range(n - 1))
|
||||||
|
|
||||||
|
|
||||||
|
def matrix(data, ecc: str = "L", mask: int = 0, version: int = None, mode: str = None):
|
||||||
|
"""QR code modules as a list of rows of booleans (True = dark), without quiet zone.
|
||||||
|
`data` is bytes or str (str is encoded as latin-1, like the display's text)."""
|
||||||
|
if isinstance(data, str):
|
||||||
|
data = data.encode("latin-1")
|
||||||
|
mode = mode or mode_of(data)
|
||||||
|
ver = version or pick_version(data, ecc, mode)
|
||||||
|
size = ver * 4 + 17
|
||||||
|
m = [[False] * size for _ in range(size)]
|
||||||
|
fn = [[False] * size for _ in range(size)]
|
||||||
|
|
||||||
|
def setf(r, c, dark):
|
||||||
|
m[r][c] = dark
|
||||||
|
fn[r][c] = True
|
||||||
|
|
||||||
|
for i in range(size): # timing patterns
|
||||||
|
setf(6, i, i % 2 == 0)
|
||||||
|
setf(i, 6, i % 2 == 0)
|
||||||
|
for fr, fc in ((3, 3), (3, size - 4), (size - 4, 3)): # finders + separators
|
||||||
|
for dr in range(-4, 5):
|
||||||
|
for dc in range(-4, 5):
|
||||||
|
r, c = fr + dr, fc + dc
|
||||||
|
if 0 <= r < size and 0 <= c < size:
|
||||||
|
d = max(abs(dr), abs(dc))
|
||||||
|
setf(r, c, d not in (2, 4))
|
||||||
|
pos = _align_positions(ver)
|
||||||
|
for i, r in enumerate(pos):
|
||||||
|
for j, c in enumerate(pos):
|
||||||
|
if (i == 0 and j == 0) or (i == 0 and j == len(pos) - 1) or (i == len(pos) - 1 and j == 0):
|
||||||
|
continue
|
||||||
|
for dr in range(-2, 3):
|
||||||
|
for dc in range(-2, 3):
|
||||||
|
setf(r + dr, c + dc, max(abs(dr), abs(dc)) != 1)
|
||||||
|
|
||||||
|
def draw_format(msk):
|
||||||
|
d = _FORMAT_LEVEL[ecc] << 3 | msk
|
||||||
|
rem = d
|
||||||
|
for _ in range(10):
|
||||||
|
rem = (rem << 1) ^ ((rem >> 9) * 0x537)
|
||||||
|
bits = (d << 10 | rem) ^ 0x5412
|
||||||
|
g = lambda i: (bits >> i) & 1 == 1
|
||||||
|
for i in range(6):
|
||||||
|
setf(i, 8, g(i))
|
||||||
|
setf(7, 8, g(6))
|
||||||
|
setf(8, 8, g(7))
|
||||||
|
setf(8, 7, g(8))
|
||||||
|
for i in range(9, 15):
|
||||||
|
setf(8, 14 - i, g(i))
|
||||||
|
for i in range(8):
|
||||||
|
setf(8, size - 1 - i, g(i))
|
||||||
|
for i in range(8, 15):
|
||||||
|
setf(size - 15 + i, 8, g(i))
|
||||||
|
setf(size - 8, 8, True) # dark module
|
||||||
|
|
||||||
|
draw_format(0) # reserve the format area
|
||||||
|
if ver >= 7:
|
||||||
|
rem = ver
|
||||||
|
for _ in range(12):
|
||||||
|
rem = (rem << 1) ^ ((rem >> 11) * 0x1F25)
|
||||||
|
bits = ver << 12 | rem
|
||||||
|
for i in range(18):
|
||||||
|
b = (bits >> i) & 1 == 1
|
||||||
|
a, c = size - 11 + i % 3, i // 3
|
||||||
|
setf(a, c, b)
|
||||||
|
setf(c, a, b)
|
||||||
|
|
||||||
|
words = _codewords(data, ver, ecc, mode)
|
||||||
|
i = 0
|
||||||
|
right = size - 1
|
||||||
|
while right >= 1:
|
||||||
|
if right == 6:
|
||||||
|
right = 5
|
||||||
|
for vert in range(size):
|
||||||
|
for j in range(2):
|
||||||
|
c = right - j
|
||||||
|
upward = ((right + 1) & 2) == 0
|
||||||
|
r = size - 1 - vert if upward else vert
|
||||||
|
if not fn[r][c] and i < len(words) * 8:
|
||||||
|
m[r][c] = (words[i >> 3] >> (7 - (i & 7))) & 1 == 1
|
||||||
|
i += 1
|
||||||
|
right -= 2
|
||||||
|
f = _MASKS[mask]
|
||||||
|
for r in range(size):
|
||||||
|
for c in range(size):
|
||||||
|
if not fn[r][c] and f(r, c):
|
||||||
|
m[r][c] = not m[r][c]
|
||||||
|
draw_format(mask)
|
||||||
|
return m
|
||||||
+40
-1
@@ -86,6 +86,37 @@ def gauge_needle(w: int, h: int, val: int, wid: int):
|
|||||||
for ax in range(lo, lo + wid) for ay in range(lo, lo + wid)}
|
for ax in range(lo, lo + wid) for ay in range(lo, lo + wid)}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def qr_rects(txt, w: int, dis: int):
|
||||||
|
"""Dark rectangles ((x0, y0), (x1, y1)) exclusive, relative to the component, for a QR code
|
||||||
|
component: the code (see nxhmi.qr) scaled to w - 2*dis pixels starting at (dis, dis);
|
||||||
|
pixel p shows module p*N//size. The display draws dark runs column by column; the run still
|
||||||
|
open at the very end (last column, reaching the bottom) comes out one pixel narrower.
|
||||||
|
The code is square (sized by the width) and is not clipped to the component's height."""
|
||||||
|
from . import qr
|
||||||
|
if isinstance(txt, str):
|
||||||
|
txt = txt.encode("latin-1", "replace")
|
||||||
|
if not txt:
|
||||||
|
return []
|
||||||
|
m = qr.matrix(txt)
|
||||||
|
n, size = len(m), w - 2 * dis
|
||||||
|
if size < n: # less than a pixel per module: nothing drawn
|
||||||
|
return []
|
||||||
|
edge = [-(-k * size // n) for k in range(n + 1)] # first pixel of module k = ceil(k*size/n)
|
||||||
|
rects = []
|
||||||
|
for col in range(n):
|
||||||
|
r = 0
|
||||||
|
while r < n:
|
||||||
|
if not m[r][col]:
|
||||||
|
r += 1
|
||||||
|
continue
|
||||||
|
r0 = r
|
||||||
|
while r < n and m[r][col]:
|
||||||
|
r += 1
|
||||||
|
x1 = edge[col + 1] - (1 if (col == n - 1 and r == n) else 0)
|
||||||
|
rects.append(((dis + edge[col], dis + edge[r0]), (dis + x1, dis + edge[r])))
|
||||||
|
return rects
|
||||||
|
|
||||||
def rgb(v: int):
|
def rgb(v: int):
|
||||||
r, g, b = v >> 11, (v >> 5) & 63, v & 31
|
r, g, b = v >> 11, (v >> 5) & 63, v & 31
|
||||||
return (r << 3 | r >> 2, g << 2 | g >> 4, b << 3 | b >> 2)
|
return (r << 3 | r >> 2, g << 2 | g >> 4, b << 3 | b >> 2)
|
||||||
@@ -437,4 +468,12 @@ class Renderer:
|
|||||||
|
|
||||||
def qrcode(self, img, c):
|
def qrcode(self, img, c):
|
||||||
x, y, w, h = self._box(c)
|
x, y, w, h = self._box(c)
|
||||||
img.paste(rgb(c.get("bco") or 0xFFFF), (x, y, x + w, y + h))
|
bco, pco = c.get("bco"), c.get("pco")
|
||||||
|
img.paste(rgb(0xFFFF if bco is None else bco), (x, y, x + w, y + h))
|
||||||
|
rects = qr_rects(c.get("txt") or "", w, c.get("dis") or 0)
|
||||||
|
for (ax, ay), (bx, by) in rects:
|
||||||
|
img.paste(rgb(pco or 0), (x + ax, y + ay, x + bx, y + by)) # not clipped to h (like the display)
|
||||||
|
if rects and c.get("sta") == 1: # logo picture, centred in the box
|
||||||
|
src = self.pic(c.get("pic"))
|
||||||
|
if src:
|
||||||
|
self._paste(img, src, 0, 0, src.width, src.height, x + (w - src.width) // 2, y + (h - src.height) // 2)
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
"""QR code encoder and QR component rendering, checked against Nextion Editor 1.68's simulator."""
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from helpers import HAVE_PIL
|
||||||
|
|
||||||
|
from nxhmi import components as C
|
||||||
|
from nxhmi import qr
|
||||||
|
from nxhmi.container import build
|
||||||
|
|
||||||
|
# module grids read back from the Editor simulator (QR code component, 100x100, dis 8)
|
||||||
|
CAPTURED = {
|
||||||
|
"hello": [ # byte mode
|
||||||
|
"111111100101101111111", "100000100111001000001", "101110101101101011101", "101110100101001011101",
|
||||||
|
"101110100010101011101", "100000100000101000001", "111111101010101111111", "000000001101100000000",
|
||||||
|
"111011111111011000100", "011111011100001000011", "011111101000100011111", "001100000000001000010",
|
||||||
|
"000010110110101010000", "000000001101010100111", "111111101111011100111", "100000101111110110000",
|
||||||
|
"101110101111011100011", "101110100010001100110", "101110101110100010101", "100000101100001010010",
|
||||||
|
"111111101010101100011"],
|
||||||
|
"HELLO WORLD 12345": [ # alphanumeric mode
|
||||||
|
"111111100010101111111", "100000100000101000001", "101110101010001011101", "101110100000101011101",
|
||||||
|
"101110100101101011101", "100000100111001000001", "111111101010101111111", "000000001010000000000",
|
||||||
|
"111011111010111000100", "010100001001001100001", "010101111111011111000", "000101000101111101110",
|
||||||
|
"101011101101000110101", "000000001011010000101", "111111101100101101100", "100000101101111101010",
|
||||||
|
"101110101100010111100", "101110100111001100010", "101110101110001101001", "100000101010000001011",
|
||||||
|
"111111101001101100001"],
|
||||||
|
"0123456789": [ # numeric mode
|
||||||
|
"111111100101101111111", "100000100111001000001", "101110101101101011101", "101110100101001011101",
|
||||||
|
"101110100010101011101", "100000100000101000001", "111111101010101111111", "000000001101100000000",
|
||||||
|
"111011111111011000100", "101010010100001000010", "000111100000100011110", "111000010000001000010",
|
||||||
|
"110101101100101010001", "000000001111010100010", "111111101001011100000", "100000101111110111111",
|
||||||
|
"101110101001011100001", "101110100100001100010", "101110101000100010001", "100000101000001101100",
|
||||||
|
"111111101000101011101"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def bits(m):
|
||||||
|
return ["".join("1" if v else "0" for v in row) for row in m]
|
||||||
|
|
||||||
|
|
||||||
|
class Encoder(unittest.TestCase):
|
||||||
|
def test_matches_display(self):
|
||||||
|
for text, grid in CAPTURED.items():
|
||||||
|
self.assertEqual(bits(qr.matrix(text)), grid, text)
|
||||||
|
|
||||||
|
def test_modes(self):
|
||||||
|
self.assertEqual(qr.mode_of(b"0123"), "numeric")
|
||||||
|
self.assertEqual(qr.mode_of(b"HELLO 1"), "alnum")
|
||||||
|
self.assertEqual(qr.mode_of(b"hello"), "byte")
|
||||||
|
self.assertEqual(qr.mode_of("caf\xe9".encode("latin-1")), "byte")
|
||||||
|
|
||||||
|
def test_versions(self):
|
||||||
|
# level L, byte mode: v1 holds 17 bytes, v2 32, v7 154 (all seen in the simulator)
|
||||||
|
self.assertEqual(qr.pick_version(b"x" * 17), 1)
|
||||||
|
self.assertEqual(qr.pick_version(b"x" * 24), 2)
|
||||||
|
self.assertEqual(qr.pick_version(b"x" * 40), 3)
|
||||||
|
self.assertEqual(qr.pick_version(b"x" * 160), 8)
|
||||||
|
self.assertEqual(len(qr.matrix("x" * 160)), 49)
|
||||||
|
|
||||||
|
def test_format_bits_level_l_mask_0(self):
|
||||||
|
m = qr.matrix("hello")
|
||||||
|
fmt = [m[8][c] for c in (0, 1, 2, 3, 4, 5, 7, 8)] + [m[r][8] for r in (7, 5, 4, 3, 2, 1, 0)]
|
||||||
|
value = int("".join("1" if b else "0" for b in fmt), 2) ^ 0x5412
|
||||||
|
self.assertEqual(value >> 10, 0b01000) # level L (01), mask 0
|
||||||
|
|
||||||
|
def test_version_info_block(self):
|
||||||
|
m = qr.matrix("x" * 160) # version 8 has the 6x3 version blocks
|
||||||
|
n = len(m)
|
||||||
|
info = sum(m[c][n - 11 + i % 3] << i for i, c in ((i, i // 3) for i in range(18)))
|
||||||
|
self.assertEqual(info >> 12, 8)
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(HAVE_PIL, "needs Pillow")
|
||||||
|
class Render(unittest.TestCase):
|
||||||
|
def render(self, page):
|
||||||
|
from nxhmi.render import Renderer
|
||||||
|
return Renderer(build([("0.pa", page.pack())])).render(page.name)
|
||||||
|
|
||||||
|
def test_scaling_and_last_run(self):
|
||||||
|
from nxhmi.render import qr_rects
|
||||||
|
rects = qr_rects("hello", 100, 8) # 84 px / 21 modules = 4 px each
|
||||||
|
self.assertIn(((8, 8), (12, 36)), rects) # first column: finder, 7 modules tall
|
||||||
|
self.assertIn(((88, 88), (91, 92)), rects) # last run is one pixel narrower
|
||||||
|
self.assertEqual(qr_rects("hello", 78, 30), []) # 18 px for 21 modules: nothing drawn
|
||||||
|
self.assertEqual(qr_rects("", 100, 8), [])
|
||||||
|
|
||||||
|
def test_component(self):
|
||||||
|
p = C.new_page("p", w=200, h=130)
|
||||||
|
C.add(p, "qrcode", x=0, y=0, w=120, h=100, txt="HELLO WORLD 12345", dis=8, bco=0xFFE0, pco=0x001F)
|
||||||
|
img = self.render(p)
|
||||||
|
self.assertEqual(img.getpixel((2, 2)), (255, 255, 0)) # margin in bco
|
||||||
|
self.assertEqual(img.getpixel((9, 9)), (0, 0, 255)) # finder in pco
|
||||||
|
self.assertEqual(img.getpixel((10, 105)), (0, 0, 255)) # sized by width, runs below h=100
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -67,6 +67,14 @@ class Cli(unittest.TestCase):
|
|||||||
sch = json.loads(self.run_cli("schema", "slider")[1])
|
sch = json.loads(self.run_cli("schema", "slider")[1])
|
||||||
self.assertIn("vertical", next(x for x in sch["attributes"] if x["name"] == "mode")["values"])
|
self.assertIn("vertical", next(x for x in sch["attributes"] if x["name"] == "mode")["values"])
|
||||||
|
|
||||||
|
def test_unknown_kind_is_a_clean_error(self):
|
||||||
|
err = io.StringIO()
|
||||||
|
with contextlib.redirect_stderr(err):
|
||||||
|
rc, _ = self.run_cli("schema", "qr_code")
|
||||||
|
self.assertEqual(rc, 2)
|
||||||
|
self.assertIn("known kinds", err.getvalue())
|
||||||
|
self.assertIn("qrcode", err.getvalue())
|
||||||
|
|
||||||
def test_decode_encode(self):
|
def test_decode_encode(self):
|
||||||
d = os.path.join(self.tmp, "dec")
|
d = os.path.join(self.tmp, "dec")
|
||||||
self.run_cli("decode", self.hmi, d)
|
self.run_cli("decode", self.hmi, d)
|
||||||
|
|||||||
Reference in new issue
Block a user