Raspberry Pi Fan

Hi umerfraz.
How do I add the pwmled as an addon in hassos?

Hi umerfraz.
Can you post the complete entries as I cannot do copy and paste from the post.
Thanks

Hi ropda, I too am trying to do this. I have made the transistor mosfet switch now since you have done it can you share the details with me please?

Hello Karanbir, sorry I did not answer you before, but I have been busy and I have not been able to take a look at the forum in a while.
I have to tell you that I have not managed to regulate the fan speed. I did several tests and failed to get it working.
Sorry I can’t help you, I hope you can get it.
Cheers!

Hi karansoi, sorry for late reply. I will share the code when i can. Problem is i dont use raspberry pi for my main hassio installation anymore but i do have one running with the fan and using rpi gpio component somewhere around the house. Just need to access that rpi when on home network.

Hello ropda.
I have been able to addon the pigpio in my home assistant, and the fans spin with pwm control using pwmled.
I have done it as in this link.
https://community.home-assistant.io/t/how-to-use-the-pwm-led-component-in-hassio/32446/10

hi everyone, I have a script similar to this for managing the cpu fan of my raspberry. I would like to implement the MQTT publishing of the fan speed in the script to be able to keep it under control on lovelace. I installed paho and tried to modify my script but when i start it, the script fails and does not work. Who can help me? Thanks in advance

Can you share the error that you get

Hi umerfraz, thank you for your answer.
I don’t know Phyton so i just try to make some change…
Can you please check if i made some error in the code? The py script is working if i comment the line i have added. I have just added the line where you can see <------ at the end. This is the code:

#!/usr/bin/env python3
import os
import time
import sys  <----------------
sys.path.append('/home/pi/.local/lib/python3.9/site-packages/paho/mqtt') <----------------  
import RPi.GPIO as GPIO
import paho.mqtt.publish as publish <----------------         
import glob

minimum_always_ON=True
minimum_speed=30
target_temp=52

current_speed=0

thermal_zones_temp_dirs=glob.glob("/sys/class/thermal/thermal_zone*/temp")


def getCPUtemperature():
    res = os.popen('vcgencmd measure_temp').readline()
    #vcgencmd measure_temp -> res="temp=NN.N'C\n"
    #temp =(res.replace("temp=","").replace("'C\n",""))
    temp=res[5:9]
    try : 
        temp= float(temp)
    except :
        print("vcgencmd measure_temp failed")
        temp=getCPUTemperature2()
            
    return temp

def getCPUTemperature2():
    temps=[]
    for file_dir in thermal_zones_temp_dirs:
        with open(file_dir, "r") as file:
            try :
                temps.append(float(file.read()))
            except :
                print("Error reading from file {}".format(file_dir))
                continue
    
    if len(temps) == 0:
        print("reading from sys files failed, no CPU temp detected using target_temp")
        temps.append(target_temp * 1000)
    
    return max(temps) / 1000

try:
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(18, GPIO.OUT)
    
    myPWM=GPIO.PWM(18,50)
    myPWM.start(minimum_speed)
    
    current_speed=minimum_speed
    
    while True:
        temp = getCPUtemperature()
        
        if(temp<target_temp and not minimum_always_ON):
            myPWM.ChangeDutyCycle(0)
            current_speed=0
            time.sleep(1)
            continue
        if(temp<target_temp and minimum_always_ON):
            myPWM.ChangeDutyCycle(minimum_speed)
            current_speed=minimum_speed
            time.sleep(1)
            continue
        
        if(temp>target_temp and temp<56):
            myPWM.ChangeDutyCycle(40)
            current_speed=40
            time.sleep(1)
            continue
        if(temp>56 and temp<60):
            myPWM.ChangeDutyCycle(50)
            time.sleep(1)
            continue
        if(temp>60 and temp<65):
            myPWM.ChangeDutyCycle(60)
            current_speed=60
            time.sleep(1)
            continue
        if(temp>65 and temp<70):
            myPWM.ChangeDutyCycle(70)
            current_speed=70
            time.sleep(1)
            continue
        if(temp>70 and temp<74):
            myPWM.ChangeDutyCycle(80)
            current_speed=80
            time.sleep(1)
            continue
        if(temp>74 and temp<76):
            myPWM.ChangeDutyCycle(90)
            current_speed=90
            time.sleep(1)
            continue
        if(temp>76):
           #handleFan(100)
            myPWM.ChangeDutyCycle(100)
            current_speed=100
            time.sleep(1)
            continue
        #try: <----------------
         #   publish.single("RPI/FanSpeed", current_speed, hostname="[X.X.X.X]", auth = {'username':"[MY_mqtt_user]",'password':"[MY_MQTT_PSW]"}) <----------------
        #except: <----------------
            #print("Unexpected error:", sys.exc_info()[0]) <----------------
        #finally: <----------------
        #return() <----------------
   

except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt 
    GPIO.cleanup() # resets all GPIO ports used by this program

/home/pi/.local/lib/python3.9/site-packages/paho/mqtt is the path where i found paho

First error is:


  File "/home/melopero-autostart/scripts/fan_controller.py", line 111
    return()
    ^
SyntaxError: 'return' outside function

If i comment the last part of the script from TRY… to RETURN()
i get another error:

Traceback (most recent call last):
  File "/home/melopero-autostart/scripts/fan_controller.py", line 7, in <module>
    import paho.mqtt.publish as publish
ModuleNotFoundError: No module named 'paho'

It seems that can’t find paho but paho is present:

pip show paho-mqtt
Name: paho-mqtt
Version: 1.5.1
Summary: MQTT version 5.0/3.1.1 client class
Home-page: http://eclipse.org/paho
Author: Roger Light
Author-email: [email protected]
License: Eclipse Public License v1.0 / Eclipse Distribution License v1.0
Location: /home/pi/.local/lib/python3.9/site-packages
Requires:
Required-by:

and i declered path in script in line 5…
Thank for your help

Sorry for slow response. My problem is i dont have an available setup to run python. But i have a feeling the problem is with indentation of your code. In python indentation is very important. are you sure the returun in probalamtic code is indented to right below finally? like


finally:
    return()

lets start by fixing that and any other indentation issues. If i am able to i will run your code to check on my end. The imports were a pain in the neck from what i remember. It took me a long time to figure out and then fix that the path i am running the python file from is what may be used to translate the import path.

thank you for your help. The Return() was wrong. I removed it, anyway i have problem with paho… I have installed it but always sam error ModuleNotFoundError: No module named ‘paho’

I really don’t understand… :frowning:

Sorry but why do you think return is wrong. every function needs to have a return. This function’s return is in finally which is always executed in the try/catch situation hence why return is in finally.

It might be better to use latest version of python but in any case can you try Pip3 instead of pip?
If you can use python3.9 try this:

python3.9 -m pip install paho-mqtt

try looking here for instructions on how to install. https://pypi.org/project/paho-mqtt/

My problem is i cannot install python3 on my work laptop which is what i am mostly using.

Hi umerfranz.
hi already have latest version of python:

:~ $ python --version
Python 2.7.16

:~ $ python3 --version
Python 3.9.0

It’s 2 days i’m on paho-mqtt · PyPI
:slight_smile: anyway thank you very much for your time and your help

once again sorry for not directly helping with your python code. Did you try the alternate approach of using Raspberry PI GPIO directly from Home assistant? this will remove the need for this python code.

details in same post at this anchor Raspberry Pi Fan

Or are you keen to get the python code working? (if i were you i would not give up until i figure this out but then there is a still a limit to how long you want to spend you time and energy on this)

Also try using the find command to see if there are any other variants of Paho on the system. and maybe you are not using the correct one.

Use pip3 to install paho again maybe?

I would like to get this script working. It’s will be a good school for learn.
I think the i understood the problem but i don’t know how to resolve it now.
Script in under a subfolder of \home path. This script is autostarted so i think that it is started from root user and paho i think is installed with pi user. I tried to istall paho with sudo ut it don’t resolve the problem…

This is been the solution!!! :- )Thank you!!!

sudo pip3 install paho-mqtt

Now i have just a little problem…

when i try to read the sensor, the result is unknow

this is what i inserted configuration.yaml

Sensor:
  - platform: mqtt
    name: "Fan RPM"
    state_topic: "RPI/FanSpeed"

and this is what i put inside the script:

import paho.mqtt.publish as publish
.......
......

publish.single("RPI/FanSpeed", current_speed, hostname="[My_ip_hostname]", auth = {'username':"[my_mqtt_user]",'password':"[my_mqtt_password]"})

Glad the import issue is resolved. Did you try running the python script directly and printing out the fanspeed to see if it is acquiring and logging data actually?

if it is then next thing to check is if your MQTT server is up and running. You can use MQTTSpy to monitor if the script is actually logging any readings. Then the last part is to make sure your Hassio is connected to this mqtt server. if you used Hassio addon for MQTT then last thing should not be a problem, the server and connection to it are automatically setup.

I’m using mqtt explorer to monitor mqtt publish and i don’t see this publish.
Mqtt is already configured in HA and it is working. I have other publish that arrive to my mqtt broker. I don’t know how i could print the fanspeed…

print([your variable like fanspeed])

In your code i do not see you establishing the connection first with the MQTT server. try to follow my original code. you have to first connect with the server before calling the publish function. also remember to put proper error etc mesasge logs