16 Dec 2011 @ 12:10 PM 

Most Computer users are familiar with the Sounds that Windows emits when you plug and unplug a USB thumb drive. It’s a useful form of auditory feedback that the drive was in fact detected. However, I’ve found linux to be oddly tacit in this regard. So I set to work writing a python script that uses DBUS to monitor for new USB devices and will play a sound whenever a new Volume is attached.

  1.  
  2. #!/usr/bin/python
  3. #by BC_Programming
  4. import dbus
  5. import gobject
  6. import time
  7. import subprocess
  8.  
  9. print "BASeCamp ‘USBSounds’ Simple USB Volume notification sound."
  10.  
  11. #playsound merely shells out to mplayer. I would have preferred an integrated solution but… meh.
  12. def playsound(soundfile):
  13.  
  14.     subprocess.call( ["mplayer", "hardwareinsert.wav"] , stdout=open(‘/dev/null’, ‘w’), stderr=open(‘/dev/null’, ‘w’))
  15.    
  16. class DeviceAddedListener:
  17.     def __init__(self):
  18.         #get the system bus…
  19.         self.bus = dbus.SystemBus()
  20.         #get the manager
  21.         self.hal_manager_obj = self.bus.get_object(
  22.                                                   ‘org.freedesktop.Hal’,
  23.                                                   ‘/org/freedesktop/Hal/Manager’)
  24.         #get the interface for the manager                                          
  25.         self.hal_manager = dbus.Interface(self.hal_manager_obj,‘org.freedesktop.Hal.Manager’)
  26.         #connect to the appropriate signals.
  27.         self.hal_manager.connect_to_signal(‘DeviceAdded’, self._filteradd)
  28.         self.hal_manager.connect_to_signal("DeviceRemoved",self._filterremove)
  29. #note: I couldn’t get DeviceRemoval sounds to work since it doesn’t let you     #inspect whether the removed device is a volume via "QueryCapability"… since it’s gone.
  30.     def _filteradd(self, udi):
  31.         device_obj = self.bus.get_object (‘org.freedesktop.Hal’, udi)
  32.         device = dbus.Interface(device_obj, ‘org.freedesktop.Hal.Device’)
  33.         #if it is a volume, call the do_add function…
  34.         if device.QueryCapability("volume"):
  35.             return self.do_add(device)
  36.            
  37.     def _filterremove(self,udi):
  38.         try:
  39.             #device_obj = self.bus.get_object(‘org.freedesktop.Hal’,udi)
  40.             #device = dbus.Interface(device_obj,’org.freedesktop.Hal.Device’)
  41.  
  42.             #if device.QueryCapability("volume"):
  43.             #    return self.do_remove(device)
  44.         except:
  45.             return
  46.     #unused….
  47.     def do_remove(self,volume):
  48.  
  49.         playsound("hardwareremove.wav")        
  50.         #displays some info about the added device to the console (maybe future changes can pop stuff like volume label, device file, size, etc into a Notification box?)
  51.     def do_add(self, volume):
  52.         device_file = volume.GetProperty("block.device")
  53.         label = volume.GetProperty("volume.label")
  54.         fstype = volume.GetProperty("volume.fstype")
  55.         mounted = volume.GetProperty("volume.is_mounted")
  56.         mount_point = volume.GetProperty("volume.mount_point")
  57.         try:
  58.             size = volume.GetProperty("volume.size")
  59.         except:
  60.             size = 0
  61.  
  62.         print "New storage device detected:"
  63.         print "  device_file: %s" % device_file
  64.         print "  label: %s" % label
  65.         print "  fstype: %s" % fstype
  66.         if mounted:
  67.             print "  mount_point: %s" % mount_point
  68.         else:
  69.             print "  not mounted"
  70.         print "  size: %s (%.2fGB)" % (size, float(size) / 1024**3)
  71.         #and play a sound.
  72.         playsound("hardwareinsert.wav")
  73.  
  74. #main loop…
  75. if __name__ == ‘__main__’:
  76.     from dbus.mainloop.glib import DBusGMainLoop
  77.     DBusGMainLoop(set_as_default=True)
  78.     loop = gobject.MainLoop()
  79.     print "in __main__…"
  80.     DeviceAddedListener()
  81.     loop.run()
  82.  

As can be seen, it’s a tad messy, and even rather hackish. For one thing, it uses DBUS, which to my understanding is deprecated. Unfortunately, the replacement I couldn’t really get a clear answer on. From what I can gather, the proper method for now is libnotify and pynotify, but I couldn’t get libnotify to compile and thus was not able to properly use pynotify, and I didn’t want to have to force people to go through that sort of hell when they tried to use my script, so I stuck to DBUS.

The only limitation I discovered is that on device removal, you can’t really inspect what device was removed. At first I just figured, Just play the sound everytime and let the user figure it out, but for some reason that just assaulted me with constant device removal sounds. So I ended up commenting (and I think removing) that particular segment of code.

Playing Sounds is unnecessarily difficult in Python, or more specifically, Linux. It’s ridiculous. First I found a build in module for python, ossdevsound (or something to that effect), but attempts to use that failed because apparently it uses OSS, which apparently was replaced by ALSA for whatever reason. So I tried pygame, which errored out that I had no mixer device when I tried to initialize the mixer. So I decided to hell with it and just spawned a mplayer process, and redirected it’s stdout to NULL to avoid the nasty business where it barfs all over the console. And amazingly, that seems to work fine for device insertions, which I decided I was content with.

By default I use the Windows insertion and removal sound files. The removal sound isn’t actually used but I kept it in the g-zipped tar because I wanted to. Personally I usually just launch this in a terminal and then tuck it away on another desktop. No doubt one can execute it as a daemon or something instead and get the functionality without the console window baggage to keep around, though.

ThumbNotify.tar.gz

630 total views, 4 views today

Have something to say about this post? Comment!

Posted By: BC_Programming
Last Edit: 16 Dec 2011 @ 12:10 PM

EmailPermalink
Tags


 

Responses to this post » (None)

 
Post a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


 Last 50 Posts
 Back
Change Theme...
  • Users » 862
  • Posts/Pages » 192
  • Comments » 67
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

PP



    No Child Pages.

Windows optimization tips



    No Child Pages.