資料來源: Control of your Appliances and IoT Devices at your Fingertips with Flask
Connecting to your database
https://dzone.com/articles/restful-web-services-with-python-flask

 

E:xample : Browser Graphical User Interface (GUI) for Sprinkler System

 

TEST & Control the relay(s) for the Sprinkler system:
This python routine starts the vales connected to the Raspberry Pi pins with the numbers listed
​​​​​​​in the array “zone” (8, 7, 14, 15, 18, 23, 24, 25), 

# import the necessary packages
import RPi.GPIO as GPIO
import time

# set the GPIO mode
GPIO.setmode(GPIO.BCM)

zone = [8, 7, 10, 9, 14, 15, 18, 23, 24, 25]
#################################################
# List of zones with the times for each zone ####
#################################################
#8  = House front left, Large tree, at walk way
s8  = [zone[0], 200]
#7  = House front left, Large tree, at garage wall
s7  = [zone[1], 200]
#10 = right corner of backyard behind shed
s10 = [zone[2], 200]
#9  = Backyard cherry trees
s9  = [zone[3], 200]

#14 = Orange Trees, Plum trees, Apple tree..
s14 = [zone[4], 200]
#15 = Front right stripe
s15 = [zone[5], 200]
#18 = Cypresses left
s18 = [zone[6], 200]
#23 = planting boxes
s23 = [zone[7], 200]
#24 = Roses house wall
s24 = [zone[8], 150]
#25 = House wall at AC
s25 = [zone[9], 150]

def openCloseValves(valve, zeit):
        print("Opening Valve",valve," for ",zeit," seconds")
        time.sleep(5.0)
        GPIO.setup(valve, GPIO.OUT)
        GPIO.output(valve, GPIO.LOW)    # Open valve
        time.sleep(zeit)
        GPIO.output(valve, GPIO.HIGH)   # Close valve
        time.sleep(5.0)
        print("done...")

def run():
        openCloseValves(s8[0],s8[1])
        openCloseValves(s7[0],s7[1])
        openCloseValves(s10[0],s10[1])
        openCloseValves(s9[0],s9[1])

        openCloseValves(s14[0],s14[1])
        openCloseValves(s15[0],s15[1])
        openCloseValves(s18[0],s18[1])
        openCloseValves(s23[0],s23[1])
        openCloseValves(s24[0],s24[1])
        openCloseValves(s25[0],s25[1])

        # perform a bit of cleanup
        GPIO.cleanup()
        
if __name__=='__main__':
        try:
                run()
        except:
                # Shut all valves...
                for num in zone:
                        GPIO.setup(num, GPIO.OUT)
                        GPIO.output(num, GPIO.HIGH)
                GPIO.cleanup()
                print("An Error occured OR user stopped routine...!!!")
                raise

The file webForm contains following python code

Flask WebForm in python
 
 
 
 
 
 
Default
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/usr/bin/python
#!/usr/bin/python
 
from flask import Flask, render_template, flash, request
from wtforms import Form, TextField, validators
import json
import RPi.GPIO as GPIO
import sprinklerMain as valvesMain
import os
 
# App config.
DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = '17d441f27d441f27567d441f2b6176a'
 
with open('/home/pi/Blog_flaskSprinkler/settings.json') as data_file:
    sprinkler = json.load(data_file)
 
class ReusableForm(Form):
    Z0 = TextField('Z0:', validators=[validators.required(), validators.Length(min=1, max=35)])
    Z1 = TextField('Z1:', validators=[validators.required(), validators.Length(min=1, max=35)])
    Z2 = TextField('Z2:', validators=[validators.required(), validators.Length(min=1, max=35)])
    Z3 = TextField('Z3:', validators=[validators.required(), validators.Length(min=1, max=35)])
 
@app.route("/", methods=['GET', 'POST'])
def guiPage():
    form = ReusableForm(request.form)
    if request.method == 'POST':
        if request.form['submit'] == "submitAll":
            Z0=request.form['Z0']
            if Z0 and Z0.isnumeric():
                valve = sprinkler['0']
                sprinkler['0'] = [valve[0], Z0]
            Z1=request.form['Z1']
            if Z1 and Z1.isnumeric():
                valve = sprinkler['1']
                sprinkler['1'] = [valve[0], Z1]
            Z2=request.form['Z2']
            if Z2 and Z2.isnumeric():
                valve = sprinkler['2']
                sprinkler['2'] = [valve[0], Z2]
            Z3=request.form['Z3']
            if Z3 and Z3.isnumeric():
                valve = sprinkler['3']
                sprinkler['3'] = [valve[0], Z3]
            flash('Zone0 : ' + Z0)
            flash('Zone1 : ' + Z1)
            flash('Zone2 : ' + Z2)
            flash('Zone3 : ' + Z3)
            # Save new values back to the json file...:
            with open('/home/pi/Blog_flaskSprinkler/settings.json','w+') as fp:
                json.dump(sprinkler, fp, sort_keys=True, indent=4)
 
        elif request.form['submit'] == "startAll":
            print("Starting all valves...")
            os.system('/home/pi/flaskSprinkler/sprinklerMain.py &')        # Start sprinklerMain in background (new thread)...
        elif request.form['submit'] == "stopAll":
            print("Stopping all valves...") 
            valvesMain.closeAllValves()    # stop all valves...
        #...0...
        elif request.form['submit'] == "start0":
            print("Starting 0 : Front left, at walkway...")
            valve = sprinkler['0']
            valvesMain.openValve(int(valve[0]))
        elif request.form['submit'] == "stop0":
            print("Stop 0")
            valve = sprinkler['0']
            valvesMain.closeValve(int(valve[0]))
        #...1...
        elif request.form['submit'] == "start1":
            print("Starting 1 : Front left, at garage wall...")
            valve = sprinkler['1']
            valvesMain.openValve(int(valve[0]))
        elif request.form['submit'] == "stop1":
            print("Stop 1")
            valve = sprinkler['1']
            valvesMain.closeValve(int(valve[0]))
        #...2...
        elif request.form['submit'] == "start2":
            print("Starting 2 : Right backyard, behind shed...")
            valve = sprinkler['2']
            valvesMain.openValve(int(valve[0]))
        elif request.form['submit'] == "stop2":
            print("Stop 2")
            valve = sprinkler['2']
            valvesMain.closeValve(int(valve[0]))
        #...3...
        elif request.form['submit'] == "start3":
            print("Starting 3 : Backyard cherry trees...")
            valve = sprinkler['3']
            valvesMain.openValve(int(valve[0]))
        elif request.form['submit'] == "stop3":
            print("Stop 3")
            valve = sprinkler['3']
            valvesMain.closeValve(int(valve[0]))
            
    valve=[]
    dynamicvalue=[]
    for i in range(0,len(sprinkler)):
        valve = sprinkler[str(i)]
        dynamicvalue.append(int(valve[1]))
    return render_template('guiPage.html', form=form, defname = dynamicvalue)
 
 
if __name__ == "__main__":
    #app.run(debug=True, host='0.0.0.0')
    app.run(host='0.0.0.0')
1
sudo chmod ug+x webForm.py
$> ./webForm

settings.json 

{
    "0": [
        "25",
        "200"
    ],
    "1": [
        "27",
        "200"
    ],
    "2": [
        "21",
        "200"
    ],
    "3": [
        "23",
        "200"
    ]
}

 

sprinklerMain.py

import RPi.GPIO as GPIO
import time
import json
import os
from collections import OrderedDict 
 
def openCloseValves(valve, zeit):
    print("Opening Valve " + str(valve) + " for " + str(zeit) + " seconds..."),
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    time.sleep(5.0)
    GPIO.setup(valve, GPIO.OUT)
    GPIO.output(valve, GPIO.LOW)    # Open valve
    time.sleep(zeit)
    GPIO.output(valve, GPIO.HIGH)    # Close valve
    time.sleep(5.0)
    print("Done")
    
def openValve(valve):
    print("Opening Valve " + str(valve) + " ..."),
    #GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(valve, GPIO.OUT)
    GPIO.output(valve, GPIO.LOW)    # Open valve
    print("Done")
    return()
    
def closeValve(valve):
    print("Closing Valve " + str(valve) + " ..."),
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(valve, GPIO.OUT)
    GPIO.output(valve, GPIO.HIGH)    # Close valve
    print("Done")
    return()
    
def run():
    value =[]
    with open('/home/pi/flaskSprinkler/settings.json') as data_file:
        sprinkler = json.load(data_file)
        for i in range(0,len(sprinkler)):
            value = sprinkler[str(i)]
            valve = int(value[0])
            zeit = int(value[1])
            print("sprinkler new " + str(valve) + " value : " + str(zeit))
            openCloseValves(valve, zeit)
    # Perform a bit of cleanup...
    GPIO.cleanup()
    
def closeAllValves():
    GPIO.setmode(GPIO.BCM)
    for value in range(2,28):
        try:
            GPIO.setup(int(value), GPIO.OUT)
            GPIO.output(int(value), GPIO.HIGH)
        except:
            continue    # continue with the next GPIO pin...
    GPIO.cleanup()
 
        # Kill routine sprinkler script in case that is running...
        try:
                os.system("sudo pkill -9 sprinklerMain.py")
                time.sleep(1)
        except:
                pass
 
  
    
if __name__=="__main__":
    try:
        run()
    except:
        closeAllValves()
        print("An Error occured OR user stopped routine...!!!")
        raise

 

 

 

 guiPage.html. This file needs to be in the folder templates/.

<div class="container">
<h2>Sprinkler Setting Web Form</h2>
&nbsp;
 
<form action="" method="post">
<div class="form-group">
<table class="responsable">
<tbody>
<tr>
<td><label for="Z0">Zone 0 : Front left, at walk way</label></td>
<td><input id="Z0" class="form-control" name="Z0" type="text" placeholder="Front left, at walk way..." /></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid green;" name="submit" type="submit" value="start0">Start0</button></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid red;" name="submit" type="submit" value="stop0">Stop0</button></td>
</tr>
<tr>
<td><label for="Z1">Zone 1 : Front left, at garage wall</label></td>
<td><input id="Z1" class="form-control" name="Z1" type="text" placeholder="Front left, at garage wall..." /></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid green;" name="submit" type="submit" value="start1">Start1</button></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid red;" name="submit" type="submit" value="stop1">Stop1</button></td>
</tr>
<tr>
<td><label for="Z2">Zone 2 : Right backyard, behind shed</label></td>
<td><input id="Z2" class="form-control" name="Z2" type="text" placeholder="Right backyard, behind shed..." /></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid green;" name="submit" type="submit" value="start2">Start2</button></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid red;" name="submit" type="submit" value="stop2">Stop2</button></td>
</tr>
<tr>
<td><label for="Z3">Zone 3 : Backyard cherry trees.</label></td>
<td><input id="Z3" class="form-control" name="Z3" type="text" placeholder="Backyard cherry trees..." /></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid green;" name="submit" type="submit" value="start3">Start3</button></td>
<td><button style="width: 100px; font-size: 18pt; padding: 2px; border: 3px solid red;" name="submit" type="submit" value="stop3">Stop3</button></td>
</tr>
</tbody>
</table>
&nbsp;
 
</div>
<button class="btn btn-success" style="width: 650px; font-size: 18pt; padding: 2px; border: 6px solid black;" name="submit" type="submit" value="submitAll">Write times specified (let-out fileds not changed)</button> <button class="btn btn-success" style="width: 650px; font-size: 18pt; padding: 2px; border: 6px solid green;" name="submit" type="submit" value="startAll">Start all zones</button> <button class="btn btn-success" style="width: 650px; font-size: 18pt; padding: 2px; border: 6px solid red;" name="submit" type="submit" value="stopAll">Stop all zones</button>
<h3>Values Set:</h3>
</form></div>
&nbsp;

 

Keeping it Running

 

@reboot /home/pi/flaskSprinkler/shutSprinkler.py

15 22 * * * nohup /home/pi/flaskSprinkler/sprinklerMain.py &
*/5 * * * * nohup /home/pi/flaskSprinkler/isFlaskRunning.sh &

#----------------------

shutSprinkler.py

# import the necessary packages
import RPi.GPIO as GPIO
import time
#import cv2

# load the input image and display it to our screen
#print("click on the image and press any key to continue...")
#image = cv2.imread("hoover_dam.jpg")
#cv2.imshow("Image", image)
#cv2.waitKey(0)
#print("moving on...")

# set the GPIO mode
GPIO.setmode(GPIO.BCM)

# loop over the LEDs on the TrafficHat and light each one
# individually
for i in (14,15,18,23,24,25,8,7,2,3,4,17,27,22,10,9):
        GPIO.setup(i, GPIO.OUT)
        time.sleep(0.1)
        GPIO.output(i, GPIO.HIGH)

# perform a bit of cleanup
GPIO.cleanup()

isFlaskRunning.sh

laskRunning.sh
 
 
 
 
 
Default
1
2
3
4
5
6
7
#!/bin/bash
#!/bin/bash
 
service="webForm"
 
if ! ps -e | grep "$service" ; then
/home/pi/flaskSprinkler/webForm
fi
文章標籤
全站熱搜
創作者介紹
創作者 stanley 的頭像
stanley

史坦利Stanley程式Maker的部落格

stanley 發表在 痞客邦 留言(0) 人氣(84)