How to check the drive power state?

175 Views Asked by At

I'm trying to read the drive power state (active/standby/sleep) using Python under Linux/Raspberry Pi.

I found here this answer and it says that I can do it using udisks2 dbus:

you can get around this by invoking a dbus method on the system bus:

Service: org.freedesktop.UDisks2
Object Path: /org/freedesktop/UDisks2/drives/<ID of the hard drive>
Method: org.freedesktop.UDisks2.Drive.Ata.PmGetState

But I don't know how to implement it...

I managed to write this code that is executed without errors, but I don't know how to continue it... Can you help me ?

from pydbus import SystemBus

def get_drive_power_state(drive_path):
    bus = SystemBus()
    udisks = bus.get(".UDisks2")
    drive_obj = bus.get("org.freedesktop.UDisks2", drive_path)


    return None


drive_path = "/org/freedesktop/UDisks2/drives/WDC_WD20NMVW_11EDZS3_WD_WXV1EA57RT6E"
power_state = get_drive_power_state(drive_path)

print(f"Drive Power State: {power_state}")
2

There are 2 best solutions below

5
VonC On

When calling a method on a DBus object, you would need to specify which DBus interface the method belongs to.
In this case, the PmGetState method belongs to the org.freedesktop.UDisks2.Drive.Ata interface, so that is the interface we specify in the method call.

import dbus

def get_drive_power_state(drive_path):
    bus = dbus.SystemBus()
    proxy = bus.get_object("org.freedesktop.UDisks2", drive_path)
    iface = dbus.Interface(proxy, "org.freedesktop.UDisks2.Drive.Ata")
    
    power_state = iface.PmGetState({})
    
    return power_state

drive_path = "/org/freedesktop/UDisks2/drives/WDC_WD20NMVW_11EDZS3_WD_WXV1EA57RT6E"
power_state = get_drive_power_state(drive_path)

print(f"Drive Power State: {power_state}")
1
deribaucourt On

I'm not sure this is the most elegant way to do this, but if the driver supports it, you can get the power management status through the sysfs. For instance, read the file /sys/class/nvme/nvme0/power/runtime_status.