Alert via SMS and shutdown the power

I started monitoring the temperature of my Raspberry Pi computer some time ago. I’ve also set up a Chatbot that can give me this information whenever I want. So next, I was thinking to write a Python script that can shut down the power of my Raspberry Pi (in fact, the smart plug where this device is connectedย ) when a threshold is reached and also alerts before this, via SMS.

The project is made of multiple python scripts:
– temperature.py this is the main app where all other python scripts/functions are used
– sendSMS.py, used to send a message via Twilio sms service using an api
– tpplug.py, used to shutdown the TP link smart plug

temperature.py
I already have the temperature logging in the LogDNA service so it would be easy to use the API to get this info. From here I only have to check if it has reached the threshold( 60 C in my case ) and then take action. Action would mean to call the send SMS function, wait 30 seconds and then call the shutdown function for my smart plug(I have a TP link smart plug ) .

import requests
from datetime import datetime
from datetime import timezone
from sendSMS import sendSMS
from tpplug import send_cmd
import time
from vault import apikey

def main():
    dt = datetime.now()
    timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
    times = int(timestamp-600)
    api_url = 'https://api.logdna.com/v1/export?from=%i&to=%i&query=PiTemp' % (times,int(timestamp))
    headers = {"servicekey": apikey}
    response = requests.get(api_url,headers=headers)
    x=int(response.text[138:140])
    text = f"Shutting down in 30s due to Pi Temperature: {x} C"
    if int(x) >= 60:
        sendSMS(text)
        time.sleep(30)
        send_cmd('off')

if __name__ == '__main__':
    main()

sendSMS.py
For SMS I’ve used the Twilio SMS service. They provide a phone number and also a Python library and API. They also have examples of how to send an SMS via a python script, so this was pretty easy to use.

# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
from vault import account,token,from_number,to_number

def sendSMS(message):
# Your Account Sid and Auth Token from twilio.com/console
# and set the environment variables. See http://twil.io/secure
  account_sid = account
  auth_token = token
  client = Client(account_sid, auth_token)

  message = client.messages \
                .create(
                     body=message,
                     from_=from_number,
                     to=to_number
                 )

  print(message.sid)

tpplug.py
I am using a TP-link smart plug for my Raspberry Pi. I’ve also found a way to use python and run commands on this smart plug. (More info here: https://github.com/softScheck/tplink-smartplug). So I’ve used some of the python functions and created a python script that executes a command(‘off’) to shutdown the power. The smart plug does not shut down, it only stops powering my Raspberry Pi.

import socket
from struct import pack

ip='192.168.8.211'
port='9999'

commands = {'on'       : '{"system":{"set_relay_state":{"state":1}}}',
            'off'      : '{"system":{"set_relay_state":{"state":0}}}',
            'info'     : '{"system":{"get_sysinfo":{}}}'}

def encrypt(string):
    key = 171
    result = pack(">I", len(string))
    for i in string:
        a = key ^ ord(i)
        key = a
        result += bytes([a])
    return result

def decrypt(string):
    key = 171
    result = ""
    for i in string:
        a = key ^ i
        key = i
        result += chr(a)
    return result

def send_cmd(string):
    cmd=commands[string]
    sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_tcp.settimeout(10)
    sock_tcp.connect((ip, int(port)))
    sock_tcp.send(encrypt(cmd))
    data = sock_tcp.recv(2048)
    sock_tcp.close()
    decrypted = decrypt(data[4:])
    return decrypted

Next, I’ve scheduled the temperature.py script to run every 5 min.
Here is a screenshot from my tests. I had to drop the threshold to 40 C for testing only.

And that’s all folks.

You can find the scripts here:
https://github.com/czirakim/SMSalert.shutdown.PI

About the author

Mihai is a Senior Network Engineer with more than 15 years of experience