05-16 05:32
Recent Posts
Recent Comments
관리 메뉴

miinsun

[토탈 솜루션] 움직임 센서를 이용한 조명 제어 + 소켓 통신 본문

Project/2020 토탈솜루션

[토탈 솜루션] 움직임 센서를 이용한 조명 제어 + 소켓 통신

miinsun 2021. 12. 6. 16:41

 

저번 게시글에 이어서 모션세서를 활용한 조명 제어 코드를 조금 업그레이드 했다. 이번에는 조명 제어기능을 구현한 motion.py에 데이터를 서버에 전송하는 server.py 와 client.py를 추가하였다.

- 이전 게시글

 

[토탈 솜루션/RaspberryPi] 움직임 감지 센서로 조명 제어하기

진행 중인 프로젝트의 모션 센서 제어 부분을 맡았다. 📌 기능을 구현하기 위한 준비물 라즈베리 파이(초기 설정된) GPIO 확장 보드 MF선 모션감지센서 3색 LED >> 3색 LED가 조명을 대체한다. 그 외

miinsun.tistory.com

 


 

💻 데이터 흐름도

  1. 서버 리스닝 소켓을 만들어 클라이언트의 응답을 기다린다.
  2. 클라이언트의 모션센서의 입력 값을 보내준다.
  3. 서버는 클라이언트의 응답을 기반으로 제어 값을 재전송한다.
  4. 클라이언트는 서버의 제어 값으로 LED를 제어한다.
  5. 모든 전송이 끝나면 socket을 닫아준다.

 

💻 Code

# server.py

import socket
import motion

HOST = '127.0.0.1'
PORT = 9999        
 
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
client_socket, addr = server_socket.accept()

print('Connected by', addr)

while True:
    data = client_socket.recv(1024)  #클라이언트로부터 응답을 받는다.
    print('server data', data)
    
    # 클라이언트 대답이 없을 경우, break 서버를 닫는다.
    if not data :
        break
    
    #클라이언트 값에 따라 다른 제어문 출력
    if data == 0:
        print("server says: No motion")
    elif data == 1:
        print("server says: OK motion")
    elif data == -1:
        print("server says: error")

    client_socket.sendall(data) #클라이언트에게 서버 제어 값 재 전송

client_socket.close()
server_socket.close()

 

# client.py

import socket
import motion

HOST = '127.0.0.1'  
PORT = 9999       

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))

while True: # ctrl + c를 누르기 전까지 무한 반복
    setMsg = motion.inputValue() # motion.py의 모션 센서 값 입력 함수 실행
    client_socket.sendall(str(setMsg).encode()) # 서버에 클라이언트 값 전송
    print('client setMsg: ', setMsg)

    getMsg = client_socket.recv(1024) # 서버로부터 제어 값 받기
    print('client getMsg: ', getMsg) 
    motion.outputValue(int(getMsg)) # 서버 제어 값으로 motion.py 함수 실행

client_socket.close()

 

# motion.py

import RPi.GPIO as GPIO
import time

def inputValue(): # 모션 센서로 입력 값 리턴
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(25, GPIO.IN) # 25번 핀을 모션 센서 입력 값으로 사용 
    
    setMsg = 0; # 초기 상태는 0 (움직임X)
    
    if GPIO.input(25) == True: # 움직임이 있으면,
        setMsg = 1             # 1을 전송
    elif GPIO.input(25) == False: # 움직임이 없으면,
        setMsg = 0                # 0을 전송
    
    GPIO.cleanup()   
    return setMsg;
        
        
def outputValue(getMsg): # getMsg = 서버 제어 값,
                         # 서버 값으로 LED 빛을 출력
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(13, GPIO.OUT) # 13번 핀을 LED 출력 값으로 사용 
    
    try:
        if getMsg == 0: # 서버 제어 값이 0이면,
            print("Sensor Off!!")
            GPIO.output(13, True) # 불을 끄고
            time.sleep(1) # 1초 sleep
                         
        elif getMsg == 1: # 서버 제어 값이 1이면,
            print("Sensor On!!")
            GPIO.output(13, False) # 불을 키고
            time.sleep(3600) # 1시간 sleep
            
        elif getMsg == -1: # -1(오류 값)이 들어오면,
            print("Error!!")
            time.sleep(1) # 1초 sleep
        
    except KeyboardInterrupt:
        getMsg = -1
        
    finally:
        GPIO.cleanup()
 


이것으로 모션센서를 활용한 기능 구현이 끝났다! 앞으로는 팀원들이 만든 코드들과 통합하고 git hub에 업로드하는 일만 남았다. 또, 다음 번에는 라떼판다를 활용해서 서버를 구현하고 각 라즈베리파이 기기의 값을 받을 수 있는 간단한 네트워크를 구현해보도록 할 것이다.

Comments