device.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2017-2020 Richard Hull and contributors
  3. # See LICENSE.rst for details.
  4. """
  5. Collection of serial interfaces to LED matrix devices.
  6. """
  7. # Example usage:
  8. #
  9. # from luma.core.interface.serial import spi, noop
  10. # from luma.core.render import canvas
  11. # from luma.led_matrix.device import max7219
  12. #
  13. # serial = spi(port=0, device=0, gpio=noop())
  14. # device = max7219(serial, width=8, height=8)
  15. #
  16. # with canvas(device) as draw:
  17. # draw.rectangle(device.bounding_box, outline="white", fill="black")
  18. #
  19. # As soon as the with-block scope level is complete, the graphics primitives
  20. # will be flushed to the device.
  21. #
  22. # Creating a new canvas is effectively 'carte blanche': If you want to retain
  23. # an existing canvas, then make a reference like:
  24. #
  25. # c = canvas(device)
  26. # for X in ...:
  27. # with c as draw:
  28. # draw.rectangle(...)
  29. #
  30. # As before, as soon as the with block completes, the canvas buffer is flushed
  31. # to the device
  32. import luma.core.error
  33. import luma.led_matrix.const
  34. from luma.core.interface.serial import noop
  35. from luma.core.device import device
  36. from luma.core.render import canvas
  37. from luma.core.util import observable
  38. from luma.core.virtual import sevensegment
  39. from luma.led_matrix.segment_mapper import dot_muncher, regular
  40. __all__ = ["max7219", "ws2812", "neopixel", "neosegment", "apa102", "unicornhathd"]
  41. class max7219(device):
  42. """
  43. Serial interface to a series of 8x8 LED matrixes daisychained together with
  44. MAX7219 chips.
  45. On creation, an initialization sequence is pumped to the display to properly
  46. configure it. Further control commands can then be called to affect the
  47. brightness and other settings.
  48. """
  49. def __init__(self, serial_interface=None, width=8, height=8, cascaded=None, rotate=0,
  50. block_orientation=0, blocks_arranged_in_reverse_order=False, contrast=0x70,
  51. **kwargs):
  52. super(max7219, self).__init__(luma.led_matrix.const.max7219, serial_interface)
  53. # Derive (override) the width and height if a cascaded param supplied
  54. if cascaded is not None:
  55. width = cascaded * 8
  56. height = 8
  57. self.blocks_arranged_in_reverse_order = blocks_arranged_in_reverse_order
  58. self.capabilities(width, height, rotate)
  59. self.segment_mapper = dot_muncher
  60. if width <= 0 or width % 8 != 0 or height <= 0 or height % 8 != 0:
  61. raise luma.core.error.DeviceDisplayModeError(
  62. f"Unsupported display mode: {width} x {height}")
  63. assert block_orientation in [0, 90, -90, 180]
  64. self._correction_angle = block_orientation
  65. self.cascaded = cascaded or (width * height) // 64
  66. self._offsets = [(y * self._w) + x
  67. for y in range(self._h - 8, -8, -8)
  68. for x in range(self._w - 8, -8, -8)]
  69. self._rows = list(range(8))
  70. self.data([self._const.SCANLIMIT, 7] * self.cascaded)
  71. self.data([self._const.DECODEMODE, 0] * self.cascaded)
  72. self.data([self._const.DISPLAYTEST, 0] * self.cascaded)
  73. self.contrast(contrast)
  74. self.clear()
  75. self.show()
  76. def preprocess(self, image):
  77. """
  78. Performs the inherited behviour (if any), and if the LED matrix
  79. orientation is declared to need correction, each 8x8 block of pixels
  80. is rotated 90° clockwise or counter-clockwise.
  81. """
  82. image = super(max7219, self).preprocess(image)
  83. if self._correction_angle != 0:
  84. image = image.copy()
  85. for y in range(0, self._h, 8):
  86. for x in range(0, self._w, 8):
  87. box = (x, y, x + 8, y + 8)
  88. rotated_block = image.crop(box).rotate(self._correction_angle)
  89. image.paste(rotated_block, box)
  90. if self.blocks_arranged_in_reverse_order:
  91. old_image = image.copy()
  92. for y in range(8):
  93. for x in range(8):
  94. for i in range(self.cascaded):
  95. image.putpixel((8 * (self.cascaded - 1) - i * 8 + x, y), old_image.getpixel((i * 8 + x, y)))
  96. return image
  97. def display(self, image):
  98. """
  99. Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the LED matrix display
  100. via the MAX7219 serializers.
  101. """
  102. assert(image.mode == self.mode)
  103. assert(image.size == self.size)
  104. image = self.preprocess(image)
  105. i = 0
  106. d0 = self._const.DIGIT_0
  107. step = 2 * self.cascaded
  108. offsets = self._offsets
  109. rows = self._rows
  110. buf = bytearray(8 * step)
  111. pix = list(image.getdata())
  112. for digit in range(8):
  113. for daisychained_device in offsets:
  114. byte = 0
  115. idx = daisychained_device + digit
  116. for y in rows:
  117. if pix[idx] > 0:
  118. byte |= 1 << y
  119. idx += self._w
  120. buf[i] = digit + d0
  121. buf[i + 1] = byte
  122. i += 2
  123. buf = list(buf)
  124. for i in range(0, len(buf), step):
  125. self.data(buf[i:i + step])
  126. def contrast(self, value):
  127. """
  128. Sets the LED intensity to the desired level, in the range 0-255.
  129. :param level: Desired contrast level in the range of 0-255.
  130. :type level: int
  131. """
  132. assert(0x00 <= value <= 0xFF)
  133. self.data([self._const.INTENSITY, value >> 4] * self.cascaded)
  134. def show(self):
  135. """
  136. Sets the display mode ON, waking the device out of a prior
  137. low-power sleep mode.
  138. """
  139. self.data([self._const.SHUTDOWN, 1] * self.cascaded)
  140. def hide(self):
  141. """
  142. Switches the display mode OFF, putting the device in low-power
  143. sleep mode.
  144. """
  145. self.data([self._const.SHUTDOWN, 0] * self.cascaded)
  146. class ws2812(device):
  147. """
  148. Serial interface to a series of RGB neopixels daisy-chained together with
  149. WS281x chips.
  150. On creation, the array is initialized with the correct number of cascaded
  151. devices. Further control commands can then be called to affect the
  152. brightness and other settings.
  153. :param dma_interface: The WS2812 interface to write to (usually omit this
  154. parameter and it will default to the correct value - it is only needed
  155. for testing whereby a mock implementation is supplied).
  156. :param width: The number of pixels laid out horizontally.
  157. :type width: int
  158. :param height: The number of pixels laid out vertically.
  159. :type width: int
  160. :param cascaded: The number of pixels in a single strip - if supplied, this
  161. will override ``width`` and ``height``.
  162. :type cascaded: int
  163. :param rotate: Whether the device dimenstions should be rotated in-situ:
  164. A value of: 0=0°, 1=90°, 2=180°, 3=270°. If not supplied, zero is
  165. assumed.
  166. :type rotate: int
  167. :param mapping: An (optional) array of integer values that translate the
  168. pixel to physical offsets. If supplied, should be the same size as
  169. ``width * height``.
  170. :type mapping: int[]
  171. .. versionadded:: 0.4.0
  172. """
  173. def __init__(self, dma_interface=None, width=8, height=4, cascaded=None,
  174. rotate=0, mapping=None, **kwargs):
  175. super(ws2812, self).__init__(const=None, serial_interface=noop)
  176. # Derive (override) the width and height if a cascaded param supplied
  177. if cascaded is not None:
  178. width = cascaded
  179. height = 1
  180. self.cascaded = width * height
  181. self.capabilities(width, height, rotate, mode="RGB")
  182. self._mapping = list(mapping or range(self.cascaded))
  183. assert(self.cascaded == len(self._mapping))
  184. self._contrast = None
  185. self._prev_contrast = 0x70
  186. ws = self._ws = dma_interface or self.__ws281x__()
  187. # Create ws2811_t structure and fill in parameters.
  188. self._leds = ws.new_ws2811_t()
  189. pin = 18
  190. channel = 0
  191. dma = 10
  192. freq_hz = 800000
  193. brightness = 255
  194. strip_type = ws.WS2811_STRIP_GRB
  195. invert = False
  196. # Initialize the channels to zero
  197. for channum in range(2):
  198. chan = ws.ws2811_channel_get(self._leds, channum)
  199. ws.ws2811_channel_t_count_set(chan, 0)
  200. ws.ws2811_channel_t_gpionum_set(chan, 0)
  201. ws.ws2811_channel_t_invert_set(chan, 0)
  202. ws.ws2811_channel_t_brightness_set(chan, 0)
  203. # Initialize the channel in use
  204. self._channel = ws.ws2811_channel_get(self._leds, channel)
  205. ws.ws2811_channel_t_count_set(self._channel, self.cascaded)
  206. ws.ws2811_channel_t_gpionum_set(self._channel, pin)
  207. ws.ws2811_channel_t_invert_set(self._channel, 0 if not invert else 1)
  208. ws.ws2811_channel_t_brightness_set(self._channel, brightness)
  209. ws.ws2811_channel_t_strip_type_set(self._channel, strip_type)
  210. # Initialize the controller
  211. ws.ws2811_t_freq_set(self._leds, freq_hz)
  212. ws.ws2811_t_dmanum_set(self._leds, dma)
  213. resp = ws.ws2811_init(self._leds)
  214. if resp != 0:
  215. raise RuntimeError(f'ws2811_init failed with code {resp}')
  216. self.clear()
  217. self.show()
  218. def __ws281x__(self):
  219. import _rpi_ws281x
  220. return _rpi_ws281x
  221. def display(self, image):
  222. """
  223. Takes a 24-bit RGB :py:mod:`PIL.Image` and dumps it to the daisy-chained
  224. WS2812 neopixels.
  225. """
  226. assert(image.mode == self.mode)
  227. assert(image.size == self.size)
  228. ws = self._ws
  229. m = self._mapping
  230. for idx, (red, green, blue) in enumerate(image.getdata()):
  231. color = (red << 16) | (green << 8) | blue
  232. ws.ws2811_led_set(self._channel, m[idx], color)
  233. self._flush()
  234. def show(self):
  235. """
  236. Simulates switching the display mode ON; this is achieved by restoring
  237. the contrast to the level prior to the last time hide() was called.
  238. """
  239. if self._prev_contrast is not None:
  240. self.contrast(self._prev_contrast)
  241. self._prev_contrast = None
  242. def hide(self):
  243. """
  244. Simulates switching the display mode OFF; this is achieved by setting
  245. the contrast level to zero.
  246. """
  247. if self._prev_contrast is None:
  248. self._prev_contrast = self._contrast
  249. self.contrast(0x00)
  250. def contrast(self, value):
  251. """
  252. Sets the LED intensity to the desired level, in the range 0-255.
  253. :param level: Desired contrast level in the range of 0-255.
  254. :type level: int
  255. """
  256. assert(0x00 <= value <= 0xFF)
  257. self._contrast = value
  258. self._ws.ws2811_channel_t_brightness_set(self._channel, value)
  259. self._flush()
  260. def _flush(self):
  261. resp = self._ws.ws2811_render(self._leds)
  262. if resp != 0:
  263. raise RuntimeError('ws2811_render failed with code {0}'.format(resp))
  264. def __del__(self):
  265. # Required because Python will complain about memory leaks
  266. # However there's no guarantee that "ws" will even be set
  267. # when the __del__ method for this class is reached.
  268. if self._ws is not None:
  269. self.cleanup()
  270. def cleanup(self):
  271. """
  272. Attempt to reset the device & switching it off prior to exiting the
  273. python process.
  274. """
  275. self.hide()
  276. self.clear()
  277. if self._leds is not None:
  278. self._ws.ws2811_fini(self._leds)
  279. self._ws.delete_ws2811_t(self._leds)
  280. self._leds = None
  281. self._channel = None
  282. # Alias for ws2812
  283. neopixel = ws2812
  284. # 8x8 Unicorn HAT has a 'snake-like' layout, so this translation
  285. # mapper linearizes that arrangement into a 'scan-like' layout.
  286. UNICORN_HAT = [
  287. 7, 6, 5, 4, 3, 2, 1, 0,
  288. 8, 9, 10, 11, 12, 13, 14, 15,
  289. 23, 22, 21, 20, 19, 18, 17, 16,
  290. 24, 25, 26, 27, 28, 29, 30, 31,
  291. 39, 38, 37, 36, 35, 34, 33, 32,
  292. 40, 41, 42, 43, 44, 45, 46, 47,
  293. 55, 54, 53, 52, 51, 50, 49, 48,
  294. 56, 57, 58, 59, 60, 61, 62, 63
  295. ]
  296. class apa102(device):
  297. """
  298. Serial interface to a series of 'next-gen' RGB DotStar daisy-chained
  299. together with APA102 chips.
  300. On creation, the array is initialized with the correct number of cascaded
  301. devices. Further control commands can then be called to affect the brightness
  302. and other settings.
  303. Note that the brightness of individual pixels can be set by altering the
  304. alpha channel of the RGBA image that is being displayed.
  305. :param serial_interface: The serial interface to write to (usually omit this
  306. parameter and it will default to the correct value - it is only needed
  307. for testing whereby a mock implementation is supplied).
  308. :param width: The number of pixels laid out horizontally.
  309. :type width: int
  310. :param height: The number of pixels laid out vertically.
  311. :type width: int
  312. :param cascaded: The number of pixels in a single strip - if supplied, this
  313. will override ``width`` and ``height``.
  314. :type cascaded: int
  315. :param rotate: Whether the device dimenstions should be rotated in-situ:
  316. A value of: 0=0°, 1=90°, 2=180°, 3=270°. If not supplied, zero is
  317. assumed.
  318. :type rotate: int
  319. :param mapping: An (optional) array of integer values that translate the
  320. pixel to physical offsets. If supplied, should be the same size as
  321. ``width * height``.
  322. :type mapping: int[]
  323. .. versionadded:: 0.9.0
  324. """
  325. def __init__(self, serial_interface=None, width=8, height=1, cascaded=None,
  326. rotate=0, mapping=None, **kwargs):
  327. super(apa102, self).__init__(luma.core.const.common, serial_interface or self.__bitbang__())
  328. # Derive (override) the width and height if a cascaded param supplied
  329. if cascaded is not None:
  330. width = cascaded
  331. height = 1
  332. self.cascaded = width * height
  333. self.capabilities(width, height, rotate, mode="RGBA")
  334. self._mapping = list(mapping or range(self.cascaded))
  335. assert(self.cascaded == len(self._mapping))
  336. self._last_image = None
  337. self.contrast(0x70)
  338. self.clear()
  339. self.show()
  340. def __bitbang__(self):
  341. from luma.core.interface.serial import bitbang
  342. return bitbang(SCLK=24, SDA=23)
  343. def display(self, image):
  344. """
  345. Takes a 32-bit RGBA :py:mod:`PIL.Image` and dumps it to the daisy-chained
  346. APA102 neopixels. If a pixel is not fully opaque, the alpha channel
  347. value is used to set the brightness of the respective RGB LED.
  348. """
  349. assert(image.mode == self.mode)
  350. assert(image.size == self.size)
  351. self._last_image = image.copy()
  352. # Send zeros to reset, then pixel values then zeros at end
  353. sz = image.width * image.height * 4
  354. buf = bytearray(sz * 3)
  355. m = self._mapping
  356. for idx, (r, g, b, a) in enumerate(image.getdata()):
  357. offset = sz + m[idx] * 4
  358. brightness = (a >> 4) if a != 0xFF else self._brightness
  359. buf[offset] = (0xE0 | brightness)
  360. buf[offset + 1] = b
  361. buf[offset + 2] = g
  362. buf[offset + 3] = r
  363. self._serial_interface.data(list(buf))
  364. def show(self):
  365. """
  366. Not supported
  367. """
  368. pass
  369. def hide(self):
  370. """
  371. Not supported
  372. """
  373. pass
  374. def contrast(self, value):
  375. """
  376. Sets the LED intensity to the desired level, in the range 0-255.
  377. :param level: Desired contrast level in the range of 0-255.
  378. :type level: int
  379. """
  380. assert(0x00 <= value <= 0xFF)
  381. self._brightness = value >> 4
  382. if self._last_image is not None:
  383. self.display(self._last_image)
  384. class neosegment(sevensegment):
  385. """
  386. Extends the :py:class:`~luma.core.virtual.sevensegment` class specifically
  387. for @msurguy's modular NeoSegments. It uses the same underlying render
  388. techniques as the base class, but provides additional functionality to be
  389. able to adddress individual characters colors.
  390. :param width: The number of 7-segment elements that are cascaded.
  391. :type width: int
  392. :param undefined: The default character to substitute when an unrenderable
  393. character is supplied to the text property.
  394. :type undefined: char
  395. .. versionadded:: 0.11.0
  396. """
  397. def __init__(self, width, undefined="_", **kwargs):
  398. if width <= 0 or width % 2 == 1:
  399. raise luma.core.error.DeviceDisplayModeError(
  400. "Unsupported display mode: width={0}".format(width))
  401. height = 7
  402. mapping = [(i % width) * height + (i // width) for i in range(width * height)]
  403. self.device = kwargs.get("device") or ws2812(width=width, height=height, mapping=mapping)
  404. self.undefined = undefined
  405. self._text_buffer = ""
  406. self.color = "white"
  407. @property
  408. def color(self):
  409. return self._colors
  410. @color.setter
  411. def color(self, value):
  412. if not isinstance(value, list):
  413. value = [value] * self.device.width
  414. assert(len(value) == self.device.width)
  415. self._colors = observable(value, observer=self._color_chg)
  416. def _color_chg(self, color):
  417. self._flush(self.text, color)
  418. def _flush(self, text, color=None):
  419. data = bytearray(self.segment_mapper(text, notfound=self.undefined)).ljust(self.device.width, b'\0')
  420. color = color or self.color
  421. if len(data) > self.device.width:
  422. raise OverflowError(
  423. "Device's capabilities insufficient for value '{0}'".format(text))
  424. with canvas(self.device) as draw:
  425. for x, byte in enumerate(data):
  426. for y in range(self.device.height):
  427. if byte & 0x01:
  428. draw.point((x, y), fill=color[x])
  429. byte >>= 1
  430. def segment_mapper(self, text, notfound="_"):
  431. for char in regular(text, notfound):
  432. # Convert from std MAX7219 segment mappings
  433. a = char >> 6 & 0x01
  434. b = char >> 5 & 0x01
  435. c = char >> 4 & 0x01
  436. d = char >> 3 & 0x01
  437. e = char >> 2 & 0x01
  438. f = char >> 1 & 0x01
  439. g = char >> 0 & 0x01
  440. # To NeoSegment positions
  441. yield \
  442. b << 6 | \
  443. a << 5 | \
  444. f << 4 | \
  445. g << 3 | \
  446. c << 2 | \
  447. d << 1 | \
  448. e << 0
  449. class unicornhathd(device):
  450. """
  451. Display adapter for Pimoroni's Unicorn Hat HD - a dense 16x16 array of
  452. high intensity RGB LEDs. Since the board contains a small ARM chip to
  453. manage the LEDs, interfacing is very straightforward using SPI. This has
  454. the side-effect that the board appears not to be daisy-chainable though.
  455. However there a number of undocumented contact pads on the underside of
  456. the board which _may_ allow this behaviour.
  457. Note that the brightness of individual pixels can be set by altering the
  458. alpha channel of the RGBA image that is being displayed.
  459. :param serial_interface: The serial interface to write to.
  460. :param rotate: Whether the device dimenstions should be rotated in-situ:
  461. A value of: 0=0°, 1=90°, 2=180°, 3=270°. If not supplied, zero is
  462. assumed.
  463. :type rotate: int
  464. .. versionadded:: 1.3.0
  465. """
  466. def __init__(self, serial_interface=None, rotate=0, **kwargs):
  467. super(unicornhathd, self).__init__(luma.core.const.common, serial_interface)
  468. self.capabilities(16, 16, rotate, mode="RGBA")
  469. self._last_image = None
  470. self._prev_brightness = None
  471. self.contrast(0x70)
  472. self.clear()
  473. self.show()
  474. def display(self, image):
  475. """
  476. Takes a 32-bit RGBA :py:mod:`PIL.Image` and dumps it to the Unicorn HAT HD.
  477. If a pixel is not fully opaque, the alpha channel value is used to set the
  478. brightness of the respective RGB LED.
  479. """
  480. assert(image.mode == self.mode)
  481. assert(image.size == self.size)
  482. self._last_image = image.copy()
  483. # Send zeros to reset, then pixel values then zeros at end
  484. sz = image.width * image.height * 3
  485. buf = bytearray(sz)
  486. normalized_brightness = self._brightness / 255.0
  487. for idx, (r, g, b, a) in enumerate(image.getdata()):
  488. offset = idx * 3
  489. brightness = a / 255.0 if a != 255 else normalized_brightness
  490. buf[offset] = int(r * brightness)
  491. buf[offset + 1] = int(g * brightness)
  492. buf[offset + 2] = int(b * brightness)
  493. self._serial_interface.data([0x72] + list(buf)) # 0x72 == SOF ... start of frame?
  494. def show(self):
  495. """
  496. Simulates switching the display mode ON; this is achieved by restoring
  497. the contrast to the level prior to the last time hide() was called.
  498. """
  499. if self._prev_brightness is not None:
  500. self.contrast(self._prev_brightness)
  501. self._prev_brightness = None
  502. def hide(self):
  503. """
  504. Simulates switching the display mode OFF; this is achieved by setting
  505. the contrast level to zero.
  506. """
  507. if self._prev_brightness is None:
  508. self._prev_brightness = self._brightness
  509. self.contrast(0x00)
  510. def contrast(self, value):
  511. """
  512. Sets the LED intensity to the desired level, in the range 0-255.
  513. :param level: Desired contrast level in the range of 0-255.
  514. :type level: int
  515. """
  516. assert(0x00 <= value <= 0xFF)
  517. self._brightness = value
  518. if self._last_image is not None:
  519. self.display(self._last_image)