Create custom energy sensor

My question is about power consumption.

Is it possible to create directly energy sensor so that later change its value with python script? I have access to device’s API and instead of current power I can fetch “added energy” (periodically). For example, in some moment of time I receive value of 5kWh, than in another 10 minutes API returns me 5.2kWh and so on.
Then I want to use such a sensor (or whatever) in energy grid. Ideal scenario would be to add historical data which I have for few previous months. Is that possible?

actually, after digging around I have understood how to resolve most of the issues.

  • Yes, it is trivial to create custom energy sensor via configuration.yaml. It will be empty.
  • Via hass.states.set it is possible set required current value (example is here: How to manually set state/value of sensor? - #23 by AhmadK)
  • Adding historical values is not straitforward and home assistant definitely should consider to add such an feature. There are numerous posts here in community about that, and feature requests to support that.
  • However, it seems to be completely possible to write such data into database directly (statistics_short_term table, from which that data will be purged according to configuration into statistics table). I think it should be absolutely possible, though I still haven’t tried that.
  • Additional recomendation is at least to have backups of DB, and I personally is a bit aftaid of manipulating with sqlite, so I’ve migrated DB to mysql. Sqlite seems to be a bit fragile.
  • There is still open question for me, not sure that it’s possible to use this energy sensor in energy dashboard without additional attributes / configuration, this is matter of more research.