Git Product home page Git Product logo

fanshim-python's Introduction

Fan Shim for Raspberry Pi

Build Status Coverage Status PyPi Package Python Versions

Installing

Stable library from PyPi:

  • Just run sudo pip install fanshim

Latest/development library from GitHub:

  • apt install git python3-pip
  • git clone https://github.com/pimoroni/fanshim-python
  • cd fanshim-python
  • sudo ./install.sh

Reference

You should first set up an instance of the FANShim class, eg:

from fanshim import FanShim
fanshim = FanShim()

Fan

Turn the fan on with:

fanshim.set_fan(True)

Turn it off with:

fanshim.set_fan(False)

You can also toggle the fan with:

fanshim.toggle_fan()

You can check the status of the fan with:

fanshim.get_fan() # returns 1 for 'on', 0 for 'off'

LED

Fan Shim includes one RGB APA-102 LED.

Set it to any colour with:

fanshim.set_light(r, g, b)

Arguments r, g and b should be numbers between 0 and 255 that describe the colour you want.

For example, full red:

fanshim.set_light(255, 0, 0)

Button

Fan Shim includes a button, you can bind actions to press, release and hold events.

Do something when the button is pressed:

@fanshim.on_press()
def button_pressed():
    print("The button has been pressed!")

Or when it has been released:

@fanshim.on_release()
def button_released(was_held):
    print("The button has been pressed!")

Or when it's been pressed long enough to trigger a hold:

fanshim.set_hold_time(2.0)

@fanshim.on_hold()
def button_held():
    print("The button was held for 2 seconds")

The function you bind to on_release() is passed a was_held parameter, this lets you know if the button was held down for longer than the configured hold time. If you want to bind an action to "press" and another to "hold" you should check this flag and perform your action in the on_release() handler:

@fanshim.on_release()
def button_released(was_held):
    if was_held:
        print("Long press!")
    else:
        print("Short press!")

To configure the amount of time the button should be held (in seconds), use:

fanshim.set_hold_time(number_of_seconds)

If you need to stop Fan Shim from polling the button, use:

fanshim.stop_polling()

You can start it again with:

fanshim.start_polling()

Alternate Software

fanshim-python's People

Contributors

burtyb avatar colindomoney avatar druck13 avatar ednl avatar gadgetoid avatar haggistech avatar jcoetzee avatar jesterret avatar magnu5 avatar sandyjmacdonald avatar seanhandley avatar svetlemodry avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fanshim-python's Issues

Change of behaviour

Hi,

I have been running the new RPi bootloader for a week or so now.

Linky

The big change is that 3V3 and 5V pins remain powered on following sudo halt, of course the upshot of this is that the fan will continue to run after you have shutdown.

Would be possible to have a trigger in the service that will turn the fan off when the system is shutdown cleanly, or maybe a cron job ?

Me.

Add flag for lite versions

Consider adding flag to setup.py or install.sh warning of dependencies needed for lite versions (setuptools + psutil?)

Install not completed, stuck@ "systemctl restart --no-pager pimoroni-fanshim.service"

Hello, I am trying to install the service by "./install-service.sh --on-threshold 60 --off-threshold 50 --delay 2". Yet the script seems to not go through and the screen is black. I tried with "sudo bash -x ./install-service.sh --on-threshold 60 --off-threshold 50 --delay 2" to debug and this is what happens:

pi@raspberrypi:~/fanshim-python/examples $ sudo bash -x ./install-service.sh --on-threshold 60 --off-threshold 50 --delay 2
+ ON_THRESHOLD=65
+ OFF_THRESHOLD=55
+ HYSTERESIS=5
+ DELAY=2
+ PREEMPT=no
+ POSITIONAL_ARGS=()
+ NOLED=no
+ NOBUTTON=no
+ BRIGHTNESS=255
+ OLD_THRESHOLD=
+ OLD_HYSTERESIS=
+ SERVICE_PATH=/etc/systemd/system/pimoroni-fanshim.service
+ '[' -f /usr/bin/python3 ']'
+ '[' -f /usr/bin/pip3 ']'
+ [[ 6 -gt 0 ]]
+ K=--on-threshold
+ case $K in
+ ON_THRESHOLD=60
+ shift
+ shift
+ [[ 4 -gt 0 ]]
+ K=--off-threshold
+ case $K in
+ OFF_THRESHOLD=50
+ shift
+ shift
+ [[ 2 -gt 0 ]]
+ K=--delay
+ case $K in
+ DELAY=2
+ shift
+ shift
+ [[ 0 -gt 0 ]]
+ set --
+ EXTRA_ARGS=
+ '[' '' == error ']'
+ '[' '' == error ']'
+ '[' no == yes ']'
+ '[' no == yes ']'
+ '[' no == yes ']'
+ '[' '' == '' ']'
+ '[' '' == '' ']'
+ cat
Setting up with:
Off Threshold:  50 C
On Threshold:   60 C
Delay:          2 seconds
Preempt:        no
Disable LED:    no
Disable Button: no
Brightness:     255

To change these options, run:
sudo ./install-service.sh --off-threshold <n> --on-threshold <n> --delay <n> --brightness <n> (--preempt) (--noled) (--nobutton)

Or edit: /etc/systemd/system/pimoroni-fanshim.service


+ read -r -d '' UNIT_FILE
++ pwd
++ pwd
+ printf 'Checking for rpi.gpio>=0.7.0 (for Pi 4 support)\n'
Checking for rpi.gpio>=0.7.0 (for Pi 4 support)
+ python3 -
+ '[' 0 -ne 0 ']'
+ printf 'rpi.gpio >= 0.7.0 already installed\n'
rpi.gpio >= 0.7.0 already installed
+ printf 'Checking for Fan SHIM\n'
Checking for Fan SHIM
+ python3 -
+ '[' 1 -ne 0 ']'
+ printf 'Installing Fan SHIM\n'
Installing Fan SHIM
+ pip3 install fanshim
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Requirement already satisfied: fanshim in /usr/local/lib/python3.7/dist-packages/fanshim-0.0.2-py3.7.egg (0.0.2)
Requirement already satisfied: plasmalights in /usr/local/lib/python3.7/dist-packages/plasmalights-0.0.1-py3.7.egg (from fanshim) (0.0.1)
Requirement already satisfied: RPi.GPIO in /usr/lib/python3/dist-packages (from plasmalights->fanshim) (0.7.0)
+ printf 'Checking for psutil\n'
Checking for psutil
+ python3 -
+ '[' 0 -ne 0 ']'
+ printf 'psutil already installed\n'
psutil already installed
+ printf '\nInstalling service to: /etc/systemd/system/pimoroni-fanshim.service\n'

Installing service to: /etc/systemd/system/pimoroni-fanshim.service
+ echo '[Unit]
Description=Fan Shim Service
After=multi-user.target

[Service]
Type=simple
WorkingDirectory=/home/pi/fanshim-python/examples
ExecStart=/home/pi/fanshim-python/examples/automatic.py --on-threshold 60 --off-threshold 50 --delay 2 --brightness 255
Restart=on-failure

[Install]
WantedBy=multi-user.target'
+ systemctl daemon-reload
+ systemctl enable --no-pager pimoroni-fanshim.service
+ systemctl restart --no-pager pimoroni-fanshim.service


Please notice I tried the "sudo usermod -a -G gpio pi", but nothing happens.
Can you please point me in the right direction?

LED always on after restart with --noled

I have the automatic example running as a service that automatically starts with my Pi. Since I don't want the LED to light up, I passed the --noled option to deactivate it.

Now after every reboot the LED is burning bright white which is quite annoying. Restarting the service fixes the problem temporarily, but it always turns on again after the next reboot.

Problem with psutil - Doesn't detect SoC temperature sensor if another temperature sensor exists.

This is actually a problem with psutil and not your code but it does cause problems with the Fan SHIM. automatic.py won't work in some specific configurations.

The way psutil works for temperature sensors is that it'll check for /sys/class/hwmon/hwmon*/temp*_* and /sys/class/hwmon/hwmon*/device/temp*_. If no temperature sensor is found only then will it look for /sys/class/thermal/thermal_zone. On a RPi, the SoC temperature sensor is on that second code path for /sys/class/thermal/thermal_zone*.

The problem I've got is that I fitted a Fan SHIM to a RPi which has a DS3231 RTC attached to it which has an internal temperature sensor. The Linux driver exposes that temperature sensor in /sys/class/hwmon and causes psutil to never check /sys/class/thermal/thermal_zone* for the RPi SoC temperature sensor. automatic.py continually prints out "Warning: Unable to get CPU temperature!" because it can't find a cpu_thermal.

My workaround was to bypass psutil for reading the SoC temperature and directly read /sys/class/thermal/thermal_zone0/temp in get_cpu_temp()

def get_cpu_temp():
    with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
        return int(f.readline()) / 1000

No control on Fan/LED

I followed the assembly instructions and installed the service. However vcgencmd measure_temp gives value 46C and pimoroni-fanshim.service is set at 50C on threshold (with no LED).

Yet fan and LED still on. Where have I gone wrong? Thanks

pip3 location

The script expects pip3 to be in /usr/bin but on my Raspbian 10 Pi's it's in /usr/local/bin

Not an issue, more a feature request

Hi, I'm new to RPi and loving it, recently installed the shim to help with temps but was wondering if it would be possible to invert the LED colours, so that it's green when "cool" and red when the fan is active i.e too hot.

Steep learning curve with this gizmo and I'm slowly getting to grips with it :)

Ta.

Request: HASSIO add-on for Fan-SHIM

As you know, Raspberry Pi is commonly used for home automation; Home Assistant is one of the mostly adopted ecosystems of this kind on Raspberry.
When installed on Raspbian, Fan SHIM could be implemented with no headache; btw when you use HASSIO distribution instead, there's no Pimoroni custom component or add-on for that. An implementation like this will be greatly appreciated by thousands of HASSIO users that what to us Fan-SHIM on their Raspberry Pi with HASSIO distribution on it.

Fan doesn't stop at all!

Hi, there, I have bad luck with my FanShim cause it doesn't stop though the off-threshold and keeps spinning all the time. Have you any ideas how I can solve this issue?
Note: I am new to programming in Python!

What is cpu-thermal?

I can't figure out what cpu-thermal is, can someone explain it? I assumed it was a raspbian binary/command, but when I did an install on one, it didn't install anything that provided that command.

https://github.com/pimoroni/fanshim-python/blob/master/examples/automatic.py#L38

0 ✓ fryfrog@arch-aarch64 ~ $ sudo fanshim
Traceback (most recent call last):
  File "/usr/bin/fanshim", line 70, in <module>
    t = get_cpu_temp()
  File "/usr/bin/fanshim", line 38, in get_cpu_temp
    return psutil.sensors_temperatures()['cpu-thermal'][0].current
KeyError: 'cpu-thermal'

LED purple and does not shutdown

Running Famshim since yesterday on a R4 with Raspbian buster. The LED ist now constantly purple. EVen with a service shutdown the led remains on. Any suggestion?

get_fan() returns 0, fan is on.

I'm not a python (or really any code) kind of person at all, but I made this script to check simply if the fan is on:

#!/usr/bin/env python3
from fanshim import FanShim
fanshim = FanShim()

status = 3

status = fanshim.get_fan()

print('status is: {}'.format(status))

if status == 1:
        print("The fan is on.")
else:
        print("The fan is off.")

It says "The fan is off" every time I run it, but the fan is on and has been on since I installed it yesterday.
I've installed the daemon, which is running, and tried using automatic.py too.

When running this directly, it doesn't turn off, either.

#!/usr/bin/env python3
from fanshim import FanShim
fanshim = FanShim()

fanshim.set_fan(False)

print("The fan is off, now.")

Have I done something wrong, or is this a different issue, maybe?

AttributeError: module 'psutil' has no attribute 'sensors_temperatures'

This raspbian install was done following the guide at https://learn.pimoroni.com/tutorial/sandyj/getting-started-with-fan-shim, basically just sudo ./install.sh and sudo ./examples/install-service.sh 65 5.

giampaolo/psutil#1271

Maybe an old version of python-psutil?

0 ✓ fryfrog@raspbian-armv7l ~ $ sudo /home/fryfrog/fanshim-python/examples/automatic.py --threshold 55 --hysteresis 5 --delay 2
Traceback (most recent call last):
  File "/home/fryfrog/fanshim-python/examples/automatic.py", line 70, in <module>
    t = get_cpu_temp()
  File "/home/fryfrog/fanshim-python/examples/automatic.py", line 38, in get_cpu_temp
    return psutil.sensors_temperatures()['cpu-thermal'][0].current
AttributeError: module 'psutil' has no attribute 'sensors_temperatures'

Python interpreter start-up spikes CPU load triggering preempt

When automatic.py first loads, the python start-up causes a CPU spike large enough to trigger the fan preempt mode. This causes the fan to spin for a few ms at start up - and if there is no other software running it will most likely never trigger again due to the 65 degree default threshold. This can lead to users thinking there is a problem if the CPU is hot enough for the fan to spin once, but then it never spins again.

I recommend suppressing preempt for a few seconds when starting up the daemon.

Check status?

Hi there,

I tend to connect to my pi via ssh remotely. Is there an API to check the status of the fan i.e. on/off?

noob-question about "Getting Started with Fan SHIM"

I'm running a raspiblitz v1.2 on a 3B + board and trying to run a "fan shim" on it.

I have followed the following description several times:
https://learn.pimoroni.com/tutorial/sandyj/getting-started-with-fan-shim.


my proceeding:

  • call console / terminal via putty,
  • git clone https://github.com/pimoroni/fanshim-python
    cd fanshim-python
  • (return)
  • sudo ./install.sh
  • (return)
  • (reboot)
  • call console / terminal via putty,
  • cd examples
  • (return)
  • cd fanshim-python
  • (return)
  • sudo ./install-service.sh 65 5
  • (return)
  • (reboot)

Obviously, no errors are recognizable during the installation


However, the "fan shim" always runs only in continuous operation and can not be controlled via the small pressure button.
The command:
cd examples
sudo ./install-service.sh 65 5
also remains after the installation without effect.

Please, what am I doing wrong?

Thanks

Using this controller with different hardware

Hey! I happen to already have a with a black and red wire which connect to ground and 3.3/5v.

Does the fan shim hardware have any special electronics that allow this script to control it?
Or are there other pins I can use to achieve the same effect with the fan I have.

Thanks

Fanshim service issue Raspbian 9.11

I went through a problem similar to #58, albeit on a Raspberry Pi 3 with Raspbian 9.11.

When I run python3 automatic.py, the fan runs fine.

But it doesn't work when installed as a service.

$ sudo ./install-service.sh --on-threshold 65 --off-threshold 55 --delay 2
Setting up with:
Off Threshold:  55 C
On Threshold:   65 C
Delay:          2 seconds
Preempt:        no
Disable LED:    no
Disable Button: no
Brightness:     255

To change these options, run:
sudo ./install-service.sh --off-threshold <n> --on-threshold <n> --delay <n> --brightness <n> (--preempt) (--noled) (--nobutton)

Or edit: /etc/systemd/system/pimoroni-fanshim.service

Checking for rpi.gpio>=0.7.0 (for Pi 4 support)
rpi.gpio >= 0.7.0 already installed
Checking for Fan SHIM
Fan SHIM already installed
Checking for psutil
psutil already installed

Installing service to: /etc/systemd/system/pimoroni-fanshim.service
● pimoroni-fanshim.service - Fan Shim Service
   Loaded: loaded (/etc/systemd/system/pimoroni-fanshim.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2019-12-09 18:46:34 CET; 409ms ago
 Main PID: 6041 (python3)
    Tasks: 1 (limit: 4915)
   CGroup: /system.slice/pimoroni-fanshim.service
           └─6041 python3 /home/pi/fanshim-python/examples/automatic.py --on-threshold 65 --off-threshold 55 --delay 2…55

Dec 09 18:46:34 myPiTwo.local systemd[1]: Started Fan Shim Service.

Checking with systemctl

$ systemctl | grep pimoroni
● pimoroni-fanshim.service   loaded failed failed    Fan Shim Service        

I went through different solutions, but the pimoroni-fanshim.service is still not working.

Thank you for your help!

Already checked: psutil —from #33

  • Installed psutil didn't provide sensors_temperatures()

Check with Python 3

import psutil
psutil.sensors_temperatures()

In case of an error, install and upgrade psutil to the latest version

$ pip3 install --upgrade psutil

And check again with Python

import psutil
psutil.__version__
'5.6.7'
psutil.sensors_temperatures()
{'cpu-thermal': [shwtemp(label='', current=55.148, high=None, critical=None)]}

Already checked: GPIO —from #39

Run on Python 3

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, 0) # Should turn fan off
GPIO.output(18, 1) # Should turn fan on

GPIO works fine.

module 'psutil' has no attribute 'sensors_temperatures'

... sorry, but I'm still trying to get the Pimoni FanShim running on my RB3+ board with Rootzol's Raspiblitz V1.2.

In the last few days I have unsuccessfully tried different suggestions from the internet.
Today I have completely reinstalled the FanShim with the improved Pimoni GitHub files.

However, I always get the following error messages:


admin@PotzBlitz00:~/fanshim-python/examples $ sudo systemctl status pimoroni-fanshim.service
â pimoroni-fanshim.service - Fan Shim Service
Loaded: loaded (/etc/systemd/system/pimoroni-fanshim.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Fri 2019-08-02 22:56:41 BST; 46min ago
Process: 30688 ExecStart=/home/admin/fanshim-python/examples/automatic.py --on-threshold 57 --off-threshold 47 --delay 2 --brightness 255 --preempt (code=
Main PID: 30688 (code=exited, status=2)
Aug 02 22:56:41 PotzBlitz00 systemd[1]: pimoroni-fanshim.service: Failed with result 'exit-code'.
Aug 02 22:56:41 PotzBlitz00 systemd[1]: pimoroni-fanshim.service: Service hold-off time over, scheduling restart.
Aug 02 22:56:41 PotzBlitz00 systemd[1]: Stopped Fan Shim Service.
Aug 02 22:56:41 PotzBlitz00 systemd[1]: pimoroni-fanshim.service: Start request repeated too quickly.
Aug 02 22:56:41 PotzBlitz00 systemd[1]: Failed to start Fan Shim Service.
Aug 02 22:56:41 PotzBlitz00 systemd[1]: pimoroni-fanshim.service: Unit entered failed state.
Aug 02 22:56:41 PotzBlitz00 systemd[1]: pimoroni-fanshim.service: Failed with result 'exit-code'.


admin@PotzBlitz00:~/fanshim-python/examples $ sudo python3 automatic.py
Traceback (most recent call last):
File "automatic.py", line 65, in
t = get_cpu_temp()
File "automatic.py", line 24, in get_cpu_temp
return psutil.sensors_temperatures()['cpu-thermal'][0].current
AttributeError: module 'psutil' has no attribute 'sensors_temperatures'


... I am a bit frustrated at the moment ...

Looking for help with a slightly customized version of automatic.py

I am working on a simple neopixel strip (8 pixels) that acts as a temperature gauge for the CPU, lighting up more of the pixels as the temp increases. I got a python script working, but one requirement of the circuitpython-neopixel library i am using requires that the script is run as root.

So I have 2 questions:

  • Is there a way to see any error messages that may be triggered by the automatic.py script when it runs (as directed by the service)?
  • Is there a way to force the automatic.py script to run as root with the -E switch? (ie run it like sudo -E filename.py)? I need the -E switch so the environment variables for the pi user carry over to running it as root.

Or is there something different that I could do to make this work?
Here is my modified code :
`
#!/usr/bin/env python3
from fanshim import FanShim
from threading import Lock
import colorsys
import psutil
import argparse
import time
import signal
import sys
import board
import neopixel
min_val = 55
max_val = 65

parser = argparse.ArgumentParser()
parser.add_argument('--threshold', type=float, default=-1, help='Temperature threshold in degrees C to enable fan')
parser.add_argument('--hysteresis', type=float, default=-1, help='Distance from threshold before fan is disabled')

parser.add_argument('--off-threshold', type=float, default=55.0, help='Temperature threshold in degrees C to enable fan')
parser.add_argument('--on-threshold', type=float, default=65.0, help='Temperature threshold in degrees C to disable fan')
parser.add_argument('--delay', type=float, default=2.0, help='Delay, in seconds, between temperature readings')
parser.add_argument('--preempt', action='store_true', default=False, help='Monitor CPU frequency and activate cooling premptively')
parser.add_argument('--verbose', action='store_true', default=False, help='Output temp and fan status messages')
parser.add_argument('--nobutton', action='store_true', default=False, help='Disable button input')
parser.add_argument('--noled', action='store_true', default=False, help='Disable LED control')
parser.add_argument('--brightness', type=float, default=255.0, help='LED brightness, from 0 to 255')

args = parser.parse_args()

Choose an open pin connected to the Data In of the NeoPixel strip, i.e. board.D18

NeoPixels must be connected to D10, D12, D18 or D21 to work.

pixel_pin = board.D21

The number of NeoPixels

num_pixels = 8

The order of the pixel colors - RGB or GRB. Some NeoPixels have red and green reversed!

For RGBW NeoPixels, simply change the ORDER to RGBW or GRBW.

ORDER = neopixel.GRBW

pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.25, auto_write=False,
pixel_order=ORDER)

def clean_exit(signum, frame):
set_fan(False)
if not args.noled:
fanshim.set_light(0, 0, 0)
sys.exit(0)

def update_led_temperature(temp):
led_busy.acquire()
temp = float(temp)
temp -= args.off_threshold
temp /= float(args.on_threshold - args.off_threshold)
temp = max(0, min(1, temp))
temp = 1.0 - temp
temp *= 120.0
temp /= 360.0
r, g, b = [int(c * 255.0) for c in colorsys.hsv_to_rgb(temp, 1.0, args.brightness / 255.0)]
fanshim.set_light(r, g, b)
led_busy.release()

def update_neo_temp(temp2):
pixels.fill((0,0,0,0))
pixels.show
temp2 = float(temp2)
print(temp2)
temp2 -= min_val
print(temp2)
temp2 /= float(max_val-min_val)
print(temp2)
temp2 = max(0, min(1,temp2))
print(temp2)
#temp2 = 1.0 - temp2
print(temp2)
color = [((0, 0, 255, 0)),
((0, 128, 255, 0)),
((0, 255, 255, 0)),
((0, 255, 128, 0)),
((128, 255, 0, 0)),
((128, 128, 0, 0)),
((255, 128, 0, 0)),
((255, 0, 0, 0))]

t_test = temp2*8
print(t_test)
t_test = int(t_test)
print(t_test)
for i in range(t_test):
    pixels[i] = color[i]
pixels.show()

def get_cpu_temp():
t = psutil.sensors_temperatures()
for x in ['cpu-thermal', 'cpu_thermal']:
if x in t:
return t[x][0].current
print("Warning: Unable to get CPU temperature!")
return 0

def get_cpu_freq():
freq = psutil.cpu_freq()
return freq

def set_fan(status):
global enabled
changed = False
if status != enabled:
changed = True
fanshim.set_fan(status)
enabled = status
return changed

def set_automatic(status):
global armed, last_change
armed = status
last_change = 0

if args.threshold > -1 or args.hysteresis > -1:
print("""
The --threshold and --hysteresis parameters have been deprecated.
Use --on-threshold and --off-threshold instead!
""")
sys.exit(1)

fanshim = FanShim()
fanshim.set_hold_time(1.0)
fanshim.set_fan(False)
armed = True
enabled = False
led_busy = Lock()
enable = False
is_fast = False
last_change = 0
signal.signal(signal.SIGTERM, clean_exit)

if args.noled:
led_busy.acquire()
fanshim.set_light(0, 0, 0)
led_busy.release()

t = get_cpu_temp()
if t >= args.threshold:
last_change = get_cpu_temp()
set_fan(True)

if not args.nobutton:
@fanshim.on_release()
def release_handler(was_held):
global armed
if was_held:
set_automatic(not armed)
elif not armed:
set_fan(not enabled)

@fanshim.on_hold()
def held_handler():
    global led_busy
    if args.noled:
        return
    led_busy.acquire()
    for _ in range(3):
        fanshim.set_light(0, 0, 255)
        time.sleep(0.04)
        fanshim.set_light(0, 0, 0)
        time.sleep(0.04)
    led_busy.release()

try:
while True:
t = get_cpu_temp()
f = get_cpu_freq()
was_fast = is_fast
is_fast = (int(f.current) == int(f.max))
if args.verbose:
print("Current: {:05.02f} Target: {:05.02f} Freq {: 5.02f} Automatic: {} On: {}".format(t, args.off_threshold, f.current / 1000.0, armed, enabled))

    if args.preempt and is_fast and was_fast:
        enable = True
    elif armed:
        if t >= args.on_threshold:
            enable = True
        elif t <= args.off_threshold:
            enable = False

    if set_fan(enable):
        last_change = t

    if not args.noled:
        update_led_temperature(t)
        update_neo_temp(t)
    time.sleep(args.delay)

except KeyboardInterrupt:
pass

`

Fan Light won't turn on.

Hi I am using a Pi 4 and I have installed the ./install.sh and then ran sudo ./install-service.sh --on-threshold 65 --off-threshold 55 --delay 2. This was worked correctly and the fan turns on and off at the thresholds however the light on the fan will not turn on. Anyone know why or how to solve this? I have installed it from the GitHub repo and not the stable package.

Review Arch Linux AUR package for fanshim?

Hi,

I don't have a fanshim yet, but I've ordered a handful to go w/ the handful of Pi 4s I've ordered. I use and <3 Arch Linux, so I went ahead and created a fanshim package... which required a python-fanshim package which required a python-plasmalights package.

It'd be great if you could give it a look to confirm correctness. The python automatic.py script (renamed to fanshim) seems to work, but of course I can't test it yet.

https://aur.archlinux.org/packages/fanshim

https://aur.archlinux.org/packages/python-fanshim

https://aur.archlinux.org/packages/python-plasmalights

Also, it seems like the library name plasma in the plasmalights package is likely to conflict with other things. For example, in searching for just "plasma", I thought it was using some machine learning library.

65 degrees is probably too hot for the on threshold

If someone takes a fresh Pi 4 and installs a fan shim and nothing else, it is possible it will never spin at all. Any older revision of the Pi definitely won't reach 65 degrees unless it is put under extreme load. As mentioned on #19, this can lead to users thinking there is a problem, when in fact the system just isn't hot enough for the fan to spin. I would therefore consider lowering the on threshold to reduce support requests. :)

Executable path is not absolute

git clone https://github.com/pimoroni/fanshim-python
cd fanshim-python
sudo ./install.sh

cd examples
sudo ./install-service.sh --on-threshold 50 --off-threshold 40 --delay 2

this is the error when i try to start the service

Feb 15 20:03:41 DietPi systemd[1]: [/etc/systemd/system/pimoroni-fanshim.service:8] Executable path is not absolute, ignoring: python3 /root/fanshim-python/exam
ples/automatic.py --on-threshold 50 --off-threshold 40 --delay 2 --brightness 255
Feb 15 20:03:41 DietPi systemd[1]: pimoroni-fanshim.service: Service lacks both ExecStart= and ExecStop= setting. Refusing.
Feb 15 20:03:41 DietPi systemd[1]: [/etc/systemd/system/pimoroni-fanshim.service:8] Executable path is not absolute, ignoring: python3 /root/fanshim-python/exam
ples/automatic.py --on-threshold 50 --off-threshold 40 --delay 2 --brightness 255
Feb 15 20:03:41 DietPi systemd[1]: pimoroni-fanshim.service: Service lacks both ExecStart= and ExecStop= setting. Refusing.
Feb 15 20:03:51 DietPi systemd[1]: [/etc/systemd/system/pimoroni-fanshim.service:8] Executable path is not absolute, ignoring: python3 /root/fanshim-python/exam
ples/automatic.py --on-threshold 50 --off-threshold 40 --delay 2 --brightness 255
Feb 15 20:03:51 DietPi systemd[1]: pimoroni-fanshim.service: Service lacks both ExecStart= and ExecStop= setting. Refusing.
Feb 15 20:03:52 DietPi systemd[1]: [/etc/systemd/system/pimoroni-fanshim.service:8] Executable path is not absolute, ignoring: python3 /root/fanshim-python/exam
ples/automatic.py --on-threshold 50 --off-threshold 40 --delay 2 --brightness 255
Feb 15 20:03:52 DietPi systemd[1]: pimoroni-fanshim.service: Service lacks both ExecStart= and ExecStop= setting. Refusing.

Missing short form arguments

The short form arguments are missing for the very tedious to type --on-threshold and --off-threshold, and also --brightness.

Unable to use service with raspbian lite

I am not sure if the library is working at all because the fan never stops but the service is definitively not working. It is hanging when you start it from command line and when you check the status after a reboot this is what I get:

   Loaded: loaded (/etc/systemd/system/pimoroni-fanshim.service; enabled; vendor preset: enabled)
   Active: inactive (dead)

I noticed that the installer installs both python2 and 3. I do not know why it need 2 versions of python to work.

Any guidance is more than welcome.

A few more information.

I just reinstalled a brand new raspbian lite, git cloned the repo and executed the install.

kyos@raspi4:~/fanshim-python/examples $ sudo ./install-service.sh --on-threshold 65 --off-threshold 50 --delay 5
[sudo] password for kyos: 
Setting up with:
Off Threshold: 50 C
On Threshold: 65 C
Delay: 5 seconds
Preempt: no
No LED: no
No Button: no

To change these options, run:
sudo ./install-service.sh --off-threshold <n> --on-threshold <n> --delay <n> (--preempt) (--noled) (--nobutton)

Or edit: /etc/systemd/system/pimoroni-fanshim.service


Checking for rpi.gpio>=0.7.0a2 (for Pi 4 support)
rpi.gpio >= 0.7.0a2 already installed
Checking for psutil
psutil already installed

Installing service to: /etc/systemd/system/pimoroni-fanshim.service
Created symlink /etc/systemd/system/multi-user.target.wants/pimoroni-fanshim.service → /etc/systemd/system/pimoroni-fanshim.service.

And here the code stops. No exit no nothing.
The led doesn't turn on.

I checked the status of the service.

kyos@raspi4:~/fanshim-python/examples $ sudo systemctl status pimoroni-fanshim.service
[sudo] password for kyos: 
● pimoroni-fanshim.service - Fan Shim Service
   Loaded: loaded (/etc/systemd/system/pimoroni-fanshim.service; enabled; vendor preset: enabled)
   Active: inactive (dead)
kyos@raspi4:~/fanshim-python/examples $ sudo systemctl start pimoroni-fanshim.service

Fan state only persists during FanShim object lifetime

I've set up a quick cron job to check the CPU temp and update the fan/LED state accordingly - but once the script exists, the fan switches back on again (regardless of what state was set by the script). I can force the LED state to persist using plasma.set_clear_on_exit(False), is there an equivalent for the fan?

My full script is below - the fan state will persist for as long as the sleep() at the end .

from subprocess import PIPE, Popen
from time import sleep

import plasma

def get_cpu_temperature():
    """get cpu temperature using vcgencmd"""
    process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
    output, _error = process.communicate()
    output = output.decode()
    val = output[output.index('=') + 1:output.rindex("'")]
    return float(val)


temp = get_cpu_temperature()

print('Temp is', temp)


from fanshim import FanShim
fanshim = FanShim()

plasma.set_clear_on_exit(False)

if temp > 60:
        print('Enabling fan')
        fanshim.set_fan(1)
        print(fanshim.get_fan())
else:
        print('Disabling fan')
        fanshim.set_fan(0)
        print(fanshim.get_fan())

light = 255 * max(0, min(1, (temp-40)/50))

fanshim.set_light(light, 0, 255-light)
sleep(30)

Looking for help to changing the LED Color from Green to Blue

I am using the command sudo ./install-service.sh --on-threshold 65 --off-threshold 55 --delay 2
which works however I do want to change the LED to turn from blue to red instead to better reflect from cool to hot. Anyone have any ideas how do I do that easily?

code review/help: c++ code for fanshim

Following up on #19, I made a quick C++ code for the fanshim (no button yet). Anyone interested in review the code for bugs, etc? Note that it's very experimental/rough around the edges, it may make the fan run all the time, or using excessive cpu/memory/disk, which may or may not cause hardware damage, so the code is only for testing/playing now, and I wouldn't run it unattended and I do not think it's ready for serious use for now. Thanks a lot!

github repo: https://github.com/daviehh/fanshim-cpp

Daemon settings should be in a config file, not hard coded into the unit

Currently the setup script generates a unit file with the settings (on/off temperature etc) hardcoded into the command line. This has a few problems:

  • The settings are difficult to find.
  • It is necessary to run an obscure systemd command if you edit the unit file.
  • It makes maintenance harder if you want to upgrade that script and people have edited it.

The solution is to put the settings into an external configuration file. This could be coded in to the python script but the easier way is to just use a systemd environment file. If you want I'll send a pull request for the latter in the next few days.

Support PWM to control speed?

I was looking at the RPi.GPIO package and I noticed that it supports software-based PWM. I was wondering if that would be an idea to add support for that to get more control over fan output than just off and on? Would that be applicable in this case? Not sure what the overhead would be. I don't have a Fan SHIM to play with (not available in my country yet) but could look at bashing around with the idea when I do get one. Unless something else makes it a non-starter.

Create tag for v0.0.2

Hey, could you guys create a tag for v0.0.2 so that I can pin the fanshim script against a specific version?

Falcon PiCap

My PiCap uses GPIO 18/19 to operate. I have a conflict with fanshim on GPIO 18 (pin 12). Is there a workaround? I am happy having the fanshim run constantly or manually controlled.

"ImportError: cannot import name FanShim" on Buster

I am getting the following error on Raspbian 10 Buster:

Traceback (most recent call last):
  File "fanshim.py", line 1, in <module>
    from fanshim import FanShim
  File "/home/pi/fanshim.py", line 1, in <module>
    from fanshim import FanShim
ImportError: cannot import name FanShim

The code is:

from fanshim import FanShim
fanshim = FanShim()
fanshim.toggle_fan()

Run via:

python fanshim.py

The install happened without errors??

Need help

I'm new to all this like new new know nothing of anything and everything I've done is from reading on the internet. Anyways I've downloaded everything I need for the fanshim it works and now I'm in Python and I've figured out how to type these commands in to get everything working the way I want and my problem lies that I have no idea how to save these commands cause as soon as I close Python it goes back to stock setting. What do I need to do to get these things implemented on my rasberry pi 4?

Changing LED colour does not work

When I try to change the LED colour on the shim for my Pi 4 nothing happens.

Is this also related to the similar issue with the shim button due to RPi.GPIO?

Automatic.py stops working after few cycles

Hey there, I am using the automatic.py script from the examples.

In the first few cycles everything works as expected. However, for some reason it stops working later.

The fan won´t turn on at the treshold and the LED stays red. I checked the service and it says it is running.

After I reboot the pi, everything is back to normal untill it again stops triggering the fan after some cycles.

I am running Raspbian Buster on a RPi 4.

Any suggestions on what I could do? Thanks in advance. Regards

Help for piromoni fanshim software or hardware problem?

Hi to everyone,i'm new of github,and I'm not very competent with linux.
I have installed the piromoni fanshim on my new raspberry pi 4 with raspbian,I have followed the guide in the piromoni website,I have installed the software and putted on the script(I have pasted in the terminal the instructions of the website).the problem is that seems the fan is always on with the green led light,even when i shutdown the system(when i click the power button in the charger the fan continues to go on).I paste what the terminal says about the script

pi@raspberrypi:~ $ cd fanshim-python
pi@raspberrypi:~/fanshim-python $ sudo ./install.sh
Checking for python-configparser
fanshim 0.0.3 Python Library: Installer

Installing for Python 2..
Checking for rpi.gpio>=0.7.0 (for Pi 4 support)
rpi.gpio >= 0.7.0 already installed
Checking for python-setuptools
Checking for python-dev
Checking for python-psutil
running install
running bdist_egg
running egg_info
writing requirements to fanshim.egg-info/requires.txt
writing fanshim.egg-info/PKG-INFO
writing top-level names to fanshim.egg-info/top_level.txt
writing dependency_links to fanshim.egg-info/dependency_links.txt
reading manifest file 'fanshim.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'fanshim.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-armv7l/egg
running install_lib
running build_py
creating build/bdist.linux-armv7l/egg
creating build/bdist.linux-armv7l/egg/fanshim
copying build/lib.linux-armv7l-2.7/fanshim/init.py -> build/bdist.linux-armv7l/egg/fanshim
byte-compiling build/bdist.linux-armv7l/egg/fanshim/init.py to init.pyc
creating build/bdist.linux-armv7l/egg/EGG-INFO
copying fanshim.egg-info/PKG-INFO -> build/bdist.linux-armv7l/egg/EGG-INFO
copying fanshim.egg-info/SOURCES.txt -> build/bdist.linux-armv7l/egg/EGG-INFO
copying fanshim.egg-info/dependency_links.txt -> build/bdist.linux-armv7l/egg/EGG-INFO
copying fanshim.egg-info/requires.txt -> build/bdist.linux-armv7l/egg/EGG-INFO
copying fanshim.egg-info/top_level.txt -> build/bdist.linux-armv7l/egg/EGG-INFO
zip_safe flag not set; analyzing archive contents...
creating 'dist/fanshim-0.0.3-py2.7.egg' and adding 'build/bdist.linux-armv7l/egg' to it
removing 'build/bdist.linux-armv7l/egg' (and everything under it)
Processing fanshim-0.0.3-py2.7.egg
Removing /usr/local/lib/python2.7/dist-packages/fanshim-0.0.3-py2.7.egg
Copying fanshim-0.0.3-py2.7.egg to /usr/local/lib/python2.7/dist-packages
fanshim 0.0.3 is already the active version in easy-install.pth

Installed /usr/local/lib/python2.7/dist-packages/fanshim-0.0.3-py2.7.egg
Processing dependencies for fanshim==0.0.3
Searching for plasmalights==0.0.1
Best match: plasmalights 0.0.1
Processing plasmalights-0.0.1-py2.7.egg
plasmalights 0.0.1 is already the active version in easy-install.pth

Using /usr/local/lib/python2.7/dist-packages/plasmalights-0.0.1-py2.7.egg
Searching for RPi.GPIO==0.7.0
Best match: RPi.GPIO 0.7.0
Adding RPi.GPIO 0.7.0 to easy-install.pth file

Using /usr/lib/python2.7/dist-packages
Finished processing dependencies for fanshim==0.0.3
Installing for Python 3..
Checking for rpi.gpio>=0.7.0 (for Pi 4 support)
rpi.gpio >= 0.7.0 already installed
Checking for python3-setuptools
Checking for python3-dev
Checking for python3-psutil
running install
running bdist_egg
running egg_info
writing fanshim.egg-info/PKG-INFO
writing dependency_links to fanshim.egg-info/dependency_links.txt
writing requirements to fanshim.egg-info/requires.txt
writing top-level names to fanshim.egg-info/top_level.txt
reading manifest file 'fanshim.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'fanshim.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-armv7l/egg
running install_lib
running build_py
creating build/bdist.linux-armv7l/egg
creating build/bdist.linux-armv7l/egg/fanshim
copying build/lib/fanshim/init.py -> build/bdist.linux-armv7l/egg/fanshim
byte-compiling build/bdist.linux-armv7l/egg/fanshim/init.py to init.cpython-37.pyc
creating build/bdist.linux-armv7l/egg/EGG-INFO
copying fanshim.egg-info/PKG-INFO -> build/bdist.linux-armv7l/egg/EGG-INFO
copying fanshim.egg-info/SOURCES.txt -> build/bdist.linux-armv7l/egg/EGG-INFO
copying fanshim.egg-info/dependency_links.txt -> build/bdist.linux-armv7l/egg/EGG-INFO
copying fanshim.egg-info/requires.txt -> build/bdist.linux-armv7l/egg/EGG-INFO
copying fanshim.egg-info/top_level.txt -> build/bdist.linux-armv7l/egg/EGG-INFO
zip_safe flag not set; analyzing archive contents...
creating 'dist/fanshim-0.0.3-py3.7.egg' and adding 'build/bdist.linux-armv7l/egg' to it
removing 'build/bdist.linux-armv7l/egg' (and everything under it)
Processing fanshim-0.0.3-py3.7.egg
Removing /usr/local/lib/python3.7/dist-packages/fanshim-0.0.3-py3.7.egg
Copying fanshim-0.0.3-py3.7.egg to /usr/local/lib/python3.7/dist-packages
fanshim 0.0.3 is already the active version in easy-install.pth

Installed /usr/local/lib/python3.7/dist-packages/fanshim-0.0.3-py3.7.egg
Processing dependencies for fanshim==0.0.3
Searching for plasmalights==0.0.1
Best match: plasmalights 0.0.1
Processing plasmalights-0.0.1-py3.7.egg
plasmalights 0.0.1 is already the active version in easy-install.pth

Using /usr/local/lib/python3.7/dist-packages/plasmalights-0.0.1-py3.7.egg
Searching for RPi.GPIO==0.7.0
Best match: RPi.GPIO 0.7.0
Adding RPi.GPIO 0.7.0 to easy-install.pth file

Using /usr/lib/python3/dist-packages
Finished processing dependencies for fanshim==0.0.3
Enjoy your Fan SHIM!
Done!
pi@raspberrypi:/fanshim-python $ cd examples
pi@raspberrypi:
/fanshim-python/examples $ sudo ./install-service.sh --on-threshold 65 --off-threshold 55 --delay 2
Setting up with:
Off Threshold: 55 C
On Threshold: 65 C
Delay: 2 seconds
Preempt: no
Disable LED: no
Disable Button: no
Brightness: 255

To change these options, run:
sudo ./install-service.sh --off-threshold --on-threshold --delay --brightness (--preempt) (--noled) (--nobutton)

Or edit: /etc/systemd/system/pimoroni-fanshim.service

Checking for rpi.gpio>=0.7.0 (for Pi 4 support)
rpi.gpio >= 0.7.0 already installed
Checking for Fan SHIM
Fan SHIM already installed
Checking for psutil
psutil already installed

Installing service to: /etc/systemd/system/pimoroni-fanshim.service
● pimoroni-fanshim.service - Fan Shim Service
Loaded: loaded (/etc/systemd/system/pimoroni-fanshim.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2019-12-11 19:27:03 CET; 25ms ago
Main PID: 1607 (python3)
Tasks: 1 (limit: 4915)
Memory: 1.0M
CGroup: /system.slice/pimoroni-fanshim.service
└─1607 python3 /home/pi/fanshim-python/examples/automatic.py --on-threshold 65 --off-threshold 55 --delay 2 --brightness 255

dic 11 19:27:03 raspberrypi systemd[1]: Started Fan Shim Service.
pi@raspberrypi:~/fanshim-python/examples $

I have no idea if I have a software or hardware problem,sorry for my english it's not perfect
thanks to everyone for any suggestion or fix
Andrea

Create new release?

The 0.0.2 release is from late June and there have been a lot of commits since then, could you do a new release? :)

Fan turns back on if `set_light()` is part of the script

Take the following two scripts for example:

# script A: simply shutting down the fan
from fanshim import FanShim
fanshim = FanShim()
fanshim.set_fan(False)
# script B: shutting down the fan and setting a colour
from fanshim import FanShim
fanshim = FanShim()
fanshim.set_fan(False)
fanshim.set_light(255, 0, 0)

The first one will shut down the fan properly, while the second one will shut it down for a split second (I assume) and turn it right back on when the script exits.

Any idea how I could gracefully change the colour of the LED while also turning the fan off/on?

fails to install

How to reproduce:

RPi 4
Raspbian Buster Lite September 2019

Fresh, default OS install. Applied the latest updates and patches. Installed git, python-pip and python3-pip

Cloned this repo. As root, ran ./install.sh

There are no apparent errors. But the service is not actually installed. systemctl does not report anything named like it. Reboot - nothing. Doesn't work.

Tried twice from scratch. Always same result.


I had it working before on the same hardware. I believe it was the previous version of Raspbian, and the install was not quite so fresh and default (had been playing a while with Python data science stuff and Tensorflow).

Fanshim Service Conflict

I am using an RPI 4 with Buster and everything is up to date.
I have installed the fanshim and installed the fanshim service according to the instructions and
it works perfectly.

Now I have installed the AlexaPi from https://github.com/alexa-pi/AlexaPi/wiki/Installation
and that is also working perfectly.

There is some kind of clash with the fanshim service.
As soon as the AlexaPi service starts either at reboot or with sudo systemctl status AlexaPi.service then my fanshim service is messed up and fan is always on. I check fanshim service status and it is running active.
If now I restart fanshim service then both fanshim and AlexaPi service are working fine until next reboot.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.