Temperature controlled fan using GPIO on rpi 3

Hello,

I am trying to create a background service which should start when libreelec starts and monitor the CPU temperature. If the temperature goes beyond certain limit switch the fan ON. I have almost got all the hardware ready and connected to the GPIO (pin 18).

Below is the script I manage to create so far. Please let me know if this will work or not and specifically if this is fine or not. I am planning to install it as a service addon uisng zip file.

Lately the temperature on my Rpi 3 (Libreelec 7.0.3) goes above 70 which was not the case before. I am running moderate overclock settings. Also, have been running transmission, couchpotato and sonarr along with Kodi. Also, during startup I get the yellow warning of temperature which I believe is displayed when CPU is above 80. Can anybody point me in correct direction how to find out which service or addon is causing the pi to overheat so much?

I am newbie in linux, but can follow steps if provided. Have learned couple of tricks so far Smile

fan.py

Code:
#!/bin/python
# Author: Arpit

import os
from time import sleep
import signal
import sys
sys.path.append('/storage/.kodi/addons/virtual.rpi-tools/lib')
import RPi.GPIO as GPIO

pin = 18 # The pin ID, edit here to change it
maxTMP = 55 # The maximum temperature in Celsius after which we trigger the fan

def setup():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(pin, GPIO.OUT)
    GPIO.setwarnings(False)
    return()
def fanON():
    GPIO.output(pin, True)
    return()
def fanOFF():
    GPIO.output(pin, False)
    return()
def getTEMP():
    res = os.popen(‘vcgencmd measure_temp’).readline()
    temp =(res.replace(“temp=”,””).replace(“’C\n”,””))
    #print(“temp is {0}”.format(temp)) #Uncomment here for testing
    CPU_temp = float(temp)
    if CPU_temp>maxTMP:
        fanON()
    else:
        fanOFF()
    return()
try:
    setup()
    while True:
        getTEMP()
sleep(10) # Read the temperature every 10 sec, increase or decrease this limit if you want
except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt
    GPIO.cleanup() # resets all GPIO ports used by this program

addon.xml

Code:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="service.gpio.temperaturecontrolledfan" name="Temperature Controlled Fan" version="1.0.0" provider-name="ArpitG">
    <requires>
<import addon="xbmc.python" version="2.20.0"/>
</requires>
<extension library="fan.py" point="xbmc.service" start="login"/>
<extension point="xbmc.addon.metadata">
<summary lang="en">Temperature Controlled Fan</summary>
<description lang="en">Driver script for GPIO controlled fan</description>
<disclaimer lang="en">This plugin requires hardware fan connected by GPIO.</disclaimer>
<platform>all</platform>
</extension>
</addon>

The circuit diagram is as follows. The DC motor is actually a fan. Never connect motor to rpi like this.

watch gallery

Thank you.

Edit: Cannot install the addon. What am I missing here?