Hello Hui,
Unfortunately, there is no way to detect a Device detachment via software, however, as you are using a self-powered device, you can monitor the 5V voltage from USB connector, this is, if device is connected to a host, the host will provide 5v from that line so you can detect that your device is plugged or unplugged according voltage level on that line.
To make this, you can configure one GPIO as input and see voltage level on this 5V line (this GPIO should be 5V-tolerant, otherwise, you should add a voltage divider to avoid damage on MCU). This way, if you previously had 5V on this line and suddenly it appears as 0V, it means a detachment event occurred.
I hope this can help you!
Best Regards
Isaac Avila
----------------------------------------------------------------------------------------------------------------------------------------
Note: If this post answers your question, please click the Correct Answer button. Thank you!
----------------------------------------------------------------------------------------------------------------------------------------