Components Home Assistant "Python Scripts"

1 minutes of reading
Proconductor: Home Assistant Community
Availability: included in thepersonale HUB Home Assistant
Category: software
Type: components Home Assistant
Implementation difficulties: half
Card revision: 1.1

Unlike the vast majority of the components Home Assistant"Python Script"Is not useful for defining entity but to the bare, raw and very useful execution of personal scripts written in language Python.

The most interesting aspect of this possibility lies in the fact to be able to control entities and services proprior to Home Assistant within the scripts, allowing you to customize the behavior of theHUB in non-natively included mode.

The variables that can be used for this purpose are:

Full NameDescription
hassThe item "Home Assistant". You can only use it to call services, set states and trigger events. API reference
dataThe data passed as a payload to the service call prothe script itself.
loggerThe logger of Home Assistant: logger.info(), logger.warning(), logger.error(). API reference

To activate this component is sufficient to indicate in configuration the voice:

python_script:

And restart Home Assistant. In addition, you need to create the folder (inside the one it contains the configuration files dell 'HUB):

python_scripts/

inside which the files related to the scripts to be executed by will be copied Home Assistant.

This done, Home Assistant will create as many services as there are scripts found in that folder.
Let's say, for example, that you have a script called "example.py"Correctly copied inside the folder"python_scripts". The service associated with it (which can be performed on a par with and in the ordinary way of performing the services Home Assistant) will be called "python_script.example"

How to evoke services

The following example explains how to write a script which includes two input variables: entity_id (required) e RGB_COLOR (optional). The script, when evoked through corresponding service, prosees to turn on the light indicated with entity_id setting any rgb color passed with RGB_COLOR and set the lumimaximum weight (255):

entity_id = data.get('entity_id')
rgb_color = data.get('rgb_color', [255, 255, 255])
if entity_id is not None:
    service_data = {'entity_id': entity_id, 'rgb_color': rgb_color, 'brightness': 255 }
    hass.services.call('light', 'turn_on', service_data, False)

It will then be sufficient to evoke the corresponding service the script and pass it a payload of this type:

{"entity_id": "light.camera", "rgb_color": [255, 0, 0] }

In order to trigger the effect of the described script.


Home Assistant Official LogoATTENZIONE: remember that there is on our FORUM community an ad hoc section dedicated to Home Assistant, for any doubt, question, information on the specific merit of these components.


telegram

Stay up to date through ours Telegram channel!