Hi everyone, i am a Home Automation addict. But this topic is about a different problem. I have Hass.io on raspberry pi 3 and that sits in the kitchen because it makes so much fan noise. So i looked at Andreas Spiess’s article to install an intelligent fan which controls its speed based on cpu temperature. it works pretty well. A python script keeps on checking the temperature and controlling fan speed and i have added a bit of my own modification to have both speed and temp sent to MQTT and shown in HA.
however, i am unable to find a way to call the concerned Python script from HA. i want it called when HA restarts which may be dumb as it should be started when raspberry pi starts but HA is all i use the RPI for. and also i failed at auto loading the script on RPI start. happy to post that python script here if someone is interested. Would highly appreciate if someone can give me a clue about what i am doing wrong. i am trying the following shell command
(excuse the silly formatting but this is auto generated from the configuration portal)
a hunch i have is that maybe because the Python script calls PAHO MQTT library and the shell command when executed, cannot find that. and hecne the script is failing, but dont know how to pass in the library/module path.
I guess that depends on perspective, and ones sense of humour :). but no this was not a joke. whats so silly here in your opinion?
Isnt that the reason why we have a CPU temperature component? to monitor the server. i am just trying to do SOMETHING about the temperature if its too high.
I have a similar script that runs on boot as system service, and reports via mqtt cpu temp.
I will add in fan control to turn on and off a fan based on temp being > xº.
strictly speaking you don’t need a fan on a Pi. i think it starts throttling at at about 80 - 85º…you’d do well to reach them temps. I only installed a fan for fun (nerd alert) as a temp project, but plan to make it permanent with proper circuitry etc, not just a breadboard and jumpers.
My RPi 3 is inside the house (average 23°C), closed inside a 30*40cm cabinet with many other heat-generating gadgets (power adapters, ethernet switch, another Pi, IPTV receiver etc.).
I only installed a small aluminum heatsink over the CPU (0,50$ on Aliexpress), completely silent.
Idle temperature around 50°C, gets around 65°C when tinkering with HA, installing plugins, restarting many times in a row.
I have other 3 RPi as media players, none needed a fan even when decoding hours of full-hd video.
Bottom line: check if you really need a fan, it’s easier
You’ll only need a fan it you are doing some serious overclocking… Are you!?
Mine, like @namadori’s is inside a closed telecoms cabinet with another Rpi, a couple of cellphones, two netbooks, Hubs, switches, patch panels, cables, PSUs, etc with no forced ventilation. The CPU temperature never passes 50 degrees and the cabinet temperature 25 degrees…
i guess you are right. should have done more research. my RPI cpu never gets any hotter than 60-65. I actually once touched the bare cpu and it almost burnt my finger so thought it needs cooling down.
Thanks alot for the SystemD article. That probably will solve my problem.
BTW, i use this to get cpu temp
platform: command_line
name: CPU Temperature
command: “cat /sys/class/thermal/thermal_zone0/temp”
yes that’s one method to get the temp. Probably much simpler too.
I use a python program for a couple of reasons.
One being I used it as a learning exercise, and another as I report a few other details via mqtt, I also have the same program on other Pis so I can see their info in HA also.
Here you go. note that this is actually authored by Andreas Spiess (Variable Speed Cooling Fan for Raspberry Pi using PWM (video#138) – SensorsIOT)
i have only added the code to publish fan speed and temperature to my MQTT broker, from where HA is picking it up. i have also trimmed the code down a bit to exclude the stuff he had for battery monitoring etc.
fancontrol.py
#!/usr/bin/env python3
# Author: Andreas Spiess
import os
import time
from time import sleep
import signal
import sys
import RPi.GPIO as GPIO
import paho.mqtt.publish as publish
fanPin = 17 # The pin ID, edit here to change it
batterySensPin = 18
desiredTemp = 40 # The maximum temperature in Celsius after which we trigger the fan
fanSpeed=100
sum=0
pTemp=15
iTemp=0.4
def Shutdown():
fanOFF()
os.system("sudo shutdown -h 1")
sleep(100)
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
temp =(res.replace("temp=","").replace("'C\n",""))
#print("temp is {0}".format(temp)) #Uncomment here for testing
return temp
def fanOFF():
myPWM.ChangeDutyCycle(0) # switch fan off
return()
def handleFan():
global fanSpeed,sum
actualTemp = float(getCPUtemperature())
diff=actualTemp-desiredTemp
sum=sum+diff
pDiff=diff*pTemp
iDiff=sum*iTemp
fanSpeed=pDiff +iDiff
if fanSpeed>100:
fanSpeed=100
if fanSpeed<15:
fanSpeed=0
if sum>100:
sum=100
if sum<-100:
sum=-100
#print("actualTemp %4.2f TempDiff %4.2f pDiff %4.2f iDiff %4.2f fanSpeed %5d" % (actualTemp,diff,pDiff,iDiff,fanSpeed))
myPWM.ChangeDutyCycle(fanSpeed)
msgs = [{'topic':"RPI/Temperature", 'payload':actualTemp},
("RPI/FanSpeed", fanSpeed, 0, False)]
publish.multiple(msgs, hostname="[mqtt server]",
auth = {'username':"[mqtt server username]", 'password':"[mqtt server password]"})
return()
def on_disconnect(client, userdata, rc):
logging.info("disconnecting reason " +str(rc))
client.connected_flag=False
client.disconnect_flag=True
def handleBattery():
#print (GPIO.input(batterySensPin))
if GPIO.input(batterySensPin)==0:
("Shutdown()")
sleep(5)
Shutdown()
return()
def setPin(mode): # A little redundant function but useful if you want to add logging
GPIO.output(fanPin, mode)
return()
try:
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(fanPin, GPIO.OUT)
myPWM=GPIO.PWM(fanPin,50)
myPWM.start(50)
#GPIO.setup(batterySensPin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setwarnings(False)
fanOFF()
while True:
handleFan()
#handleBattery()
sleep(5) # Read the temperature every 5 sec, increase or decrease this limit if you want
except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt
fanOFF()
GPIO.cleanup() # resets all GPIO ports used by this program
except:
print("probably mqtt connection failed")
Scorpion, happy to help but what is your setup? how far are you? have you managed to get the python script running and feeding fan speed via mqtt? or do you need help from scratch?
BTW i switched to a better and easier option if you are using Raspberry Pi: using the HA’s GPIO and Climate components. So basically HA handles when to start or stop the fan based on a low and high limit that you set. Only problem is you dont get to control (or monitor) the speed of fan. see a screenshot below.
Plug the fan onto Raspberry Pi. Power to any of the power (making sure the voltage matches i.e. 3v or 5v) and ground to ground. The control pin, plug it onto pin 17.
Add a switch with gpio platform to your configuration.yaml. This is my code for pin 17.
Add a climate entity to your configuration.yaml. you can read the official documentation for climate control to fine tune these parameters to adjust to your needs
Add the climate and if needed the switch to groups.yaml
sorry just noticed your reply. How are you controlling the speed? from a python script? if so you can publish it at the same time, to an MQTT server. And in HAssio just create an MQTT sensor to subscribe to same topic. let me know if you need details for either side.