Hal Dbus and Python

Page content

How to tie into dbus to get alerts on had drive device insertion also generates pretty notifications.

Its the first set in making the code decrypt a usb device on insertion run a rdiff backup and then eject the device.

Step two is to work out how to generate a key file for a pass phrase with luks.

import pynotify
import dbus
import gobject
from dbus.mainloop.glib import DBusGMainLoop
import time
class DeviceFinder ( ):

     def run ( self ):
          pynotify.init( "AutoRdiff" )
          n = pynotify.Notification("Auto Rdiff", "Application Started")
          n.set_urgency(pynotify.URGENCY_LOW)
          n.set_timeout(2)
          n.show()
          DBusGMainLoop(set_as_default=True)
          self.dbus()

     def dbus ( self ):
          self.bus = dbus.SystemBus()
          self.hal_manager_obj = self.bus.get_object(
                                             "org.freedesktop.Hal",
                                              "/org/freedesktop/Hal/Manager")
          self.hal_manager = dbus.Interface(self.hal_manager_obj,
                                               "org.freedesktop.Hal.Manager")
          self.hal_manager.connect_to_signal("DeviceAdded", self._filter)

     def _filter(self, udi):
          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_something(device)

     def do_something(self, volume):
          #give the device time to get mounted
          time.sleep(4)
          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 detectec:"
          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)

          n = pynotify.Notification("Auto Rdiff", " mount_point: %s" % mount_point)
          n.set_urgency(pynotify.URGENCY_LOW)
          n.set_timeout(2)
          n.show()