Reading previous answers, it looks like there’s no way to do this exclusively in software. However, it should be relatively easy to do it with a little hardware help – i.e. by using any Bluetooth- or WiFi-enabled smart electrical switch with open API. The phone could then switch the charger on or off programmatically whenever it feels like it.