김유현

Modify videorecord and doorlock process

...@@ -7,3 +7,4 @@ db.sqlite3 ...@@ -7,3 +7,4 @@ db.sqlite3
7 *.json 7 *.json
8 venv/ 8 venv/
9 .idea/ 9 .idea/
10 +*.out
......
1 -# Generated by Django 3.1.2 on 2020-11-18 11:21 1 +# Generated by Django 3.1.2 on 2020-11-20 01:49
2 2
3 from django.db import migrations, models 3 from django.db import migrations, models
4 import django.utils.timezone 4 import django.utils.timezone
...@@ -13,6 +13,13 @@ class Migration(migrations.Migration): ...@@ -13,6 +13,13 @@ class Migration(migrations.Migration):
13 13
14 operations = [ 14 operations = [
15 migrations.CreateModel( 15 migrations.CreateModel(
16 + name='AddDevice',
17 + fields=[
18 + ('id', models.IntegerField(primary_key=True, serialize=False)),
19 + ('state', models.BooleanField(default=False)),
20 + ],
21 + ),
22 + migrations.CreateModel(
16 name='Device', 23 name='Device',
17 fields=[ 24 fields=[
18 ('device_id', models.AutoField(primary_key=True, serialize=False)), 25 ('device_id', models.AutoField(primary_key=True, serialize=False)),
...@@ -45,7 +52,7 @@ class Migration(migrations.Migration): ...@@ -45,7 +52,7 @@ class Migration(migrations.Migration):
45 fields=[ 52 fields=[
46 ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 53 ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
47 ('device_name', models.CharField(max_length=255)), 54 ('device_name', models.CharField(max_length=255)),
48 - ('ctrtime', models.DateTimeField(default=django.utils.timezone.now)), 55 + ('created', models.DateTimeField(default=django.utils.timezone.now)),
49 ], 56 ],
50 ), 57 ),
51 migrations.CreateModel( 58 migrations.CreateModel(
......
1 -# Generated by Django 3.1.2 on 2020-11-18 19:55
2 -
3 -from django.db import migrations, models
4 -
5 -
6 -class Migration(migrations.Migration):
7 -
8 - dependencies = [
9 - ('api', '0001_initial'),
10 - ]
11 -
12 - operations = [
13 - migrations.CreateModel(
14 - name='AddDevice',
15 - fields=[
16 - ('id', models.IntegerField(primary_key=True, serialize=False)),
17 - ('add', models.BooleanField(default=False)),
18 - ],
19 - ),
20 - ]
...@@ -111,8 +111,8 @@ class Devices(APIView) : ...@@ -111,8 +111,8 @@ class Devices(APIView) :
111 # 기기 추가 111 # 기기 추가
112 def post(self, request, format = None) : # request body에 rfid_id 포함되어있음  112 def post(self, request, format = None) : # request body에 rfid_id 포함되어있음 
113 try : 113 try :
114 - print(request.body) 114 + print(request.data)
115 - data = json.loads(request.body) 115 + data = {x: request.POST.get(x) for x in request.POST.keys()}
116 request_id = data.get('rfid_id', None) 116 request_id = data.get('rfid_id', None)
117 if request_id == None : 117 if request_id == None :
118 raise FieldDoesNotExist 118 raise FieldDoesNotExist
......
...@@ -7,7 +7,10 @@ import requests ...@@ -7,7 +7,10 @@ import requests
7 from multiprocessing import Queue 7 from multiprocessing import Queue
8 import os 8 import os
9 import django 9 import django
10 +import datetime
11 +import sys
10 12
13 +sys.path.append('/home/pi/Desktop/smartdoorlock-backend')
11 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings') 14 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings')
12 django.setup() 15 django.setup()
13 16
...@@ -16,11 +19,12 @@ from api.models import Lock, AddDevice, Device ...@@ -16,11 +19,12 @@ from api.models import Lock, AddDevice, Device
16 from api.serializers import LockSerializer, AddDeviceSerializer, DeviceSerializer 19 from api.serializers import LockSerializer, AddDeviceSerializer, DeviceSerializer
17 20
18 21
22 +GPIO.setmode(GPIO.BCM)
19 MFIAREReader = mfrc522.MFRC522() # RFID Reader 23 MFIAREReader = mfrc522.MFRC522() # RFID Reader
20 BASE_URL = "http://127.0.0.1:8000" 24 BASE_URL = "http://127.0.0.1:8000"
21 PIN = { 25 PIN = {
22 - 'Motor_MT_N': 17, 26 + 'Motor_MT_N': 12,
23 - 'Motor_MT_P': 4 27 + 'Motor_MT_P': 6
24 } 28 }
25 29
26 30
...@@ -51,48 +55,38 @@ class Motor: ...@@ -51,48 +55,38 @@ class Motor:
51 55
52 def RFIDProcess(signalQueue): 56 def RFIDProcess(signalQueue):
53 while True: 57 while True:
54 - """
55 - # RFID ID가 등록된 기기의 ID인 경우 success에 True를 넣습니다.
56 - #
57 - # RFID 태그가 된 경우 API에 요청을 보내 (GET /api/device) ID 목록을
58 - # 가져온 후 이 목록 안에 태그된 기기의 ID가 있는지 여부를 확인하는 방식으로
59 - # 동작하면 될 것 같습니다.
60 - #
61 - # ID 목록을 미리 받아온 후 비교하도록 하면 ID 목록 업데이트가 안 될 수 있으니
62 - # 태그가 된 경우 ID 목록을 받아오도록 해주세요.
63 - #
64 - # 기기 추가 상태인 경우를 확인해 기기 추가 상태라면 success를 True로 하지 않고
65 - # 그냥 기기 목록에 태그된 기기의 ID를 추가합니다.
66 - #
67 - # success가 True인 경우 모터가 회전합니다.
68 - """
69 success = False 58 success = False
70 try: 59 try:
71 (readerStatus, tagType) = MFIAREReader.MFRC522_Request(MFIAREReader.PICC_REQIDL) 60 (readerStatus, tagType) = MFIAREReader.MFRC522_Request(MFIAREReader.PICC_REQIDL)
72 (readerStatus, uid) = MFIAREReader.MFRC522_Anticoll() # uid = [1, 2, 3, 4, 5] 61 (readerStatus, uid) = MFIAREReader.MFRC522_Anticoll() # uid = [1, 2, 3, 4, 5]
73 if readerStatus == MFIAREReader.MI_OK: # if RFID 태그가 됨: 62 if readerStatus == MFIAREReader.MI_OK: # if RFID 태그가 됨:
63 + time.sleep(1)
64 + print("RIFD tag")
74 deviceId = "" # 방금 태그된 RFID 장치의 ID. 65 deviceId = "" # 방금 태그된 RFID 장치의 ID.
75 for i in uid: 66 for i in uid:
76 deviceId += str(i) # deviceId = 12345 67 deviceId += str(i) # deviceId = 12345
68 + print("DeviceID : ", deviceId)
77 69
78 # devices = callApi(GET /api/device) # 기기 조회 70 # devices = callApi(GET /api/device) # 기기 조회
79 response = requests.get(BASE_URL+"/api/device") 71 response = requests.get(BASE_URL+"/api/device")
80 deviceList = [] # 기기 목록 72 deviceList = [] # 기기 목록
81 if response.status_code == 200: 73 if response.status_code == 200:
74 + print("Success view device list")
82 deviceList = (response.json()['deviceList']) 75 deviceList = (response.json()['deviceList'])
83 - 76 + print("device list : ", deviceList)
84 # state = getFromIPC(기기추가여부) 77 # state = getFromIPC(기기추가여부)
85 78
86 - target = AddDevice.objects.get(id=1) # 장고 모델에서 잠금 상태 모델(Lock) 객체 가져옴 79 + target = AddDevice.objects.get(id=1) # 장고 모델에서 AddDevice 객체 가져옴
87 serializer = AddDeviceSerializer(target, many=False) # python 데이터타입으로 변환 80 serializer = AddDeviceSerializer(target, many=False) # python 데이터타입으로 변환
88 state = serializer.data['state'] # state에 저장(boolean) 81 state = serializer.data['state'] # state에 저장(boolean)
89 82
90 findDevice = False # 기기 등록 여부 83 findDevice = False # 기기 등록 여부
91 for i in deviceList: 84 for i in deviceList:
92 - if deviceId in i["rfid"]: 85 + if deviceId in i["rfid_id"]:
93 findDevice = True 86 findDevice = True
94 - 87 + print("findDevice : ", findDevice)
95 if state == True: # if state == 기기추가: 88 if state == True: # if state == 기기추가:
89 + print("1-1 AddDevice is True")
96 try: 90 try:
97 if findDevice: # if devices.find(deviceId): 91 if findDevice: # if devices.find(deviceId):
98 print("이미 등록된 RFID 장치") # raise 92 print("이미 등록된 RFID 장치") # raise
...@@ -109,6 +103,7 @@ def RFIDProcess(signalQueue): ...@@ -109,6 +103,7 @@ def RFIDProcess(signalQueue):
109 target.state = False 103 target.state = False
110 target.save() 104 target.save()
111 else: # 기기 추가 상태가 아님 = 도어락 해제 프로세스 105 else: # 기기 추가 상태가 아님 = 도어락 해제 프로세스
106 + print("1-2 Open Door")
112 try: 107 try:
113 if not findDevice: # if not devices.find(deviceId) 108 if not findDevice: # if not devices.find(deviceId)
114 print("등록되지 않은 RFID 장치") # raise 109 print("등록되지 않은 RFID 장치") # raise
...@@ -123,23 +118,12 @@ def RFIDProcess(signalQueue): ...@@ -123,23 +118,12 @@ def RFIDProcess(signalQueue):
123 print("등록된 RFID ID가 확인됨") 118 print("등록된 RFID ID가 확인됨")
124 signalQueue.put("RFID") 119 signalQueue.put("RFID")
125 except KeyboardInterrupt: 120 except KeyboardInterrupt:
126 - pass 121 + GPIO.cleanup()
127 - # GPIO.cleanup() 122 + break
128 123
129 124
130 def RemoteProcess(signalQueue): 125 def RemoteProcess(signalQueue):
131 while True: 126 while True:
132 - """
133 - # 원격 잠금해제 요청이 들어온 경우 success에 True를 넣습니다.
134 - # 원격 잠금해제 요청은 IPC로 처리합니다.
135 - # 지우님과 협업하여 작업해주세요.
136 - #
137 - # 제 생각으로는 한 파일에 대해서 (ex ~/IPC.txt) API에서는 write하고
138 - # 도어락 프로세스에서는 read하는 방법으로 하면 될 것 같습니다.
139 - # 원격 잠금해제 요청이 들어온 경우 API에서 write하도록 하면 되겠죠..?
140 - #
141 - # success가 True인 경우 모터가 회전합니다.
142 - """
143 success = False 127 success = False
144 target = Lock.objects.get(id=1) # 장고 모델에서 잠금 상태 모델(Lock) 객체 가져옴 128 target = Lock.objects.get(id=1) # 장고 모델에서 잠금 상태 모델(Lock) 객체 가져옴
145 serializer = LockSerializer(target, many=False) # python 데이터타입으로 변환 129 serializer = LockSerializer(target, many=False) # python 데이터타입으로 변환
...@@ -162,27 +146,27 @@ def signalProcess(signalQueue): ...@@ -162,27 +146,27 @@ def signalProcess(signalQueue):
162 146
163 147
164 def doorProcess(doorQueue): 148 def doorProcess(doorQueue):
165 - motor = Motor() 149 + # motor = Motor()
166 while True: 150 while True:
167 signal = doorQueue.get() 151 signal = doorQueue.get()
168 print("{} 신호를 받아 문 열기 동작 수행 시작".format(signal)) 152 print("{} 신호를 받아 문 열기 동작 수행 시작".format(signal))
169 if signal is not None: 153 if signal is not None:
170 print("문 열림") 154 print("문 열림")
171 - motor.rotate(Motor.LEFT) 155 + #motor.rotate(Motor.LEFT)
172 time.sleep(0.5) 156 time.sleep(0.5)
173 - motor.stop() 157 + #motor.stop()
174 time.sleep(5) # 열린 후 5초 지나면 닫힘 158 time.sleep(5) # 열린 후 5초 지나면 닫힘
175 print("문 닫힘") 159 print("문 닫힘")
176 - motor.rotate(Motor.RIGHT) 160 + #motor.rotate(Motor.RIGHT)
177 time.sleep(0.5) 161 time.sleep(0.5)
178 - motor.stop() 162 + #motor.stop()
179 163
180 164
181 if __name__ == '__main__': 165 if __name__ == '__main__':
182 try: 166 try:
183 - # GPIO.setmode(GPIO.BCM) 167 + GPIO.setmode(GPIO.BCM)
184 - # GPIO.setup(PIN['Motor_MT_N'], GPIO.OUT, initial=GPIO.LOW) 168 + #GPIO.setup(PIN['Motor_MT_N'], GPIO.OUT, initial=GPIO.LOW)
185 - # GPIO.setup(PIN['Motor_MT_P'], GPIO.OUT, initial=GPIO.LOW) 169 + #GPIO.setup(PIN['Motor_MT_P'], GPIO.OUT, initial=GPIO.LOW)
186 170
187 signalQueue = Queue() 171 signalQueue = Queue()
188 pid = os.fork() 172 pid = os.fork()
...@@ -192,6 +176,7 @@ if __name__ == '__main__': ...@@ -192,6 +176,7 @@ if __name__ == '__main__':
192 if pid == 0: 176 if pid == 0:
193 while True: 177 while True:
194 signal = signalQueue.get() 178 signal = signalQueue.get()
179 + print(signal)
195 print("{} 신호가 들어와 전달 준비".format(signal)) 180 print("{} 신호가 들어와 전달 준비".format(signal))
196 print(signal) 181 print(signal)
197 if signal is not None: 182 if signal is not None:
...@@ -202,7 +187,6 @@ if __name__ == '__main__': ...@@ -202,7 +187,6 @@ if __name__ == '__main__':
202 else: 187 else:
203 signalProcess(signalQueue) 188 signalProcess(signalQueue)
204 except Exception as e: 189 except Exception as e:
205 - print(e) 190 + raise e
206 finally: 191 finally:
207 - pass 192 + GPIO.cleanup()
208 - # GPIO.cleanup()
......
...@@ -4,7 +4,10 @@ import botocore ...@@ -4,7 +4,10 @@ import botocore
4 import time 4 import time
5 import datetime 5 import datetime
6 import django 6 import django
7 +import sys
8 +import json
7 9
10 +sys.path.append('/home/pi/Desktop/smartdoorlock-backend')
8 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings') 11 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings')
9 django.setup() 12 django.setup()
10 from django.core import serializers 13 from django.core import serializers
...@@ -17,19 +20,29 @@ import RPi.GPIO as GPIO ...@@ -17,19 +20,29 @@ import RPi.GPIO as GPIO
17 from picamera import PiCamera 20 from picamera import PiCamera
18 21
19 22
23 +
24 +def get_secret():
25 + file_path = "/home/pi/Desktop/smartdoorlock-backend/.aws_key.json"
26 + if os.path.exists(file_path):
27 + with open(file_path) as fp:
28 + secret_file = json.load(fp)['aws']
29 + access_key_id = secret_file.get('access_key_id', None)
30 + secret_access_key = secret_file.get('secret_access_key', None)
31 + return (access_key_id, secret_access_key)
32 + else:
33 + return False
34 +
20 def record() : 35 def record() :
21 path = '/home/pi/recorded' # save path 36 path = '/home/pi/recorded' # save path
22 37
23 target = Record.objects.get(id = 1) 38 target = Record.objects.get(id = 1)
24 serializer = RecordSerializer(target, many = False) 39 serializer = RecordSerializer(target, many = False)
25 state = serializer.data['recording'] 40 state = serializer.data['recording']
26 - #'''
27 # rpi setting 41 # rpi setting
28 GPIO.setmode(GPIO.BCM) 42 GPIO.setmode(GPIO.BCM)
29 pir_pin = 7 43 pir_pin = 7
30 GPIO.setup(pir_pin, GPIO.IN) 44 GPIO.setup(pir_pin, GPIO.IN)
31 camera = PiCamera() 45 camera = PiCamera()
32 - #'''
33 46
34 try: 47 try:
35 while state : 48 while state :
...@@ -38,6 +51,7 @@ def record() : ...@@ -38,6 +51,7 @@ def record() :
38 state = serializer.data['recording'] 51 state = serializer.data['recording']
39 52
40 if GPIO.input(pir_pin): # motion detected 53 if GPIO.input(pir_pin): # motion detected
54 + print("motion detected")
41 # take a video 55 # take a video
42 camera.resolution = [320, 240] 56 camera.resolution = [320, 240]
43 camera.start_preview() 57 camera.start_preview()
...@@ -61,19 +75,28 @@ def record() : ...@@ -61,19 +75,28 @@ def record() :
61 vid_time = time.strftime("%M:%S", time.gmtime(time.time()-start_time)) 75 vid_time = time.strftime("%M:%S", time.gmtime(time.time()-start_time))
62 76
63 # s3 upload 77 # s3 upload
64 - s3 = boto3.client('s3', region_name = 'ap-northeast-2') 78 + secret = get_secret()
65 - s3.upload_file(Filename = vid_path, Bucket = S3_STORAGE_BUCKET_NAME, Key = vid_name) 79 + if not secret:
66 - s3.upload_file(Filename = thumbnail_path, Bucket = S3_STORAGE_BUCKET_NAME, Key = vid_name + '_thumb') 80 + print(vid_path, "upload failed")
81 + print("please make credential file")
82 + exit(0)
83 + else:
84 + ACCESS_KEY, SECRET_KEY = secret
85 + s3 = boto3.client('s3', region_name = 'ap-northeast-2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY)
86 + s3.upload_file(Filename = vid_path, Bucket = S3_STORAGE_BUCKET_NAME, Key = vid_name)
87 + s3.upload_file(Filename = thumbnail_path, Bucket = S3_STORAGE_BUCKET_NAME, Key = vid_name + '_thumb')
67 88
68 - uploadVideo = {} 89 + uploadVideo = {}
69 - uploadVideo['vid_name'] = vid_name 90 + uploadVideo['vid_name'] = vid_name
70 - uploadVideo['created'] = now 91 + uploadVideo['created'] = now
71 - uploadVideo['vid_time'] = vid_time 92 + uploadVideo['vid_time'] = vid_time
72 - uploadVideo['thumb'] = S3_ACCESS_URL + vid_name + '_thumb' 93 + uploadVideo['thumb'] = S3_ACCESS_URL + vid_name + '_thumb'
73 - serializer = VideoSerializer(data = uploadVideo) 94 + serializer = VideoSerializer(data = uploadVideo)
74 - serializer.save() 95 + serializer.is_valid()
75 - print(vid_path, "upload success") 96 + serializer.save()
76 - os.remove(vid_path) 97 + print(vid_path, "upload success")
98 + os.remove(vid_path)
99 + os.remove(thumbnail_path)
77 else: 100 else:
78 camera.stop_preview() 101 camera.stop_preview()
79 except KeyboardInterrupt: 102 except KeyboardInterrupt:
......
...@@ -4,3 +4,7 @@ sqlparse==0.3.1 ...@@ -4,3 +4,7 @@ sqlparse==0.3.1
4 pytz==2020.1 4 pytz==2020.1
5 django-cors-headers==3.5.0 5 django-cors-headers==3.5.0
6 boto3==1.15.15 6 boto3==1.15.15
7 +requests==2.25.0
8 +mfrc522==0.0.7
9 +RPi.GPIO==0.7.0
10 +picamera==1.13
......
1 -import os
2 -import boto3
3 -import botocore
4 -import time
5 -import datetime
6 -import django
7 -
8 -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings')
9 -django.setup()
10 -from django.core import serializers
11 -from api.models import Video, Record
12 -from api.serializers import VideoSerializer, RecordSerializer
13 -'''
14 -from boto3.session import Session
15 -from src.settings import AWS_REGION, S3_ACCESS_URL, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_STORAGE_BUCKET_NAME
16 -import RPi.GPIO as GPIO
17 -from picamera import PiCamera
18 -'''
19 -
20 -def record() :
21 - path = '/home/pi/recorded' # save path
22 -
23 - target = Record.objects.get(id = 1)
24 - serializer = RecordSerializer(target, many = False)
25 - state = serializer.data['recording']
26 - #'''
27 - # rpi setting
28 - GPIO.setmode(GPIO.BCM)
29 - pir_pin = 7
30 - GPIO.setup(pir_pin, GPIO.IN)
31 - camera = PiCamera()
32 - #'''
33 -
34 - try:
35 - while state :
36 - target = Record.objects.get(id = 1)
37 - serializer = RecordSerializer(target, many = False)
38 - state = serializer.data['recording']
39 -
40 - if GPIO.input(pir_pin): # motion detected
41 - # take a video
42 - camera.resolution = [320, 240]
43 - camera.start_preview()
44 -
45 - now = datetime.datetime.now()
46 - start_time = time.time()
47 -
48 - vid_name = now.strftime('%Y%m%d-%H%M%S')
49 - vid_path = path + '/' + vid_name + '.h264'
50 - thumbnail_path = path + '/' + vid_name + '.jpg'
51 -
52 - camera.start_recording(output=vid_path)
53 - time.sleep(1)
54 - camera.capture(thumbnail_path)
55 - while GPIO.input(pir_pin) :
56 - print("recoring..")
57 - time.sleep(2)
58 - camera.stop_recording()
59 - camera.stop_preview()
60 -
61 - vid_time = time.strftime("%M:%S", time.gmtime(time.time()-start_time))
62 -
63 - # s3 upload
64 - '''
65 - s3 = boto3.client('s3', region_name = 'ap-northeast-2')
66 - s3.upload_file(Filename = vid_path, Bucket = S3_STORAGE_BUCKET_NAME, Key = vid_name)
67 - s3.upload_file(Filename = thumbnail_path, Bucket = S3_STORAGE_BUCKET_NAME, Key = vid_name + '_thumb')
68 -
69 - uploadVideo = {}
70 - uploadVideo['vid_name'] = vid_name
71 - uploadVideo['created'] = now
72 - uploadVideo['vid_time'] = vid_time
73 - uploadVideo['thumb'] = S3_ACCESS_URL + vid_name + '_thumb'
74 - serializer = VideoSerializer(data = uploadVideo)
75 - serializer.save()
76 - '''
77 - print(vid_path, "upload success")
78 - os.remove(vid_path)
79 - else:
80 - camera.stop_preview()
81 - except KeyboardInterrupt:
82 - print("quit")
83 - GPIO.cleanup()
84 -
85 -
86 -if __name__ == '__main__':
87 - record()