이론





***pulse_duration * 17000 ?***

속도 공식(속도 = 거리 / 시간)에 따라, 속도(340m/s라고 함) = 거리(x) / 시간(duration/2)

duration/2 : 초음파센서의 원리가 초음파를 내보내고(1번) 돌아오기까지의(2번) 시간을 측정하는 것이므로 거리를 2번지난것과 같음

따라서 거리(x) = 속도(340) * 시간(duration/2)

duartion * (340m/s / 2) -> duration * (170m/s) -> m를 cm로 바꾸면 -> duration * 17000



[Flask(플라스크) 서버 구축]

sudo pip3 install flask  



*** index.html 코드 내용도 정상, 파일경로도 정상인데 자꾸 Internal Server Error가 뜨면, 넷빈즈에서 Webbrower로 새 프로젝트 만든후, 디폴트로 생기는 index.html에 작성해서 fileZilla로 업로드 해볼것!!! ***





실습


hc_demo.py

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
import RPi.GPIO as gpio
import time
gpio.setmode(gpio.BCM)
trig = 13
echo = 19
led_pin = 18
buz_pin=12
print("start")
gpio.setwarnings(False)
gpio.setup(trig,gpio.OUT)
gpio.setup(led_pin, gpio.OUT)
gpio.setup(echo, gpio.IN)
gpio.setup(buz_pin, gpio.OUT)
try:
    while True:
        gpio.output(trig, False)
        time.sleep(0.5)
        gpio.output(trig, True)
        time.sleep(0.00001)
        gpio.output(trig, False)
        pulse_end = 0
        pulse_start = 0
        while gpio.input(echo) == 0:
            pulse_start = time.time()
        while gpio.input(echo) == 1:
            pulse_end = time.time()
        pulse_duration = pulse_end -  pulse_start
        distance = pulse_duration * 17000
        distance = round(distance,2)
        if distance >= 10: #cm
            gpio.output(led_pin,False)
            gpio.output(buz_pin,False)
        else:
            gpio.output(led_pin, True)
            gpio.output(buz_pin, True)
        print("Distance : ", distance, "cm")
except KeyboardInterrupt as e:
    print(e)
finally:
    print("clean up...")
    gpio.cleanup()

hcr0531_java

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
package ultrawave0531;
  
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jdk.dio.gpio.GPIOPin;
  
public class Hcr0531 {
     
     public static int getDistance(GPIOPin trigPin, GPIOPin echoPin){
        int distance = 0;
        try {
            //펄스를 10마이크로초 동안 발생
            trigPin.setValue(true);
            Thread.sleep(0, 10000);
            trigPin.setValue(false);
            //high 수신 시작일 때 시간 측정
            while(echoPin.getValue() ==false){}
            double startTime = System.nanoTime();
            //low 수신 시작일 때 시간 측정
            while(echoPin.getValue() ==true){}
            double endTime = System.nanoTime();
            double distance_val = (endTime - startTime)/1000000000/2;
            distance = (int) (distance_val * 34000); //cm단위
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return distance;
    }
}

FXMLDocumentController.java

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
package ultrawave0531;
  
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import jdk.dio.ClosedDeviceException;
import jdk.dio.DeviceManager;
import jdk.dio.gpio.GPIOPinConfig;
import jdk.dio.gpio.GPIOPin;
  
/**
 *
 * @author kosta
 */
public class FXMLDocumentController implements Initializable {
  
    @FXML
    private Label lbDistance;
    private boolean flag;
    private LED led;
    private LED buz;
  
    @FXML
    private void handleButtonAction(ActionEvent event) {
        try {
            led = new LED(27);
            buz = new LED(12);
  
            System.out.println("You clicked me!");
            GPIOPin trigPin = DeviceManager.open(new GPIOPinConfig.Builder()
                    .setPinNumber(13)
                    .setDirection(GPIOPinConfig.DIR_OUTPUT_ONLY).build()); //gpio.setup(변수명, gpio.OUT)와 동일
  
            GPIOPin echoPin = DeviceManager.open(new GPIOPinConfig.Builder()
                    .setPinNumber(19)
                    .setDirection(GPIOPinConfig.DIR_INPUT_ONLY).build());
  
            //스레드!!!
            Thread th = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("thread start...");
                    while (!flag) {
                        try {
                            Thread.sleep(200);
                        } catch (Exception e) {
                        }
                        int distance = Hcr0531.getDistance(trigPin, echoPin);
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if (distance < 10) {
                                        led.on();
                                        buz.on();
                                    } else {
                                        led.off();
                                        buz.off();
                                    }
                                } catch (Exception e) {
                                }
                                lbDistance.setText(String.valueOf(distance));
                            }
                        });
                    }//while문 끝
                    try {
                        trigPin.close();
                        echoPin.close();
                    } catch (IOException ex) {
                    }
                }
            });
            th.setDaemon(true);
            th.start();
        } catch (Exception ex) {
        }
         
        //종료시...
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                try {
                    led.close();
                    buz.close();
                } catch (IOException ex) {
                }
            }
        });
    }
  
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        try {
        } catch (Exception ex) {
        }
    }
}

web_server.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from flask import Flask
app = Flask(__name__)
  
@app.route('/')
def index():
    return "This is main page"
  
@app.route('/sub')
def sub():
    return "This is sub page"
  
@app.route('/led/<state>')
def led(state):
    if state == "on" or state == "off":
        str = "Led is now %s." %state
    else:
        str = "Invalid Pages"
    return str
  
if __name__ == "__main__":
    print("Webserver stasrts...")
    app.run(host="192.168.0.164")

web_server2.py

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
from flask import Flask, render_template, request
import RPi.GPIO as GPIO
  
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
  
buz_pin = 12  # buz
GPIO.setup(buz_pin, GPIO.OUT)
  
app=Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html')
  
#index.html에서 on/off를 클릭 했을 경우 파라미터를 처리하기 위한 route
@app.route('/param',methods=['GET','POST'])
def params():
    if request.method == 'GET':
        paramv = request.args.get('status', '')
        print('status:'+paramv)
        if paramv == "on":
            GPIO.output(buz_pin, True)
        elif paramv == "off":
            GPIO.output(buz_pin,False)
        return paramv
  
if __name__ =='__main__':
    print('Webserver starts')
    app.run(host='0.0.0.0')


'학원수업 > 파이썬' 카테고리의 다른 글

학원 50일차 복습(5/30)  (0) 2018.05.30
학원 49일차 복습(5/29)  (0) 2018.05.29
학원 48일차 복습(5/28)  (0) 2018.05.28
학원 45일차 복습(5/18)  (0) 2018.05.23
학원 44일차 복습(5/17)  (0) 2018.05.17

이론





***플로팅 상태란 ?***

디지털 신호에는 1과 0으로 표현되지만 1도 아니고 0도 아닌 애매모호한 상태가 있습니다. 이 상태를 우리는 떠있다 혹은 플롯 상태라고 정의합니다. 이 상태에서는 주변의 전기장 상태에 따라 입력 값이 불안정하게 변하기 때문에 부정전압으로 오작동이 생기게 됩니다.이러한 상태를 해결하기 위한것이 바로 풀업 저항과 풀다운 저항 회로입니다.


**풀업 / 풀다운***

풀업 저항 :

+(5V. 3.3V)쪽에 저항을 연결해주는 방법.

전류가 항상 VCC(+) 쪽으로 흐르기 때문에, 스위치를 누르지 않아도 1(HIGH)의 신호를 갖게되며, 스위치를 누를경우 0(LOW)상태가 됩니다.


풀다운 저항 :

그라운드(GND, -)쪽에 저항을 연결해주는 방법

스위치를 누르지 않으면 전류가 GND로 흐르기때문에, 0의 상태가 유지되며 스위치를 누를경우 1의 상태가 됨


PWM(Pulse Width Modulation : 펄스신호) : 부저의 소리를 줄이고 낮추는 등에 사용


https://github.com/aterrien/jQuery-Kontrol 에서 zip파일을 다운받고


[초음파 회로 그려보기]

1.http://fritzing.org/projects/hc-sr04-project 에서 HC-SR04.fzpz 파일 다운받기 

2.프리징에 드래그앤드롭해서, 초음파(HC-SR04.fzpz) Import하고 회로도 만들기




실습


btn_LedDemo0529.py

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
#btn_LedDemo0529.py
import RPi.GPIO as GPIO
from time import sleep
 
class Btn_Led():
    def __init__(self):
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
 
        self.led_pin = 27 #red
        self.led_pin1 = 17 #blue
        self.btn_pin=21 #button
        self.buz_pin=12 #buz
 
        GPIO.setup(self.led_pin,GPIO.OUT)
        GPIO.setup(self.led_pin1, GPIO.OUT)
        GPIO.setup(self.btn_pin, GPIO.IN) #눌러서 상태값 변경
        GPIO.setup(self.buz_pin, GPIO.OUT)
 
    def execProcess(self):
        try:
            while True:
                inputIO = GPIO.input(self.btn_pin) #button
                if inputIO == False:
                    GPIO.output(self.led_pin,True)
                    GPIO.output(self.led_pin1, True)
                    GPIO.output(self.buz_pin, True)
                    sleep(1)
                else:
                    GPIO.output(self.led_pin,False)
                    GPIO.output(self.led_pin1, False)
                    GPIO.output(self.buz_pin, False)
                    sleep(1)
 
        except KeyboardInterrupt:
            GPIO.cleanup()
 
if __name__ == "__main__":
    btn = Btn_Led()#생성자
    btn.execProcess()


pwmDial.0530.py

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
import RPi.GPIO as GPIO
led_pin = 27
led_pin1 = 25
buz_pin = 12 #buz
  
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(led_pin, GPIO.OUT)
GPIO.setup(led_pin1, GPIO.OUT)
GPIO.setup(buz_pin, GPIO.OUT)
#1.pwd 초기화, 핀번호, 주파수
pwm_led = GPIO.PWM(led_pin,500)
pwm_led1 = GPIO.PWM(led_pin1,500)
pwm_buz = GPIO.PWM(buz_pin,500)
  
#출력 100 duty cycle 설정
pwm_led.start(100)
pwm_led1.start(100)
pwm_buz.start(0)
try:
    while True:
        duty_str = input("입력 (1~100) : ")
        duty = int(duty_str)
        if duty > 100:
            print("초기값을 넘었습니다")
        else:
            pwm_led.ChangeDutyCycle(duty)
            pwm_led1.ChangeDutyCycle(duty)
            pwm_buz.ChangeDutyCycle(duty)
        end_key = input("end를 입력하면 멈춥니다")
        if end_key == "end":
            break;
  
except KeyboardInterrupt as e:
    GPIO.cleanup()


pwmDialExam0530.py

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
from urllib.request import urlopen
  
from PyQt5 import QtCore, QtGui, QtWidgets
import RPi.GPIO as GPIO
import threading
import time
class Ui_Dialog(object):
  
    def __init__(self):
        t1 = threading.Thread(target=self.getUrl)
        t1.daemon=True
        t1.start()
    def getUrl(self):
        print("url")
        self.myUrl()
    def myUrl(self):
        while True:
            time.sleep(2)
            url = "http://192.168.0.116/20180530/f5.jsp" #send number
            with urlopen(url) as f:
                doc = f.read().decode()
                self.dial.setValue(int(doc))
                #self.pwm_led.ChangeDutyCycle(doc)
                #self.pwm_led1.ChangeDutyCycle(doc)
                print(doc)
  
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(381, 215)
        self.dial = QtWidgets.QDial(Dialog)
        self.dial.setGeometry(QtCore.QRect(210, 50, 121, 111))
        self.dial.setObjectName("dial")
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(70, 90, 141, 31))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(16)
        self.label.setFont(font)
        self.label.setObjectName("label")
  
        #연습문제2(exam_pwmDial.py) : pwd를 적용해서 led의 밝기와 부저 소리의 크기를 조절하도록 구현하기
        self.led_pin = 27  # red
        self.led_pin1 = 25  # blue
        self.buz_pin = 12 #buz
  
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        GPIO.setup(self.buz_pin, GPIO.OUT)
        GPIO.setup(self.led_pin, GPIO.OUT)
        GPIO.setup(self.led_pin1, GPIO.OUT)
  
        #최솟값, 최댓값 설정
        self.dial.setMinimum(0)
        self.dial.setMaximum(100)
  
        self.pwm_buz = GPIO.PWM(self.buz_pin, 100)
        self.pwm_led = GPIO.PWM(self.led_pin, 100)
        self.pwm_led1 = GPIO.PWM(self.led_pin1, 100)
  
        #출력사이클 설정
        self.pwm_buz.start(0)
        self.pwm_led.start(0)
        self.pwm_led1.start(0)
  
        #dial에 변화된 값 이벤트를 감지해서, 콜백메서드 호출시 값을 전달함
        self.dial.valueChanged.connect(self.dial_value_change)
  
        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
  
    def dial_value_change(self,value):
        self.label.setText("Dial : "+str(value))
        self.pwm_buz.ChangeDutyCycle(value)
        self.pwm_led.ChangeDutyCycle(value)
        self.pwm_led1.ChangeDutyCycle(value)
  
        url = "http://192.168.0.116/20180530/LedProcess.jsp?number="+str(value)  # send number
        with urlopen(url) as f:
            doc = f.read().decode()
            print("value changed : "+doc)
  
    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.label.setText(_translate("Dialog", "PWM : 0"))
  
  
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())


'학원수업 > 파이썬' 카테고리의 다른 글

학원 51일차 복습(5/31)  (0) 2018.05.31
학원 49일차 복습(5/29)  (0) 2018.05.29
학원 48일차 복습(5/28)  (0) 2018.05.28
학원 45일차 복습(5/18)  (0) 2018.05.23
학원 44일차 복습(5/17)  (0) 2018.05.17

이론




파이참에서 setting->ProjectInterpreter-> 초록색 + 에서 필요한것 install Package 가능

Pyqt5를 인스톨하여 파이참에서도 UI창 사용가능


파이썬이 서버일때의 장점 :라즈베리가 서버가 되면, 하드웨어들의 연동이 가능해진다.





실습


Ex1_Server.java

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
package ex1;
 
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
 
//서버 코드: 클라이언트로부터 소켓의 연결 요청이 오면 accept()메서드가 호출이 되어서 Socket객체를 반환하고
//다중 소켓을 처리하기 위해서 ArrayList에 적재한다.
//이때 ArrayList에 들어갈 소켓들은 스레드가 담당하게 되며, 접속한 클라이언트당 소켓이 각각 ArrayList에 들어가게 되는 구조이다.
//Thread는 결국 각 소켓의 연결된 스트림을 담당하게 되고 서버는 이 스트림을 통해서 각각의 클라이언트에게 응답메세지를 전달하게 된다.
 
public class Ex1_Server {
    private ServerSocket ss;
    private ArrayList<ServerThread> clist;
    private String reip;
 
    public Ex1_Server(int port) {
            //2. 생성자 초기화
            //소켓생성, ServerThread를 저장할 ArrayList생성
        try {
            ss= new ServerSocket(port);
            clist = new ArrayList<>();
            System.out.println("Start Server!");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    public void execute(){
        //4.무한반복하면서 Socket의 accept() 접속을 대기한다.
        while(true){
            try {
                Socket s = ss.accept();
                //----------------------
                //6.접속해온 클라이언트의 소켓을 ServerThread가 관리하도록 한명이 접속해 올때 마다 생성시켜두고
                //이것을 Generic로 가지고 있는 ArrayList에 그 주소를 넣어서 소켓의 주소를 메모리영역에 참조하게 한다.
                // 스레드는 start한다.
                ServerThread ct = new ServerThread(s,this);
                clist.add(ct); //ArrayList에 클라이언트를 담당할 스레드를 저장한다.
                ct.start(); // 스레드를 시작한다.
                System.out.println("Current number of Clients :"+clist.size());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
             
        }
    }
 
    public void sendMsg(String str1, String str2, String str3, String reip) {
        // str1/str2/str3/str4/str5
        //서버를 제작할? 각 조에 맞는 프로토콜을 설계하기 바람
        String str = "";
        if(str1.equals("msg")){
            str = "msg/["+reip+"]"+str2+"/"+str3;
        }else if(str1.equals("enter")){
            //이런식으로... x/y/color등을 보낼 수 있다.
            str= "enter/"+str2+"/"+str3;
        }
        //모든 유저에게 브로드캐스팅을 한다.
        //모든 유저는 for문을 사용해서
        for(ServerThread c : clist){
            c.getPw().println(str);
        }
    }
    public static void main(String[] args) {
        //1. 서버 시작을 위해서 port를 9999번으로 입력한 서버객체를 생성한다.
        Ex1_Server es = new Ex1_Server(9999);
        //3. 생성된 Ex1_Server객체의 execute메서드를 호출한다.
        es.execute();
    }
}

FXMLDocumentController.java

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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaclient0529;
 
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
 
public class FXMLDocumentController implements Initializable {
 
    @FXML
    private TextField hostv, portv, userv,msgv;
    @FXML
    private TextArea chatmsgv;
    //StackPane 가져오기
    @FXML
    private StackPane rootP;
    private ObservableList<Node> childs;
    private Node firstNode, secondNode;
    private Socket s;
    //사용자 이름
    private String userName;
    private boolean flag;
    private String[] token;
 
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        childs = rootP.getChildren();
        firstNode = childs.get(childs.size() - 1);
        secondNode = childs.get(childs.size() - 2);
    }
 
    //첫번째 Pane에서 소켓으로 접속하는 버튼
    @FXML
    private void connectButtonAction(ActionEvent event) {
        //SocketServerDemo.Ex1_Server에 접속하기 위해서 소켓을 연결한다.
        try {
            userName=userv.getText().trim();
            s = new Socket(hostv.getText().trim(), Integer.parseInt(portv.getText().trim()));
            firstNode.setVisible(false);
            firstNode.toBack();
            secondNode.setVisible(true);
            PrintWriter out = new PrintWriter(s.getOutputStream(),true);
            //enter/user/null/null
            //msg/user/message/null
            //btn/user/value/null
            //통신규약을 가지고 서버로 전송한다.
            out.println("enter/"+userName+"/null/null");
            responseThread();
        } catch (IOException ex) {
        }
    }
     
     private void responseThread() {
         Thread th = new Thread(new Runnable() {
             @Override
             public void run() {
                 BufferedReader br = null;
                 try {
                     br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                     while(!flag){
                         String msg = br.readLine();
                         Platform.runLater(new Runnable() {
                             @Override
                             public void run() {
                                 token = msg.split("/");
                                 String message = "";
                                 if(token[0].equals("enter")){
                                     message=token[1]+" 님이 들어왔어요! \n";
                                 }else if(token[0].equals("msg")){
                                     message="["+token[1]+"]"+token[2]+"\n";
                                 }
                                 chatmsgv.appendText(message);
                             }
                         });
                     }
                 } catch (IOException ex) {
                     ex.printStackTrace();
                 }finally{
                     try {
                         if(br != null) br.close();
                     } catch (IOException ex) {
                         ex.printStackTrace();
                     }
                 }
             }
         });
         th.setDaemon(true);
         th.start();
    }
      
    @FXML
    private void sendMessageAction(ActionEvent event) {
        String msg = msgv.getText().trim();
        //msg/user/message/null
        StringBuffer msgBuf = new StringBuffer();
        msgBuf.append("msg/").append(userName).append("/").append(msg).append("/null");
        try {
            sendData(msgBuf.toString());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
     
    private void sendData(String data) throws IOException{
        PrintWriter out = new PrintWriter(new BufferedOutputStream(s.getOutputStream()),true);
        out.println(data);
    }
    @FXML
    private void exitButtonAction(ActionEvent event) {
        secondNode.setVisible(false);
        secondNode.toBack();
        firstNode.setVisible(true);
    }
 
    // 두번째 버튼들.. red,blue,all ->Led값을 전송
    //protocol형식으로 전송
    @FXML
    private void redLedButtonAction(ActionEvent event) {
    }
 
    @FXML
    private void blueLedButtonAction(ActionEvent event) {
    }
 
    @FXML
    private void allLedButtonAction(ActionEvent event) {
    }
}

echoSocket0529.py

1
2
3
4
5
6
7
8
9
10
11
12
13
#echoSocket0529.py
import socket
HOST = '192.168.0.115'
PORT = 9999
def run():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST,PORT))
        line = input('Msg:')
        s.sendall(bytes(line+"\n",'ascii'))
        resp = s.recv(1024)
        print(resp.decode())
if __name__=='__main__':
    run()

echoSocketServer0529.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#echoSocketServer0529.py
import socketserver
import time
HOST = ""
PORT = 9999
class MyTcpHandler(socketserver.BaseRequestHandler):
    def handle(self):
        print("[%s] connect"%self.client_address[0])
        try:
            while True:
                self.data = self.request.recv(1024)
                print("[%s]"%self.data.decode())
 
        except Exception as e:
            print(e)
def runServer():
    print("Echo서버 시작")
    print("에코서버 중지는 ctrl+C")
    try:
        server = socketserver.TCPServer((HOST,PORT),MyTcpHandler)
        server.serve_forever()
    except KeyboardInterrupt:
        print("에코서버 종료")
runServer()

EchoSocketServerLed0529.py

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
#EchoSocketServerLed0529.py
import RPi.GPIO as GPIO
from time import sleep
import socketserver
import time
HOST=""
PORT=9999
class MyTcpHandler(socketserver.BaseRequestHandler):
    def handle(self):
        print("__init__")
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        self.led_pin = 27
        self.led_pin1 = 17
        GPIO.setup(self.led_pin, GPIO.OUT)
        GPIO.setup(self.led_pin1, GPIO.OUT)
        print("[%s] connect" % self.client_address[0])
        try:
            while True:
                self.data = self.request.recv(1024)
                print("[%s]" % self.data.decode())
                # bytes(line+"\n", 'ascii')
                toks = self.data.decode()
                t1 = toks.split("/")
                print("Message Log=============================")
                print(t1[0])
                print(t1[1])
                print(t1[2])
                if t1[0] == "enter" or t1[0] == "msg":
                    self.request.sendall(self.data)
                else:
                    if t1[2] == "red":
                        print("Red Led On")
                        GPIO.output(self.led_pin, True)
                        GPIO.output(self.led_pin1, False)
                        self.request.sendall("btn/null/RedLedOn/null \n".encode())
                        sleep(1)
                    elif t1[2] == "blue":
                        print("Blue Led On")
                        GPIO.output(self.led_pin, False)
                        GPIO.output(self.led_pin1, True)
                        self.request.sendall("btn/null/BlueLedOn/null \n".encode())
                        sleep(1)
                    elif t1[2] == "all":
                        GPIO.output(self.led_pin, False)
                        GPIO.output(self.led_pin1, False)
                        self.request.sendall("btn/null/ALLLedOff/null \n".encode())
                        # GPIO.cleanup()
                        sleep(1)
        except Exception as e:
            print(e)
            GPIO.cleanup()
 
 
def runServer():
    print("Echo서버 시작")
    print("에코서버 중지는 Ctrl+C")
    try:
        server = socketserver.TCPServer((HOST, PORT), MyTcpHandler)
        server.serve_forever()
    except KeyboardInterrupt:
        server.server_close()
        print("에코서버 종료")
runServer()


'학원수업 > 파이썬' 카테고리의 다른 글

학원 51일차 복습(5/31)  (0) 2018.05.31
학원 50일차 복습(5/30)  (0) 2018.05.30
학원 48일차 복습(5/28)  (0) 2018.05.28
학원 45일차 복습(5/18)  (0) 2018.05.23
학원 44일차 복습(5/17)  (0) 2018.05.17

이론




mkdir pythonDevice

sudo apt-get update

sudo apt-get install –y python-dev python-setuptools

git clone git://git.drogon.net/wiringPi

cd wiringPi/

 ./build

git clone https://github.com/Gadgetoid/WiringPi2-Python.git

cd WiringPi2-Python

sudo python3 setup.py install


LED확인을 위해 c코드로 확인

gcc led_test.c -o led_test -lwiringPi

./led_test 로 실행


gpio readall 입력시



ui파일 py파일로 변환하기

pyuic5 -x holjak.ui -o holjak.py -> pyuic5 [.ui위치].ui [저장위치].py



*** $(this) : 어떤 버튼을 클릭하든, 그 버튼의 주소값을 받아온다 ***

attr()요소는 선택한 선택자 : onBtn,offBtn의 value인 속성의 값을 가져옴


GPIO관련 메서드들


실습


led_test.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <wiringPi.h>
#define LED1 27
int main(void)
{
    printf("Test GPIO\n");
    //setup실패시 -1값을 리턴한다.
    if(wiringPiSetupGpio() == -1){
        return 1;
    }
    pinMode(LED1,OUTPUT);
    while(1){
    digitalWrite(LED1,1);
    delay(500);
    digitalWrite(LED1,0);
    delay(500);
    }
}

ledtest.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import RPi.GPIO as GPIO
from time import sleep
 
PIN1 = 27
PIN2 = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN1, GPIO.OUT)
GPIO.setup(PIN2, GPIO.OUT)
 
try:
    while True:
        GPIO.output(PIN1, 1)
        GPIO.output(PIN2, 0)
        sleep(0.5)
        GPIO.output(PIN1, 0)
        GPIO.output(PIN2, 1)
        sleep(0.5)
 
except KeyboardInterrupt:
    GPIO.cleanup()

holjack.py

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
import threading
from time import sleep
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from urllib.request import urlopen
 
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(683, 376)
        font = QtGui.QFont()
        font.setFamily("Arial")
        Form.setFont(font)
        Form.setStyleSheet("background-color: rgb(0, 255, 127);")
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(120, 80, 251, 51))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(22)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(60, 200, 141, 121))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(22)
        self.pushButton.setFont(font)
        self.pushButton.setStyleSheet("background-color: rgb(255, 0, 0);")
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(260, 200, 151, 121))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(22)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setStyleSheet("background-color: rgb(0, 85, 255);")
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_3 = QtWidgets.QPushButton(Form)
        self.pushButton_3.setGeometry(QtCore.QRect(480, 200, 141, 121))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(22)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setStyleSheet("background-color: rgb(0, 170, 0);")
        self.pushButton_3.setObjectName("pushButton_3")
        self.retranslateUi(Form)
        self.pushButton.clicked.connect(self.hol1)
        self.pushButton_2.clicked.connect(self.jack1)
        self.pushButton_3.clicked.connect(self.gend)
        QtCore.QMetaObject.connectSlotsByName(Form)
 
        t1 = threading.Thread(target=self.getUrl)
        t1.daemon = True
        t1.start()
 
    def myUrl(self):
        while True:
            url="http://192.168.0.115/pyforweb0528/ledResp.jsp"
            with urlopen(url) as f:
                docs = f.read().decode()
                if docs == "1":
                    print("Service On")
                    sleep(1)
                elif docs == "2":
                    print("Service Off")
                    sleep(1)
                else:
                    print("Service Not")
                    sleep(1)
    def getUrl(self):
        print("Starting Thread")
        self.myUrl()
        print("Exiting")
    def hol1(self):
        print("Hol clicked")
        self.sendNum(1)
    def jack1(self):
        print("Jack clicked")
        self.sendNum(2)
    def gend(self):
        print("Gend clicked")
        self.sendNum(3)
    def sendNum(self,inputv):
        print(str(inputv))
        with urlopen(url) as f:
            doc = f.read().decode()
 
    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "My Hol Jak"))
        self.pushButton.setText(_translate("Form", "Hol"))
        self.pushButton_2.setText(_translate("Form", "Jack"))
        self.pushButton_3.setText(_translate("Form", "End"))
 
 
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

holjackGpio.py

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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import RPi.GPIO as GPIO
import threading
from time import sleep
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from urllib.request import urlopen
 
class Ui_Form(object):
 
    def __init__(self):
        print("__init__")
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        self.PIN1 = 27
        self.PIN2 = 17
        GPIO.setup(self.PIN1, GPIO.OUT)
        GPIO.setup(self.PIN2, GPIO.OUT)
 
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(683, 376)
        font = QtGui.QFont()
        font.setFamily("Arial")
        Form.setFont(font)
        Form.setStyleSheet("background-color: rgb(0, 255, 127);")
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(120, 80, 251, 51))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(22)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(60, 200, 141, 121))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(22)
        self.pushButton.setFont(font)
        self.pushButton.setStyleSheet("background-color: rgb(255, 0, 0);")
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        self.pushButton_2.setGeometry(QtCore.QRect(260, 200, 151, 121))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(22)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setStyleSheet("background-color: rgb(0, 85, 255);")
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_3 = QtWidgets.QPushButton(Form)
        self.pushButton_3.setGeometry(QtCore.QRect(480, 200, 141, 121))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setPointSize(22)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setStyleSheet("background-color: rgb(0, 170, 0);")
        self.pushButton_3.setObjectName("pushButton_3")
        self.retranslateUi(Form)
        self.pushButton.clicked.connect(self.hol1)
        self.pushButton_2.clicked.connect(self.jack1)
        self.pushButton_3.clicked.connect(self.gend)
        QtCore.QMetaObject.connectSlotsByName(Form)
 
        t1 = threading.Thread(target=self.getUrl)
        t1.daemon = True
        t1.start()
 
    def myUrl(self):
        while True:
            url="http://192.168.0.115/pyforweb0528/ledResp.jsp"
            with urlopen(url) as f:
                docs = f.read().decode()
                if docs == "1":
                    print("Service On")
                    sleep(1)
                    GPIO.output(self.PIN1, 1)
                    GPIO.output(self.PIN2, 0)
                elif docs == "2":
                    print("Service Off")
                    GPIO.output(self.PIN1, 0)
                    GPIO.output(self.PIN2, 1)
                    sleep(1)
                else:
                    print("Service Not")
                    GPIO.output(self.PIN1, 0)
                    GPIO.output(self.PIN2, 0)
                    sleep(1)
    def getUrl(self):
        print("Starting Thread")
        self.myUrl()
        print("Exiting")
    def hol1(self):
        print("Hol clicked")
        self.sendNum(1)
    def jack1(self):
        print("Jack clicked")
        self.sendNum(2)
    def gend(self):
        print("Gend clicked")
        self.sendNum(3)
    def sendNum(self,inputv):
        print(str(inputv))
        with urlopen(url) as f:
            doc = f.read().decode()
 
    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "My Hol Jak"))
        self.pushButton.setText(_translate("Form", "Hol"))
        self.pushButton_2.setText(_translate("Form", "Jack"))
        self.pushButton_3.setText(_translate("Form", "End"))
 
 
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

respData.jsp

1
2
3
4
5
6
7
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
    //라즈베리의 Python에서 디자인한 버튼 값을 받기 위한 파라미터
    int number = Integer.parseInt(request.getParameter("number"));
    System.out.println(number);
%>

ledResp.jsp

1
2
3
4
5
6
7
8
<%@ page import="ex1.StateNumber"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page trimDirectiveWhitespaces="true"%>
<%
    String savedStatus = StateNumber.getStateNumber().view();
    System.out.println("View : "+savedStatus);
%><%=savedStatus%>

StateNumber.java

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
package ex1;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
 
public class StateNumber {
     
    private static StateNumber stateNumber;
    //String path ="";
    private static final String PATH = "C:\\kosta182\\spring\\workspace\\pyforweb0528\\src\\ex1\\status.txt";
    public synchronized static StateNumber getStateNumber() {
        if(stateNumber == null) stateNumber = new StateNumber();
        return stateNumber;
    }
     
    public void save(String status) {
        try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(PATH))){
            dos.writeInt(Integer.parseInt(status));
            System.out.println("저장된 상태값 :"+status);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    public String view() {
        String status="";
        try(DataInputStream dis = new DataInputStream(new FileInputStream(PATH))){
            status = String.valueOf(dis.readInt());
        }catch (Exception e) {
            e.printStackTrace();
        }
        return status;
    }
 
}


'학원수업 > 파이썬' 카테고리의 다른 글

학원 50일차 복습(5/30)  (0) 2018.05.30
학원 49일차 복습(5/29)  (0) 2018.05.29
학원 45일차 복습(5/18)  (0) 2018.05.23
학원 44일차 복습(5/17)  (0) 2018.05.17
학원 43일차 복습(5/16)  (0) 2018.05.16

이론


thread 두가지 종류: kernel thread, user thread

kernal Thread : 임의의 메서드를 지정, 호환성 문제때문에 잘 안쓰임. _thread

user_Thread : threading 모듈을 상속, run 함수


python3 thread 지원 모듈 _thread, threading

_thread는 권장사항은 아니나 이전 모듈과의 호환성을 위해서 유지

_thread.start_new_thread(function,args[,kwargs])


사용사례 PyQt에서 정의하는 클래스가 이미 class Form(QtWidgets.QDialog): 처럼 다른 클래스를 상속 받았다면, 스레드를 상속받지 않고 바로 사용할 수 있는 형태

자바에서 Runnable 인터페이스를 구현한 클래스로 인자로 전달하여 스레드를 생성해서 사용하는 것과 같음!


target지정하면 내부적으로 run()메서드가 호출되어서 target메서드를 호출!



실습


ex1_thread.py

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
#ex1_thread.py
#thread에선 두가지 종류
#kernel thread, user thread
#python3 thread 지원 모듈 _thread, threading
#_thread는 권장사항은 아니나 이전 모듈과의 호환성을 위해서 유지
#_thread.start_new_thread(function,args[,kwargs])
import _thread
import time
  
def print_time(threadName,delay):
    count=0
    while count < 5:
        time.sleep(delay)
        count += 1
        print("%s : %s" %(threadName, time.ctime(time.time())))
  
#create tow threads as follows
try:
    _thread.start_new_thread(print_time,("thread1",2,))
    _thread.start_new_thread(print_time,("thread2",4,))
except:
    print("error : unable to start thread")
  
#주 스레드가 종료되기 전에 모든 스레드가 완료될때까지 대기하기 위함
while 1 :
    pass

ex1_threading.py

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
#ex1_threading.py
import threading
import time
exitFlag = 0
class myThread(threading.Thread):
    def __init__(self,threadID,name,counter):
        threading.Thread.__init__(self)
        self.threadID=threadID
        self.name=name
        self.counter=counter
    def run(self):
        print("Start Thread"+self.name)
        print_time(self.name,self.counter,5)
        print("Exiting" + self.name)
def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print("%s %s"%(threadName,time.ctime(time.time())))
        counter -= 1
#Create new Threads
thread1 = myThread(1,"Thread-1",1)
thread2 = myThread(2,"Thread-2",2)
#start new Thread
thread1.start()
thread2.start()

ex2_threading_target.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#ex2_threading_target.py
import threading
import time
from urllib.request import urlopen
#사용사례 PyQt에서 정의하는 클래스가 이미 class Form(QtWidgets.QDialog):
#처럼 다른 클래스를 상속 받았다면, 스레드를 상속받지 않고 바로 사용할 수 있는 형태
#자바에서 Runnable 인터페이스를 구현한 클래스로 인자로 전달하여 스레드를 생성해서 사용하는 것과 같음!
def myGets(inputv):
    while True:
        time.sleep(5)
        print("Message")
        with urlopen(url) as f:
            doc = f.read().decode()
            print(doc)
#target지정하면 내부적으로 run()메서드가 호출되어서 target메서드를 호출!
t1 = threading.Thread(target=myGets,args=('1',))
#t1.deamon= True
t1.start()
 
print("____Main__End__")

ex2_urlopen.py

1
2
3
4
5
6
7
from urllib.request import urlopen
 
with urlopen(url) as f:
    doc = f.read().decode()
    print(doc)

exam_thread.py

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
import sys
from urllib.request import urlopen
from PyQt5.QtWidgets import *
from PyQt5 import uic
import threading as th
import time
 
# 연습문제
# ex0_firstClassPyQT.py로 복사해서
# QWidget 상속받는 MyWidget 클래스를 정의해서 실행하시오
 
class MyWidget(QWidget,th.Thread):
 
    def __init__(self):
        super().__init__()  # 부모클래스를 초기화 해주기 위해서...
        self.beforeVal = 0
        self.currentVal = 0
        self.ui = uic.loadUi("exam_thread.ui")
        self.ui.btn1.clicked.connect(self.serviceOn)
        self.ui.btn2.clicked.connect(self.serviceOff)
        self.ui.show()
 
    def run(self):
        with urlopen(url2) as f:
            doc1 = f.read().decode()
            self.currentVal = doc1
            self.beforeVal = self.currentVal
        while True:
            url = "http://192.168.0.115/pyforweb0518/thread.jsp"
            with urlopen(url) as f:
                doc = f.read().decode()
                self.currentVal = doc
                if(self.currentVal != self.beforeVal):
                    if (doc == "1"):
                        print("Service On")
                        self.ui.label.setText("Service On")
                        # 배경색도 바꿈ㅎㅎ
                        self.ui.setStyleSheet("background:red;")
                    elif (doc == "2"):
                        print("Service Off")
                        self.ui.label.setText("Service Off")
                        # 배경색도 바꿈ㅎㅎ
                        self.ui.setStyleSheet("background:blue;")
                self.beforeVal = self.currentVal
 
    def serviceOn(self):
        self.getNumber(1)
 
    def serviceOff(self):
        self.getNumber(2)
 
    def getNumber(self,number):
        url = "http://192.168.0.115/pyforweb0518/status.jsp?status="+str(number)  # 스프링 서버에 값 전달...
        with urlopen(url) as f:  # urlopen쓰려면, with를 적어줘야 함
            doc = f.read().decode()
            if (doc == "1"):
                print("Service On")
                self.ui.label.setText("Service On")
                #배경색도 바꿈ㅎㅎ
                self.ui.setStyleSheet("background:red;")
            elif (doc == "2"):
                print("Service Off")
                self.ui.label.setText("Service Off")
                # 배경색도 바꿈ㅎㅎ
                self.ui.setStyleSheet("background:blue;")
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    # ---------------------------------------------------------
    widget = MyWidget()
    widget.start()
    # ---------------------------------------------------------
    sys.exit(app.exec_())

exam_threadClass.py

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
#exam_threadClass.py
#URLGet이란 클래스를 정의해서 서버(이클립스로 요청을 보내고 받은 값을 출력하시오)
import threading
import time
from urllib.request import urlopen
class URLGet1(threading.Thread):
    def myUrl(self,name,inputv):
        while True:
            time.sleep(5)
            url="http://192.168.0.115/pyforweb0518/status.jsp?status="+str(inputv)
            with urlopen(url) as f:
                doc = f.read().decode()
                if doc == "1":
                    self.ui.label.setText("Service On")
                else:
                    self.ui.label.setText("Service Off")
    def __init__(self,threadID,name,counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
 
    def run(self):
        print("Starting Thread" + self.name)
        self.myUrl(self.name,self.counter)
        print("Exiting" + self.name)
 
thread1 = URLGet(1,"Thread-1",1)
thread1.start()
thread2 = URLGet(2,"Thread-2",2)
thread2.start()

exam_urlGet_Thread.py

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
#exam_urlGet_Thread.py
#URLGet이란 클래스를 정의해서 서버(이클립스로 요청을 보내고 받은 값을 출력하시오)
import threading
import time
from urllib.request import urlopen
class URLGet(threading.Thread):
    def myUrl(self,name,inputv):
        while True:
            time.sleep(5)
            url="http://192.168.0.115/pyforweb0518/status.jsp?status="+str(inputv)
            with urlopen(url) as f:
                doc = f.read().decode()
                if doc == "1":
                    print("Service On")
                else:
                    print("Service Off")
    def __init__(self,threadID,name,counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
 
    def run(self):
        print("Starting Thread" + self.name)
        self.myUrl(self.name,self.counter)
        print("Exiting" + self.name)
 
thread1 = URLGet(5,"Thread-1",1)
thread1.start()


'학원수업 > 파이썬' 카테고리의 다른 글

학원 49일차 복습(5/29)  (0) 2018.05.29
학원 48일차 복습(5/28)  (0) 2018.05.28
학원 44일차 복습(5/17)  (0) 2018.05.17
학원 43일차 복습(5/16)  (0) 2018.05.16
학원 42일차 복습(5/15)  (0) 2018.05.15

이론




__name__은 파이썬에서 제공하는 변수

python3 calModule.py : 스스로 독립적으로 실행

__main__ 출력


다른 영역에서 import되었을 때는 모듈이름을 출력한다

python3

>>>import calModule

calModule 출력


calModClass의 CalClass() 생성은

if __name__ == "__main__": 때문에 실행이 안되기때문에

대화형 인터프리터나 다른 파일에서 이모듈을 불러서 사용할 때는

__name__ == "__main__"이 거짓이 되어 if문 다음 문장들이 수행되지 않는다.


case1 : import calModule

case2 : from calModule import cal_upper

case3 : from calModule import *

가장좋은 방식은 case1

import calModule as cal



[PyQt] https://sourceforge.net/projects/pyqt/files/PyQt5/PyQt-5.6/

두번째 항목 다운로드 후 설치


다른패키지 모듈불러오기

sys.path.append(모듈을 저장한 디렉터리) 사용하기



객체의 이벤트에서 connect함수를 호출하고 인자값으로 호출될 함수를 작성한다.




실습


ex3_private.py

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
#ex3_private.py
class privateDemo:
    def __init__(self,w,h):
        self.w=w
        self.h=h
        #initializer __초기화
        self.__area=w*h
        print(self.__area) #생성자가 초기화할때 private메서드(상식)
        self.myDef()
        self.__privateDef()
    def __privateDef(self):
        print('private method')
    def myDef(self):
        print('print method!')
        print('@'*10)
        print('MyDef : ',self.__area) #다른 메서드에서 사용
obj=privateDemo(100,100)
print('*'*15)
print(dir(obj))
print('*'*15)
#print(obj.__privateDef())
#obj.__privateDemo__privateDef()
# __:반드시 클래스로 접근해서 사용할수 있다.
#print(obj._privateDemo__area)
#print(obj.__area)
#print("클래스변수 __val의 값 : %d"%privateDemo._privateDemo__val)

Inheritance.py

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
#Inheritance.py
class Animal:
    def __init__(self, name):
        self.name = name
    def move(self):
        print("move")
    def speak(self):
        pass
class Dog (Animal):
    #def __init__(self,names,n):
    #    print(names)
    def speak(self):
        print("%s 가 왈왈 거립니다."%self.name)
class Duck (Animal):
    def speak(self):
        print("%s 가 꽥꽥 거립니다."%self.name)
class Cat (Animal):
    def speak(self):
        print("%s 가 야옹 거립니다."%self.name)
 
dog = Dog('삐삐') #부모클래스의 생성자
n =dog.name #부모클래스의 인스턴스변수
print(n)
#dog.move() #부모클래스의 함수
#dog.speak() #자식클래스의 오버라이드 된 함수
 
animals = [Dog('바둑이'), Duck('꽥꽥이'), Cat('야옹이')]
for a in animals:
    a.speak()

calModule.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#calModule.py
def cal_upper(price):
    increment = price * 3
    upper_price = price + increment
    return upper_price
def cal_lower(price):
    increment = price * 3
    upper_lower = price - increment
    return upper_lower
if __name__ == "__main__":
    print(cal_upper(10000))
    print(cal_lower(10000))
    print(__name__)
"""
__name__은 파이썬에서 제공하는 변수
python3 calModule.py : 스스로 독립적으로 실행
__main__ 출력
 
다른 영역에서 import되었을 때는 모듈이름을 출력한다
python3
>>>import calModule
calModule 출력
"""

calUse.py

1
2
3
4
#calUse.py
import calModule
 
print(calModule.cal_upper(10000))

calModClass.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#calModClass.py
class CalClass:
    author = "kosta"
    def cal_upper(price):
        increment = price * 3
        upper_price = price + increment
        return upper_price
    def cal_lower(price):
        increment = price * 3
        upper_lower = price - increment
        return upper_lower
if __name__ == "__main__":
    cal = CalClass()
    print(cal_upper(10000))
    print(cal_lower(10000))
    print(__name__)

calClassUse.py

1
2
3
4
5
6
7
8
9
10
11
12
#calClassUse.py
import calModClass
#중요포인트
"""
calModClass의 CalClass() 생성은
if __name__ == "__main__": 때문에 실행이 안되기때문에
대화형 인터프리터나 다른 파일에서 이모듈을 불러서 사용할 때는
__name__ == "__main__"이 거짓이 되어 if문 다음 문장들이 수행되지 않는다.
"""
cal = calModClass.CalClass()
print(cal.cal_upper(30000))
print(cal.cal_lower(30000))

importDemo.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#importDemo.py
from calModule import *
"""
case1 : import calModule
case2 : from calModule import cal_upper
case3 : from calModule import *
가장좋은 방식은 case1
import calModule as cal
 
다른패키지 모듈불러오기
sys.path.append(모듈을 저장한 디렉터리) 사용하기
"""
print(cal_upper(10000))
print(cal_lower(10000))
"""
calModule에서 cal_upper함수만 import되며, 모듈이름을
별도로 붙이지 않고도 사용이 가능하다.
print(cal.cal_upper(10000))
import되지 않기 때문에 cal_lower는 사용불가
print(cal.cal_lower(10000))
"""

calExtendsUseDemo.py

1
2
3
4
5
6
7
8
9
10
11
12
13
#calExtendsUseDemo.py
import calModClass
#class 클래스명(모듈이름.클래스명)
class MyCalClass(calModClass.CalClass):
     
    def priceRes(self,name,price):
        self.result = self.cal_upper(price)
        return self.result
     
n = input("이름을 입력하세요:")
p = input("금액을 입력하세요:")
mycal=MyCalClass()
print("입금 금액 : %d"%int(mycal.priceRes(n,p)))

install.sh

1
2
3
#!/bin/bash
sudo apt-get update
sudo apt-get install python3-pyqt5

ex0_firstPyQT.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#ex0_firstPyQT.py
import  sys
from PyQt5.QtWidgets import *
 
if __name__ == '__main__':
 
    app = QApplication(sys.argv)
    label = QLabel("Hello MyPyQT!")
    w = QWidget()
    layout = QHBoxLayout()
    #QLabel을 레이아웃에 추가
    layout.addWidget(label)
    #QWidget 레이아웃을 설정
    w.setLayout(layout)
    w.resize(250,150)
    w.move(300,300)
    w.setWindowTitle('Simple')
    w.show()
 
    sys.exit(app.exec_())

ex0_firstClassPyQT.py

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
#ex0_firstClassPyQT.py
import  sys
from PyQt5.QtWidgets import *
class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.label = QLabel("Hello MyPyQT!")
        self.setStyleSheet("background-color:yellow;")
        btn1 = QPushButton('RedBtn')
        btn1.setStyleSheet("background-color:yellow;")
        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(btn1)
        #객체의 이벤트에서 connect함수를 호출하고
        #인자값으로 호출될 함수를 작성한다.
        btn1.clicked.connect(self.btn1_clicked)
        self.setLayout(layout)
        self.setWindowTitle('Class')
        self.resize(250, 150)
        self.move(300, 300)
        self.show()
    def btn1_clicked(self):
        self.label.setText("RedClick")
if __name__ == '__main__':
    app = QApplication(sys.argv)
    widget = MyWidget()
    sys.exit(app.exec_())

exam1_btn_changeColor.py

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
#exam1_btn_changeColor.py
import  sys
from PyQt5.QtWidgets import *
class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.label = QLabel("Hello MyPyQT!")
        self.setStyleSheet("background-color:yellow;")
        btn1 = QPushButton('RedBtn')
        btn2 = QPushButton('GreenBtn')
        btn3 = QPushButton('BlueBtn')
        closedBtn = QPushButton('Close')
        layout = QHBoxLayout()
        layout.addWidget(btn1)
        layout.addWidget(btn2)
        layout.addWidget(btn3)
        layout.addWidget(closedBtn)
        #객체의 이벤트에서 connect함수를 호출하고
        #인자값으로 호출될 함수를 작성한다.
        btn1.clicked.connect(self.btn1_clicked)
        btn2.clicked.connect(self.btn2_clicked)
        btn3.clicked.connect(self.btn3_clicked)
        closedBtn.clicked.connect(QApplication.instance().quit)
        self.setLayout(layout)
        self.setWindowTitle('Class')
        self.resize(450, 250)
        self.move(300, 200)
        self.show()
    def btn1_clicked(self):
        self.setStyleSheet("background-color:red;")
    def btn2_clicked(self):
        self.setStyleSheet("background-color:green;")
    def btn3_clicked(self):
        self.setStyleSheet("background-color:blue;")
if __name__ == '__main__':
    app = QApplication(sys.argv)
    widget = MyWidget()
    sys.exit(app.exec_())

ex1_helloUI.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ex1_helloUI.py
import sys
 
from PyQt5 import uic
from PyQt5.QtWidgets import *
 
class MyWidget(QWidget):
    def __init__(self):
        super().__init__() #부모클래스를 초기화 해주기 위해서...
        self.ui = uic.loadUi("ex1_hello_msg.ui")
        self.ui.show()
if __name__ == '__main__':
    app = QApplication(sys.argv)
    widget = MyWidget()
    sys.exit(app.exec_())

changeWidgetColor.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#changeWidgetColor.py
import sys
 
from PyQt5 import uic
from PyQt5.QtWidgets import *
 
class MyWidget(QWidget):
    def __init__(self):
        super().__init__() #부모클래스를 초기화 해주기 위해서...
        self.ui = uic.loadUi("exam_colChange.ui")
        self.ui.show()
        self.ui.btn1.clicked.connect(self.btn1_clicked)
        self.ui.btn2.clicked.connect(self.btn2_clicked)
        self.ui.btn3.clicked.connect(self.btn3_clicked)
    def btn1_clicked(self):
        self.ui.setStyleSheet("background-color:red;")
    def btn2_clicked(self):
        self.ui.setStyleSheet("background-color:green;")
    def btn3_clicked(self):
        self.ui.setStyleSheet("background-color:blue;")
if __name__ == '__main__':
    app = QApplication(sys.argv)
    widget = MyWidget()
    sys.exit(app.exec_())


'학원수업 > 파이썬' 카테고리의 다른 글

학원 48일차 복습(5/28)  (0) 2018.05.28
학원 45일차 복습(5/18)  (0) 2018.05.23
학원 43일차 복습(5/16)  (0) 2018.05.16
학원 42일차 복습(5/15)  (0) 2018.05.15
학원 41일차 복습(5/14)  (0) 2018.05.14

이론




파일 객체 = open(파일 이름, 파일 열기 모드)

r   읽기모드 - 파일을 읽기만 할 때 사용

w   쓰기모드 - 파일에 내용을 쓸 때 사용

a   추가모드 - 파일의 마지막에 새로운 내용을 추가 시킬 때 사용



def 함수명(매개변수):

    <수행할 문장1>

    <수행할 문장2>

    ...


try:

    ...

except [발생 오류[as 오류 메시지 변수]]:

    ...


바이너리를 복사하기 위해서는 반드시 버퍼가 필요 **


***인스턴스와 객체의 차이***

a = Cookie()

인스턴스라는 말은 특정 객체(a)가 어떤 클래스(Cookie)의 객체인지를 관계 위주로 설명할 때 사용된다.

즉, "a는 인스턴스" 보다는 "a는 객체"라는 표현이 어울리며, "a는 Cookie의 객체" 보다는 "a는 Cookie의 인스턴스"라는 표현이 훨씬 잘 어울린다.


***self란?***

간단히 말하면, 이 함수를 부르는 객체가 해당 클래스의 인스턴스인지 확인해주기 위한 장치이다.

하지만 단순히 확인하는 것에서 나아가 self를 이용하여 객체 내의 정보를 저장하거나 불러올수 있다.


__init__은 생성자

클래스변수 static

_ 언더바 하나는 protected 변수라고 함.

__ 언더바 두개는 private 변수.



실습


ex6_while.py

1
2
3
4
5
6
7
8
9
10
#ex6_while.py
n=0
while n<10:
  n=n+1
  print('n을 %d번 반복합니다.'%n)
 
print('-------------------------------')
for n in range(0,10):
  print(n,end=" ")
print()

ex7_input.py

1
2
3
4
5
#ex7_input.py
myname=input('당신의 이름:')
print('당신의 이름은 %s 입니다.'%myname)
money=int(input('당신의 자산 입력 :')) * 2
print('보유자산을 2배 :%d'%money)

ex8_input.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ex8_input.py
num=0
while True:
  unum=input('1-입력,2-출력,3-종료 : ')
  if unum == '3':
    print('Exit')
    break
  if unum == '1':
    print('insert Mode')
  if unum == '2':
    print('Select Mode')
  else:
    print(num)
    num +=1
  

ex9_math_random.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ex9_math_random.py
import math
import random
num1=3.14
#올림처리
res1=math.ceil(num1)
print('Res : ',res1)
#내림처리
res1=math.floor(num1)
print('Res : ',res1)
res1=math.trunc(num1)
print('Res : ',res1)
#반올림 round(num1,소수점자리수)
res1=round(num1,1)
print('Res : ',res1)
#난수 - import random
for i in range(1,11):
  res1 = random.randrange(1,7)
  print(i,":",res1)

exam1_py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#exam1.py
res=[]
while True:
  unum=input('Menu :[1.입력,2.출력,3.종료] ')
  if unum == '3':
    print('Exit')
    break
  elif unum == '1':
    print('insert Mode')
    str=input('문자열 입력:')
    res.append(str)
  elif unum == '2':
    print('Select Mode')
    for n in res:
        print(n)

exam2_Holjak.py

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
#exam2_Holjak.py
import random
import math
num = 0
msg=["","","짝"]
winnum=0
totalnum=0
while True:
    youv=input("1.홀, 2.짝, 3.종료:")
    #1 ~에서 3보다 작은 2까지의 범위의 난수
    cpunum = random.randrange(1, 3)
    print(cpunum)
    younum = int(youv)
    if younum != 3:
        print("CPU :", msg[cpunum])
        print("YOU :", msg[younum])
        totalnum += 1
 
    if younum == 3:
        print("게임을 종료합니다.")
        print("총 게임 횟수 %d" %totalnum)
        winPer = winnum * 100 / totalnum
        #문자 %를 출력 %%
        print("승률 : %d %%" %math.trunc(winPer))
        break
    elif younum == cpunum:
        winnum +=1
        print("YOU WIN !")
    elif younum != cpunum:
        print("YOU LOSE !")
    num += 1

exam3_gugu.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#exam3_gugu.py
dan=int(input('단입력 :'))
leng=int(input('범위 (1,3,5,7,9) 입력'))
d=int(leng/2)
x=dan-d
y=dan+d+1
if leng == 1 or leng == 3 or leng == 5  or leng == 7  or leng == 9:
    for a in range(0,10):
        for b in range(x,y):
            if a==0:
                print(b,'단\t\t',end="")
            else:
                print(b,' x ',a,' = ',b*a,end="\t")
        print("")
 
else:
    print('잘못된 범위입니다.')

ex1_def01.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ex1_def01.py
"""
def 함수명(매개변수):
    <수행할 문장1>
    <수행할 문장2>
    ...
"""
#합을 구해주는 함수 정의
def sum(a, b):
    return int(a) + int(b)
#곱한 값을 구해주는 함수 정의
def mul(a, b):
    return int(a) * int(b)
print('sum / mul 로 호출한 함수')
num1 = input('num1 :')
num2 = input('num2 :')
 
print("sum함수의 리턴 값 : %d"%int(sum(num1,num2)))
print("mul함수의 리턴 값 : %d"%int(mul(num1,num2)))

ex3_try_catch.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#ex3_try_catch.py
"""
try:
    ...
except [발생 오류[as 오류 메시지 변수]]:
    ...
"""
import time
import sys
def testCheck():
    try:
        print('On')
        time.sleep(2)
        print('Off')
    except KeyboardInterrupt:
        print('Exit')
        sys.exit()
 
while True:
    testCheck()

exam1_def.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#exam1_def.py
def sum_mul(choice,*args):
    if choice == "sum":
        result = 0
        for i in args:
            result = result + i
    elif choice == "mul":
        result = 0
        for i in args:
            result = result * i
    return result
print('sum / mul 로 호출한 함수')
choice = input('sum/mul:')
res=sum_mul(choice,1,2,3,4,5,6,7,8,9,10)
print(res)

exam_Def_Holjak.py

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
#exam_Def_Holjak.py
import random
 
def percent(win, game):
    print('게임종료')
    print('총게임 횟수:%d'%game)
    print('이긴 횟수:%d'%win)
    per=(win*100)/game
    print('승률:%d'%per)
    return per
 
def gift(game, per):
    if game >= 5:
        if per >= 30:
            print('상품 페러리 자동차 장난감!')
        else:
            print('승률 30프로 이하 상품없음')
    else:
        print('5게임 이상해야함')
 
def Execute():
    msg = ["", "", "짝"]
    win = 0
    game = 0
    while True:
        youv = input("1.홀, 2.짝, 3.종료:")
        # 1 ~에서 3보다 작은 2까지의 범위의 난수
        cpunum = random.randrange(1, 3)
        print(cpunum)
        younum = int(youv)
        if younum != 3:
            print("CPU :", msg[cpunum])
            print("YOU :", msg[younum])
            game += 1
        if younum == 3:
            percent(win,game)
            gift(game,percent(win,game))
            break
        elif younum == cpunum:
            win += 1
            print("YOU WIN !")
        elif younum != cpunum:
            print("YOU LOSE !")
Execute()

ex1_file.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ex1_file.py
"""
파일 객체 = open(파일 이름, 파일 열기 모드)
r   읽기모드 - 파일을 읽기만 할 때 사용
w   쓰기모드 - 파일에 내용을 쓸 때 사용
a   추가모드 - 파일의 마지막에 새로운 내용을 추가 시킬 때 사용
"""
f = open('myMessage.txt','r')
print('Name of the File',f.name)
print('Closed or not',f.closed)
print('Opening mode',f.mode)
f.close()
print('Closed or not :',f.closed)
#위의 프로그램을 함수로 정의해서 입력한 파일이 없을 경우에는
#새롭게 생성하고, 있으면 위처럼 정보가 보이도록 구현하시오.

ex2_file.py

1
2
3
4
5
6
7
8
9
10
11
12
#ex2_file.py
def fileWriter(filename,msg,mode):
    f=open(filename,mode)
    f.write(msg)
    f.close()
 
print("파일의 내용작성하기 예제 ")
text = input('파일의 내용 작성 :')
fileWriter('myMessage.txt',text+'\n','a')
 
#간단하게 해보기 ex1_file.py를 ex3_file.py로 복사한 후
#위와 같이 fileReader함수로 정의해서 출력하기

ex3_file.py

1
2
3
4
5
6
7
8
9
#ex3_file.py
#작성한 파일을 읽어들이기
def fileRead(filename,mode):
    f=open(filename,mode)
    while True:
        line = f.readline()
        if not line:break
        print(line)
    f.close()

ex1.filecopy.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ex1_filecopy.py
import time
t1=time.time()
#바이너리를 복사하기 위해서는 반드시 버퍼가 필요 **
bufsize = 1024
f=open('home.tar.gz','rb')
h=open('home2.tar.gz','wb')
while True:
    data = f.read(bufsize)
    h.write(data)
    if not data: break
t2=time.time()
print('걸리는 시간 %s'%((t2-t1)*1000))
f.close()
h.close()

ex1_def_filecopy.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ex1_def_filecopy.py
import time
def fileCp(oriFn,targetFn):
    t1 = time.time()
    bufsize = 1024
    f = open(oriFn, 'rb')
    h = open(targetFn, 'wb')
    while True:
        data = f.read(bufsize)
        h.write(data)
        if not data: break
    t2 = time.time()
    print('걸리는 시간 %s' % ((t2 - t1) * 1000))
    f.close()
    h.close()
print('-'*10)
oriFn=input('복사할 파일 원본:')
targetFn=input('이동될 파일 사본:')
fileCp(oriFn,targetFn)

ex2_rename.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#ex2_rename.py
from os import rename
#실제 존재하는 파일명 작성
target_file = 'stcp.txt'
#사용자로부터 /home/pi/mystudy/pythonBasic/subdir 존재하는 경로를 입력
newpath = input('[%s]를 이동할 디렉터리의 절대경로를 입력하세요: ' %target_file)
print("Path :"+str(newpath))
print("Path - 1: "+str(newpath[-1]))
print('-'*20)
#마지막 문자열에서 / 있을 경우, 없을 경우를 판별
if newpath[-1] == '/':
    newname = newpath + target_file
else:
    newname = newpath + '/' + target_file
 
try:
    #파일의 이름을 변경  함수를 호출!
    rename(target_file, newname)
    print('[%s] -> [%s]로 이동되었습니다.' %(target_file, newname))
except FileNotFoundError as e:
    print(e)

ex2_rename_getsize.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ex2_rename_getsize.py
from os.path import getsize
from os import rename
 
file1 = 'stcode.txt'
file2 = 'home.tar.gz'
file_size1=getsize(file1)
file_size2=getsize(file2)
 
print('File Name : %s \t File Size : %d' %(file1,file_size1))
print('File Name : %s \t File Size : %d' %(file2,file_size2))
print('-'*15)
newname = input(' %s 에 대한 새로운 파일 이름 입력 :'%file1)
rename(file1,newname)
print(' %s -> %s 로 파일이 변경되었습니다.' %(file1,newname))

ex3_TestClass.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ex3_TestClass.py
class TestClass:
    def __init__(self):
        print(self)
test=TestClass()
print(test)
"""
 
<__main__.TestClass object at 0x76ab18d0>
"""
print(type(test))
"""
<class '__main__.TestClass'>
"""

ex3_class2.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#ex3_class2.py
class MyClass2:
    #클래스 변수 static
    var = 'static __ okokok'
    #self 인스턴스 변수
    def __init__(self):
        self.var='안녕하세요'
        print('MyClass 인스턴스 객체가 생성되었음',MyClass2.var)
 
    def sayHello(self):
        self.msg='hi'
        #localMsg='hello'
 
    def printHello(self):
        print(self.msg)
        #print(self.localMsg)
print(MyClass2.var)
obj= MyClass2()
print(obj.var)
obj.sayHello()
obj.printHello()

ex3_class3.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ex3_class3.py
class Ractangle:
    count = 0 #클래스 변수 static
 
    def __init__(self,w,h):
        #self : 인스턴스 변수
        self.w=w
        self.h=h
        Ractangle.count += 1
    def calcArea(self):
        area = self.w * self.h
        return area
 
#클래스로 생성해서 calcArea 함수를 호출!
obj=Ractangle(20,20)
print(obj.calcArea())
print(obj.count)
print(Ractangle.count)


'학원수업 > 파이썬' 카테고리의 다른 글

학원 48일차 복습(5/28)  (0) 2018.05.28
학원 45일차 복습(5/18)  (0) 2018.05.23
학원 44일차 복습(5/17)  (0) 2018.05.17
학원 42일차 복습(5/15)  (0) 2018.05.15
학원 41일차 복습(5/14)  (0) 2018.05.14

이론



문자열을 만드는 총 4가지 방법

1. "문자열"

2. '문자열'

3. """문자열"""

4. '''문자열'''


문자열과 튜플은 불변적인 요소이기 때문에 변경이 불가능하다.

문자열인 경우는 슬라이싱을 이용해서 변경이 가능하다.


문자열 포맷코드

문자열 포매팅 예제에서는 대입시켜 넣는 자료형으로 정수와 문자열을 사용했으나

이외에도 다양한 것들을 대입시킬수 있다. 문자열 포맷코드로는 다음과 같은 것들이 있다.

코드 설명

%s  문자열(String)

%c  문자 1개(Character)

%d  정수(Integer)

%f  부동소수(Floating-point)

%o  8진수

%x  16진수

%%  Literal % (문자 % 자체)



자료형은 모두 객체이다.***


리스트: 값의 생성,삭제,수정이 가능

튜플: 값을 바꿀 수 없음

불(bool) 자료형이란 참(Ture)과 거짓(False)을 나타내는 자료형이다

문자열 ""->False

리스트 /튜플 []() ->False

딕셔너리 {} ->False

숫자형 0,None ->False


nano 편집기에서

alt+p : 스페이스 view

ctrl + 6 : 블록지정

alt + 6 :복사

ctrl + u :붙여넣기


실습


ex1_string.py

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
#ex1_string.py
#문자열을 만드는 총 4가지 방법
#1. "문자열"
#2. '문자열'
#3. """문자열"""
#4. '''문자열'''
food="Python's a favorite food is pert"
print(food)
food="""
Test message : Love is too Long
You need python
"""
print(food)
food='excellent language.'
print(food)
 
print("----------------------------------")
a="Love is too Long, You need !Python"
print(a[3])
print(a[:5])
print(a[-7:])
print("-"*20)
a="Python"
a=a*2
print(a)
print(a[:])
print(a[1:-5])
aa=a[:6]
bb=a[6:]
print(aa)
print(bb)
 
#연습문제 ..
a="MyTast"
#a[1]='0' =>문자열과 튜플은 불변적인 요소이기 때문에 변경이 불가능하다.
#문자열인 경우는 슬라이싱을 이용해서 변경이 가능하다.
a=a[:3]+'e'+a[4:]
print(a)

ex2_string.py

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
#ex2_string.py
comm="""
문자열 포맷코드
문자열 포매팅 예제에서는 대입시켜 넣는 자료형으로 정수와 문자열을 사용했으나
이외에도 다양한 것들을 대입시킬수 있다. 문자열 포맷코드로는 다음과 같은 것들이 있다.
코드 설명
%s  문자열(String)
%c  문자 1개(Character)
%d  정수(Integer)
%f  부동소수(Floating-point)
%o  8진수
%x  16진수
%%  Literal % (문자 % 자체)
"""
print("-----------------------")
print(comm)
print("-----------------------")
msg="I eat %d apples." %3
print(msg)
print("I eat %d apples."%300)
five="Five"
print("I eat %s apples."%five)
#하나 이상의 값을 넣을 경우
number=10
day="three"
print("I ate %d apples. so I was sick for %s days"%(number,day))
 
print('success %d%%'%number)
#전체 길이가 20인 문자열 공간에 hello를 오른쪽으로 정렬하고 나머지는 공백으로 표현
#%-20s 왼쪽정렬
space="%20s"%"hello"
print(space)
space="%-20s ok"%"hello"
print(space)
#소수점 표현하기
fnum=3.141111
print("소수점 값 %f "%fnum)
print("소수점 0.X자리 값 %0.2f "%fnum)
print("소수점 X0.X자리 값 %10.4f "%fnum)
 
comm=""" format 함수 """
print(comm)
print('-'*15)
number=5
str="I have {0} apples".format(number)
print(str)
str="I have {0} apples".format("five")
print(str)
#한번해보기
print('-'*15)
str="당신이 가진 사과는 [{0}] 개이며, 색상은 [{1}] 입니다.".format(3,"빨간색")
print(str)
#변수명으로 적용하기
str="당신이 가진 자동차는 {car} 입니다.".format(car="페러리")
print(str)
#또해보기
print('-'*15)
str="당신이 가진 사과는 [{0}] 개이며, [{name}]은 [{1}] 입니다.".format(3,"빨간색",name="색상")
print(str)

ex3_string.py

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
#ex3_string.py
#문자 관련 함수 ***
msg="nobody"
print(len(msg))
print("문자 개수 %d "%msg.count('b'))
print("문자 o의 개수 %d" %msg.count('o'))
#문자 위치 알려주기 - 찾을 문자열이 없으면 -1
print("문자의 위치 %d"%msg.find('o'))
print("문자의 위치 %d"%msg.index('o'))
#문자열 삽입
str2=","
print("%s"%str2.join('abcdefg'))
str3=" hi hello "
print("%d"%len(str3))
print("%s"%str3.upper())
print("%s"%str3.lower())
#문자열 공백지우기
#str3.lstrip(),str3.rstrip(),str3.strip() 이후 len으로 문자길이 출력하기
print("*"*10)
print("%s %d "%(str3.lstrip(),len(str3.lstrip())))
#str3.replace()
print("%s"%str3.replace("hi","ok"))
#str3.split()
str3 = str3.split()
print("%s"%str3[0])
str3= "AA:BB:CC"
#여기에 split로 출력 구분자 :
print("*"*10)
str3 = str3.split(":")
print(str3) #list로 출력 => "AA,BB,CC"
print("#list로 출력")
str3="%s,%s,%s"%(str3[0],str3[1],str3[2])
print(str3)

ex4_string.py

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
#ex4_string.py
num=[1,2,3,4,5]
print("%d"%num[1])
msg=str(num[1])+"hi"
print(type(msg))
print("%s"%msg)
print("*"*10)
#중첩리스트
listn=[1,2,['a','b',['test','test1']]]
msg=listn[2]
print(msg)
msg=listn[2][2][1]
print(msg)
 
#중첩 리스트 슬라이싱
a = [1, 2, 3, ['a', 'b', 'c'], 4, 5]
msg= a[3][:3]
print(msg)
#연습문제 - 슬라이싱으로 ['test','test1'] 출력하기
print("*"*10)
msg=listn[2][2][:2]
print(msg)
print("*"*10)
 
num=[1,2,3]
print("-----------------------------\n")
print("%s"%num[1])
print("#변수를 저장할 때는 문자열로 변경해야 한다.")
msg=str(num[0])+"hello"
print("%s"%msg)
print("------------------------------\n")
del num[1]
print(num)
a=[1,2,3]
a.append(5)
print(a)
a.insert(3,7)
a.sort()
print(a)
a.reverse()
print(a)
a.remove(3)
print(a)
a.pop(3)
print(a)
a.extend([9,10])
print(a)

ex1_tuple.py

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
#ex1_tuple.py
#리스트: 값의 생성,삭제,수정이 가능
#튜플: 값을 바꿀 수 없음
t1=(1,2,'a','b')
#t1[0] = 'c'
"""
Traceback (most recent call last):
  File "ex1_tuple.py", line 5, in <module>
    t1[0] = 'c'
TypeError: 'tuple' object does not support item assignment
"""
#tuple 연산 : 더하기, 곱하기
t2=(3,4)
t3=t1+t2
print(t3)
for n in t3:
    print(n)
print("*"*10)
t3=t1*3
for n in t3:
    print(n, end=' ')
print("")
 
#연습문제
ex=(1,2,3)
 
ex1=ex+(4,5)
print(ex1)
print(id(ex1) == id(ex))
for n in ex1:
    print(n, end=" ")
print("")

ex2_dic.py

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
#ex2_dic.py
a={1:'김길동'}
a[2]='애일리'
a['name']='kim'
print(a)
del a[1]
print(a)
print('-------------------------\n')
grade={'pay':1000,'daddy':100}
print(grade['pay'])
print(grade['daddy'])
print('-------------------------\n')
#make dic key
a={'name':'김길동','phone':'010-1212-2128','pay':8000}
print(a.keys())
print(a.values())
print(a.items())
for n in a.keys():
    print("key : %s"%n)
print('-------------------------\n')
for n in a.values():
    print("value : %s"%n)
print('-------------------------\n')
print("Items print")
for n in a.items():
    print(n)
#get메서드 사용해서 value값을 가져옴
print(a.get('name'))
print(a.get('aa')) #None을 반환
print("list--------------------------------------\n")
#연습문제 a.items()의 키와 값을 구분하여 출력
#plist=[('number','001')] 의 리스트를 추가하여 출력
plist=[('number','001')]
listn = list(a.items())
listn.extend(plist)
listn.reverse()
for(key,val) in listn:
    print("{0} : {1}".format(key,val))
print("list--------------------------------------\n")
#딕셔너리 삭제
a.clear()
print(a)

ex3_set.py

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
#ex3_set.py
s1=set([1,2,3])
print(s1)
#set은 중복을 허용하지 않으면서 순서가 없는 구조이다.
s2=set('Hello python')
print(s2)
#set을 list, tuple로 변환
list1 = list(s1)
for n in list1:
    print(n)
tuple1 = tuple(s1)
for n in tuple1:
    print(n)
#set을 가지고 연산하기 교집합,합집합,차집합
s1=set([1,2,3,4,5,6])
s2=set([5,6,7,8,9,10])
s3=s1&s2
print('교집합')
print(s3)
s3=s1|s2
print('합집합')
print(s3)
s3=s1=s2
print('차집합')
print(s3)
 
print('-------------------\n')
#set 메서드 add(value),update([list]),remove(index)
print(s1)
s1.add(10)
print(s1)
s1.update([15,16,17])
print(s1,end=" ")
print("")
s1.remove(15)
print(s1,end=" ")
print("")
print('-------------------\n')
#불(bool) 자료형이란 참(Ture)과 거짓(False)을 나타내는 자료형이다.
a=[1,2,3,4,5,6]
while a:
    n=a.pop()
    print(n)
    print("-"*10)
#자료형은 모두 객체이다.***
a=10
print(type(a))
#문자열 ""->False
#리스트 /튜플 []() ->False
#딕셔너리 {} ->False
#숫자형 0,None ->False
if[]:
    print("True")
else:
    print("False")
 
#nano 편집기에서
#alt+p : 스페이스 view
#ctrl + 6 : 블록지정
#alt + 6 :복사
#ctrl + u :붙여넣기

ex4_if.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ex4_if.py
money = 1000
if money > 200:
    print('택시를 타고가라')
    print('aaaa')
else:
    print('걸어가라')
 
print('-------------------------')
 
p=['paper','myphone','money']
if 'money2' in p:
    print('택시를 타고가라')
    print('aaaa')
elif 'myphone' in p:
    print('전화해라')
else:
    print('걸어가라')

ex5_time.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ex5_time.py
 
import time
import calendar
 
localtime=time.localtime(time.time())
print("Local Current time:",localtime)
print("------------------------------")
print(localtime[:6])
#연습문제 : 오늘은 2018년 5월 15일 입니다. 로 출력해보기
print("오늘은 %d년 %d월 %d일 %d시 %d분 %d초입니다"%(localtime[0],localtime[1],localtime[2],localtime[3],localtime[4],localtime[5]))
print("------------------------------")
localtime=time.asctime(localtime)
print("Local Current time:",localtime)
 
print("------------------------------")
cal=calendar.month(2018,5)
print(cal)

exam_ifwhile.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#exam_ifwhile.py
# a=[1~11]
# 1,3,5,8,9,11 을 출력하면서 true라고 출력함께하고
# 나머지는 false라고 숫자와 함께 출력하시오. 반드시 if else로
"""
a=[1,2,3,4,5,6,7,8,9,10,11]
a.reverse()
while a:
    n=a.pop()
    if n in [1,3,5,8,9,11]:
        print("true %s"%n)
    else: print("false %s"%n)
"""
# a=[1,2,3,4,5,6,7,8,9] 리스트를 다음과 같이 출력하시오.
# for in , if else 사용
a=list(range(1,10))
for n in a:
    print(n,end=" ")
    if n%3==0:
        print("")


'학원수업 > 파이썬' 카테고리의 다른 글

학원 48일차 복습(5/28)  (0) 2018.05.28
학원 45일차 복습(5/18)  (0) 2018.05.23
학원 44일차 복습(5/17)  (0) 2018.05.17
학원 43일차 복습(5/16)  (0) 2018.05.16
학원 41일차 복습(5/14)  (0) 2018.05.14

이론



[소프트웨어]

1.키트에 들어있는 SD카드를, USB 포트에 꽂고

2. https://www.sdcard.org/downloads/formatter_4/eula_windows/index.html 에 들어가서 SD Card Formatter 설치

3.라즈비안 다운 https://www.raspberrypi.org/downloads/raspbian/ 로 이동

4. https://sourceforge.net/projects/win32diskimager/?source=directory 다운

5. https://etcher.io/ 로 이동해서 다운(포맷+IMAGE설치 한번에 해줌)


[하드웨어]

전력(5V)과 접지(GND) 연결



전력 : 전원연결. (+)와 같다.

접지(GND) : (-)와 같다. 0V


충전기 연결

PC케이블 연결




라즈베리모양->Raspberry Pi Configuration클릭 후 Interface 설정




라즈베리에서 터미널 실행

sudo systemctl start ssh ->ssh을 실행하라

비밀번호 설정

터미널에서 ifconfig로 자신의 inet알아낸 후 putty로 접속

sudo apt-get -y install vsftpd

sudo vi /etc/vsftpd.conf 들어가서

:ser number로 행번호 띄운후,

31행 주석제거 (write_enable=YES)

122,123,125행 주석 제거(chroot_locar_user=YES, chroot_list_enable=YES, chroot_list_file=/etc/vsftpd.chroot_list)

sudo vi /etc/vsftpd.chroot_list 에서 내 아이디 추가해준후 :wq(아이디 한줄만 넣어주면 됨)

sudo systemctl restart vsftpd 

**vim에서 백스페이스, 방향키가 이상하면  sudo apt-get install vim로 vim 새롭게 인스톨 할것**

FileZilla(ftp)로 연결!


putty를 이용해 라즈베리파이에 파이썬 작업폴더 생성

mkdir mystudy

cd mystudy/

mkdir pythonBasic

cd pythonBasic/

mkdir day01

cd day01/





1.POWER

-전원. 라즈베리를 구동시킨다. +극과 같음.


2.GND

-접지. 0V 전위를 가지고, 감전 보호에 사용됨. -극과 같음.


3. GPIO?

- 입출력포트

- General Purpose Input/Output

- 일반적인 입출력을 위한 포트

- 라즈베리 파이나 아두이노 같은 보드(임베디드 시스템)에서 외부 하드웨어 연결을 위해 사용


4.UART 통신(비동기식 시리얼 통신)

시리얼 통신을 담당하는 회로

비동기는 1:1통신만 가능


5.SPI 통신(동기식 시리얼 통신)

장점

클럭(CLK) 라인을 이용해 데이터 라인을 동기화 하므로, 하드웨어 구조가 간단하고 1:N 통신이 가능하다

송신용 핀 / 수신용 핀이 분리되어 있음(동시 송수신) 연결을 이용해 10만 비트의 전송 속도를 지원하기도 함

단점

통신에 필요한 핀이 많아지는 단점이 있음.(하나의 장치를 연결하는데 4개의 라인(CLK,MOSI,MISO,SS)가 필요하고, 추가로 장치를 더할 떄마다 라인이 하나씩 추가됨.

N:N 통신은 불가


6.I2C 통신(동기식 시리얼 통신)

SPI통신의 단점을 보완가능.

UART통신처럼 단 2라인만 사용하고, 1008개의 슬레이브 장치를 지원

N:N 통신 가능(단 마스터 장치끼리 통신은 불가)

하드웨어 요구사항 SPI < I2C < UART , 통신속도 SPI와 UART의 중간쯤 됨


[파이썬 환경설정]

파이참 Community https://www.jetbrains.com/pycharm/download/

#인덱싱:: 원하는 부분의 글자를 출력!

#슬라이싱(숫자로 지정한 부분앞까지 출력)


실습


ex2_string.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ex2_string.py
food="Python은 먹는 음식이 아닙니다."
print(food)
food="""
Test Message : Python Test Message!
you need Python
"""
print(food)
 
str="Python Test Message! you need Python!"
#인덱싱:: 원하는 부분의 글자를 출력!
#슬라이싱(숫자로 지정한 부분앞까지 출력)
print(str[3])
print(str[:6])


'학원수업 > 파이썬' 카테고리의 다른 글

학원 48일차 복습(5/28)  (0) 2018.05.28
학원 45일차 복습(5/18)  (0) 2018.05.23
학원 44일차 복습(5/17)  (0) 2018.05.17
학원 43일차 복습(5/16)  (0) 2018.05.16
학원 42일차 복습(5/15)  (0) 2018.05.15

+ Recent posts