Hey,
sure I can do that. But know I am not an expert either, so my solution might be more complicated than it has to be.
I am using the GitHub - AlexxIT/PythonScriptsPro at v1.0.4 integration through HACS for the python scripts (if it is about how to install an extension with HACS, there are much better tutorials out there then I could give so I will skip that part here)
This integration give the option to use a python script as a sensor just like you did with the rest sensor in your configuration.yaml. That would then look something like this:
- platform: python_script
file: <relative_path_to_script_from_configuration.yaml>/script.py
name: Solar
unique_id: solar
scan_interval: 15
For the path, if you place the python script right beside the configuration.yaml it would just be the script name.
My python script looks like this:
import re
import requests
cookie_name = "kiwisessionid"
url = "http://<ip-of-the-iq-smartbox>"
payload = {
"username": "installer",
"url": "/",
"password": "<your-pw>",
"submit": "Login"
}
auth = requests.post(url + "/auth/login", data=payload)
session_id = auth.cookies[cookie_name]
cookies = { cookie_name: session_id }
response = requests.get(
url + "<rest-method-for-value0>",
cookies=cookies)
value0 = response.json()['state']
response = requests.get(
url + "<rest-method-for-value1>",
cookies=cookies)
value1 = response.json()['state']
values = {
"value0": value0,
"value1": value1,
# add more values if you want
}
# I am using this to remove any units like Watt(W) from the response to just have a number
cleaned_values = {k: re.sub('([^\\d.-]+)', '',v) for k, v in values.items()}
self.attributes = cleaned_values
If you don’t want to write your password and the IP in plain text in the script you can pass them through as secrets as well. It would be better practice to do that.
This script saves the values as attributes of an entity and not as the state. You can transform those back into their own entities by using a template sensor.
template:
sensor:
- name: Value0
unique_id: value0
unit_of_measurement: "W"
device_class: power
state_class: measurement
availability: >-
{{
not state_attr('sensor.solar', 'value0') == None
}}
state: >
{% set value = state_attr('sensor.solar', 'value0') | float %}
{{ value }}
This is the part I am not sure about if there is a better solution, converting attributes to their own entities with states. But it is working.
You can give the attributes proper names in the python script and use them in the template sensors.
As a hint, if you change anything in the python script, you will have to restart home assistant. Reloading the yaml configuration is not enough, because the script is compiled at start up.
I hope this helps. If you have any questions, just feel free to ask.