Python code to control GPIO at specific times

I want to build a Raspberry Pi based irrigation automation system. I have a script that generates a .CSV file based on sprinkler schedule input parameters (station no, time / station, rain sensor use / absence, etc.).

The .CSV file looks like this:

1 00:00:00 00:29:59 110000
2 00:30:00 00:44:59 101000
3 00:45:00 01:14:59 100100
.
.
.
.

      

where each line represents a time interval and a six-digit binary number represents the state of the GPIO pins (1 = valve on, 0 = valve off).

What is the best way to scan this .CSV file and run valves based on binary?

At the moment I have two options, but I'm sure there should be a better one:

  • Loop the code continuously at 1 second intervals, read each .CSV line until the interval hides the current time, then trigger the appropriate ports
  • Read the .CSV file and create a cron job for each line.

In any case, the solution should be very simple and reliable, the program should work throughout the summer season without errors or errors.

Thank!

+3


source to share


3 answers


This program should do what you want. When it starts, your file is read into the schedule. The schedule is sorted and the for loop runs on your schedule as needed. Once the schedule is complete, your program should be started again.



import operator
import time


def main():
    schedule = []
    with open('example.csv') as file:
        for line in file:
            _, start, _, state = line.split()
            data = time.strptime(start, '%H:%M:%S')
            schedule.append((time_to_seconds(data), int(state, 2)))
    schedule.sort(key=operator.itemgetter(0))
    for start, state in schedule:
        current_time = time_to_seconds(time.localtime())
        difference = start - current_time
        if difference >= 0:
            time.sleep(difference)
            set_gpio_pins(state)


def time_to_seconds(data):
    return (data.tm_hour * 60 + data.tm_min) * 60 + data.tm_sec


def set_gpio_pins(state):
    raise NotImplementedError()

if __name__ == '__main__':
    main()

      

+1


source


A possible idea might be to use crontab to run a program that scans the .CSV file and also triggers the valves so you can only do this when you really need to.



0


source


You might want to look into linux sync commands to help set when your sprinklers will be disabled:

#this is pseudocode
While True :

    If *clocktime* == *target activation time*
         *these sprinklers activate*

      

0


source







All Articles