Sun2000 power regulation, suplementing grid power from battery (powerwall)

Hello
I want to regulate output of my sun2000 grid tie inverter.
I have esp8266 pwm and I can regulate the output power by changing the slider position manualy. the name of the (light) is “sun2000_L1PWM”
I also have data from my power meter how much energy my house consume , the sensor name is : “sensor.energija”, the value is from - 9000 to +20000 (W) and the refresh time is 2 seconds
I would like to make automation that corect’s pwm output every 2 seconds(refresh time from my power meter).

in basic the code vould look like this
’ ’ ’
wait 2 seconds
if sun2000_L1PWM < 101 then
if sensor.energija >50 then sun2000_L1PWM +1;
end if
end if
if sun2000_L1PWM > 0 then
if sensor.energija <0 then sun2000_L1PWM -1
end if
end if
’ ’ ’
and it must run every 2 seconds.

or
if value from sensor is greater then 50 then increase pwm value by 1 until pwm value is 255 and if sensor value is less then 0 then decrease pwm value by 1 until pwm value is 0
This vould slowly corect output power of my inverter until it maches power my house consume.
How can I formulate this in yaml automation?
thank you