Esempio n. 1
0
def to_code(config):
    var = cg.new_Pvariable(config[CONF_ID])
    yield cg.register_component(var, config)

    cg.add(var.set_host(config[CONF_HOST]))
    cg.add(var.set_port(config[CONF_PORT]))
    cg.add(var.set_max_packet_size(config[CONF_MAX_PACKET_SIZE]))
    cg.add(var.set_send_timeout(config[CONF_SEND_TIMEOUT]))
    cg.add(var.set_publish_all(config[CONF_PUBLISH_ALL]))
    cg.add(
        var.set_tags(''.join(',{}={}'.format(tag, value)
                             for tag, value in config[CONF_TAGS].items())))
    for sensor_id, sensor_config in config[CONF_SENSORS].items():
        if sensor_config[CONF_IGNORE] == False:
            tags = ''.join(',{}={}'.format(tag, value) for tag, value in {
                **config[CONF_TAGS],
                **sensor_config[CONF_TAGS]
            }.items())
            if 'measurement' in sensor_config:
                measurement = f"\"{sensor_config[CONF_MEASUREMENT]}\""
            else:
                measurement = f"{sensor_id}->get_object_id()"
            cg.add(
                var.add_setup_callback(
                    cg.RawExpression(
                        f"[]() -> Nameable* {{ {sensor_id}->add_on_state_callback([](float state) {{ {config[CONF_ID]}->on_sensor_update({sensor_id}, {measurement}, \"{tags}\", state); }}); return {sensor_id}; }}"
                    )))
        else:
            cg.add(
                var.add_setup_callback(
                    cg.RawExpression(
                        f"[]() -> Nameable* {{ return {sensor_id}; }}")))

    cg.add_define('USE_INFLUXDB')
    cg.add_global(influxdb_ns.using)
Esempio n. 2
0
async def to_code(config):
    var = await fastled_base.new_fastled_light(config)

    rgb_order = None
    if CONF_RGB_ORDER in config:
        rgb_order = cg.RawExpression(config[CONF_RGB_ORDER])
    template_args = cg.TemplateArguments(
        cg.RawExpression(config[CONF_CHIPSET]), config[CONF_PIN], rgb_order)
    cg.add(var.add_leds(template_args, config[CONF_NUM_LEDS]))
Esempio n. 3
0
async def to_code(config):
    cg.add_global(cg.global_ns.namespace("esphome").using)
    # These can be used by user lambdas, put them to default scope
    cg.add_global(cg.RawExpression("using std::isnan"))
    cg.add_global(cg.RawExpression("using std::min"))
    cg.add_global(cg.RawExpression("using std::max"))

    cg.add(
        cg.App.pre_setup(
            config[CONF_NAME],
            cg.RawExpression('__DATE__ ", " __TIME__'),
            config[CONF_NAME_ADD_MAC_SUFFIX],
        ))

    CORE.add_job(_add_automations, config)

    cg.add_build_flag("-fno-exceptions")

    # Libraries
    for lib in config[CONF_LIBRARIES]:
        if "@" in lib:
            name, vers = lib.split("@", 1)
            cg.add_library(name, vers)
        elif "://" in lib:
            # Repository...
            if "=" in lib:
                name, repo = lib.split("=", 1)
                cg.add_library(name, None, repo)
            else:
                cg.add_library(None, None, lib)

        else:
            cg.add_library(lib, None)

    cg.add_build_flag("-Wno-unused-variable")
    cg.add_build_flag("-Wno-unused-but-set-variable")
    cg.add_build_flag("-Wno-sign-compare")

    if CORE.using_arduino:
        CORE.add_job(add_arduino_global_workaround)

    if config[CONF_INCLUDES]:
        CORE.add_job(add_includes, config[CONF_INCLUDES])

    if CONF_PROJECT in config:
        cg.add_define("ESPHOME_PROJECT_NAME", config[CONF_PROJECT][CONF_NAME])
        cg.add_define("ESPHOME_PROJECT_VERSION",
                      config[CONF_PROJECT][CONF_VERSION])

    if config[CONF_PLATFORMIO_OPTIONS]:
        CORE.add_job(_add_platformio_options, config[CONF_PLATFORMIO_OPTIONS])
Esempio n. 4
0
async def add_pin_initial_states_array():
    # Add includes at the very end, so that they override everything
    initial_states: List[PinInitialState] = CORE.data[KEY_ESP8266][
        KEY_PIN_INITIAL_STATES]
    initial_modes_s = ", ".join(str(x.mode) for x in initial_states)
    initial_levels_s = ", ".join(str(x.level) for x in initial_states)

    cg.add_global(
        cg.RawExpression(
            f"const uint8_t ESPHOME_ESP8266_GPIO_INITIAL_MODE[16] = {{{initial_modes_s}}}"
        ))
    cg.add_global(
        cg.RawExpression(
            f"const uint8_t ESPHOME_ESP8266_GPIO_INITIAL_LEVEL[16] = {{{initial_levels_s}}}"
        ))
def to_code(config):
    cg.add_global(cg.global_ns.namespace('esphome').using)
    cg.add(cg.App.pre_setup(config[CONF_NAME], cg.RawExpression('__DATE__ ", " __TIME__')))

    for conf in config.get(CONF_ON_BOOT, []):
        trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], conf.get(CONF_PRIORITY))
        yield cg.register_component(trigger, conf)
        yield automation.build_automation(trigger, [], conf)

    for conf in config.get(CONF_ON_SHUTDOWN, []):
        trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID])
        yield cg.register_component(trigger, conf)
        yield automation.build_automation(trigger, [], conf)

    for conf in config.get(CONF_ON_LOOP, []):
        trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID])
        yield cg.register_component(trigger, conf)
        yield automation.build_automation(trigger, [], conf)

    # Build flags
    if CORE.is_esp8266 and CORE.board in ESP8266_FLASH_SIZES and \
            CORE.arduino_version != ARDUINO_VERSION_ESP8266_2_3_0:
        flash_size = ESP8266_FLASH_SIZES[CORE.board]
        ld_scripts = ESP8266_LD_SCRIPTS[flash_size]
        ld_script = None

        if CORE.arduino_version in ('[email protected]', '[email protected]',
                                    '[email protected]'):
            ld_script = ld_scripts[0]
        elif CORE.arduino_version in (ARDUINO_VERSION_ESP8266_DEV, ARDUINO_VERSION_ESP8266_2_5_0,
                                      ARDUINO_VERSION_ESP8266_2_5_1, ARDUINO_VERSION_ESP8266_2_5_2):
            ld_script = ld_scripts[1]

        if ld_script is not None:
            cg.add_build_flag(f'-Wl,-T{ld_script}')

    cg.add_build_flag('-fno-exceptions')

    # Libraries
    if CORE.is_esp32:
        cg.add_library('ESPmDNS', None)
    elif CORE.is_esp8266:
        cg.add_library('ESP8266WiFi', None)
        cg.add_library('ESP8266mDNS', None)

    for lib in config[CONF_LIBRARIES]:
        if '@' in lib:
            name, vers = lib.split('@', 1)
            cg.add_library(name, vers)
        else:
            cg.add_library(lib, None)

    cg.add_build_flag('-Wno-unused-variable')
    cg.add_build_flag('-Wno-unused-but-set-variable')
    cg.add_build_flag('-Wno-sign-compare')
    if config.get(CONF_ESP8266_RESTORE_FROM_FLASH, False):
        cg.add_define('USE_ESP8266_PREFERENCES_FLASH')

    if config[CONF_INCLUDES]:
        CORE.add_job(add_includes, config[CONF_INCLUDES])
Esempio n. 6
0
def to_code(config):
    var = yield new_fastled_matrix(config)

    rgb_order = None
    if CONF_RGB_ORDER in config:
        rgb_order = cg.RawExpression(config[CONF_RGB_ORDER])
    template_args = cg.TemplateArguments(
        cg.RawExpression(config[CONF_CHIPSET]), config[CONF_PIN], rgb_order)
    cg.add(var.add_leds(template_args, config[CONF_NUM_LEDS]))

    cg.add(
        var.set_matrix(config[CONF_WIDTH], config[CONF_HEIGHT],
                       sum([MATRIX_TYPE[i] for i in config[CONF_TYPE]])))
    cg.add(var.set_max_current(config[CONF_MAX_CURRENT]))
    cg.add(var.set_max_brightness(config[CONF_MAX_BRIGHTNESS]))
    cg.add(var.set_rotation(config[CONF_ROTATION]))
Esempio n. 7
0
async def to_code(config):
    cg.add_global(cg.global_ns.namespace("esphome").using)
    cg.add(
        cg.App.pre_setup(
            config[CONF_NAME],
            cg.RawExpression('__DATE__ ", " __TIME__'),
            config[CONF_NAME_ADD_MAC_SUFFIX],
        ))

    CORE.add_job(_add_automations, config)

    # Set LWIP build constants for ESP8266
    if CORE.is_esp8266:
        CORE.add_job(_esp8266_add_lwip_type)

    cg.add_build_flag("-fno-exceptions")

    # Libraries
    for lib in config[CONF_LIBRARIES]:
        if "@" in lib:
            name, vers = lib.split("@", 1)
            cg.add_library(name, vers)
        else:
            cg.add_library(lib, None)

    cg.add_build_flag("-Wno-unused-variable")
    cg.add_build_flag("-Wno-unused-but-set-variable")
    cg.add_build_flag("-Wno-sign-compare")
    if config.get(CONF_ESP8266_RESTORE_FROM_FLASH, False):
        cg.add_define("USE_ESP8266_PREFERENCES_FLASH")

    if config[CONF_INCLUDES]:
        CORE.add_job(add_includes, config[CONF_INCLUDES])
Esempio n. 8
0
async def logger_log_action_to_code(config, action_id, template_arg, args):
    esp_log = LOG_LEVEL_TO_ESP_LOG[config[CONF_LEVEL]]
    args_ = [cg.RawExpression(str(x)) for x in config[CONF_ARGS]]

    text = str(cg.statement(esp_log(config[CONF_TAG], config[CONF_FORMAT], *args_)))

    lambda_ = await cg.process_lambda(Lambda(text), args, return_type=cg.void)
    return cg.new_Pvariable(action_id, template_arg, lambda_)
Esempio n. 9
0
def as_hex_array(value):
    value = value.replace("-", "")
    cpp_array = [
        f'0x{part}'
        for part in [value[i:i + 2] for i in range(0, len(value), 2)]
    ]
    return cg.RawExpression('(uint8_t*)(const uint8_t[16]){{{}}}'.format(
        ','.join(reversed(cpp_array))))
Esempio n. 10
0
def as_reversed_hex_array(value):
    value = value.replace("-", "")
    cpp_array = [
        f"0x{part}"
        for part in [value[i:i + 2] for i in range(0, len(value), 2)]
    ]
    return cg.RawExpression(
        f"(uint8_t*)(const uint8_t[16]){{{','.join(reversed(cpp_array))}}}")
Esempio n. 11
0
def to_code(config):
    var = yield fastled_base.new_fastled_light(config)

    rgb_order = cg.RawExpression(config[CONF_RGB_ORDER] if CONF_RGB_ORDER in config else "RGB")
    data_rate = None

    if CONF_DATA_RATE in config:
        data_rate_khz = int(config[CONF_DATA_RATE] / 1000)
        if data_rate_khz < 1000:
            data_rate = cg.RawExpression(f"DATA_RATE_KHZ({data_rate_khz})")
        else:
            data_rate_mhz = int(data_rate_khz / 1000)
            data_rate = cg.RawExpression(f"DATA_RATE_MHZ({data_rate_mhz})")
    template_args = cg.TemplateArguments(cg.RawExpression(config[CONF_CHIPSET]),
                                         config[CONF_DATA_PIN], config[CONF_CLOCK_PIN], rgb_order,
                                         data_rate)
    cg.add(var.add_leds(template_args, config[CONF_NUM_LEDS]))
Esempio n. 12
0
async def to_code(config):
    from PIL import ImageFont

    conf = config[CONF_FILE]
    if conf[CONF_TYPE] == TYPE_LOCAL:
        path = CORE.relative_config_path(conf[CONF_PATH])
    elif conf[CONF_TYPE] == TYPE_GFONTS:
        path = _compute_gfonts_local_path(conf)
    try:
        font = ImageFont.truetype(str(path), config[CONF_SIZE])
    except Exception as e:
        raise core.EsphomeError(f"Could not load truetype file {path}: {e}")

    ascent, descent = font.getmetrics()

    glyph_args = {}
    data = []
    for glyph in config[CONF_GLYPHS]:
        mask = font.getmask(glyph, mode="1")
        _, (offset_x, offset_y) = font.font.getsize(glyph)
        width, height = mask.size
        width8 = ((width + 7) // 8) * 8
        glyph_data = [0] * (height * width8 // 8)
        for y in range(height):
            for x in range(width):
                if not mask.getpixel((x, y)):
                    continue
                pos = x + y * width8
                glyph_data[pos // 8] |= 0x80 >> (pos % 8)
        glyph_args[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)

    glyph_initializer = []
    for glyph in config[CONF_GLYPHS]:
        glyph_initializer.append(
            cg.StructInitializer(
                GlyphData,
                ("a_char", glyph),
                (
                    "data",
                    cg.RawExpression(
                        f"{str(prog_arr)} + {str(glyph_args[glyph][0])}"),
                ),
                ("offset_x", glyph_args[glyph][1]),
                ("offset_y", glyph_args[glyph][2]),
                ("width", glyph_args[glyph][3]),
                ("height", glyph_args[glyph][4]),
            ))

    glyphs = cg.static_const_array(config[CONF_RAW_GLYPH_ID],
                                   glyph_initializer)

    cg.new_Pvariable(config[CONF_ID], glyphs, len(glyph_initializer), ascent,
                     ascent + descent)
Esempio n. 13
0
async def to_code(config):
    cg.add_global(cg.global_ns.namespace("esphome").using)
    cg.add(
        cg.App.pre_setup(
            config[CONF_NAME],
            cg.RawExpression('__DATE__ ", " __TIME__'),
            config[CONF_NAME_ADD_MAC_SUFFIX],
        ))

    CORE.add_job(_add_automations, config)

    # Set LWIP build constants for ESP8266
    if CORE.is_esp8266:
        CORE.add_job(_esp8266_add_lwip_type)

    cg.add_build_flag("-fno-exceptions")

    # Libraries
    for lib in config[CONF_LIBRARIES]:
        if "@" in lib:
            name, vers = lib.split("@", 1)
            cg.add_library(name, vers)
        elif "://" in lib:
            # Repository...
            if "=" in lib:
                name, repo = lib.split("=", 1)
                cg.add_library(name, None, repo)
            else:
                cg.add_library(None, None, lib)

        else:
            cg.add_library(lib, None)

    if CORE.is_esp8266:
        # Arduino 2 has a non-standards conformant new that returns a nullptr instead of failing when
        # out of memory and exceptions are disabled. Since Arduino 2.6.0, this flag can be used to make
        # new abort instead. Use it so that OOM fails early (on allocation) instead of on dereference of
        # a NULL pointer (so the stacktrace makes more sense), and for consistency with Arduino 3,
        # which always aborts if exceptions are disabled.
        # For cases where nullptrs can be handled, use nothrow: `new (std::nothrow) T;`
        cg.add_build_flag("-DNEW_OOM_ABORT")

    cg.add_build_flag("-Wno-unused-variable")
    cg.add_build_flag("-Wno-unused-but-set-variable")
    cg.add_build_flag("-Wno-sign-compare")
    if config.get(CONF_ESP8266_RESTORE_FROM_FLASH, False):
        cg.add_define("USE_ESP8266_PREFERENCES_FLASH")

    if config[CONF_INCLUDES]:
        CORE.add_job(add_includes, config[CONF_INCLUDES])

    cg.add_define("ESPHOME_BOARD", CORE.board)
    if CONF_PROJECT in config:
        cg.add_define("ESPHOME_PROJECT_NAME", config[CONF_PROJECT][CONF_NAME])
        cg.add_define("ESPHOME_PROJECT_VERSION",
                      config[CONF_PROJECT][CONF_VERSION])
Esempio n. 14
0
def to_code(config):
    uuid = config[CONF_UUID].hex
    uuid_arr = [
        cg.RawExpression("0x{}".format(uuid[i:i + 2]))
        for i in range(0, len(uuid), 2)
    ]
    var = cg.new_Pvariable(config[CONF_ID], uuid_arr)
    yield cg.register_component(var, config)
    cg.add(var.set_major(config[CONF_MAJOR]))
    cg.add(var.set_minor(config[CONF_MINOR]))
Esempio n. 15
0
async def to_code(config):
    uuid = config[CONF_UUID].hex
    uuid_arr = [cg.RawExpression(f"0x{uuid[i:i + 2]}") for i in range(0, len(uuid), 2)]
    var = cg.new_Pvariable(config[CONF_ID], uuid_arr)
    await cg.register_component(var, config)
    cg.add(var.set_major(config[CONF_MAJOR]))
    cg.add(var.set_minor(config[CONF_MINOR]))

    if CORE.using_esp_idf:
        add_idf_sdkconfig_option("CONFIG_BT_ENABLED", True)
Esempio n. 16
0
def to_code(config):
    type_ = cg.RawExpression(config[CONF_TYPE])
    template_args = cg.TemplateArguments(type_)
    res_type = GlobalsComponent.template(template_args)

    initial_value = None
    if CONF_INITIAL_VALUE in config:
        initial_value = cg.RawExpression(config[CONF_INITIAL_VALUE])

    rhs = GlobalsComponent.new(template_args, initial_value)
    glob = cg.Pvariable(config[CONF_ID], rhs, res_type)
    yield cg.register_component(glob, config)

    if config[CONF_RESTORE_VALUE]:
        value = config[CONF_ID].id
        if isinstance(value, str):
            value = value.encode()
        hash_ = int(hashlib.md5(value).hexdigest()[:8], 16)
        cg.add(glob.set_restore_value(hash_))
Esempio n. 17
0
async def logger_log_action_to_code(config, action_id, template_arg, args):
    args_ = [cg.RawExpression(str(x)) for x in config[CONF_ARGS]]

    text = str(
        cg.statement(
            GLOBAL_BLE_CONTROLLER_VAR.send_command_result(
                config[CONF_FORMAT], *args_)))

    lambda_ = await cg.process_lambda(Lambda(text), args, return_type=cg.void)
    return cg.new_Pvariable(action_id, template_arg, lambda_)
Esempio n. 18
0
async def to_code(config):
    hub = await cg.get_variable(config[CONF_DSMR_ID])

    sensors = []
    for key, conf in config.items():
        if not isinstance(conf, dict):
            continue
        id = conf.get("id")
        if id and id.type == sensor.Sensor:
            s = await sensor.new_sensor(conf)
            cg.add(getattr(hub, f"set_{key}")(s))
            sensors.append(f"F({key})")

    cg.add_define("DSMR_SENSOR_LIST(F, sep)",
                  cg.RawExpression(" sep ".join(sensors)))
Esempio n. 19
0
async def to_code(config):
    hub = await cg.get_variable(config[CONF_DSMR_ID])

    text_sensors = []
    for key, conf in config.items():
        if not isinstance(conf, dict):
            continue
        id = conf.get("id")
        if id and id.type == text_sensor.TextSensor:
            var = cg.new_Pvariable(conf[CONF_ID])
            await text_sensor.register_text_sensor(var, conf)
            cg.add(getattr(hub, f"set_{key}")(var))
            text_sensors.append(f"F({key})")

    cg.add_define("DSMR_TEXT_SENSOR_LIST(F, sep)",
                  cg.RawExpression(" sep ".join(text_sensors)))
Esempio n. 20
0
async def to_code(config):
    var = cg.new_Pvariable(config[CONF_ID])
    await cg.register_component(var, config)
    await uart.register_uart_device(var, config)

    cg.add_define(
        "HYDREON_RGXX_PROTOCOL_LIST(F, sep)",
        cg.RawExpression(" sep ".join(
            [f'F("{name}")' for name in PROTOCOL_NAMES.values()])),
    )
    cg.add_define("HYDREON_RGXX_NUM_SENSORS", len(PROTOCOL_NAMES))

    for i, conf in enumerate(PROTOCOL_NAMES):
        if conf in config:
            sens = await sensor.new_sensor(config[conf])
            cg.add(var.set_sensor(sens, i))
Esempio n. 21
0
def to_code(config):
    cg.add_global(cg.global_ns.namespace('esphome').using)
    cg.add(cg.App.pre_setup(config[CONF_NAME], cg.RawExpression('__DATE__ ", " __TIME__')))

    for conf in config.get(CONF_ON_BOOT, []):
        trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], conf.get(CONF_PRIORITY))
        yield cg.register_component(trigger, conf)
        yield automation.build_automation(trigger, [], conf)

    for conf in config.get(CONF_ON_SHUTDOWN, []):
        trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID])
        yield cg.register_component(trigger, conf)
        yield automation.build_automation(trigger, [], conf)

    for conf in config.get(CONF_ON_LOOP, []):
        trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID])
        yield cg.register_component(trigger, conf)
        yield automation.build_automation(trigger, [], conf)

    # Set LWIP build constants for ESP8266
    if CORE.is_esp8266:
        CORE.add_job(_esp8266_add_lwip_type)

    cg.add_build_flag('-fno-exceptions')

    # Libraries
    if CORE.is_esp32:
        cg.add_library('ESPmDNS', None)
    elif CORE.is_esp8266:
        cg.add_library('ESP8266WiFi', None)
        cg.add_library('ESP8266mDNS', None)

    for lib in config[CONF_LIBRARIES]:
        if '@' in lib:
            name, vers = lib.split('@', 1)
            cg.add_library(name, vers)
        else:
            cg.add_library(lib, None)

    cg.add_build_flag('-Wno-unused-variable')
    cg.add_build_flag('-Wno-unused-but-set-variable')
    cg.add_build_flag('-Wno-sign-compare')
    if config.get(CONF_ESP8266_RESTORE_FROM_FLASH, False):
        cg.add_define('USE_ESP8266_PREFERENCES_FLASH')

    if config[CONF_INCLUDES]:
        CORE.add_job(add_includes, config[CONF_INCLUDES])
Esempio n. 22
0
def to_code(config):
    serial = HARDWARE_UART_TO_SERIAL[config[CONF_HARDWARE_UART]]
    var = cg.new_Pvariable(config[CONF_ID], cg.RawExpression(f'&{serial}'))

    if CONF_BAUD_RATE in config:
        cg.add(var.set_baud_rate(config[CONF_BAUD_RATE]))

    traits = []
    for mode in config[CONF_SUPPORTS][CONF_MODE]:
        if mode == 'OFF':
            continue
        traits.append(f'set_supports_{mode.lower()}_mode')
    for mode in config[CONF_SUPPORTS][CONF_FAN_MODE]:
        traits.append(f'set_supports_fan_mode_{mode.lower()}')
    for mode in config[CONF_SUPPORTS][CONF_SWING_MODE]:
        traits.append(f'set_supports_swing_mode_{mode.lower()}')
    for trait in traits:
        cg.add(getattr(var.config_traits(), trait)(True))

    yield cg.register_component(var, config)
    yield climate.register_climate(var, config)
    cg.add_library("https://github.com/SwiCago/HeatPump", None)
Esempio n. 23
0
def to_code(config):
    cg.add_global(cg.global_ns.namespace('esphome').using)
    cg.add(
        cg.App.pre_setup(config[CONF_NAME],
                         cg.RawExpression('__DATE__ ", " __TIME__')))

    CORE.add_job(_add_automations, config)

    # Set LWIP build constants for ESP8266
    if CORE.is_esp8266:
        CORE.add_job(_esp8266_add_lwip_type)

    cg.add_build_flag('-fno-exceptions')

    # Libraries
    if CORE.is_esp32:
        cg.add_library('ESPmDNS', None)
    elif CORE.is_esp8266:
        cg.add_library('ESP8266WiFi', None)
        cg.add_library('ESP8266mDNS', None)

    for lib in config[CONF_LIBRARIES]:
        if '@' in lib:
            name, vers = lib.split('@', 1)
            cg.add_library(name, vers)
        else:
            cg.add_library(lib, None)

    cg.add_build_flag('-Wno-unused-variable')
    cg.add_build_flag('-Wno-unused-but-set-variable')
    cg.add_build_flag('-Wno-sign-compare')
    if config.get(CONF_ESP8266_RESTORE_FROM_FLASH, False):
        cg.add_define('USE_ESP8266_PREFERENCES_FLASH')

    if config[CONF_INCLUDES]:
        CORE.add_job(add_includes, config[CONF_INCLUDES])
Esempio n. 24
0
def to_code(config):
    var = cg.new_Pvariable(config[CONF_ID])
    yield cg.register_component(var, config)

    cg.add_library('AsyncMqttClient', '0.8.2')
    cg.add_define('USE_MQTT')
    cg.add_global(mqtt_ns.using)

    cg.add(var.set_broker_address(config[CONF_BROKER]))
    cg.add(var.set_broker_port(config[CONF_PORT]))
    cg.add(var.set_username(config[CONF_USERNAME]))
    cg.add(var.set_password(config[CONF_PASSWORD]))
    if CONF_CLIENT_ID in config:
        cg.add(var.set_client_id(config[CONF_CLIENT_ID]))

    discovery = config[CONF_DISCOVERY]
    discovery_retain = config[CONF_DISCOVERY_RETAIN]
    discovery_prefix = config[CONF_DISCOVERY_PREFIX]

    if not discovery:
        cg.add(var.disable_discovery())
    elif discovery == "CLEAN":
        cg.add(var.set_discovery_info(discovery_prefix, discovery_retain, True))
    elif CONF_DISCOVERY_RETAIN in config or CONF_DISCOVERY_PREFIX in config:
        cg.add(var.set_discovery_info(discovery_prefix, discovery_retain))

    cg.add(var.set_topic_prefix(config[CONF_TOPIC_PREFIX]))

    birth_message = config[CONF_BIRTH_MESSAGE]
    if not birth_message:
        cg.add(var.disable_birth_message())
    else:
        cg.add(var.set_birth_message(exp_mqtt_message(birth_message)))
    will_message = config[CONF_WILL_MESSAGE]
    if not will_message:
        cg.add(var.disable_last_will())
    else:
        cg.add(var.set_last_will(exp_mqtt_message(will_message)))
    shutdown_message = config[CONF_SHUTDOWN_MESSAGE]
    if not shutdown_message:
        cg.add(var.disable_shutdown_message())
    else:
        cg.add(var.set_shutdown_message(exp_mqtt_message(shutdown_message)))

    log_topic = config[CONF_LOG_TOPIC]
    if not log_topic:
        cg.add(var.disable_log_message())
    else:
        cg.add(var.set_log_message_template(exp_mqtt_message(log_topic)))

        if CONF_LEVEL in log_topic:
            cg.add(var.set_log_level(logger.LOG_LEVELS[log_topic[CONF_LEVEL]]))

    if CONF_SSL_FINGERPRINTS in config:
        for fingerprint in config[CONF_SSL_FINGERPRINTS]:
            arr = [cg.RawExpression("0x{}".format(fingerprint[i:i + 2])) for i in range(0, 40, 2)]
            cg.add(var.add_ssl_fingerprint(arr))
        cg.add_build_flag('-DASYNC_TCP_SSL_ENABLED=1')

    cg.add(var.set_keep_alive(config[CONF_KEEPALIVE]))

    cg.add(var.set_reboot_timeout(config[CONF_REBOOT_TIMEOUT]))

    for conf in config.get(CONF_ON_MESSAGE, []):
        trig = cg.new_Pvariable(conf[CONF_TRIGGER_ID], conf[CONF_TOPIC])
        cg.add(trig.set_qos(conf[CONF_QOS]))
        if CONF_PAYLOAD in conf:
            cg.add(trig.set_payload(conf[CONF_PAYLOAD]))
        yield cg.register_component(trig, conf)
        yield automation.build_automation(trig, [(cg.std_string, 'x')], conf)

    for conf in config.get(CONF_ON_JSON_MESSAGE, []):
        trig = cg.new_Pvariable(conf[CONF_TRIGGER_ID], conf[CONF_TOPIC], conf[CONF_QOS])
        yield automation.build_automation(trig, [(cg.JsonObjectConstRef, 'x')], conf)
Esempio n. 25
0
async def to_code(config):
    var = cg.new_Pvariable(config[CONF_ID])
    await cg.register_component(var, config)

    # https://github.com/OttoWinter/async-mqtt-client/blob/master/library.json
    cg.add_library("ottowinter/AsyncMqttClient-esphome", "0.8.6")
    cg.add_define("USE_MQTT")
    cg.add_global(mqtt_ns.using)

    cg.add(var.set_broker_address(config[CONF_BROKER]))
    cg.add(var.set_broker_port(config[CONF_PORT]))
    cg.add(var.set_username(config[CONF_USERNAME]))
    cg.add(var.set_password(config[CONF_PASSWORD]))
    if CONF_CLIENT_ID in config:
        cg.add(var.set_client_id(config[CONF_CLIENT_ID]))

    discovery = config[CONF_DISCOVERY]
    discovery_retain = config[CONF_DISCOVERY_RETAIN]
    discovery_prefix = config[CONF_DISCOVERY_PREFIX]
    discovery_unique_id_generator = config[CONF_DISCOVERY_UNIQUE_ID_GENERATOR]

    if not discovery:
        cg.add(var.disable_discovery())
    elif discovery == "CLEAN":
        cg.add(
            var.set_discovery_info(
                discovery_prefix, discovery_unique_id_generator, discovery_retain, True
            )
        )
    elif CONF_DISCOVERY_RETAIN in config or CONF_DISCOVERY_PREFIX in config:
        cg.add(
            var.set_discovery_info(
                discovery_prefix, discovery_unique_id_generator, discovery_retain
            )
        )

    cg.add(var.set_topic_prefix(config[CONF_TOPIC_PREFIX]))

    if config[CONF_USE_ABBREVIATIONS]:
        cg.add_define("USE_MQTT_ABBREVIATIONS")

    birth_message = config[CONF_BIRTH_MESSAGE]
    if not birth_message:
        cg.add(var.disable_birth_message())
    else:
        cg.add(var.set_birth_message(exp_mqtt_message(birth_message)))
    will_message = config[CONF_WILL_MESSAGE]
    if not will_message:
        cg.add(var.disable_last_will())
    else:
        cg.add(var.set_last_will(exp_mqtt_message(will_message)))
    shutdown_message = config[CONF_SHUTDOWN_MESSAGE]
    if not shutdown_message:
        cg.add(var.disable_shutdown_message())
    else:
        cg.add(var.set_shutdown_message(exp_mqtt_message(shutdown_message)))

    log_topic = config[CONF_LOG_TOPIC]
    if not log_topic:
        cg.add(var.disable_log_message())
    else:
        cg.add(var.set_log_message_template(exp_mqtt_message(log_topic)))

        if CONF_LEVEL in log_topic:
            cg.add(var.set_log_level(logger.LOG_LEVELS[log_topic[CONF_LEVEL]]))

    if CONF_SSL_FINGERPRINTS in config:
        for fingerprint in config[CONF_SSL_FINGERPRINTS]:
            arr = [
                cg.RawExpression(f"0x{fingerprint[i:i + 2]}") for i in range(0, 40, 2)
            ]
            cg.add(var.add_ssl_fingerprint(arr))
        cg.add_build_flag("-DASYNC_TCP_SSL_ENABLED=1")

    cg.add(var.set_keep_alive(config[CONF_KEEPALIVE]))

    cg.add(var.set_reboot_timeout(config[CONF_REBOOT_TIMEOUT]))

    for conf in config.get(CONF_ON_MESSAGE, []):
        trig = cg.new_Pvariable(conf[CONF_TRIGGER_ID], conf[CONF_TOPIC])
        cg.add(trig.set_qos(conf[CONF_QOS]))
        if CONF_PAYLOAD in conf:
            cg.add(trig.set_payload(conf[CONF_PAYLOAD]))
        await cg.register_component(trig, conf)
        await automation.build_automation(trig, [(cg.std_string, "x")], conf)

    for conf in config.get(CONF_ON_JSON_MESSAGE, []):
        trig = cg.new_Pvariable(conf[CONF_TRIGGER_ID], conf[CONF_TOPIC], conf[CONF_QOS])
        await automation.build_automation(trig, [(cg.JsonObjectConst, "x")], conf)
Esempio n. 26
0
def as_hex(value):
    return cg.RawExpression(f"0x{value}ULL")
Esempio n. 27
0
async def to_code(config):
    cg.add(esp8266_ns.setup_preferences())

    cg.add_platformio_option("lib_ldf_mode", "off")

    cg.add_platformio_option("board", config[CONF_BOARD])
    cg.add_build_flag("-DUSE_ESP8266")
    cg.add_define("ESPHOME_BOARD", config[CONF_BOARD])
    cg.add_define("ESPHOME_VARIANT", "ESP8266")

    cg.add_platformio_option("extra_scripts", ["post:post_build.py"])

    conf = config[CONF_FRAMEWORK]
    cg.add_platformio_option("framework", "arduino")
    cg.add_build_flag("-DUSE_ARDUINO")
    cg.add_build_flag("-DUSE_ESP8266_FRAMEWORK_ARDUINO")
    cg.add_build_flag("-Wno-nonnull-compare")
    cg.add_platformio_option("platform", conf[CONF_PLATFORM_VERSION])
    cg.add_platformio_option(
        "platform_packages",
        [f"platformio/framework-arduinoespressif8266 @ {conf[CONF_SOURCE]}"],
    )

    # Default for platformio is LWIP2_LOW_MEMORY with:
    #  - MSS=536
    #  - LWIP_FEATURES enabled
    #     - this only adds some optional features like IP incoming packet reassembly and NAPT
    #       see also:
    #  https://github.com/esp8266/Arduino/blob/master/tools/sdk/lwip2/include/lwipopts.h

    # Instead we use LWIP2_HIGHER_BANDWIDTH_LOW_FLASH with:
    #  - MSS=1460
    #  - LWIP_FEATURES disabled (because we don't need them)
    # Other projects like Tasmota & ESPEasy also use this
    cg.add_build_flag(
        "-DPIO_FRAMEWORK_ARDUINO_LWIP2_HIGHER_BANDWIDTH_LOW_FLASH")

    if config[CONF_RESTORE_FROM_FLASH]:
        cg.add_define("USE_ESP8266_PREFERENCES_FLASH")

    # Arduino 2 has a non-standards conformant new that returns a nullptr instead of failing when
    # out of memory and exceptions are disabled. Since Arduino 2.6.0, this flag can be used to make
    # new abort instead. Use it so that OOM fails early (on allocation) instead of on dereference of
    # a NULL pointer (so the stacktrace makes more sense), and for consistency with Arduino 3,
    # which always aborts if exceptions are disabled.
    # For cases where nullptrs can be handled, use nothrow: `new (std::nothrow) T;`
    cg.add_build_flag("-DNEW_OOM_ABORT")

    cg.add_platformio_option("board_build.flash_mode",
                             config[CONF_BOARD_FLASH_MODE])

    ver: cv.Version = CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]
    cg.add_define(
        "USE_ARDUINO_VERSION_CODE",
        cg.RawExpression(
            f"VERSION_CODE({ver.major}, {ver.minor}, {ver.patch})"),
    )

    if config[CONF_BOARD] in ESP8266_FLASH_SIZES:
        flash_size = ESP8266_FLASH_SIZES[config[CONF_BOARD]]
        ld_scripts = ESP8266_LD_SCRIPTS[flash_size]

        if ver <= cv.Version(2, 3, 0):
            # No ld script support
            ld_script = None
        if ver <= cv.Version(2, 4, 2):
            # Old ld script path
            ld_script = ld_scripts[0]
        else:
            ld_script = ld_scripts[1]

        if ld_script is not None:
            cg.add_platformio_option("board_build.ldscript", ld_script)

    CORE.add_job(add_pin_initial_states_array)
Esempio n. 28
0
async def to_code(config):
    cg.add_platformio_option("board", config[CONF_BOARD])
    cg.add_build_flag("-DUSE_ESP32")
    cg.add_define("ESPHOME_BOARD", config[CONF_BOARD])
    cg.add_build_flag(f"-DUSE_ESP32_VARIANT_{config[CONF_VARIANT]}")
    cg.add_define("ESPHOME_VARIANT", VARIANT_FRIENDLY[config[CONF_VARIANT]])

    cg.add_platformio_option("lib_ldf_mode", "off")

    framework_ver: cv.Version = CORE.data[KEY_CORE][KEY_FRAMEWORK_VERSION]

    conf = config[CONF_FRAMEWORK]
    cg.add_platformio_option("platform", conf[CONF_PLATFORM_VERSION])

    cg.add_platformio_option("extra_scripts", ["post:post_build.py"])

    if conf[CONF_TYPE] == FRAMEWORK_ESP_IDF:
        cg.add_platformio_option("framework", "espidf")
        cg.add_build_flag("-DUSE_ESP_IDF")
        cg.add_build_flag("-DUSE_ESP32_FRAMEWORK_ESP_IDF")
        cg.add_build_flag("-Wno-nonnull-compare")
        cg.add_platformio_option(
            "platform_packages",
            [f"platformio/framework-espidf @ {conf[CONF_SOURCE]}"],
        )
        add_idf_sdkconfig_option("CONFIG_PARTITION_TABLE_SINGLE_APP", False)
        add_idf_sdkconfig_option("CONFIG_PARTITION_TABLE_CUSTOM", True)
        add_idf_sdkconfig_option("CONFIG_PARTITION_TABLE_CUSTOM_FILENAME",
                                 "partitions.csv")
        add_idf_sdkconfig_option("CONFIG_COMPILER_OPTIMIZATION_DEFAULT", False)
        add_idf_sdkconfig_option("CONFIG_COMPILER_OPTIMIZATION_SIZE", True)

        # Increase freertos tick speed from 100Hz to 1kHz so that delay() resolution is 1ms
        add_idf_sdkconfig_option("CONFIG_FREERTOS_HZ", 1000)

        # Setup watchdog
        add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT", True)
        add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_PANIC", True)
        add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0",
                                 False)
        add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1",
                                 False)

        cg.add_platformio_option("board_build.partitions", "partitions.csv")

        for name, value in conf[CONF_SDKCONFIG_OPTIONS].items():
            add_idf_sdkconfig_option(name, RawSdkconfigValue(value))

        if conf[CONF_ADVANCED][CONF_IGNORE_EFUSE_MAC_CRC]:
            cg.add_define("USE_ESP32_IGNORE_EFUSE_MAC_CRC")
            add_idf_sdkconfig_option(
                "CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE", False)

        cg.add_define(
            "USE_ESP_IDF_VERSION_CODE",
            cg.RawExpression(
                f"VERSION_CODE({framework_ver.major}, {framework_ver.minor}, {framework_ver.patch})"
            ),
        )

    elif conf[CONF_TYPE] == FRAMEWORK_ARDUINO:
        cg.add_platformio_option("framework", "arduino")
        cg.add_build_flag("-DUSE_ARDUINO")
        cg.add_build_flag("-DUSE_ESP32_FRAMEWORK_ARDUINO")
        cg.add_platformio_option(
            "platform_packages",
            [f"platformio/framework-arduinoespressif32 @ {conf[CONF_SOURCE]}"],
        )

        cg.add_platformio_option("board_build.partitions", "partitions.csv")

        cg.add_define(
            "USE_ARDUINO_VERSION_CODE",
            cg.RawExpression(
                f"VERSION_CODE({framework_ver.major}, {framework_ver.minor}, {framework_ver.patch})"
            ),
        )