Skip to content

Instantly share code, notes, and snippets.

@h3po
Last active July 7, 2016 16:07
Show Gist options
  • Save h3po/bae49af49e793353b0779b72bedbdf29 to your computer and use it in GitHub Desktop.
Save h3po/bae49af49e793353b0779b72bedbdf29 to your computer and use it in GitHub Desktop.
I have a Sata Hotplug Bay with a rather loud fan hotwired to the back of it. To keep the noise down, I use a udev rule in combination with this python script to only turn on the fan while there is one or more disks attached to the controller card that services the ports.
#!/usr/bin/python
"""
turn the fan to dc mode and off when the fan controller is initialized
/etc/udev/rules.d/97-hwmon.rules:
ACTION=="add", SUBSYSTEM=="hwmon", DRIVERS=="nct6775", ATTR{pwm5_mode}="0", ATTR{pwm5_enable}="1", ATTR{pwm5}="0"
declare the disk as hotpluggable and run the script
/etc/udev/rules.d/98-sata.rules:
ACTION=="add", SUBSYSTEM=="scsi_host", DRIVERS=="sata_sil24", ENV{UDISKS_SYSTEM_INTERNAL}="0"
ACTION=="add|remove", SUBSYSTEM=="block", KERNEL=="sd?", RUN+="/usr/local/bin/onSataHotplug.py"
"""
import os
#get list of scsi controllers
scsiControllers = os.listdir("/sys/class/scsi_host")
#get controllers with driver sil24
bayControllers = [c for c in scsiControllers \
if open(os.path.join(
"/sys/class/scsi_host", c, "proc_name")
).read() == "sata_sil24\n"]
#get sil24 controllers that have a target scsi_device attached
isBayOccupied = [any(map(lambda x: x.startswith("target"),
os.listdir(os.path.join(
"/sys/bus/scsi/devices", c)))) \
for c in bayControllers]
#get hwmon devices
hwmonDevices = os.listdir("/sys/class/hwmon/")
#filter out the Nuvoton fan controller
fanController = [c for c in hwmonDevices \
if open(os.path.join(
"/sys/class/hwmon/", c, "name")
).read() == "nct6793\n"][0]
#set the pwm to on if there is one or more disk, otherwise off
with open(
os.path.join(
"/sys/class/hwmon", fanController, "pwm5"
), "w") as f:
if any(isBayOccupied):
f.write("100\n")
else:
f.write("0\n")
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment