import pyudev import os def detect_plug_unplug(): # Create a context for monitoring context = pyudev.Context() # Define the subsystem and attribute to monitor subsystem = 'power_supply' attribute = 'online' # Set the initial charging state charging = True # Monitor for changes monitor = pyudev.Monitor.from_netlink(context) monitor.filter_by(subsystem=subsystem) for device in iter(monitor.poll, None): if device.attributes.get(attribute): plugged_in = int(device.attributes.get(attribute)) # Check if the charging state has changed if plugged_in != charging: charging = plugged_in # Play the sound based on the charging state if charging: # Sound when the charging cable is plugged in sound_file = "/usr/share/sounds/Yaru/stereo/device-added.oga" else: # Sound when the charging cable is unplugged sound_file = "/usr/share/sounds/Yaru/stereo/device-removed.oga" # Use the "aplay" command to play the sound file os.system(f"ogg123 {sound_file}") if __name__ == "__main__": detect_plug_unplug()