From 898d4c1217e69497c67ca2ddb66641406a03700b Mon Sep 17 00:00:00 2001 From: Damien George Date: Thu, 8 Dec 2016 15:17:47 +1100 Subject: [PATCH] extmod/modframebuf: Make framebuf implement the buffer protocol. So that one can easily access the underlying data of the frame buffer, eg to write the data out to a display. --- extmod/modframebuf.c | 10 ++++++++++ tests/extmod/framebuf1.py | 3 +++ tests/extmod/framebuf1.py.exp | 1 + 3 files changed, 14 insertions(+) diff --git a/extmod/modframebuf.c b/extmod/modframebuf.c index b055a89389..eb639c1725 100644 --- a/extmod/modframebuf.c +++ b/extmod/modframebuf.c @@ -159,6 +159,15 @@ STATIC mp_obj_t framebuf_make_new(const mp_obj_type_t *type, size_t n_args, size return MP_OBJ_FROM_PTR(o); } +STATIC mp_int_t framebuf_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { + (void)flags; + mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(self_in); + bufinfo->buf = self->buf; + bufinfo->len = self->stride * self->height * (self->format == FRAMEBUF_RGB565 ? 2 : 1); + bufinfo->typecode = 'B'; // view framebuf as bytes + return 0; +} + STATIC mp_obj_t framebuf_fill(mp_obj_t self_in, mp_obj_t col_in) { mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(self_in); mp_int_t col = mp_obj_get_int(col_in); @@ -441,6 +450,7 @@ STATIC const mp_obj_type_t mp_type_framebuf = { { &mp_type_type }, .name = MP_QSTR_FrameBuffer, .make_new = framebuf_make_new, + .buffer_p = { .get_buffer = framebuf_get_buffer }, .locals_dict = (mp_obj_t)&framebuf_locals_dict, }; diff --git a/tests/extmod/framebuf1.py b/tests/extmod/framebuf1.py index 7be3655284..7f09050b04 100644 --- a/tests/extmod/framebuf1.py +++ b/tests/extmod/framebuf1.py @@ -10,6 +10,9 @@ h = 16 buf = bytearray(w * h // 8) fbuf = framebuf.FrameBuffer(buf, w, h, framebuf.MVLSB) +# access as buffer +print(memoryview(fbuf)[0]) + # fill fbuf.fill(1) print(buf) diff --git a/tests/extmod/framebuf1.py.exp b/tests/extmod/framebuf1.py.exp index dae02ad868..4a83a2e9c8 100644 --- a/tests/extmod/framebuf1.py.exp +++ b/tests/extmod/framebuf1.py.exp @@ -1,3 +1,4 @@ +0 bytearray(b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff') bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') bytearray(b'\x01\x00\x00\x00\x01\x80\x00\x00\x00\x80')