How to use the esphome.config_validation.Optional function in esphome

To help you get started, we’ve selected a few esphome examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github esphome / esphome / esphome / components / neopixelbus / light.py View on Github external
if CONF_PIN in config:
        if CONF_CLOCK_PIN in config or CONF_DATA_PIN in config:
            raise cv.Invalid("Cannot specify both 'pin' and 'clock_pin'+'data_pin'")
        return config
    if CONF_CLOCK_PIN in config:
        if CONF_DATA_PIN not in config:
            raise cv.Invalid("If you give clock_pin, you must also specify data_pin")
        return config
    raise cv.Invalid("Must specify at least one of 'pin' or 'clock_pin'+'data_pin'")


CONFIG_SCHEMA = cv.All(light.ADDRESSABLE_LIGHT_SCHEMA.extend({
    cv.GenerateID(CONF_OUTPUT_ID): cv.declare_id(NeoPixelBusLightOutputBase),

    cv.Optional(CONF_TYPE, default='GRB'): validate_type,
    cv.Optional(CONF_VARIANT, default='800KBPS'): validate_variant,
    cv.Optional(CONF_METHOD, default=None): validate_method,
    cv.Optional(CONF_PIN): pins.output_pin,
    cv.Optional(CONF_CLOCK_PIN): pins.output_pin,
    cv.Optional(CONF_DATA_PIN): pins.output_pin,

    cv.Required(CONF_NUM_LEDS): cv.positive_not_null_int,
}).extend(cv.COMPONENT_SCHEMA), validate, validate_method_pin)


def to_code(config):
    has_white = 'W' in config[CONF_TYPE]
    template = cg.TemplateArguments(getattr(cg.global_ns, format_method(config)))
    if has_white:
        out_type = NeoPixelRGBWLightOutput.template(template)
    else:
        out_type = NeoPixelRGBLightOutput.template(template)
github esphome / esphome / esphome / components / my9231 / __init__.py View on Github external
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins
from esphome.const import (CONF_BIT_DEPTH, CONF_CLOCK_PIN, CONF_DATA_PIN, CONF_ID,
                           CONF_NUM_CHANNELS, CONF_NUM_CHIPS)

AUTO_LOAD = ['output']
my9231_ns = cg.esphome_ns.namespace('my9231')
MY9231OutputComponent = my9231_ns.class_('MY9231OutputComponent', cg.Component)

MULTI_CONF = True
CONFIG_SCHEMA = cv.Schema({
    cv.GenerateID(): cv.declare_id(MY9231OutputComponent),
    cv.Required(CONF_DATA_PIN): pins.gpio_output_pin_schema,
    cv.Required(CONF_CLOCK_PIN): pins.gpio_output_pin_schema,
    cv.Optional(CONF_NUM_CHANNELS, default=6): cv.int_range(min=3, max=1020),
    cv.Optional(CONF_NUM_CHIPS, default=2): cv.int_range(min=1, max=255),
    cv.Optional(CONF_BIT_DEPTH, default=16): cv.one_of(8, 12, 14, 16, int=True),
}).extend(cv.COMPONENT_SCHEMA)


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

    di = yield cg.gpio_pin_expression(config[CONF_DATA_PIN])
    cg.add(var.set_pin_di(di))
    dcki = yield cg.gpio_pin_expression(config[CONF_CLOCK_PIN])
    cg.add(var.set_pin_dcki(dcki))

    cg.add(var.set_num_channels(config[CONF_NUM_CHANNELS]))
    cg.add(var.set_num_chips(config[CONF_NUM_CHIPS]))
github esphome / esphome / esphome / components / stepper / __init__.py View on Github external
return 1e6

    try:
        value = float(value)
    except ValueError:
        raise cv.Invalid(f"Expected speed as floating point number, got {value}")

    if value <= 0:
        raise cv.Invalid("Speed must be larger than 0 steps/s!")

    return value


STEPPER_SCHEMA = cv.Schema({
    cv.Required(CONF_MAX_SPEED): validate_speed,
    cv.Optional(CONF_ACCELERATION, default='inf'): validate_acceleration,
    cv.Optional(CONF_DECELERATION, default='inf'): validate_acceleration,
})


@coroutine
def setup_stepper_core_(stepper_var, config):
    if CONF_ACCELERATION in config:
        cg.add(stepper_var.set_acceleration(config[CONF_ACCELERATION]))
    if CONF_DECELERATION in config:
        cg.add(stepper_var.set_deceleration(config[CONF_DECELERATION]))
    if CONF_MAX_SPEED in config:
        cg.add(stepper_var.set_max_speed(config[CONF_MAX_SPEED]))


@coroutine
def register_stepper(var, config):
github esphome / esphome / esphome / components / remote_base / __init__.py View on Github external
pl = config[CONF_PULSE_LENGTH]
    return RCSwitchBase(config[CONF_SYNC][0] * pl, config[CONF_SYNC][1] * pl,
                        config[CONF_ZERO][0] * pl, config[CONF_ZERO][1] * pl,
                        config[CONF_ONE][0] * pl, config[CONF_ONE][1] * pl,
                        config[CONF_INVERTED])


RC_SWITCH_RAW_SCHEMA = cv.Schema({
    cv.Required(CONF_CODE): validate_rc_switch_raw_code,
    cv.Optional(CONF_PROTOCOL, default=1): RC_SWITCH_PROTOCOL_SCHEMA,
})
RC_SWITCH_TYPE_A_SCHEMA = cv.Schema({
    cv.Required(CONF_GROUP): cv.All(validate_rc_switch_code, cv.Length(min=5, max=5)),
    cv.Required(CONF_DEVICE): cv.All(validate_rc_switch_code, cv.Length(min=5, max=5)),
    cv.Required(CONF_STATE): cv.boolean,
    cv.Optional(CONF_PROTOCOL, default=1): RC_SWITCH_PROTOCOL_SCHEMA,
})
RC_SWITCH_TYPE_B_SCHEMA = cv.Schema({
    cv.Required(CONF_ADDRESS): cv.int_range(min=1, max=4),
    cv.Required(CONF_CHANNEL): cv.int_range(min=1, max=4),
    cv.Required(CONF_STATE): cv.boolean,
    cv.Optional(CONF_PROTOCOL, default=1): RC_SWITCH_PROTOCOL_SCHEMA,
})
RC_SWITCH_TYPE_C_SCHEMA = cv.Schema({
    cv.Required(CONF_FAMILY): cv.one_of('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                                        'l', 'm', 'n', 'o', 'p', lower=True),
    cv.Required(CONF_GROUP): cv.int_range(min=1, max=4),
    cv.Required(CONF_DEVICE): cv.int_range(min=1, max=4),
    cv.Required(CONF_STATE): cv.boolean,
    cv.Optional(CONF_PROTOCOL, default=1): RC_SWITCH_PROTOCOL_SCHEMA,
})
RC_SWITCH_TYPE_D_SCHEMA = cv.Schema({
github esphome / esphome / esphome / components / bme680 / sensor.py View on Github external
IIR_FILTER_OPTIONS = {
    'OFF': BME680IIRFilter.BME680_IIR_FILTER_OFF,
    '1X': BME680IIRFilter.BME680_IIR_FILTER_1X,
    '3X': BME680IIRFilter.BME680_IIR_FILTER_3X,
    '7X': BME680IIRFilter.BME680_IIR_FILTER_7X,
    '15X': BME680IIRFilter.BME680_IIR_FILTER_15X,
    '31X': BME680IIRFilter.BME680_IIR_FILTER_31X,
    '63X': BME680IIRFilter.BME680_IIR_FILTER_63X,
    '127X': BME680IIRFilter.BME680_IIR_FILTER_127X,
}

BME680Component = bme680_ns.class_('BME680Component', cg.PollingComponent, i2c.I2CDevice)

CONFIG_SCHEMA = cv.Schema({
    cv.GenerateID(): cv.declare_id(BME680Component),
    cv.Optional(CONF_TEMPERATURE):
        sensor.sensor_schema(UNIT_CELSIUS, ICON_THERMOMETER, 1).extend({
            cv.Optional(CONF_OVERSAMPLING, default='16X'):
                cv.enum(OVERSAMPLING_OPTIONS, upper=True),
        }),
    cv.Optional(CONF_PRESSURE):
        sensor.sensor_schema(UNIT_HECTOPASCAL, ICON_GAUGE, 1).extend({
            cv.Optional(CONF_OVERSAMPLING, default='16X'):
                cv.enum(OVERSAMPLING_OPTIONS, upper=True),
        }),
    cv.Optional(CONF_HUMIDITY):
        sensor.sensor_schema(UNIT_PERCENT, ICON_WATER_PERCENT, 1).extend({
            cv.Optional(CONF_OVERSAMPLING, default='16X'):
                cv.enum(OVERSAMPLING_OPTIONS, upper=True),
        }),
    cv.Optional(CONF_GAS_RESISTANCE):
        sensor.sensor_schema(UNIT_OHM, ICON_GAS_CYLINDER, 1),
github esphome / esphome / esphome / components / sun / text_sensor / __init__.py View on Github external
def validate_optional_icon(config):
    if CONF_ICON not in config:
        config = config.copy()
        config[CONF_ICON] = {
            'sunset': ICON_WEATHER_SUNSET_DOWN,
            'sunrise': ICON_WEATHER_SUNSET_UP,
        }[config[CONF_TYPE]]
    return config


CONFIG_SCHEMA = cv.All(text_sensor.TEXT_SENSOR_SCHEMA.extend({
    cv.GenerateID(): cv.declare_id(SunTextSensor),
    cv.GenerateID(CONF_SUN_ID): cv.use_id(Sun),
    cv.Required(CONF_TYPE): cv.one_of(*SUN_TYPES, lower=True),
    cv.Optional(CONF_ELEVATION, default=DEFAULT_ELEVATION): elevation,
    cv.Optional(CONF_FORMAT, default='%X'): cv.string_strict,
}).extend(cv.polling_component_schema('60s')), validate_optional_icon)


def to_code(config):
    var = cg.new_Pvariable(config[CONF_ID])
    yield cg.register_component(var, config)
    yield text_sensor.register_text_sensor(var, config)

    paren = yield cg.get_variable(config[CONF_SUN_ID])
    cg.add(var.set_parent(paren))
    cg.add(var.set_sunrise(SUN_TYPES[config[CONF_TYPE]]))
    cg.add(var.set_elevation(config[CONF_ELEVATION]))
    cg.add(var.set_format(config[CONF_FORMAT]))
github esphome / esphome / esphome / components / mqtt / __init__.py View on Github external
cv.GenerateID(): cv.declare_id(MQTTClientComponent),
    cv.Required(CONF_BROKER): cv.string_strict,
    cv.Optional(CONF_PORT, default=1883): cv.port,
    cv.Optional(CONF_USERNAME, default=''): cv.string,
    cv.Optional(CONF_PASSWORD, default=''): cv.string,
    cv.Optional(CONF_CLIENT_ID): cv.string,
    cv.Optional(CONF_DISCOVERY, default=True): cv.Any(cv.boolean, cv.one_of("CLEAN", upper=True)),
    cv.Optional(CONF_DISCOVERY_RETAIN, default=True): cv.boolean,
    cv.Optional(CONF_DISCOVERY_PREFIX, default="homeassistant"): cv.publish_topic,

    cv.Optional(CONF_BIRTH_MESSAGE): MQTT_MESSAGE_SCHEMA,
    cv.Optional(CONF_WILL_MESSAGE): MQTT_MESSAGE_SCHEMA,
    cv.Optional(CONF_SHUTDOWN_MESSAGE): MQTT_MESSAGE_SCHEMA,
    cv.Optional(CONF_TOPIC_PREFIX, default=lambda: CORE.name): cv.publish_topic,
    cv.Optional(CONF_LOG_TOPIC): cv.Any(None, MQTT_MESSAGE_BASE.extend({
        cv.Optional(CONF_LEVEL): logger.is_log_level,
    }), validate_message_just_topic),

    cv.Optional(CONF_SSL_FINGERPRINTS): cv.All(cv.only_on_esp8266,
                                               cv.ensure_list(validate_fingerprint)),
    cv.Optional(CONF_KEEPALIVE, default='15s'): cv.positive_time_period_seconds,
    cv.Optional(CONF_REBOOT_TIMEOUT, default='15min'): cv.positive_time_period_milliseconds,
    cv.Optional(CONF_ON_MESSAGE): automation.validate_automation({
        cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(MQTTMessageTrigger),
        cv.Required(CONF_TOPIC): cv.subscribe_topic,
        cv.Optional(CONF_QOS, default=0): cv.mqtt_qos,
        cv.Optional(CONF_PAYLOAD): cv.string_strict,
    }),
    cv.Optional(CONF_ON_JSON_MESSAGE): automation.validate_automation({
        cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(MQTTJsonMessageTrigger),
        cv.Required(CONF_TOPIC): cv.subscribe_topic,
        cv.Optional(CONF_QOS, default=0): cv.mqtt_qos,
github esphome / esphome / esphome / components / waveshare_epaper / display.py View on Github external
def validate_full_update_every_only_type_a(value):
    if CONF_FULL_UPDATE_EVERY not in value:
        return value
    if MODELS[value[CONF_MODEL]][0] != 'a':
        raise cv.Invalid("The 'full_update_every' option is only available for models "
                         "'1.54in', '2.13in' and '2.90in'.")
    return value


CONFIG_SCHEMA = cv.All(display.FULL_DISPLAY_SCHEMA.extend({
    cv.GenerateID(): cv.declare_id(WaveshareEPaper),
    cv.Required(CONF_DC_PIN): pins.gpio_output_pin_schema,
    cv.Required(CONF_MODEL): cv.one_of(*MODELS, lower=True),
    cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
    cv.Optional(CONF_BUSY_PIN): pins.gpio_input_pin_schema,
    cv.Optional(CONF_FULL_UPDATE_EVERY): cv.uint32_t,
}).extend(cv.polling_component_schema('1s')).extend(spi.SPI_DEVICE_SCHEMA),
                       validate_full_update_every_only_type_a,
                       cv.has_at_most_one_key(CONF_PAGES, CONF_LAMBDA))


def to_code(config):
    model_type, model = MODELS[config[CONF_MODEL]]
    if model_type == 'a':
        rhs = WaveshareEPaperTypeA.new(model)
        var = cg.Pvariable(config[CONF_ID], rhs, type=WaveshareEPaperTypeA)
    elif model_type == 'b':
        rhs = model.new()
        var = cg.Pvariable(config[CONF_ID], rhs, type=model)
    else:
github esphome / esphome / esphome / components / image / __init__.py View on Github external
import esphome.codegen as cg
from esphome.const import CONF_FILE, CONF_ID, CONF_RESIZE
from esphome.core import CORE, HexInt
_LOGGER = logging.getLogger(__name__)

DEPENDENCIES = ['display']
MULTI_CONF = True

Image_ = display.display_ns.class_('Image')

CONF_RAW_DATA_ID = 'raw_data_id'

IMAGE_SCHEMA = cv.Schema({
    cv.Required(CONF_ID): cv.declare_id(Image_),
    cv.Required(CONF_FILE): cv.file_,
    cv.Optional(CONF_RESIZE): cv.dimensions,
    cv.GenerateID(CONF_RAW_DATA_ID): cv.declare_id(cg.uint8),
})

CONFIG_SCHEMA = cv.All(font.validate_pillow_installed, IMAGE_SCHEMA)


def to_code(config):
    from PIL import Image

    path = CORE.relative_config_path(config[CONF_FILE])
    try:
        image = Image.open(path)
    except Exception as e:
        raise core.EsphomeError(f"Could not load image file {path}: {e}")

    if CONF_RESIZE in config:
github esphome / esphome / esphome / components / pid / climate.py View on Github external
CONF_POSITIVE_OUTPUT = 'positive_output'
CONF_NEGATIVE_OUTPUT = 'negative_output'
CONF_MIN_INTEGRAL = 'min_integral'
CONF_MAX_INTEGRAL = 'max_integral'

CONFIG_SCHEMA = cv.All(climate.CLIMATE_SCHEMA.extend({
    cv.GenerateID(): cv.declare_id(PIDClimate),
    cv.Required(CONF_SENSOR): cv.use_id(sensor.Sensor),
    cv.Required(CONF_DEFAULT_TARGET_TEMPERATURE): cv.temperature,
    cv.Optional(CONF_COOL_OUTPUT): cv.use_id(output.FloatOutput),
    cv.Optional(CONF_HEAT_OUTPUT): cv.use_id(output.FloatOutput),
    cv.Required(CONF_CONTROL_PARAMETERS): cv.Schema({
        cv.Required(CONF_KP): cv.float_,
        cv.Optional(CONF_KI, default=0.0): cv.float_,
        cv.Optional(CONF_KD, default=0.0): cv.float_,
        cv.Optional(CONF_MIN_INTEGRAL, default=-1): cv.float_,
        cv.Optional(CONF_MAX_INTEGRAL, default=1): cv.float_,
    }),
}), cv.has_at_least_one_key(CONF_COOL_OUTPUT, CONF_HEAT_OUTPUT))


def to_code(config):
    var = cg.new_Pvariable(config[CONF_ID])
    yield cg.register_component(var, config)
    yield climate.register_climate(var, config)

    sens = yield cg.get_variable(config[CONF_SENSOR])
    cg.add(var.set_sensor(sens))

    if CONF_COOL_OUTPUT in config:
        out = yield cg.get_variable(config[CONF_COOL_OUTPUT])
        cg.add(var.set_cool_output(out))