I am a very new person for Python.
There is a script containing a function.
Let it be this example:
def my_function(fname):
print(fname + " Refsnes")
How to call this function by using a HA service?
I want to use the result as a value for some sensor.
I found this:
Actually, I was able to call it as long as the main entity is not a python_script:
entity: [entity thats not a python_script]
tap_action:
action: call-service
service: python_script.endpoint
service_data:
action: this
payload: that
type: entity-button
This seems to work decently enough
PS: im even more green, just looked at the new “Python script” doc the other day
Thank you very much for a reply.
Unfortunately, it does not help me.
I need to pass a parameter to a function my_function
.
dproffer
(David Proffer)
April 17, 2022, 1:28am
4
Have you had a go at this example?
Simple python script that reads a parameter from a service call and writes parameter value to the HA log. Good hunting!
Yes i thought this was too simple example for you, below is a more “complicated”, and way above my understanding example, and then you can hope “123” will catch your post, he seems to be familiar with python also.
Here is a script I’ve used (python_scripts/set_state.py
):
if 'entity_id' not in data:
logger.warning("===== entity_id is required if you want to set something.")
else:
data = data.copy()
inputEntity = data.pop('entity_id')
inputStateObject = hass.states.get(inputEntity)
if inputStateObject:
inputState = inputStateObject.state
inputAttributesObject = inputStateObject.attributes.copy()
else:
inputState = 'unknown'
inputAttributesObject = {}
if 'state' in data:
inputState = data.pop('state')
logger.debug("===== new attrs: {}".format(data))
inputAttributesObject.update(data)
hass.states.set(inputEntity, inputState, inputAttributesObject)
You call it like this:
- service: python_script.set_state
data:
entity_id: sensor.blah
state: blah blah
abc: 123
xyz: do re mi
This will result in an entity with an id of ‘sensor.blah’ whose state will be ‘blah blah’ and which will have two attributes – abc = 123, and xyz = ‘do re mi’.
You need to specify at least entity_id. If you specify state, it will set the state to that value. If you don’t specify state, then the state will not change (or be set to ‘unknown’ if the entity did not yet exist in the state machine.) All other parameters will be written as attributes.
Did you ever get this figured out? I’ve got the same problem