First, we install gpiozero, if we don't already have it.
sudo apt-get update
sudo apt-get install python3-gpiozero
Next we create the file relay-trigger.py
with the follwoing contents:
from gpiozero import Button
from signal import pause
from time import sleep
import socket
import subprocess
DEST_PORT = 17473
DEST_IP = "255.255.255.255"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
def doShutdown():
print("GPIO Change Detected")
for i in range(3):
sock.sendto(b'\x01\x01', (DEST_IP, DEST_PORT))
sleep(0.5)
subprocess.Popen(['sudo', 'shutdown', '-h', 'now'])
# GPIO where relay is connected
button = Button(21)
button.when_released = doShutdown
pause()
As written, the script detects GPIO 21 and proceeds to send out three sequential UDP packets telling other computer on the network to initiate shutdown.
Now we create a systemd script to automatically launch this program at system startup. Create the file /lib/systemd/system/relay-trigger.service
with the following contents:
[Unit]
Description=Relay trigger upon GPIO 2
After=network-online.target
[Service]
ExecStart=/usr/bin/python3 /home/pi/relay-trigger.py
[Install]
WantedBy=network-online.target
Next, we ensure systemd is aware of our new service:
sudo systemctl daemon-reload
Next, we enable the new service:
sudo systemctl enable relay-trigger.service
Finally, we reboot the Raspberry Pi.
sudo reboot
Once reboot completes, we can check if our new services started up:
sudo systemctl | grep relay
The client can be installed on any Linux or Windows based system. This specific example will focus on a Windows use case.
Create a file titled cliente.py
with the following contents:
import subprocess
import socket
import platform
UDP_PORT = 17473
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('',UDP_PORT))
sysname = platform.system()
while True:
data, addr = sock.recvfrom(1024)
if data == b'\x01\x01':
if sysname == 'Windows':
subprocess.run(["shutdown", "/p", "/f"])
elif sysname == 'Linux':
subprocess.Popen(['sudo', 'shutdown', '-h', 'now'])
Create a shortcut to this file in the Windows startup folder, replacing USERNAME with the actual username of the active user in Windows:
C:\Users\USERNAME\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Before restarting Windows, make sure Python 3.0 or newer is installed.