NickWaterton / Flair-Vents-MQTT-Interface

Interface to Flair Smart vents and pucks via MQTT
MIT License
13 stars 3 forks source link

Program continuity #1

Open Ioez opened 5 years ago

Ioez commented 5 years ago

We have been trying to use the program for keeping the humidity in an apartment below certain level. For this we have the need to run it continously so we can check the % value throughout the day. Although we been successful in running it several hours at a time, we sometimes run into an unexpected error. Our solution for this is to shutdown and restart the program every 24 hours. While trying this we found out that the program needed to have a terminal open for it to work, otherwise, when we closed putty it would stop. We tried to use tmux to solve the terminal problem and cron to run the program, but we have not been successful at making both work together. Is there a better way keep the program running continously?

NickWaterton commented 5 years ago

I use nohup to start the program and disconnect it from the terminal. This is my script start_flair_vents

#!/bin/bash

pid_file=/var/run/flairvents.pid

if [ -e $pid_file ]; then
   /home/nick/Scripts/stop_process $pid_file
fi

echo "Starting flairvents"
cd /home/nick/Scripts/flair
nohup ./vents_bridge.py -C -l /home/nick/Scripts/flair_vents.log > /dev/null  2>&1 & echo $! > $pid_file
echo "End of start flairvents"

The script /home/nick/Scripts/stop_process is a script that takes a pid file and kills the process. This is to stop the process if it's already running.

This is stop_process:

#!/bin/bash

# $1 is process('s) to stop

if [ -f $1 ]
then
    for pid in $(cat $1)
    do

        #pid=$(cat $1)
        echo "stop process: $1 received, process id $pid"
        /usr/bin/sudo kill -INT "$pid"
        sleep 10
        process=$(ps -p $pid | wc -l)
        if (( "$process" >= 2 ))
        then
           echo "process count is  $process so process \n$(ps -p "$pid")\n is still running attempt to kill it sith SIGTERM"
           if [[ "$1" != /var/run/dead/dead_processes.pid ]]
           then
              if [ ! -d /var/run/dead ]; then
                /usr/bin/sudo mkdir /var/run/dead/
                /usr/bin/sudo chown nick:nick /var/run/dead/
              fi
             /usr/bin/sudo echo "$pid" >> /var/run/dead/dead_processes.pid
           fi
           /usr/bin/sudo kill -9 "$pid"
        fi
    done
    /usr/bin/sudo rm $1
else
        echo "stop process: $1 does not exist or is not readable"
fi

I use monit to automatically restart the script if it stops running. This is on Ubuntu 18.04.1

You would have to edit the locations (eg /home/nick is my home directory), but it shows how to use nohup.