1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
|
#!/usr/bin/env python
"""
The crystalfontz 635 has these characters in ROM:
....X. ...... ......
...XX. .XXXXX ..XXX.
..XXX. .XXXXX .XXXXX
.XXXX. .XXXXX .XXXXX
..XXX. .XXXXX .XXXXX
...XX. .XXXXX ..XXX.
....X. ...... ......
...... ...... ......
0x11 0xd0 0xbb
By adding the characters in CGRAM below we can use them as part of a
horizontal slider control, selected check box and selected radio button
respectively.
"""
from __future__ import annotations
import sys
import typing
import urwid
if typing.TYPE_CHECKING:
from collections.abc import Callable
from typing_extensions import Literal
CGRAM = """
...... ...... ...... ...... ..X... ...... ...... ......
XXXXXX XXXXXX XXXXXX XXXXXX X.XX.. .XXXXX ..XXX. .....X
...... XX.... XXXX.. XXXXXX X.XXX. .X...X .X...X ....XX
...... XX.... XXXX.. XXXXXX X.XXXX .X...X .X...X .X.XX.
...... XX.... XXXX.. XXXXXX X.XXX. .X...X .X...X .XXX..
XXXXXX XXXXXX XXXXXX XXXXXX X.XX.. .XXXXX ..XXX. ..X...
...... ...... ...... ...... ..X... ...... ...... ......
...... ...... ...... ...... ...... ...... ...... ......
"""
def program_cgram(screen_inst: urwid.display.lcd.CF635Screen) -> None:
"""
Load the character data
"""
# convert .'s and X's above into integer data
cbuf = [[] for x in range(8)]
for row in CGRAM.strip().split("\n"):
rowsegments = row.strip().split()
for num, r in enumerate(rowsegments):
accum = 0
for c in r:
accum = (accum << 1) + (c == "X")
cbuf[num].append(accum)
for num, cdata in enumerate(cbuf):
screen_inst.program_cgram(num, cdata)
class LCDCheckBox(urwid.CheckBox):
"""
A check box+label that uses only one character for the check box,
including custom CGRAM character
"""
states: typing.ClassVar[dict[bool, urwid.SelectableIcon]] = {
True: urwid.SelectableIcon("\xd0"),
False: urwid.SelectableIcon("\x05"),
}
reserve_columns = 1
class LCDRadioButton(urwid.RadioButton):
"""
A radio button+label that uses only one character for the radio button,
including custom CGRAM character
"""
states: typing.ClassVar[dict[bool, urwid.SelectableIcon]] = {
True: urwid.SelectableIcon("\xbb"),
False: urwid.SelectableIcon("\x06"),
}
reserve_columns = 1
class LCDProgressBar(urwid.Widget):
"""
The "progress bar" used by the horizontal slider for this device,
using custom CGRAM characters
"""
segments = "\x00\x01\x02\x03"
_sizing = frozenset([urwid.Sizing.FLOW])
def __init__(self, data_range, value) -> None:
super().__init__()
self.range = data_range
self.value = value
def rows(self, size, focus=False) -> int:
return 1
def render(self, size, focus=False):
"""
Draw the bar with self.segments where [0] is empty and [-1]
is completely full
"""
(maxcol,) = size
steps = self.get_steps(size)
filled = urwid.int_scale(self.value, self.range, steps)
full_segments = int(filled / (len(self.segments) - 1))
last_char = filled % (len(self.segments) - 1) + 1
s = (
self.segments[-1] * full_segments
+ self.segments[last_char]
+ self.segments[0] * (maxcol - full_segments - 1)
)
return urwid.Text(s).render(size)
def move_position(self, size, direction):
"""
Update and return the value one step +ve or -ve, based on
the size of the displayed bar.
direction -- 1 for +ve, 0 for -ve
"""
steps = self.get_steps(size)
filled = urwid.int_scale(self.value, self.range, steps)
filled += 2 * direction - 1
value = urwid.int_scale(filled, steps, self.range)
value = max(0, min(self.range - 1, value))
if value != self.value:
self.value = value
self._invalidate()
return value
def get_steps(self, size):
"""
Return the number of steps available given size for rendering
the bar and number of segments we can draw.
"""
(maxcol,) = size
return maxcol * (len(self.segments) - 1)
class LCDHorizontalSlider(urwid.WidgetWrap[urwid.Columns]):
"""
A slider control using custom CGRAM characters
"""
def __init__(self, data_range, value, callback):
self.bar = LCDProgressBar(data_range, value)
cols = urwid.Columns(
[
(1, urwid.SelectableIcon("\x11")),
self.bar,
(1, urwid.SelectableIcon("\x04")),
]
)
super().__init__(cols)
self.callback = callback
def keypress(self, size, key: str):
# move the slider based on which arrow is focused
if key == "enter":
# use the correct size for adjusting the bar
self.bar.move_position((self._w.column_widths(size)[1],), self._w.focus_position != 0)
self.callback(self.bar.value)
return None
return super().keypress(size, key)
class MenuOption(urwid.Button):
"""
A menu option, indicated with a single arrow character
"""
def __init__(self, label, submenu):
super().__init__("")
# use a Text widget for label, we want the cursor
# on the arrow not the label
self._label = urwid.Text("")
self.set_label(label)
self._w = urwid.Columns([(1, urwid.SelectableIcon("\xdf")), self._label])
urwid.connect_signal(self, "click", lambda option: show_menu(submenu))
def keypress(self, size, key: str):
if key == "right":
key = "enter"
return super().keypress(size, key)
class Menu(urwid.ListBox):
def __init__(self, widgets):
self.menu_parent = None
super().__init__(urwid.SimpleListWalker(widgets))
def keypress(self, size, key: str):
"""
Go back to the previous menu on cancel button (mapped to esc)
"""
key = super().keypress(size, key)
if key in {"left", "esc"} and self.menu_parent:
show_menu(self.menu_parent)
return None
return key
def build_menus():
cursor_option_group = []
def cursor_option(label: str, style: Literal[1, 2, 3, 4]) -> LCDRadioButton:
"""A radio button that sets the cursor style"""
def on_change(b, state):
if state:
screen.set_cursor_style(style)
b = LCDRadioButton(cursor_option_group, label, screen.cursor_style == style)
urwid.connect_signal(b, "change", on_change)
return b
def display_setting(label: str, data_range: int, fn: Callable[[int], None]) -> urwid.Columns:
slider = LCDHorizontalSlider(data_range, data_range / 2, fn)
return urwid.Columns(
[
urwid.Text(label),
(10, slider),
]
)
def led_custom(index: Literal[0, 1, 2, 3]) -> urwid.Columns:
def exp_scale_led(rg: Literal[0, 1]) -> Callable[[int], None]:
"""
apply an exponential transformation to values sent so
that apparent brightness increases in a natural way.
"""
return lambda value: screen.set_led_pin(
index,
rg,
[0, 1, 2, 3, 4, 5, 6, 8, 11, 14, 18, 23, 29, 38, 48, 61, 79, 100][value],
)
return urwid.Columns(
[
(2, urwid.Text(f"{index:d}R")),
LCDHorizontalSlider(18, 0, exp_scale_led(0)),
(2, urwid.Text(" G")),
LCDHorizontalSlider(18, 0, exp_scale_led(1)),
]
)
menu_structure = [
(
"Display Settings",
[
display_setting("Brightness", 101, screen.set_backlight),
display_setting("Contrast", 76, lambda x: screen.set_lcd_contrast(x + 75)),
],
),
(
"Cursor Settings",
[
cursor_option("Block", screen.CURSOR_BLINKING_BLOCK),
cursor_option("Underscore", screen.CURSOR_UNDERSCORE),
cursor_option("Block + Underscore", screen.CURSOR_BLINKING_BLOCK_UNDERSCORE),
cursor_option("Inverting Block", screen.CURSOR_INVERTING_BLINKING_BLOCK),
],
),
(
"LEDs",
[
led_custom(0),
led_custom(1),
led_custom(2),
led_custom(3),
],
),
(
"About this Demo",
[
urwid.Text(
"This is a demo of Urwid's CF635Display "
"module. If you need an interface for a limited "
"character display device this should serve as a "
"good example for implementing your own display "
"module and menu-driven application."
),
],
),
]
def build_submenu(ms):
"""
Recursive menu building from structure above
"""
options = []
submenus = []
for opt in ms:
# shortform for MenuOptions
if isinstance(opt, tuple):
name, sub = opt
submenu = build_submenu(sub)
opt = MenuOption(name, submenu) # noqa: PLW2901
submenus.append(submenu)
options.append(opt)
menu = Menu(options)
for s in submenus:
s.menu_parent = menu
return menu
return build_submenu(menu_structure)
screen = urwid.display.lcd.CF635Screen(sys.argv[1])
# set up our font
program_cgram(screen)
loop = urwid.MainLoop(build_menus(), screen=screen)
# FIXME: want screen to know it is in narrow mode, or better yet,
# do the unicode conversion for us
urwid.set_encoding("narrow")
def show_menu(menu):
loop.widget = menu
loop.run()
|