Assumes you only have a single optical drive, only tested under Windows 10. Exploits the quirk that the C callback takes a much shorter period of time to return if the drive is already open, then it does when opening (presumably waits until the drive reports a successful opening somehow). It assumes that if the time passed after an opening command is below a certain value (1.0), then the drive is already open and needs closing.
You may need to change the float value on line 5 if your drive opens super quick. (I was getting values between 0.1-0.3 when already open, and 2.0+ when closed).