Ruan du Preez
Ruan du Preez

Reputation: 99

Python script on Headless Pi OS not closing relay correctly

Good day

I have created a python script to automount a USB flash drive and read the content of 2 files inside. When the content in the files corresponds it opens a relay. My problem is that it mounts the USB and opens the Relay but it closes it immediately. It should keep relay open as long as USB is connected. What am I missing. Here is the code:

 import os
import time
import RPi.GPIO as GPIO

# GPIO setup
RELAY_PIN = 17  # Use the pin where your relay is connected
GPIO.setmode(GPIO.BCM)
GPIO.setup(RELAY_PIN, GPIO.OUT)

# File paths
MOUNT_POINT = '/media'
DEVICE = '/dev/sda'  # Adjust if necessary
FILE1_PATH = f"{MOUNT_POINT}/Key.txt"  # Adjust the file path as needed
FILE2_PATH = f"{MOUNT_POINT}/Boot.txt"  # Adjust the file path as needed

# Expected contents
expected_content_file1 = "AAA001"
expected_content_file2 = "BBB002"

# Initialize flags
file1_correct = False
file2_correct = False
usb_connected = False
relay_state = GPIO.LOW

def mount_usb():
    if not os.path.exists(MOUNT_POINT):
        os.makedirs(MOUNT_POINT)
    os.system(f'sudo mount {DEVICE} {MOUNT_POINT}')
    print(f'Device {DEVICE} mounted to {MOUNT_POINT}')

def unmount_usb():
    os.system(f'sudo umount {MOUNT_POINT}')
    print(f'Device unmounted from {MOUNT_POINT}')

def check_usb():
    return os.path.ismount(MOUNT_POINT)

def device_exists():
    return os.path.exists(DEVICE)

def check_files():
    global file1_correct, file2_correct
    try:
        with open(FILE1_PATH, 'r') as file1:
            content_file1 = file1.read().strip()
            file1_correct = (content_file1 == expected_content_file1)

        with open(FILE2_PATH, 'r') as file2:
            content_file2 = file2.read().strip()
            file2_correct = (content_file2 == expected_content_file2)

    except FileNotFoundError:
        file1_correct = False
        file2_correct = False

def update_relay():
    global relay_state
    if usb_connected and file1_correct and file2_correct:
        if relay_state == GPIO.LOW:
            GPIO.output(RELAY_PIN, GPIO.HIGH)
            relay_state = GPIO.HIGH
            print("Relay activated.")
    else:
        if relay_state == GPIO.HIGH:
            GPIO.output(RELAY_PIN, GPIO.LOW)
            relay_state = GPIO.LOW
            print("Relay deactivated.")

def monitor_usb():
    global usb_connected
    last_usb_connected = None
    while True:
        current_usb_connected = check_usb()
        
        if device_exists():
            if not current_usb_connected:
                mount_usb()
                usb_connected = True
                last_usb_connected = True
            elif usb_connected and last_usb_connected is False:
                last_usb_connected = True
                print('USB is reconnected.')

        else:
            if current_usb_connected:
                unmount_usb()
                usb_connected = False
                last_usb_connected = False
                print('USB is disconnected.')
        
        if usb_connected:
            print("USB is mounted. Checking files...")
            check_files()
            update_relay()
        else:
            update_relay()

        time.sleep(1)  # Check every second

try:
    monitor_usb()
finally:
    GPIO.cleanup()

Thanks

Upvotes: 0

Views: 26

Answers (0)

Related Questions