C#

2020.07.28(화) - 라즈베리파이 & C#

J_Bin 2020. 7. 28. 18:28

*라즈베리파이

 

1-1-1. Flask 웹서버

 

title 제목달기

 

ul은 순서가 없는 목록, ol은 순서가 있는 목록
"<!doctype html> <html lang=\"ko\"> <head> <meta charset=\"utf-8\"> <title>HTML</title> </head> <body> <img src=\"https://www.kfq.or.kr/admin/img/logo.gif\" alt=\"My Image\"><br><img src=\"https://www.kfq.or.kr/images/intro/kfq_intro_171130.gif\" alt=\"My Image\"> </body> </html>"
checkbox, textbox 설정하기 : <!doctype html> <html lang=\"ko\"> <head> <meta charset=\"utf-8\"> <title>HTML</title> </head> <body> <p> <label for=\"jb-input-text\">Input - Text</label> <input type=\"text\" id=\"jb-input-text\"> </p> <p> <label for=\"jb-input-checkbox\">Input - Checkbox</label> <input type=\"checkbox\" id=\"jb-input-checkbox\"> </p> </body> </html>

 

1-1-2. 웹페이지를 구축하여 LED on/off 하기 (버튼생성)

from flask import Flask, request
from flask import render_template
import RPi.GPIO as GPIO

app = Flask(__name__)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(21, GPIO.OUT, initial=GPIO.LOW)

@app.route("/")
def home():
	return render_template("index.html")

@app.route("/led/on")
def led_on():
	try:
		GPIO.output(21, GPIO.LOW)
		return "ok"
	except expression as identifier:
		return "fail"

@app.route("/led/off")
def led_off():
	try:
		GPIO.output(21, GPIO.HIGH)
		return "ok"
	except expression as identifier:
		return "fail"

if __name__ == "__main__":
	app.run(host="0.0.0.0")


//index.py
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>HOME NETWORK</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css')}}" />
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>HOME IoT</h2>
        </div>
        <div class="main">
            <div>
                <button onclick="led_on()">LED ON</button>
            </div>
            <div>
                <button onclick="led_off()">LED OFF</button>
            </div>
        </div>
        <div id="result">

        </div>
    </div>
    <script>
        function led_on() {
            fetch("/led/on")
                .then(response => response.text())
                .then(data => {
                    console.log(data);
                    let result = document.querySelector("#result");
                    if (data == "ok") {
                        result.innerHTML = "<h1>LED is running</h1>";
                    } else {
                        result.innerHTML = "<h1>error</h1>";
                    }
                });
        }
        function led_off() {
            fetch("/led/off")
                .then(response => response.text())
                .then(data => {
                    console.log(data);
                    let result = document.querySelector("#result");
                    if (data == "ok") {
                        result.innerHTML = "<h1>LED is stoping</h1>";
                    } else {
                        result.innerHTML = "<h1>error</h1>";
                    }
                });
        }
    </script>
</body>
</html>


//index.html
body {
    background-color: antiquewhite;
}

.container {
    width: 700px;
    margin: 0 auto;
    text-align: center;
}

.main {
    display: flex;
}

    .main div {
        flex: 1;
    }

        .main div button {
            background-color: rgb(192, 114, 114);
            width: 150px;
            height: 80px;
            border-radius: 10px;
        }

// style.css

 

* C# Review

-네트워크

-프로그램을 만들 때 포트번호를 명시해줘야 한다.

 

1-1-1. Network

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace _2020._07._28_001
{
    class Program
    {
        static void Main(string[] args)
        {   // IP주소 다루기
            //IPAddress ipAddr = IPAddress.Parse("202.179.177.21");
            //Console.WriteLine(ipAddr);
            //IPAddress ipAddr2 = new IPAddress(new byte[] { 202, 179, 177, 21 });
            //Console.WriteLine(ipAddr2);

            // 아이피 주소와 포트번호를 할당하여 endPoint 객체 생성
            //IPAddress ipAddr3 = IPAddress.Parse("192.168.0.1");
            //IPEndPoint endPoint = new IPEndPoint(ipAddr3, 9000);

            //현재 컴퓨터에 할당된 IP 주소 출력
            string myComputer = Dns.GetHostName();
            Console.WriteLine("컴퓨터 이름: " + myComputer);
            IPHostEntry entry = Dns.GetHostEntry(myComputer);
            foreach(IPAddress ipAddress in entry.AddressList    )
            {
                Console.WriteLine(ipAddress.AddressFamily + ": " + ipAddress);
            }

        }
    }
}

1-1-2. Socket

using System;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        Socket Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        // Any : 현재 내 컴퓨터에 할당된 IP아무거나, 포트번호 : 7000
        Server.Bind(new IPEndPoint(IPAddress.Any, 7000));
        Server.Listen(100);
        // 블로킹메서드(socket)
        Socket Client = Server.Accept();
        Console.WriteLine("Client Incomming");

        byte[] Buffer = new byte[] { 65, 66, 67, 68 };
        // send가 char형으로 안보내줌
        Client.Send(Buffer);


        Client.Close();
        Server.Close();
    }



}

 

데이터를 어떻게 보내는지 잘 알아야함.

1-1-3. putty로 접속

내 아이피주소, port번호

 

c# 의 서버가 받았다!