2015. 9. 22.

감시카메라를 만들어보자(Let's make a cctv using a raspberry pi) - 2

  자, 저번에는 vnc서버를 이용해서 라즈베리파이에 원격 접속하는 것을 했다.
이번에는 cctv를 만들기에 앞서 무선랜을 설정하는 방법을 먼저 설명하겠다. 무선랜을 설정하기 위해서는 무선랜카드가 있어야한다.
 Well, the last time, we connected with RPi2 using a VNC server.
This time, before make a cctv, I explain how to use a wlan. We need a wlan card to use a wlan.


1. 무선랜 설정 (wlan setting)


  
1. lsusb 명령어를 이용하여 무선랜카드가 인식되는지 확인한다.
1. Input a lsusb command to check a wlan card has been recongized.

2. iwconfig 명령어를 이용하여 wlan이 잡히는지 확인한다. 처음에는 아무것도 연결되지 않았을 것이다.
2. Input a iwconfig command to check wlan has been detected. Maybe at first, there is no wlan.

3. iwlist 를 이용하여 주변 공유기를 검색한다. 이때 원하는 공유기의 SSID(ESSID) 와 IP주소(Address)를 기억해둔다.
3. Input iwlist command to find wlan signal. And remember your SSID and IP address.

4. /etc/wpa_supplicant/wpa_supplicant.conf 에 아래를 vi 등을 이용하여 추가한다.
4. Add the following lines by using the vi editor or any editor in /etc/wpa_supplicant/wpa_supplicant.conf

network={                
    ssid="SSID"                
    psk="PASSWARD"
}

cs

  물론 이렇게만 해놓으면 누가 라즈베리파이를 뒤져서 공유기 비밀번호를 알아낼 수 있다.
설마 그것이 꺼림칙하다면 인터넷에 암호화 하는 방법이 있으니 참고하시길.
 Of course, it can easy to be found by someone.
If you want to further strengthen security, just find on the internet how to do that.


5. 이제 라즈베리파이를 껏다 켜도 자동으로 무선랜이 연결되도록 하자. 아래의 명령어를 입력하자.
5. Now, let's make RPi2 that automatically connect with wlan even it was rebooted. Input the following lines.

cd /etc/ifplugd/action.d/
sudo mv ifupdown ifupdown.original
sudo cp /etc/wpa_supplicant/ifupdown.sh ./ifupdown
sudo reboot
cs


6. 이제 vnc로 무선랜을 통해 라즈베리파이에 접속하려면 할당된 라즈베리파이의 무선랜 IP주소를 이용해 접속하면 된다.
6. Now, if you want connect RPi2 using wlan then just use an wlan IP address.


이제 무선랜으로 원격접속이 가능하니 거리의 제약이 많이 없어졌다! 야호!

Now we can access to RPi with wlan. So there are not much a constraint for distance! Yay!


2. cctv 코드(code)


1. Basic code


#import
import os
import RPi.GPIO as GPIO
import datetime
import time
#set GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN)
#program start
print "Start!!"
#check a door is opened
try:
    while True:
        timeNow = datetime.datetime.now() #set timeNow value
        if GPIO.input(18== 1#if a door is opened, activate below
            print "\n-------------------------------------------------------------------"
            print "Door is opened!! - Taking a picture!!!!!"
            print timeNow #print timeNow value
            print "-------------------------------------------------------------------\n"
            os.system("raspistill -t 500 -vf -hf -o /home/pi/Desktop/images/$(date +\"%Y-%m-%d_%T\").jpg -w 960 -h 720") #taking a picture
        if GPIO.input(18== 0#if a door is not opened, activate below
                print "Door is closed..."
        time.sleep(1) #delay 1s
except KeyboardInterrupt:      
    GPIO.cleanup()
cs

  간단히 설명하자면 1초마다 문이 열렸는지 확인을 하다가 문이 열리면 외부명령어를 실행하는 os.system을 이용하여 사진을 찍는다.
이때 raspistill이라는 명령어로 사진을 찍게 되는데 몇가지 옵션이 있다.
  To explain briefly, This code just check 'the door is opened?' in every 1s. Then if the door is opened, use an external command 'os.system' to take a picture.
At that time, we used raspistill. And here is some option for raspistill.


1. -t 500 : 500ms 후에 찍는다
2. -vf : 수직반전
3. -hf : 수평반전
4. -o /home/pi/Desktop/images/$(date +\%Y-%m-%d_%T\").jpg  : /home/pi/Desktop/images 경로에 찍는 순간의 '년, 월, 일, 시간' 을 이름으로 하는 .jpg 확장자를 가진 이미지를 저장
5. -w 960 : 사진 폭
6. -h 720 : 사진 높이

1. -t 500 : take a picture after 500ms 
2. -vf : Vertical reverse
3. -hf : Horizontal reverse
4. -o /home/pi/Desktop/images/$(date +\%Y-%m-%d_%T\").jpg  : Save a '.jpg' picture file that name is 'Year, Month, Day, Time' at that moment. And the path is /home/pi/Desktop/images
5. -w 960 : Width of picture
6. -h 720 : Height of picture


2. With SMS code


-*- coding: utf8 -*-
"""
Copyright (C) 2008-2014 NURIGO
http://www.coolsms.co.kr
"""
#import
import os
import RPi.GPIO as GPIO
import datetime
import time
import sys
sys.path.append("..")
import coolsms
#Set GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN)
#Define sms method
def sms():
    api_key = 'INSURT YOUR API_KEY'
    api_secret = 'INSURT YOUR API_SECRET'
    to = 'INSERT NUMBER'
    sender = 'INSERT NUMBER'
    message = 'INSERT MESSAGE'
    cool = coolsms.rest(api_key, api_secret)
        status = cool.send(to,message,sender)
        print status
    
    return None
#Start program
print "Start!!"
#Set flag for sending sms
flag = True
#Check a door is opened
try:
    while True:
        timeNow = datetime.datetime.now() #set timeNow value
        if GPIO.input(18== 1#if a door is open, activate below
            print "\n-------------------------------------------------------------------"
            print "Door is opened!! - Taking a picture!!!!!"
            print timeNow #print timeNow value
            print "-------------------------------------------------------------------\n"
            os.system("raspistill -t 500 -vf -hf -o /home/pi/Desktop/images/$(date +\"%Y-%m-%d_%T\").jpg -w 960 -h 720") #taking a picture
            #sending sms once
            if flag is True:
                sms() 
                    flag = False
        if GPIO.input(18== 0#if door is not opened, activate below
                print "Door is closed..."
        time.sleep(1) #delay 1s
except KeyboardInterrupt:      
    GPIO.cleanup()
cs


  sms코드는 문이 열렸을 때 sms를 지정된 번호로 보내는 코드를 추가하였다. 이 서비스를 이용하려면 coolsms 홈페이지에서 제공하는 coolsms.py를 다운로드 받아서 cctv 코드와 가은 경로에 저장되어 있어야 한다. 서비스는 유료이며 회원가입시 기본금을 공짜로 준다. 연습삼아 쓰기에는 충분한 양을 준다.
 다른 방법으로는 웹사이트를 만들어서 실시간으로 확인하게 할 수 있으나 자취방의 공유기 설정을 바꿔야하기 때문에 포기했다..
 This sms code is just sending a sms to user when the door is opened. If you want this service, you have to download a coolsms.py file on coolsms homepage and save it in the same path with cctv code. This service is not free. But you can get a basic amount when you sign up. And that is enough for practice.
 Alternatively, it may be checked in real-time by creating a website. But I can not change my building's router port settings. So I just gave up..



3. 도어센서 설치 (Install a door sensor)


<라즈베리파이와 라즈베리카메라>
<A RPi2 and a RPi camera>


<도어센서>
<A door sensor>


<일단 전기테이프로 부착했다.>
<As a temporary solution, I just attached with electrical tape.>


<선 정리. 도와준 현수, 민수에게 감사를.>
<Clean lines. Thanks for hsjoe's and minsoo's help.>


<데모 영상>
<Demonstration video>


<문 열기 전 찍은 모습>
<A picture before the door is opened.>


<문을 열고 나서 자동으로 찍힌 모습>
<A picture after the door is opened.>


 이제 무선으로 원격접속이 가능하니 나중에 시간이 나면 문 앞쪽에 라즈베리파이를 설치해야 겠다.
 Now, I can wireless remote access to RPi so if I have a time, I will reinstall a RPi in front of the door.


참조(References)

-coolsms 홈페이지

-coolsms.py 다운로드 링크

댓글 1개:

Unknown :

하드웨어 최적화해서 상용제품으로 용돈벌어도 될정도로 좋음ㅋ