Shutdown Script

From NURDspace
Shutdown Script
Shutdown.png
Participants
Skills Python, Linux
Status Finished
Niche
Purpose Saving energy and money
Tool No
Location
Cost
Tool category

Shutdown Script

Shutdown.png {{#if:No | [[Tool Owner::{{{ProjectParticipants}}} | }} {{#if:No | [[Tool Cost::{{{Cost}}} | }}

A script that shuts PC's down on the space when space state is off.

It checks space status on MQTT and shuts machine down if space is closed.

  • Make sure you have paho installed.
apt install python3
apt install python-is-python3
apt install python-pip
pip install paho-mqtt

new script

Make a directory called /etc/spaceStateExecutor/ and make a new file called config.yaml

mqtt:
  host: mqtt.vm.nurd.space
  port: 1883

on_space_open:
    - echo "Space is open"
    - your_command_here

on_space_closed:
    - echo "Space is closed"
    - your_command_here

Now make a systemd service using `systemctl edit spaceStateExecutor --full --force` and paste the following:

[Unit]
Description=NurdSpace State Executor
After=network-online.target

[Service]
Type=simple
Restart=always
ExecStart=/usr/bin/spacestate-executor

[Install]
WantedBy=multi-user.target

Make sure to save this file as /usr/bin/spacestate-executor and finally run `chmod +x /usr/bin/spacestate-executor` after that you can start and enable the service with `systemctl enable spaceStateExecutor --now`. You don't need to restart the service after you change the config (except for mqtt) as the script reloads the config.

#! /usr/bin/python3
import os
import yaml
import time
import logging
import paho.mqtt.client

 
/etc/systemd/system/.service example


"""

logging.basicConfig(level=logging.INFO)

class spaceStateExecutor():
    client = paho.mqtt.client.Client()
    spacestate = False

    def __init__(self):
        logging.info("Starting spaceStateExecutor")
        self.setup_mqtt()
        self.client.loop_forever()

    def load_config(self):
        with open("/etc/spaceStateExecutor/config.yaml", 'r') as stream:
            try:
                return yaml.load(stream, Loader=yaml.FullLoader)
            except yaml.YAMLError as exc:
                logging.error("Error loading config: " + str(exc))
                import sys; sys.exit(1)

    def setup_mqtt(self):
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_disconnect = self.on_disconnect
        self.client.connect("mqtt.vm.nurd.space")

    def on_disconnect(self, client, userdata, rc):
        self.setup_mqtt()

    def on_connect(self, client, userdata, flags, rc):
        self.client.subscribe("space/state")
        logging.info("Connected to MQTT")
    
    def on_space_open(self):
        self.callback_executor("on_space_open")

    def on_space_closed(self):
        self.callback_executor("on_space_closed")

    def callback_executor(self, callback_name):
        config = self.load_config()
        callbacks = config[callback_name]

        for callback in callbacks:
            logging.info("Executing for " + callback_name + ": " + callback)
            os.system(callback)

    def on_message(self, client, userdata, msg):
        if msg.topic == "space/state":
            _current_spacestate = self.spacestate
            self.spacestate = True if msg.payload.decode("utf-8").lower() == "true" else False

            if _current_spacestate == self.spacestate: # Spacestate didn't change
                return

            if self.spacestate == True:
                try:
                    self.on_space_open()
                except Exception as e:
                    logging.error("An error occured while executing on_space_open: " + str(e) + "\n")
                    
            else:
                try:
                    self.on_space_closed()
                except Exception as e:
                    logging.error("An error occured while executing on_space_closed: " + str(e) + "\n")

while True:
    try:
        spaceStateExecutor()
    except Exception as e:
        logging.error("An error occured while executing spaceStateExecutor: " + str(e) + "\n")
        time.sleep(5)

older script

  • Log in as root and access root folder.
sudo -s
cd /root/
  • Enter crontab.
crontab -e
  • Add a cronjob on the last line with the location of the script file.
* * * * *  python /home/user/space_status_shutdown.py

The Script

Make sure the file has a .py extension.


  1. !/usr/bin/env python
  1. 2019 The_Niz
  1. checks space status and shuts machine down if space is closed


import paho.mqtt.client as mqtt import os

  1. The callback for when the client receives a CONNACK response from the server.

def on_connect(client, userdata, flags, rc):

   if rc==0:
       client.connected_flag=True #set flag
       print("Connected with result code "+str(rc))
   else:
       print("Bad connection Returned code=",rc)
       client.loop_stop()
       client.disconnect()
   client.subscribe("space/state")
  1. The callback for when a PUBLISH message is received from the server.

def on_message(client, userdata, msg):

   print(msg.topic+" "+str(msg.payload))
   if msg.payload.decode('utf-8')=="False":
       print("Space is uit")
       os.system('sudo /bin/systemctl poweroff')
   else:
       print("Space is aan")
   client.loop_stop()
   client.disconnect()


client = mqtt.Client()

client.on_connect = on_connect

client.on_message = on_message

client.connect("mqtt.vm.nurd.space", 1883, 60)

client.loop_forever()

</nowiki>