Package: ha-mqtt-discoverable
ha-mqtt-discoverableA Python 3 module that takes advantage of Home Assistant'sMQTT discovery protocolto create sensors without having to define anything on the HA side.Using MQTT discoverable devices lets us add new sensors and devices to HA without having to restart HA. Theha-mqtt-discoverable-climodule includes scripts to make it easy to create discoverable devices from the command line if you don't want to bother writing Python.Table of ContentsInstallingPythonSupported entitiesBinary sensorUsageButtonDeviceUsageDevice triggerUsageSwitchUsageLightUsageCoversUsageTextUsageNumberUsageContributingUsers of ha-mqtt-discoverableContributorsInstallingPythonha-mqtt-discoverable runs on Python 3.10 or later.pip install ha-mqtt-discoverableif you want to use it in your own python scripts. This will also install thehmdutility scripts.Supported entitiesThe following Home Assistant entities are currently implemented:Binary sensorButtonCoverDeviceDevice triggerLightNumberSensorSwitchTextEach entity can associated to a device. See below for details.Binary sensorUsageThe following example creates a binary sensor and sets its state:fromha_mqtt_discoverableimportSettingsfromha_mqtt_discoverable.sensorsimportBinarySensor,BinarySensorInfo# Configure the required parameters for the MQTT brokermqtt_settings=Settings.MQTT(host="localhost")# Information about the sensorsensor_info=BinarySensorInfo(name="MySensor",device_class="motion")settings=Settings(mqtt=mqtt_settings,entity=sensor_info)# Instantiate the sensormysensor=BinarySensor(settings)# Change the state of the sensor, publishing an MQTT message that gets picked up by HAmysensor.on()mysensor.off()# You can also set custom attributes on the sensor via a Python dictmysensor.set_attributes({"my attribute":"awesome"})ButtonThe button publishes no state, it simply receives a command from HA.You must callwrite_configon a Button after creating it to make it discoverable.fromha_mqtt_discoverableimportSettingsfromha_mqtt_discoverable.sensorsimportButton,ButtonInfofrompaho.mqtt.clientimportClient,MQTTMessage# Configure the required parameters for the MQTT brokermqtt_settings=Settings.MQTT(host="localhost")# Information about the buttonbutton_info=ButtonInfo(name="test")settings=Settings(mqtt=mqtt_settings,entity=button_info)# To receive button commands from HA, define a callback function:defmy_callback(client:Client,user_data,message:MQTTMessage):perform_my_custom_action()# Define an optional object to be passed back to the callbackuser_data="Some custom data"# Instantiate the buttonmy_button=Button(settings,my_callback,user_data)# Publish the button's discoverability message to let HA automatically notice itmy_button.write_config()DeviceFrom theHome Assistant documentation:A device is a special entity in Home Assistant that is represented by one or more entities.
A device is automatically created when an entity defines itsdeviceproperty.
A device will be matched up with an existing device via supplied identifiers or connections, like serial numbers or MAC addresses.UsageThe following example create a device, by associating multiple sensors to the sameDeviceInfoinstance.fromha_mqtt_discoverableimportSettings,DeviceInfofromha_mqtt_discoverable.sensorsimportBinarySensor,BinarySensorInfo# Configure the required parameters for the MQTT brokermqtt_settings=Settings.MQTT(host="localhost")# Define the device. At least one of `identifiers` or `connections` must be supplieddevice_info=DeviceInfo(name="My device",identifiers="device_id")# Associate the sensor with the device via the `device` parameter# `unique_id` must also be set, otherwise Home Assistant will not display the device in the UImotion_sensor_info=BinarySensorInfo(name="My motion sensor",device_class="motion",unique_id="my_motion_sensor",device=device_info)motion_settings=Settings(mqtt=mqtt_settings,entity=motion_sensor_info)# Instantiate the sensormotion_sensor=BinarySensor(motion_settings)# Change the state of the sensor, publishing an MQTT message that gets picked up by HAmotion_sensor.on()# An additional sensor can be added to the same device, by re-using the DeviceInfo instance previously defineddoor_sensor_info=BinarySensorInfo(name="My door sensor",device_class="door",unique_id="my_door_sensor",device=device_info)door_settings=Settings(mqtt=mqtt_settings,entity=door_sensor_info)# Instantiate the sensordoor_sensor=BinarySensor(settings)# Change the state of the sensor, publishing an MQTT message that gets picked up by HAdoor_sensor.on()# The two sensors should be visible inside Home Assistant under the device `My device`Device triggerThe following example creates a device trigger and generates a trigger event:Usagefromha_mqtt_discoverableimportSettingsfromha_mqtt_discoverable.sensorsimportDeviceInfo,DeviceTriggerInfo,DeviceTrigger# Configure the required parameters for the MQTT brokermqtt_settings=Settings.MQTT(host="localhost")# Define the device. At least one of `identifiers` or `connections` must be supplieddevice_info=DeviceInfo(name="My device",identifiers="device_id")# Associate the sensor with the device via the `device` parametertrigger_into=DeviceTriggerInfo(name="MyTrigger",type="button_press",subtype="button_1",unique_id="my_device_trigger",device=device_info)settings=Settings(mqtt=mqtt_settings,entity=trigger_info)# Instantiate the device triggermytrigger=DeviceTrigger(settings)# Generate a device trigger event, publishing an MQTT message that gets picked up by HA# Optionally include a payload as part of the eventmytrigger.trigger("My custom payload")SwitchThe switch is similar to abinary sensor, but in addition to publishing state changes toward HA it can also receive 'commands' from HA that request a state change.
It is possible to act upon reception of this 'command', by defining acallbackfunction, as the following example shows:Usagefromha_mqtt_discoverableimportSettingsfromha_mqtt_discoverable.sensorsimportSwitch,SwitchInfofrompaho.mqtt.clientimportClient,MQTTMessage# Configure the required parameters for the MQTT brokermqtt_settings=Settings.MQTT(host="localhost")# Information about the switchswitch_info=SwitchInfo(name="test")settings=Settings(mqtt=mqtt_settings,entity=switch_info)# To receive state commands from HA, define a callback function:defmy_callback(client:Client,user_data,message:MQTTMessage):payload=message.payload.decode()ifpayload=="ON":turn_my_custom_thing_on()# Let HA know that the switch was successfully activatedmy_switch.on()elifpayload=="OFF":turn_my_custom_thing_off()# Let HA know that the switch was successfully deactivatedmy_switch.off()# Define an optional object to be passed back to the callbackuser_data="Some custom data"# Instantiate the switchmy_switch=Switch(settings,my_callback,user_data)# Set the initial state of the switch, which also makes it discoverablemy_switch.off()LightThe light is different from other current sensor as it needs its payload encoded/decoded as json.
It is possible to set brightness, effects and the color of the light. Similar to aswitchit can
also receive 'commands' from HA that request a state change.
It is possible to act upon reception of this 'command', by defining acallbackfunction, as the following example shows:Usageimportjsonfromha_mqtt_discoverableimportSettingsfromha_mqtt_discoverable.sensorsimportLight,LightInfofrompaho.mqtt.clientimportClient,MQTTMessage# Configure the required parameters for the MQTT brokermqtt_settings=Settings.MQTT(host="localhost")# Information about the lightlight_info=LightInfo(name="test_light",brightness=True,color_mode=True,supported_color_modes=["rgb"],effect=True,effect_list=["blink","my_cusom_effect"])settings=Settings(mqtt=mqtt_settings,entity=light_info)# To receive state commands from HA, define a callback function:defmy_callback(client:Client,user_data,message:MQTTMessage):# Make sure received payload is jsontry:payload=json.loads(message.payload.decode())exceptValueErroraserror:print("Ony JSON schema is supported for light entities!")return# Parse received dictionaryif"color"inpayload:set_color_of_my_light()my_light.color("rgb",payload["color"])elif"brightness"inpayload:set_brightness_of_my_light()my_light.brightness(payload["brightness"])elif"effect"inpayload:set_effect_of_my_light()my_light.effect(payload["effect"])elif"state"inpayload:ifpayload["state"]==light_info.payload_on:turn_on_my_light()my_light.on()else:turn_off_my_light()my_light.off()else:print("Unknown payload")# Define an optional object to be passed back to the callbackuser_data="Some custom data"# Instantiate the switchmy_light=Light(settings,my_callback,user_data)# Set the initial state of the light, which also makes it discoverablemy_light.off()CoversA cover has five possible statesopen,closed,opening,closingandstopped. Most other entities use the states as command payload, but covers differentiate on this. The user HA user can either open, close or stop it in the covers current position.Covers do not currently support tilt.Acallbackfunction is needed in order to parse the commands sent from HA, as the following
example shows:Usagefromha_mqtt_discoverableimportSettingsfromha_mqtt_discoverable.sensorsimportCover,CoverInfofrompaho.mqtt.clientimportClient,MQTTMessage# Configure the required parameters for the MQTT brokermqtt_settings=Settings.MQTT(host="localhost")# Information about the covercover_info=CoverInfo(name="test")settings=Settings(mqtt=mqtt_settings,entity=cover_info)# To receive state commands from HA, define a callback function:defmy_callback(client:Client,user_data,message:MQTTMessage):payload=message.payload.decode()ifpayload=="OPEN":# let HA know that the cover is openingmy_cover.opening()# call function to open coveropen_my_custom_cover()# Let HA know that the cover was openedmy_cover.open()ifpayload=="CLOSE":# let HA know that the cover is closingmy_cover.closing()# call function to close the coverclose_my_custom_cover()# Let HA know that the cover was closedmy_cover.closed()ifpayload=="STOP":# call function to stop the coverstop_my_custom_cover()# Let HA know that the cover was stoppedmy_cover.stopped()# Define an optional object to be passed back to the callbackuser_data="Some custom data"# Instantiate the covermy_cover=Cover(settings,my_callback,user_data)# Set the initial state of the cover, which also makes it discoverablemy_cover.closed()TextThe text is anhelper entity, showing an input field in the HA UI that the user can interact with.
It is possible to act upon reception of the inputted text by defining acallbackfunction, as the following example shows:Usagefromha_mqtt_discoverableimportSettingsfromha_mqtt_discoverable.sensorsimportText,TextInfofrompaho.mqtt.clientimportClient,MQTTMessage# Configure the required parameters for the MQTT brokermqtt_settings=Settings.MQTT(host="localhost")# Information about the `text` entitytext_info=TextInfo(name="test")settings=Settings(mqtt=mqtt_settings,entity=text_info)# To receive text updates from HA, define a callback function:defmy_callback(client:Client,user_data,message:MQTTMessage):text=message.payload.decode()logging.info(f"Received{text}from HA")do_some_custom_thing(text)# Send an MQTT message to confirm to HA that the text was changedmy_text.set_text(text)# Define an optional object to be passed back to the callbackuser_data="Some custom data"# Instantiate the textmy_text=Text(settings,my_callback,user_data)# Set the initial text displayed in HA UI, publishing an MQTT message that gets picked up by HAmy_text.set_text("Some awesome text")NumberThe number entity is similar to the text entity, but for a numeric value instead of a string.
It is possible to act upon receiving changes in HA by defining acallbackfunction, as the following example shows:Usagefromha_mqtt_discoverableimportSettingsfromha_mqtt_discoverable.sensorsimportNumber,NumberInfofrompaho.mqtt.clientimportClient,MQTTMessage# Configure the required parameters for the MQTT brokermqtt_settings=Settings.MQTT(host="localhost")# Information about the `number` entity.number_info=NumberInfo(name="test",min=0,max=50,mode="slider",step=5)settings=Settings(mqtt=mqtt_settings,entity=number_info)# To receive number updates from HA, define a callback function:defmy_callback(client:Client,user_data,message:MQTTMessage):number=int(message.payload.decode())logging.info(f"Received{number}from HA")do_some_custom_thing(number)# Send an MQTT message to confirm to HA that the number was changedmy_number.set_value(number)# Define an optional object to be passed back to the callbackuser_data="Some custom data"# Instantiate the numbermy_number=Number(settings,my_callback,user_data)# Set the initial number displayed in HA UI, publishing an MQTT message that gets picked up by HAmy_number.set_value(42.0)ContributingPlease runblackon your code before submitting. There aregithooks already configured to runblackand other checks before every commit, please runpre-commit installto enable them.Users of ha-mqtt-discoverableIf you use this module for your own project, please add a link here.ha-mqtt-discoverable-cli- Command line tools that allow using this module from shell scriptsplejd-mqtt-ha- A containerized Python application that bridges Plejd devices to Home AssistantContributorsMade withcontributors-img.