look at any (and likely all) of the binary sensors to get an idea of how others have created external components to satisfy this need.
here is the code for a GPIO binary sensor:
You need to understand everything this code is doing.
Before you do that, look here
https://developers.esphome.io/contributing/code/#contributing-to-esphome
There is also these (but I didn’t find them that helpful):
This is something that is either new or moved recently.
https://developers.esphome.io/architecture/components/
It is new and at first glance looks good and might be what was needed to make this process easier.