How to measure consumption of device only when using power grid

Use a utility meter with tariffs. See this explanation: How to use Utility Meter Tariffs to conditionally measure things

If you have any issues with it post what you tried here (not in the community guide) and I’ll help you get it going.