我一直在玩Dbus 2.7和java一段时间,我几乎得到了我想要的东西,但最终又被卡住了。 我需要的是一个监听SYSTEM总线的java程序,特别是org.freedesktop.UDisks接口信号,以便检测何时在机器上添加或删除某些设备(通常是块设备)(对我来说意味着“将设备插入和拔出“)。请注意,我只需要检测这些信号,而不是与它们一起传播的信息。
我特别感兴趣的dbus信号是DeviceAdded和DeviceRemoved:
[dbus-monitor output]
signal sender=:1.45 -> dest=(null destination) serial=186 path=/org/freedesktop/UDisks; interface=org.freedesktop.UDisks; member=DeviceAdded
object path "/org/freedesktop/UDisks/devices/sdb"
signal sender=:1.45 -> dest=(null destination) serial=230 path=/org/freedesktop/UDisks; interface=org.freedesktop.UDisks; member=DeviceRemoved
object path "/org/freedesktop/UDisks/devices/sdb"
要在Java中完成此任务,我创建了以下类[1]和[2]:
[1] org.freedesktop.UDisks.java
/** Created with 'createinterface' utility on org.freedesktop.UDisks system bus interface**/
package org.freedesktop;
import java.util.List;
import org.freedesktop.dbus.DBusInterface;
import org.freedesktop.dbus.DBusSignal;
import org.freedesktop.dbus.UInt32;
import org.freedesktop.dbus.UInt64;
import org.freedesktop.dbus.exceptions.DBusException;
public interface UDisks extends DBusInterface
{
/** ... **/
public static class DeviceRemoved extends DBusSignal
{
public final DBusInterface a;
public DeviceRemoved(String path, DBusInterface a) throws DBusException
{
super(path, a);
this.a = a;
}
}
public static class DeviceAdded extends DBusSignal
{
public final DBusInterface a;
public DeviceAdded(String path, DBusInterface a) throws DBusException
{
super(path, a);
this.a = a;
}
}
public void Uninhibit(String cookie);
public String Inhibit();
public DBusInterface LinuxMdCreate(List<DBusInterface> components, String level, UInt64 stripe_size, String name, List<String> options);
...
/** ... Remaining code removed for the sake of post length**/
}
[2] org.freedesktop.ListenHWDBusSignal.java
package org.freedesktop;
import org.freedesktop.dbus.DBusConnection;
import org.freedesktop.dbus.DBusSigHandler;
import org.freedesktop.dbus.exceptions.DBusException;
public class ListenHWDBusSignal {
public static void main(String[] args) throws DBusException, ParseException {
System.out.println("Creating Connection");
DBusConnection conn=DBusConnection.getConnection(DBusConnection.SYSTEM);
conn.addSigHandler(UDisks.DeviceAdded.class,new DBusSigHandler<UDisks.DeviceAdded>() {
@Override
public void handle(
UDisks.DeviceAdded added) {
System.out.println("Device added!");
}
});
conn.addSigHandler(UDisks.DeviceRemoved.class,new DBusSigHandler<UDisks.DeviceRemoved>() {
@Override
public void handle(
UDisks.DeviceRemoved removed) {
System.out.println("Device removed!");
}
});
System.out.println("Waiting for signals...");
}
}
好吧,我执行[2],一切顺利,程序等待信号:
Creating Connection
Waiting for signals...
当我手动添加USB设备时,我得到这一行: 已添加设备! 但是当我手动移除usb时,我的意思是不能安全地移除它,只是把它插出来,我什么都没得到。
我还用dbus-monitor检查了总线信号,看到DeviceRemoved信号实际上是由org.freedesktop.UDisks发送到系统总线的,所以我认为java方面有一个我没有看到的问题。为什么我没有得到“Device remove!”这一行?代码中有什么问题吗?
非常感谢任何帮助,谢谢!