본문 바로가기

프로젝트형 IoT 서비스 개발 4회차/3. 게이트웨이 디바이스 제어

[Day61] 2022-04-25(월) Flask 활용 - 김서연 강사님

728x90

[1] Flask 활용

  - 라즈베리파이 자체를 Web 서버로 활용 : 실제 프로젝트에서는 웹서버를 라즈베리파이에 만들지는 않음

  1. 기본 예제

    - 라즈베리파이IP:5000 으로 접속

from flask import Flask

# Flask 인스턴스 생성
app = Flask(__name__)

# flask에서 Flask 객체의 route 메소드를 @ 기호와 함께 추가해서 요청 path를 설정

@app.route("/")
def hello():
    return "Hello Raspberry Pi"


# flask의 실행을 요청 - 기본 포트가 5000
# debug=True는 코드가 변경되면 서버를 restart하지 않아도 반영된다는 의미
app.run(host="0.0.0.0", debug=True)

  2. LED 제어 예제

    1) Python 파일

flask_led.py

from flask import Flask, render_template
import RPi.GPIO as gpio
import random

from matplotlib.style import context

app = Flask(__name__)
led_pin =22
gpio.setmode(gpio.BCM)
gpio.setup(led_pin, gpio.OUT)

@app.route("/<command>")
def action(command):
    if command == "on":
        gpio.output(led_pin, gpio.HIGH)
        message = "GPIO"+str(led_pin)+" ON"
    elif command == "off":
        gpio.output(led_pin, gpio.LOW)
        message = "GPIO"+str(led_pin)+" OFF"
    else:
        pass
    # response 되는 웹 페이지에 값을 넘기고 싶은 경우
    context = {
        "message": message,
        "status": gpio.input(led_pin),
        "hum": random.randrange(40, 50),
        "temp": random.randrange(20, 25),
        "distance": random.randrange(20, 100)
    }
    return render_template("led.html", **context)


if __name__ == "__main__":
    try:
        app.run(host="0.0.0.0", debug=True)    
    except KeyboardInterrupt:
        pass
    finally:
        gpio.cleanup()

    2) HTML 파일

 

      - 테스트용 페이지

led.html

<!--led.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Flask LED제어</h1>
    <h3>
        <!--falsk 내부에서 사용하는 프레임워크 (jinja2)-->
        {% if message %}
            {{message}}
            {{status}}
            {{hum}}
            {{temp}}
            {{distance}}
        {% endif %}
        {% if status == true %}
            <a href="/off">Turn Off</a>
        {% else %}
            <a href="/on">Turn On</a>
        {% endif %}
    </h3>
</body>
</html>

 

- 끝 -

728x90