From 46538840e9aa8072e1c0b8bc060d0abbcd0a52a6 Mon Sep 17 00:00:00 2001 From: sza Date: Fri, 11 Feb 2022 17:36:49 +0100 Subject: [PATCH] init --- components/rasterfont/__init__.py | 82 +++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 components/rasterfont/__init__.py diff --git a/components/rasterfont/__init__.py b/components/rasterfont/__init__.py new file mode 100644 index 0000000..d1f9365 --- /dev/null +++ b/components/rasterfont/__init__.py @@ -0,0 +1,82 @@ +# coding=utf-8 +from esphome import core +from esphome.components import display +import esphome.config_validation as cv +import esphome.codegen as cg +from esphome.const import CONF_ID, CONF_GLYPHS, CONF_DATA +from esphome.core import CORE, HexInt +#from esphome.py_compat import sort_by_cmp + +DEPENDENCIES = ['display'] +MULTI_CONF = True + +Font = display.display_ns.class_('Font') +Glyph = display.display_ns.class_('Glyph') + + +def validate_data(value): + r = type(value)() + for k, v in value.items(): + r[str(k)] = v + + return type(value)(sorted(r.items())) + +CONF_RAW_DATA_ID = 'raw_data_id' +BIT0_DEFAULT = '0 ' + +RASTERFONT_SCHEMA = cv.Schema({ + cv.Required(CONF_ID): cv.declare_id(Font), + cv.Required(CONF_DATA): validate_data, + cv.Optional(CONF_GLYPHS): cv.string_strict, + cv.Optional('bit0', default=BIT0_DEFAULT): cv.string_strict, + cv.GenerateID(CONF_RAW_DATA_ID): cv.declare_id(cg.uint8), +}) + +CONFIG_SCHEMA = cv.All(RASTERFONT_SCHEMA) + + +def string_to_int(s, bit0): + b = ''.join(map(lambda x: '0' if x in bit0 else '1', s+'0'*((8-len(s) % 8) % 8))) + r = [int(b[i:i+8], 2) for i in range(0, len(b), 8)] + return r + +def to_code(config): + + glyph_args = {} + data = [] + include_glyphs = config.get(CONF_GLYPHS, None) + bit0 = config.get('bit0') + for glyph, gconfig in config[CONF_DATA].items(): + if include_glyphs and glyph not in include_glyphs: continue + + height = 0 + maxwidth = 0 + offset_x = gconfig.get('offset_x', 0) + offset_y = gconfig.get('offset_y', 0) + + rows = gconfig.get('bitmap', []) + if isinstance(rows, str): + rows = rows.split('\n') + while rows[-1] == '': rows.pop() + + for row in rows: + maxwidth = max(maxwidth, len(row)) + width = gconfig.get('width', maxwidth) + + glyph_data = [] + for row in rows: + height += 1 + glyph_data += string_to_int(row + '0'*(maxwidth-len(row)), bit0) + + width8 = ((width + 7) // 8) * 8 + glyph_args[str(glyph)] = (len(data), offset_x, offset_y, width, height) + data += glyph_data + + rhs = [HexInt(x) for x in data] + prog_arr = cg.progmem_array(config[CONF_RAW_DATA_ID], rhs) + + glyphs = [] + for glyph in config[CONF_DATA].keys(): + glyphs.append(Glyph(str(glyph), prog_arr, *glyph_args[str(glyph)])) + + cg.new_Pvariable(config[CONF_ID], glyphs, 0, 0)