Use enum validation in code generator

This commit is contained in:
cvwillegen 2024-05-28 11:39:23 +02:00 committed by GitHub
parent d135a3ce70
commit 5040a9146d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -68,29 +68,22 @@ def validate_speed(value):
return value return value
def validate_rotation(value): Rotation = stepper_ns.enum("Rotation")
value = cv.string(value) ROTATIONS = {
"BOTH": Rotation.ROTATION_BOTH,
if value in ("both"): "CW": Rotation.ROTATION_CW,
return 0 "CLOCKWISE": Rotation.ROTATION_CW,
"CCW": Rotation.ROTATION_CCW,
if value in ("cw", "clockwise"): "COUNTERCLOCKWISE": Rotation.ROTATION_CCW,
return 1 "COUNTER-CLOCKWISE": Rotation.ROTATION_CCW,
}
if value in ("ccw", "counterclockwise", "counter-clockwise"):
return -1
raise cv.Invalid(
f"Expected rotation as 'both', 'cw', 'ccw', 'clockwise', 'counterclockwise', 'counter-clockwise', got {value}"
)
STEPPER_SCHEMA = cv.Schema( STEPPER_SCHEMA = cv.Schema(
{ {
cv.Required(CONF_MAX_SPEED): validate_speed, cv.Required(CONF_MAX_SPEED): validate_speed,
cv.Optional(CONF_ACCELERATION, default="inf"): validate_acceleration, cv.Optional(CONF_ACCELERATION, default="inf"): validate_acceleration,
cv.Optional(CONF_DECELERATION, default="inf"): validate_acceleration, cv.Optional(CONF_DECELERATION, default="inf"): validate_acceleration,
cv.Optional(CONF_ROTATION, default="both"): validate_rotation, cv.Optional(CONF_ROTATION, default="both"): cv.enum(ROTATIONS, upper=True),
} }
) )
@ -208,15 +201,14 @@ async def stepper_set_deceleration_to_code(config, action_id, template_arg, args
cv.Schema( cv.Schema(
{ {
cv.Required(CONF_ID): cv.use_id(Stepper), cv.Required(CONF_ID): cv.use_id(Stepper),
cv.Required(CONF_ROTATION): cv.templatable(validate_rotation), cv.Required(CONF_ROTATION): cv.enum(ROTATIONS, upper=True),
} }
), ),
) )
async def stepper_set_rotation_to_code(config, action_id, template_arg, args): async def stepper_set_rotation_to_code(config, action_id, template_arg, args):
paren = await cg.get_variable(config[CONF_ID]) paren = await cg.get_variable(config[CONF_ID])
var = cg.new_Pvariable(action_id, template_arg, paren) var = cg.new_Pvariable(action_id, template_arg, paren)
template_ = await cg.templatable(config[CONF_ROTATION], args, cg.int32) cg.add(var.set_rotation(config[CONF_ROTATION]))
cg.add(var.set_rotation(template_))
return var return var