[DIY 스마트팜] 파이썬 + 웹캠 + Cloudflare Tunnel을 이용한 간이 CCTV 구축
개요
USB 웹캠이 연결된 PC에서 주기적으로 사진을 촬영하고, Cloudflare Tunnel을 이용하여 외부에서 휴대폰으로 확인할 수 있는 간이 CCTV 시스템을 구축한다.
특징:
무료
포트포워딩 불필요
공인 IP 불필요
공유기 설정 불필요
휴대폰 브라우저로 접속 가능
Python만으로 구현 가능
시스템 구성
USB 웹캠
↓
Python(OpenCV)
↓
latest.jpg 생성
Python HTTP Server
↓
localhost:8000
Cloudflare Tunnel
↓
https://xxxxx.trycloudflare.com
휴대폰 브라우저
프로젝트 폴더 구조
camera_server/
├── camera.py
├── index.html
└── latest.jpg
1. OpenCV 설치
pip install opencv-python
설치 확인:
python -c "import cv2; print(cv2.__version__)"
2. 웹캠 촬영 프로그램
camera.py
import cv2
import time
from datetime import datetime
# 웹캠 열기
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("카메라 열기 실패")
exit()
print("카메라 시작")
try:
while True:
ret, frame = cap.read()
if not ret:
print("프레임 읽기 실패")
time.sleep(1)
continue
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cv2.putText(
frame,
timestamp,
(20, 40),
cv2.FONT_HERSHEY_SIMPLEX,
1.0,
(0, 255, 0),
2,
cv2.LINE_AA
)
success = cv2.imwrite(
"latest.jpg",
frame
)
if success:
print(f"촬영 완료 : {timestamp}")
else:
print("이미지 저장 실패")
time.sleep(1)
except KeyboardInterrupt:
print("종료 요청")
finally:
cap.release()
print("카메라 종료")
기능:
1초마다 웹캠 촬영
촬영 시각 오버레이 표시
latest.jpg 갱신
3. 웹 페이지
index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: black;
overflow: hidden;
}
.container {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
#cam {
width: 100%;
height: 100%;
object-fit: contain;
}
</style>
</head>
<body>
<div class="container">
<img id="cam" src="latest.jpg">
</div>
<script>
const cam = document.getElementById("cam");
setInterval(() => {
cam.src = "latest.jpg?t=" + Date.now();
}, 1000);
</script>
</body>
</html>
기능:
모바일/PC 반응형 지원
전체 화면 표시
1초마다 자동 갱신
브라우저 캐시 방지
4. Python 웹서버 실행
camera_server 폴더에서:
python -m http.server 8000
브라우저 접속:
http://localhost:8000
정상적으로 이미지가 보이면 성공.
5. Cloudflare Tunnel 설치
Cloudflare Tunnel 실행 파일 다운로드
https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/
Windows AMD64 버전:
cloudflared-windows-amd64.exe
6. Cloudflare Tunnel 실행
명령 프롬프트:
cloudflared-windows-amd64.exe tunnel --url http://localhost:8000
실행 예:
Your quick Tunnel has been created!
https://partly-flexibility-raid-experiences.trycloudflare.com
생성된 주소를 복사한다.
7. 휴대폰 접속
휴대폰 브라우저에서:
https://partly-flexibility-raid-experiences.trycloudflare.com
접속.
현재 PC 웹캠 화면이 실시간으로 표시된다.
실행 순서
창 1
python camera.py
창 2
python -m http.server 8000
창 3
cloudflared-windows-amd64.exe tunnel --url http://localhost:8000
장점
완전 무료
포트포워딩 불필요
공유기 설정 불필요
공인 IP 불필요
Firebase 불필요
서버 구축 불필요
스마트폰에서 즉시 확인 가능
향후 확장 아이디어
움직임 감지(Motion Detection)
타임랩스 생성
여러 대 카메라 지원
온도/습도 표시
PLC 상태 표시
스마트팜 대시보드 통합
QR 코드 접속
PWA(Web App) 형태로 홈 화면 설치
참고사항
Quick Tunnel은 테스트 및 개인 용도에 적합하다.
https://xxxxx.trycloudflare.com
주소는 Cloudflare Tunnel 재실행 시 변경될 수 있다.
장기간 운영 시에는 Cloudflare 계정을 생성하여 Named Tunnel과 고정 도메인을 사용하는 것을 권장한다.
댓글
댓글 쓰기