Adding a Home Assistant entity via python

Hello. I’m trying to add a custom switch via the python code (not the configuration file). I currently have the following code:

attributes = {"platform" : "mqtt",  "assumed_state" : True , "name" : "Bedroom Switch", "state_topic" :  "home/bedroom/switch1", "command_topic" : "home/bedroom/switch1/set", "payload_on:" : "ON", "payload_off" : "OFF", "optimistic" : False, "qos" : 0, "retain" : True, "value_template" : "{{ value.x }}"}
hass.states.set("switch.coded_switch",  "off", attributes)

This works completely, but in the Home Assistant UI the “Coded Switch” does not turn up as a switch. It has all the attributes, but it shows up just in state “Off”, where I wanted it to be a switch that’s off.

Thanks in advance for helping!

hass.states.set sets only the state of an entity. To create switches you need to inherit from SwitchDevice.

Hello. Thanks for your reaction!

Could you give me any pointers on how to do that in python code? Thanks in advance.

1 Like