Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: USB Drive sounds (Linux Mint 10)  (Read 12734 times)

0 Members and 1 Guest are viewing this topic.

BC_Programmer

    Topic Starter

    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
USB Drive sounds (Linux Mint 10)
« on: December 15, 2011, 06:34:40 AM »
So I googled my head off trying to find out if there is a way to make it so that Linux can play a short sound file when a USB drive/device is added or removed. I couldn't find anything, so I figured I'd write a python script to do it.

It uses the apparently deprecated DBUS api, because I couldn't figure ut how to install half the crap the "new" method wanted (pynotify's installation scripts had broken shebangs and crashed seemingly randomly when I tried to install it, and I have no idea how to get libnotify working). Also, so far it only seems to work for adding volumes, since dbus won't let me inspect the removed device in the remove hook to determine if it's a volume, and I got weird behaviour when I just played the removal sound for any removal without inspecting.

For sound, I tried about a dozen different APIs and packages, which either refused to install, had issues during ./configure that I couldn't resolve (particularly the one where it complained that I didn't have the header to compile python extensions which made sense except it was integrated into the core python includes and thus was extraneous and I wasn't able to find the part in the shell script to remove so I gave up). I had luck with pygame, mostly because I was able to simply apt-get it, but it crashed with audio errors when I tried to use pygame.mixer.init(). the Python-standard ossaudiodev was promising but OSS is outdated and I couldn't get it to even pretend to work.

I basically ended up just shelling out to mplayer to play the sound. Which works, I guess.

Anyway, here is the script. I now have it running off in another desktop so I get the standard windows USB add sound whenever I plug in a USB drive, heh.

Code: [Select]
#!/usr/bin/python
#by BC_Programming
import dbus
import gobject
import time
import subprocess

print "BASeCamp 'USBSounds' Simple USB Volume notification sound."

#playsound merely shells out to mplayer. I would have preferred an integrated solution but... meh.
def playsound(soundfile):

    subprocess.call(["mplayer", "hardwareinsert.wav"], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))
   
class DeviceAddedListener:
    def __init__(self):
        #get the system bus...
        self.bus = dbus.SystemBus()
        #get the manager
        self.hal_manager_obj = self.bus.get_object(
                                                  'org.freedesktop.Hal',
                                                  '/org/freedesktop/Hal/Manager')
        #get the interface for the manager                                         
        self.hal_manager = dbus.Interface(self.hal_manager_obj,'org.freedesktop.Hal.Manager')
        #connect to the appropriate signals.
        self.hal_manager.connect_to_signal('DeviceAdded', self._filteradd)
        self.hal_manager.connect_to_signal("DeviceRemoved",self._filterremove)
#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.
    def _filteradd(self, udi):
        device_obj = self.bus.get_object ('org.freedesktop.Hal', udi)
        device = dbus.Interface(device_obj, 'org.freedesktop.Hal.Device')
        #if it is a volume, call the do_add function...
        if device.QueryCapability("volume"):
            return self.do_add(device)
           
    def _filterremove(self,udi):
        try:
            #device_obj = self.bus.get_object('org.freedesktop.Hal',udi)
            #device = dbus.Interface(device_obj,'org.freedesktop.Hal.Device')

            #if device.QueryCapability("volume"):
            #    return self.do_remove(device)
        except:
            return
    #unused....
    def do_remove(self,volume):

        playsound("hardwareremove.wav")       
        #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?)
    def do_add(self, volume):
        device_file = volume.GetProperty("block.device")
        label = volume.GetProperty("volume.label")
        fstype = volume.GetProperty("volume.fstype")
        mounted = volume.GetProperty("volume.is_mounted")
        mount_point = volume.GetProperty("volume.mount_point")
        try:
            size = volume.GetProperty("volume.size")
        except:
            size = 0

        print "New storage device detected:"
        print "  device_file: %s" % device_file
        print "  label: %s" % label
        print "  fstype: %s" % fstype
        if mounted:
            print "  mount_point: %s" % mount_point
        else:
            print "  not mounted"
        print "  size: %s (%.2fGB)" % (size, float(size) / 1024**3)
        #and play a sound.
        playsound("hardwareinsert.wav")

#main loop...
if __name__ == '__main__':
    from dbus.mainloop.glib import DBusGMainLoop
    DBusGMainLoop(set_as_default=True)
    loop = gobject.MainLoop()
    print "in __main__..."
    DeviceAddedListener()
    loop.run()
I was trying to dereference Null Pointers before it was cool.

Rob Pomeroy



    Prodigy

  • Systems Architect
  • Thanked: 124
    • Me
  • Experience: Expert
  • OS: Other
Re: USB Drive sounds (Linux Mint 10)
« Reply #1 on: December 19, 2011, 02:06:04 AM »
You'd think there'd be some kind of hook out of automount, wouldn't you?  Probably introducing such a feature into the code and recompiling would be the most elegant solution.  Heave you heard of inotifyincron builds on inotify and there's even an example of playing a sound on the basis of a change within the file system.
Only able to visit the forums sporadically, sorry.

Geek & Dummy - honest news, reviews and howtos

BC_Programmer

    Topic Starter

    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: USB Drive sounds (Linux Mint 10)
« Reply #2 on: December 19, 2011, 02:17:45 AM »
I wanted a solution that I could share easily, most of the others, even assuming I was able to get them working, would generally need somebody to go off and download some other package (for example, pyinotify). I might explore that for a more robust solution, at least for myself, but this script has been working well enough for me.
I was trying to dereference Null Pointers before it was cool.

Rob Pomeroy



    Prodigy

  • Systems Architect
  • Thanked: 124
    • Me
  • Experience: Expert
  • OS: Other
Re: USB Drive sounds (Linux Mint 10)
« Reply #3 on: December 19, 2011, 02:18:59 AM »
Ah, I see.  In that case, well done!
Only able to visit the forums sporadically, sorry.

Geek & Dummy - honest news, reviews and howtos

Raptor

  • Guest
Re: USB Drive sounds (Linux Mint 10)
« Reply #4 on: January 08, 2012, 05:44:23 PM »
Why do you need a sound for that?

BC_Programmer

    Topic Starter

    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: USB Drive sounds (Linux Mint 10)
« Reply #5 on: January 08, 2012, 06:50:57 PM »
Why do you need a sound for that?

So that I know the drive was detected.
I was trying to dereference Null Pointers before it was cool.

JJ 3000



    Egghead
  • Thanked: 237
  • Experience: Familiar
  • OS: Linux variant
Re: USB Drive sounds (Linux Mint 10)
« Reply #6 on: January 08, 2012, 07:00:56 PM »
So that I know the drive was detected.

Can't you just look?

If I recall correctly, the default behavior for Linux Mint is to auto-mount usb drives and show an icon on the desktop.

By the way, good job on the script!  :)
Save a Life!
Adopt a homeless pet.
http://www.petfinder.com/

BC_Programmer

    Topic Starter

    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: USB Drive sounds (Linux Mint 10)
« Reply #7 on: January 08, 2012, 07:05:56 PM »
Can't you just look?
If I recall correctly, the default behavior for Linux Mint is to auto-mount usb drives and show an icon on the desktop.
It doesn't always show up and opening nautilus or showing the desktop is a big pain in the *censored* compared to just being able to hear a sound.
I was trying to dereference Null Pointers before it was cool.

Raptor

  • Guest
Re: USB Drive sounds (Linux Mint 10)
« Reply #8 on: January 09, 2012, 08:13:55 AM »
It's pretty cool that you wrote an entire script for that. I still think Firefox is the best browser, though.

BC_Programmer

    Topic Starter

    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: USB Drive sounds (Linux Mint 10)
« Reply #9 on: January 09, 2012, 11:19:44 PM »
It's pretty cool that you wrote an entire script for that. I still think Firefox is the best browser, though.
What does firefox have to do with any of this?
I was trying to dereference Null Pointers before it was cool.

Veltas



    Intermediate

    Thanked: 7
    • Yes
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Linux variant
Re: USB Drive sounds (Linux Mint 10)
« Reply #10 on: January 10, 2012, 04:05:57 AM »
What does firefox have to do with any of this?

At least it's not "or alternatively you could just install Windows, which plays the USB-add sound".

BC_Programmer

    Topic Starter

    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: USB Drive sounds (Linux Mint 10)
« Reply #11 on: January 10, 2012, 04:14:38 AM »
At least it's not "or alternatively you could just install Windows, which plays the USB-add sound".

Windows is installed in a dual boot with it, so I can properly test my programs installers without fiddling with a VM :)

the Apache/MySQL/PHP stack  is a lot easier to install & administer via on Linux, and it is the primary role of the laptop.
I was trying to dereference Null Pointers before it was cool.

Veltas



    Intermediate

    Thanked: 7
    • Yes
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Linux variant
Re: USB Drive sounds (Linux Mint 10)
« Reply #12 on: January 10, 2012, 04:23:02 AM »
the Apache/MySQL/PHP stack  is a lot easier to install & administer via on Linux, and it is the primary role of the laptop.

Is it running a website?

Raptor

  • Guest
Re: USB Drive sounds (Linux Mint 10)
« Reply #13 on: January 10, 2012, 04:31:47 AM »
What does firefox have to do with any of this?

Nothing. Just trolling!

Veltas



    Intermediate

    Thanked: 7
    • Yes
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Linux variant
Re: USB Drive sounds (Linux Mint 10)
« Reply #14 on: January 10, 2012, 04:34:08 AM »
Nothing. Just trolling!

Oh Raptor...

BC_Programmer

    Topic Starter

    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: USB Drive sounds (Linux Mint 10)
« Reply #15 on: January 10, 2012, 04:34:19 AM »
Is it running a website?
technically, Yes, but it's not internet exposed at the moment. Normally, I have home.bc-programming.com redirect to it, but I'm not using my router (so there is no "Virtual Server" configured) and I'm at a different IP address  than usual so it just times out (since there's nothing there). Mostly it's just for quick testing of PHP and server side stuff; much easier to edit a file in var/www than have to download it, edit it, and then upload it back to my web host, then test it.

More specifically at the moment, I'm using the MySQL server to test and debug my "JobClock" Application for a Vehicle Repair Shop in Iowa. it holds the database server; my .NET application connects to it and issues queries and all that etc. Of course in-site they have their own MySQL server, but since their server is separate from where the applications run I like to try to keep my environment as close to that as possible (thus using a separate machine for the DB Server).
I was trying to dereference Null Pointers before it was cool.

Veltas



    Intermediate

    Thanked: 7
    • Yes
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Linux variant
Re: USB Drive sounds (Linux Mint 10)
« Reply #16 on: January 10, 2012, 04:35:56 AM »
the Apache/MySQL/PHP stack  is a lot easier to install & administer via on Linux

I know what you mean!

Rob Pomeroy



    Prodigy

  • Systems Architect
  • Thanked: 124
    • Me
  • Experience: Expert
  • OS: Other
Re: USB Drive sounds (Linux Mint 10)
« Reply #17 on: January 10, 2012, 06:02:04 AM »
much easier to edit a file in var/www than have to download it, edit it, and then upload it back to my web host, then test it.

It took me a while to come up with a development setup that was convenient and quick and which worked no matter where my laptop was, but this is how I've cracked this nut:

  • web development server (LAMP) is at home
  • my main development domain is registered and the DNS hosted is by one of the usual suspects
  • at home I am also running a local DNS server (BIND), which has its own zone files for my development domain
  • my IDE of choice is NetBeans; all changes are immediately uploaded to the development server via SFTP - firewall friendly

When I'm at home, my laptop uses the local DNS server (which forwards queries for domains it doesn't know about, in the usual way).  So file uploads and browsing happen over the LAN.  When I'm out and about, it gets the external DNS host.  (This is the most foolproof method of overcoming the problem of hairpin NAT - going out of your router and back in again when using an external IP address.)

The only hassle here is that when I make a change at my domain host, I have to remember to make a similar change at home.  But with judicious use of wildcards, I don't have to touch DNS records that often.

You might recall, BC that I had an issue with NetBeans caching DNS entries - that was the final wrinkle to iron out.  It all now works gloriously (thanks).
Only able to visit the forums sporadically, sorry.

Geek & Dummy - honest news, reviews and howtos

BC_Programmer

    Topic Starter

    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: USB Drive sounds (Linux Mint 10)
« Reply #18 on: January 11, 2012, 04:09:38 AM »
For me, normally, I use EditpadPro's FTP panel to rather seamlessly edit PHP/HTML/whatever files on my webhost, which worked well. Only reason I have to use FTP now is purely convenience; I'm using a cat-5 cable directly between my desktop and laptop to test the aforementioned program, and so I can't actually use that cat cable to connect my desktop to the internet. I could, of course, just use my LAN for the connection, but when I was first setting it up it seemed to have issues with DNS names on the LAN (Satellite refused to resolve to the laptop) so I plugged in the cat5 to test it and since it worked I just haven't bothered to change it. (another plus, with internet only available on my laptop, there are fewer distractions :P)

Also, I tend to not use IDE's for most dynamic languages. (Python, PHP, etc) there just isn't enough context in the language for any useful "intellisense" type functionality that I would like, by virtue of them being dynamic. (Also, Editpad Pro- and gedit's- syntax highlighting is usually enough for me). I also avoid frameworks, because they tend to simply introduce complications rather than resolve them (in my experience); Not that they are bad, of course- just that, this way, if something doesn't work, I know it's my fault, and I don't have to go hunting through my code only to discover that it was in fact an obscure issue in a framework I was using. Those are rare but it's happened before to me and, well, once-bitten twice shy.

And now I have the unenviable (but perhaps inevitable) task of fixing a bug that occurs at the client site (apparently elapsed times are jumping somewhat erratically, from say 1:40 to 2:00 and 2:59 rolling over to 2:00) which I can't for the life of me reproduce locally. But it definitely exists and it's driving me freaking nuts. (And apparently my client entry application crashes during these discrepancies as well). I'm crossing my fingers that the one instance where I used the Local system time (DateTime.Now) when I was supposed to use the time on the database server could somehow be the cause of all those issues... though since my laptop and desktop aren't in sync time-wise I would have expected to see the symptoms myself... That, and I'm completely rewriting the code  that goes through the database records to calculate the elapsed times for orders and users.

TL;DR
databases are a pain
I was trying to dereference Null Pointers before it was cool.

Rob Pomeroy



    Prodigy

  • Systems Architect
  • Thanked: 124
    • Me
  • Experience: Expert
  • OS: Other
Re: USB Drive sounds (Linux Mint 10)
« Reply #19 on: January 11, 2012, 08:51:25 AM »
TL;DR
databases are a pain

Ha.  I've been using CodeIgniter for ages and I must say it did wonders for my programming practice (viz. it made me much tidier, more disciplined, wrote less code to do more, etc.).  I'm now learning CakePHP, which has great strengths of its own - integrated ORM for example.  I have absolutely no interest in writing my own DB mappers.

Again, because I'm lazy, I've used 960.gs for layout on several websites and now I'm playing with Twitter's Bootstrap.  Both have helped me make prettier websites, more quickly.  I guess I'm just too lazy to come up with these elements all on my own - plus I am extremely confident that I would make many mistakes and spend hours just having to debug my own support code.  No ta!  ;)
Only able to visit the forums sporadically, sorry.

Geek & Dummy - honest news, reviews and howtos

kpac

  • Web moderator


  • Hacker

  • kpac®
  • Thanked: 184
    • Yes
    • Yes
    • Yes
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 7
Re: USB Drive sounds (Linux Mint 10)
« Reply #20 on: January 11, 2012, 10:55:30 AM »
Quote
I guess I'm just too lazy to come up with these elements all on my own
Using code that is already publically and freely available for use doesn't make you lazy, it makes you efficient. Or so my lecturer says.

BC_Programmer

    Topic Starter

    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: USB Drive sounds (Linux Mint 10)
« Reply #21 on: January 11, 2012, 11:46:29 AM »
Using code that is already publically and freely available for use doesn't make you lazy, it makes you efficient. Or so my lecturer says.

No. it's lazy. But that's good. As Larry Wall notes, Sloth is one of the hallmarks of a good programmer.
I was trying to dereference Null Pointers before it was cool.

kpac

  • Web moderator


  • Hacker

  • kpac®
  • Thanked: 184
    • Yes
    • Yes
    • Yes
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 7
Re: USB Drive sounds (Linux Mint 10)
« Reply #22 on: January 11, 2012, 11:59:41 AM »
No. it's lazy. But that's good. As Larry Wall notes, Sloth is one of the hallmarks of a good programmer.
No, it's not. No need to re-invent the wheel when it comes to programming.

BC_Programmer

    Topic Starter

    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: USB Drive sounds (Linux Mint 10)
« Reply #23 on: January 11, 2012, 12:20:53 PM »
No, it's not. No need to re-invent the wheel when it comes to programming.
Laziness:A natural disposition that results in being economic (at least that would be the definition used with regards to the quote)

How that doesn't cover exactly what you are saying I haven't a clue.

With regards to "re-inventing the wheel".

sometimes you need a different kind of wheel. You can't put a wagon wheel on a Dump Truck. If nobody ever "reinvented the wheel" programming-wise, we'd all still be using punch-cards and FORTRAN. Things can't be improved much without being rethought and reinvented.

Sometimes, you should stop killing your imagination by always using things others have done. And, most importantly, if nobody re-invented the wheel, we wouldn't have frameworks to use in the first place.
 
"re-inventing the wheel" is an often quoted passage, as you've demonstrated. But as a rule of thumb it has exceptions.

-If you want to learn more about the wheel
-If the existing wheels don't fit your "vehicle" (to follow the analogy)
-if the existing wheel(s) sucks

It's fine to re-invent the wheel. Just know why you are doing it.
I was trying to dereference Null Pointers before it was cool.

kpac

  • Web moderator


  • Hacker

  • kpac®
  • Thanked: 184
    • Yes
    • Yes
    • Yes
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 7
Re: USB Drive sounds (Linux Mint 10)
« Reply #24 on: January 11, 2012, 12:23:53 PM »
Yes, I agree with everything you've said. But for the majority of things you're going to be doing programming-wise, there is code out there which can make things a lot easier.

jQuery is an example. No point in writing a whole piece of Javascript just to make something fade in and out when jQuery or one of its plugins can do it. But I see what you're saying.

BC_Programmer

    Topic Starter

    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: USB Drive sounds (Linux Mint 10)
« Reply #25 on: January 11, 2012, 02:31:55 PM »
HAHA! so I figured out what was causing the bug.

The bug in the program was that times would have mysterious effects.

after 30 minutes, for example, it would say 1 hour 30 minutes; then at 1:59, it would roll over to 1 hour. and so forth.

this was the cause:

Code: [Select]
String FormatTimeSpan(TimeSpan formatthis)
{
    return String.Format("{0:00}:{1:00}",formatthis.TotalHours,formatthis.Minutes);
}
A short translation: basically, this will give the result of the TimeSpan's TotalHours field and Minutes fields, separated by a colon. And it worked perfectly, actually.

So what was the bug? Well, I thought the TotalHours field was a integer; or, rather, that it would return 0 until the first hour passed, then roll over to 1. Turns out it is a float, and therefore the minute portion was included as a fraction. This resulted in the value being rounded for the format string; so once the minutes passed 30 (.5) it would round up; resulting in all sorts of ridiculousness.

Face-palm worthy, really. All the complicated stuff to look through the various databases, calculate the appropriate date-ranges and cull the right overlaps and so forth works perfectly fine, and then this single line goes and simply formats the otherwise correct value wrongly.

of course my fix was to simply Floor() the TotalHours field. And suddenly all the "calculation issues" went away. VICTORY.
I was trying to dereference Null Pointers before it was cool.