Dynamic call service

Hey all
I am trying to convert a flow from “pure modbus” to an integration (huawei solar cells) and have a question regarding the function nodes to call service nodes.
If I can make use of {“value”:msg.payload} in charge dynamic.


In the ‘Call Service’ node:

Set ‘Data’ UI field option to J: (JSONata expression)

Use the JSONata expression

{"value": payload}

This will take the value held in msg.payload, and create the call service data object you require.

You should use JSONata for this as mustache templates don’t work correctly when building objects.
You don’t need the leading ‘msg.’ in JSONata.
You don’t need to make msg.payload an object {“value”: 33}, you can just set msg.payload to 33.

In the ‘Function’ node:
I am going to have to assume that you are using this node to prepare a value for the Call Service.

You are attempting to get ‘sensor.inverter_input_power’, and I assume you want the entity state value, but you can’t get this value using flow.get as it is not stored in the flow context. You can get at this using global context variable ‘homeassistant’, but there are other ways to get this.
You are creating an object in msg.payload - if you really want to do this you don’t need the stringify, just set msg.payload = {“value”: diff}.
As an aside, you are using ‘var’ to declare variables and this is not ‘best practise’ and can lead to memory leakage - suggest you use ‘let’ or ‘const’ instead.

You can do all of this in one go, inside the Call Service node. This is a bit more advanced, but it may help you get where you want to be a little quicker.

Just put the following code in to the Call Service node ‘Data’ UI field, with the option set to J: JSONata.

(
    $input:= $entities('sensor.inverter_input_power').state;
    $diff:=  $exists($input) ? $round($number($input)* 0.3, 0) : 0;
    {"value": $diff < 200 ? 200 : $diff}
)

This should work - I can only test it on my sensors. It may also need a bit more code to deal with ‘unavailable’, but I think this is a lot easier than using function nodes!

1 Like

Tnx i will try.

Option two worked fine, thanks a lot for the help

If you want use a message in json templates, they must be in a mustache template.

{{payload}}

if you are trying to pass a web adress use triple

{{{payload}}}