File Sensor With Dynamic File Path

I have a file sensor to report the current fan speed of my Raspberry Pi POE+ hat:

  - platform: file
    name: Fan Speed Pct
    file_path: /sys/devices/platform/pwm-fan/hwmon/hwmon3/pwm1
    value_template: '{{ (int(value)/255*100) | round(2) }}'
    unit_of_measurement: "%"

This works great, except after a reboot, sometimes the file is instead located at:

/sys/devices/platform/pwm-fan/hwmon/hwmon2/pwm1

Is there a way to setup this sensor to dynamically look at some path to get this file?

For example, from the terminal, I can do this:

ls /sys/devices/platform/pwm-fan/hwmon/*/pwm1

and it will print

/sys/devices/platform/pwm-fan/hwmon/hwmon3/pwm1

or I can simply use

cat /sys/devices/platform/pwm-fan/hwmon/*/pwm1

and it will print

50

but if I setup my file sensor with this syntax

  - platform: file
    name: Fan Speed Pct
    file_path: /sys/devices/platform/pwm-fan/hwmon/*/pwm1
    value_template: '{{ (int(value)/255*100) | round(2) }}'
    unit_of_measurement: "%"

the configuration is invalid

Invalid config for [sensor.file]: not a file for dictionary value @ data['file_path']. Got '/sys/devices/platform/pwm-fan/hwmon/*/pwm1'. (See ?, line ?).

Any ideas? Is this a worthwhile feature request?

Edit: It should be noted that the * in this case works because there is only a single directory within hwmon, and that directory is the one that changes names upon each reboot. If there were multiple directories, this could still be accomplished by instead specifying hwmon*.

In case anyone is interested, this was a simple fix, just use a command_line sensor instead of a file sensor:

  - platform: command_line
    name: Fan Speed Pct
    command: cat /sys/devices/platform/pwm-fan/hwmon/hwmon*/pwm1
    scan_interval: 30
    value_template: '{{ (int(value)/255*100) | round(2) }}'
    unit_of_measurement: "%"
2 Likes