How to calculate Tesla PowerWall batter charging from gid/solar

I could use some help creating a power sensor showing how much of my Tesla PowerWall battery charging is coming from solar and a separate one for how much is coming from the grid. I want to use these sensors in my overall power and electricity usage graphs and dashboards.

I have the Tesla Fleet Integration installed and in the Tesla Powerwall integration, there is a battery power sensor (negative is charging, positive is discharging), there is also a power sensor for grid power (positive for importing, negative for exporting), solar generation (positive or zero), and % battery charged. I’m not sure how set it up properly since the battery can charge from gird and solar at the same time, plus thereare other loads drawing from these power sources at the same time, and the Powerwall charge rate limitation may also effect the calculation.

The Tesla Powerwall integration does have energy sensor values for Battery Charged by Grid and by Solar, but I need a power sensor not energy sensor, and also the battery charge energy sensors periodically reset, which causes issue with energy calculations.

Any guidance is greatly appreciated.

With the help of Claude, I came up with a calculation for the battery power from grid and from solar, which I convert to energy values using an integral sensor/helper. These values seem to match pretty well with the values from the Tesla PowerWall, so it seems as though the calculation is pretty solid. Sharing here in case anyone else is looking for the same thing and can use this as a foundation.

Battery Power from Solar:

{% set solar_power = states('sensor.my_house_solar_power') | float(0) %}
{% set load_power = states('sensor.my_house_load_power') | float(0) %}
{% set grid_power_export = [0, -(states('sensor.my_house_grid_power') | float(0))] | max %}
{% set battery_charge_power = states('sensor.battery_charge_power') | float(0) %}
{% set solar_surplus = [solar_power - load_power, 0] | max %}
{% set solar_to_battery = [solar_surplus - grid_power_export, 0] | max %}
{{ [solar_to_battery, battery_charge_power] | min | round(3) }}

Battery Power from Grid is simply the Battery Power less the value calculated above:

{% set battery_charge_power = states('sensor.battery_charge_power') | float(0) %}
{% set battery_charge_solar = states('sensor.battery_charge_from_solar') | float(0) %}
{{ [battery_charge_power - battery_charge_solar, 0] | max | round(3) }}