Hello,
I have the following situation: I have a TCP service that returns a JSON with various fields and, currently, I have set up several sensors using TCP platform, each with the SAME payload but extracting different fields from the service response.
What I want to do is to avoid making multiple identical calls to the TCP service (because all data can be retrieve with a single call) and still have several sensors, one for each value/field returned as JSON.
example of my current config (two sensor with the same request payload):
- platform: tcp
name: my_tcp_sensor1
host: 192.168.0.1
port: 11111
payload: "{\"method\": \"service_method\"}\n"
value_template: "{{(value|from_json).result[2].split(\";\")[0]|float / 1000}}"
- platform: tcp
name: my_tcp_sensor2
host: 192.168.0.1
port: 11111
payload: "{\"method\": \"service_method\"}\n"
value_template: "{{(value|from_json).result[2].split(\";\")[1]|float / 1000}}"
Thanks in advance.
finity
March 2, 2021, 2:46am
2
I can think of a way to do it that is fairly easy.
Just create a sensor that contains the entire data of “result[2]” then use that sensor state data in the other two sensors:
- platform: tcp
name: my_tcp_sensor
host: 192.168.0.1
port: 11111
payload: "{\"method\": \"service_method\"}\n"
value_template: "{{(value|from_json).result[2]}}"
- platform: template
sensors:
my_tcp_sensor1:
friendly_name: my_tcp_sensor1
value_template: "{{states('sensor.my_tcp_sensor').split(';')[0] | float / 1000}}"
my_tcp_sensor2:
friendly_name: my_tcp_sensor2
value_template: "{{states('sensor.my_tcp_sensor').split(';')[1] | float / 1000}}"
that should work as long as the state of the first data sensor isn’t longer than 255 characters.
But without knowing the complete returned data I’m just guessing that it will work as expected.
1 Like
nickrout
(Nick Rout)
March 2, 2021, 8:18am
3
jq is probably a better tool than split for extracting json, but I agree with @finity
Shame you can’t do json_attributes
like the rest sensor.
it worked, thanks a lot for the ideia!
Had to do some json juggling to fit everything I needed inside 255 bytes, but it is working! \o/
1 Like