김유현

Add RFIDProcess, RemoteProcess & Add 기기추가요청api, 원격잠금해제api

...@@ -5,3 +5,5 @@ db.sqlite3 ...@@ -5,3 +5,5 @@ db.sqlite3
5 /static 5 /static
6 .DS_Store 6 .DS_Store
7 *.json 7 *.json
8 +venv/
9 +.idea/
......
1 from django.contrib import admin 1 from django.contrib import admin
2 -from .models import Video, Device, History, Lock, Record, Door 2 +from .models import Video, Device, RemoteHistory, Lock, Record, Door
3 # Register your models here. 3 # Register your models here.
4 admin.site.register(Door) 4 admin.site.register(Door)
5 admin.site.register(Video) 5 admin.site.register(Video)
6 admin.site.register(Device) 6 admin.site.register(Device)
7 -admin.site.register(History) 7 +admin.site.register(RemoteHistory)
8 admin.site.register(Lock) 8 admin.site.register(Lock)
9 admin.site.register(Record) 9 admin.site.register(Record)
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -15,7 +15,8 @@ class Migration(migrations.Migration): ...@@ -15,7 +15,8 @@ class Migration(migrations.Migration):
15 migrations.CreateModel( 15 migrations.CreateModel(
16 name='Device', 16 name='Device',
17 fields=[ 17 fields=[
18 - ('rfid_id', models.CharField(max_length=255, primary_key=True, serialize=False)), 18 + ('device_id', models.AutoField(primary_key=True, serialize=False)),
19 + ('rfid_id', models.CharField(max_length=255)),
19 ('created', models.DateTimeField(default=django.utils.timezone.now)), 20 ('created', models.DateTimeField(default=django.utils.timezone.now)),
20 ], 21 ],
21 ), 22 ),
...@@ -26,14 +27,6 @@ class Migration(migrations.Migration): ...@@ -26,14 +27,6 @@ class Migration(migrations.Migration):
26 ], 27 ],
27 ), 28 ),
28 migrations.CreateModel( 29 migrations.CreateModel(
29 - name='History',
30 - fields=[
31 - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
32 - ('device_name', models.CharField(max_length=255)),
33 - ('ctrtime', models.DateTimeField(default=django.utils.timezone.now)),
34 - ],
35 - ),
36 - migrations.CreateModel(
37 name='Lock', 30 name='Lock',
38 fields=[ 31 fields=[
39 ('id', models.IntegerField(primary_key=True, serialize=False)), 32 ('id', models.IntegerField(primary_key=True, serialize=False)),
...@@ -48,6 +41,14 @@ class Migration(migrations.Migration): ...@@ -48,6 +41,14 @@ class Migration(migrations.Migration):
48 ], 41 ],
49 ), 42 ),
50 migrations.CreateModel( 43 migrations.CreateModel(
44 + name='RemoteHistory',
45 + fields=[
46 + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
47 + ('device_name', models.CharField(max_length=255)),
48 + ('ctrtime', models.DateTimeField(default=django.utils.timezone.now)),
49 + ],
50 + ),
51 + migrations.CreateModel(
51 name='Video', 52 name='Video',
52 fields=[ 53 fields=[
53 ('vid_name', models.CharField(max_length=255, primary_key=True, serialize=False)), 54 ('vid_name', models.CharField(max_length=255, primary_key=True, serialize=False)),
......
...@@ -7,7 +7,8 @@ class Door(models.Model) : ...@@ -7,7 +7,8 @@ class Door(models.Model) :
7 door_id = models.CharField(max_length = 255, primary_key = True) 7 door_id = models.CharField(max_length = 255, primary_key = True)
8 8
9 class Device(models.Model) : 9 class Device(models.Model) :
10 - rfid_id = models.CharField(max_length = 255, primary_key = True) 10 + device_id = models.AutoField(primary_key=True)
11 + rfid_id = models.CharField(max_length = 255)
11 created = models.DateTimeField(default = timezone.now) 12 created = models.DateTimeField(default = timezone.now)
12 13
13 class Video(models.Model) : 14 class Video(models.Model) :
...@@ -20,9 +21,9 @@ class Lock(models.Model) : ...@@ -20,9 +21,9 @@ class Lock(models.Model) :
20 id = models.IntegerField(primary_key = True) 21 id = models.IntegerField(primary_key = True)
21 state = models.BooleanField(default = True) 22 state = models.BooleanField(default = True)
22 23
23 -class History(models.Model) : 24 +class RemoteHistory(models.Model) :
24 device_name = models.CharField(max_length = 255) 25 device_name = models.CharField(max_length = 255)
25 - ctrtime = models.DateTimeField(default = timezone.now) 26 + created = models.DateTimeField(default = timezone.now)
26 27
27 class Record(models.Model) : 28 class Record(models.Model) :
28 id = models.IntegerField(primary_key = True) 29 id = models.IntegerField(primary_key = True)
......
1 -from api.models import Device, Video, Lock, History, Record, Door, AddDevice 1 +from api.models import Device, Video, Lock, RemoteHistory, Record, Door, AddDevice
2 from rest_framework import serializers 2 from rest_framework import serializers
3 3
4 class DoorSerializer(serializers.ModelSerializer) : 4 class DoorSerializer(serializers.ModelSerializer) :
...@@ -16,9 +16,9 @@ class VideoSerializer(serializers.ModelSerializer) : ...@@ -16,9 +16,9 @@ class VideoSerializer(serializers.ModelSerializer) :
16 model = Video 16 model = Video
17 fields = '__all__' 17 fields = '__all__'
18 18
19 -class HistorySerializer(serializers.ModelSerializer) : 19 +class RemoteHistorySerializer(serializers.ModelSerializer) :
20 class Meta : 20 class Meta :
21 - model = History 21 + model = RemoteHistory
22 fields = '__all__' 22 fields = '__all__'
23 23
24 class RecordSerializer(serializers.ModelSerializer) : 24 class RecordSerializer(serializers.ModelSerializer) :
......
...@@ -7,8 +7,9 @@ from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist ...@@ -7,8 +7,9 @@ from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist
7 from django.shortcuts import render 7 from django.shortcuts import render
8 8
9 from api.videorecord import record 9 from api.videorecord import record
10 -from api.models import Video, Device, History, Lock, Record, Door, AddDevice 10 +from api.models import Video, Device, RemoteHistory, Lock, Record, Door
11 -from api.serializers import VideoSerializer, DeviceSerializer, HistorySerializer, RecordSerializer 11 +from api.serializers import VideoSerializer, DeviceSerializer, RemoteHistorySerializer, RecordSerializer, LockSerializer
12 +
12 13
13 from rest_framework import status 14 from rest_framework import status
14 from rest_framework.views import APIView 15 from rest_framework.views import APIView
...@@ -22,8 +23,143 @@ from src.settings import S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_STORAGE_BUCK ...@@ -22,8 +23,143 @@ from src.settings import S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_STORAGE_BUCK
22 """ 23 """
23 import time 24 import time
24 from datetime import datetime, timedelta 25 from datetime import datetime, timedelta
26 +import json
25 # Create your views here. 27 # Create your views here.
26 28
29 +#로그인 및 토큰 반환
30 +class Login(APIView) :
31 + def get(self, request, format = None) : # request query에 door_id 포함되어있음 : api/auth?door_id=12345
32 + try :
33 + request_id = request.GET.get('door_id', None)
34 + if request_id == None :
35 + raise FieldDoesNotExist
36 + queryset = Door.objects.filter(door_id = request_id) # door_id 유효성 검색
37 + if queryset.exists() :# 유효할 때
38 + res = {
39 + 'is_available' : True,
40 + 'access_token' : '토큰' # 토큰 도입 후 수정 필요
41 + }
42 + else :
43 + res = {
44 + 'is_available' : False
45 + }
46 +
47 + return Response(res, status = status.HTTP_200_OK)
48 +
49 + except FieldDoesNotExist as error :
50 + return Response({
51 + 'error' : "FieldDoesNotExist ",
52 + 'date' : datetime.now()
53 + }, status = status.HTTP_400_BAD_REQUEST)
54 +
55 +#기기 관련 api
56 +class Devices(APIView) :
57 + # 기기 목록 조회
58 + def get(self, request, format = None) :
59 + queryset = Device.objects.all()
60 + serializer = DeviceSerializer(queryset, many = True)
61 + res = {
62 + 'deviceList': serializer.data
63 + }
64 + return Response(res, status = status.HTTP_200_OK)
65 +
66 + # 기기 추가 요청
67 + def put(self, request, format = None) :
68 + try :
69 + print(request.body)
70 + data = json.loads(request.body)
71 + rfid_id = data.get('rfid_id', None)
72 + res = {
73 + 'rfid_id': rfid_id
74 + }
75 + if rfid_id == None:
76 + raise FieldDoesNotExist
77 + return Response(res, status = status.HTTP_200_OK)
78 + except FieldDoesNotExist as error :
79 + return Response({
80 + 'error' : "FieldDoesNotExist ",
81 + 'date' : datetime.now()
82 + }, status = status.HTTP_400_BAD_REQUEST)
83 +
84 + # 기기 추가
85 + def post(self, request, format = None) : # request body에 rfid_id 포함되어있음 
86 + try :
87 + print(request.body)
88 + data = json.loads(request.body)
89 + request_id = data.get('rfid_id', None)
90 + if request_id == None :
91 + raise FieldDoesNotExist
92 + queryset = Device.objects.create(rfid_id = request_id)
93 + return Response({
94 + 'msg' : 'success device add'
95 + })
96 +
97 + except FieldDoesNotExist as error :
98 + return Response({
99 + 'error' : "FieldDoesNotExist ",
100 + 'date' : datetime.now()
101 + }, status = status.HTTP_400_BAD_REQUEST)
102 +
103 +
104 +
105 + # 기기 삭제
106 + def delete(self, request, device_id, format = None): # request URI에 device_id(자동생성되는 기기 고유 번호 != rfid_id) 포함
107 + try :
108 + request_id = device_id
109 + if request_id == None:
110 + raise FieldDoesNotExist
111 + queryset = Device.objects.get(device_id=request_id)
112 + queryset.delete()
113 + return Response({
114 + 'msg' : 'success delete device'
115 + })
116 +
117 + except FieldDoesNotExist as error :
118 + return Response({
119 + 'error' : "FieldDoesNotExist ",
120 + 'date' : datetime.now()
121 + }, status = status.HTTP_400_BAD_REQUEST)
122 +
123 +# 원격 잠금 해제
124 +class Remote(APIView):
125 + # 원격 잠금 해제 기록 조회
126 + def get(self, request, format = None) :
127 + #models.py의 class History 사용.
128 + queryset = RemoteHistory.objects.all()
129 + serializer = RemoteHistorySerializer(queryset, many = True)
130 + res = {
131 + "remoteHistoryList": serializer.data
132 + }
133 + return Response(res, status = status.HTTP_200_OK)
134 +
135 + # 원격 잠금 해제
136 + def post(self, request, format = None) :
137 + try:
138 + print(request.body)
139 + data = json.loads(request.body)
140 + device_name = data.get('device_name', None)
141 + if device_name == None :
142 + raise FieldDoesNotExist
143 + else:
144 + # 잠금 상태 변경
145 + target = Lock.objects.get(id=1)
146 + serializer = LockSerializer(target, many=False)
147 + state = serializer.data['state']
148 + if state == True:
149 + print(">> 원격 잠금해제 요청이 들어옴")
150 + target.state = False
151 + target.save()
152 + return Response({
153 + 'msg' : 'success remote unlock'
154 + }, status = status.HTTP_200_OK)
155 + except FieldDoesNotExist as error:
156 + return Response({
157 + 'error': "FieldDoesNotExist ",
158 + 'date': datetime.now()
159 + }, status=status.HTTP_400_BAD_REQUEST)
160 +
161 +
162 +
27 # 비디오 목록 조회 163 # 비디오 목록 조회
28 class VideoList(APIView) : 164 class VideoList(APIView) :
29 def get(self, request, format = None) : 165 def get(self, request, format = None) :
......
1 -#-*- coding:utf-8 -*- 1 +# -*- coding:utf-8 -*-
2 2
3 import time 3 import time
4 import RPi.GPIO as GPIO 4 import RPi.GPIO as GPIO
5 +import mfrc522
6 +import requests
5 from multiprocessing import Queue 7 from multiprocessing import Queue
6 import os 8 import os
9 +import django
7 10
11 +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings')
12 +django.setup()
13 +
14 +from django.core import serializers
15 +from api.models import Lock, AddDevice, Device
16 +from api.serializers import LockSerializer, AddDeviceSerializer, DeviceSerializer
17 +
18 +
19 +MFIAREReader = mfrc522.MFRC522() # RFID Reader
20 +BASE_URL = "http://127.0.0.1:8000"
8 PIN = { 21 PIN = {
9 - 'Motor_MT_N':17, 22 + 'Motor_MT_N': 17,
10 - 'Motor_MT_P':4 23 + 'Motor_MT_P': 4
11 } 24 }
12 25
26 +
13 class Motor: 27 class Motor:
14 LEFT = 0 28 LEFT = 0
15 RIGHT = 1 29 RIGHT = 1
...@@ -34,9 +48,10 @@ class Motor: ...@@ -34,9 +48,10 @@ class Motor:
34 self.pwmP.ChangeDutyCycle(0) 48 self.pwmP.ChangeDutyCycle(0)
35 self.pwmN.ChangeDutyCycle(0) 49 self.pwmN.ChangeDutyCycle(0)
36 50
51 +
37 def RFIDProcess(signalQueue): 52 def RFIDProcess(signalQueue):
38 while True: 53 while True:
39 - ################## 이곳을 지우고 코드를 작성해주세요 ################ 54 + """
40 # RFID ID가 등록된 기기의 ID인 경우 success에 True를 넣습니다. 55 # RFID ID가 등록된 기기의 ID인 경우 success에 True를 넣습니다.
41 # 56 #
42 # RFID 태그가 된 경우 API에 요청을 보내 (GET /api/device) ID 목록을 57 # RFID 태그가 된 경우 API에 요청을 보내 (GET /api/device) ID 목록을
...@@ -50,48 +65,70 @@ def RFIDProcess(signalQueue): ...@@ -50,48 +65,70 @@ def RFIDProcess(signalQueue):
50 # 그냥 기기 목록에 태그된 기기의 ID를 추가합니다. 65 # 그냥 기기 목록에 태그된 기기의 ID를 추가합니다.
51 # 66 #
52 # success가 True인 경우 모터가 회전합니다. 67 # success가 True인 경우 모터가 회전합니다.
53 - # 68 + """
54 - # 아래 코드는 테스트를 위한 코드입니다. 아래 코드까지 지우고 작성해주세요. 69 + success = False
55 - time.sleep(30) 70 + try:
56 - success = True 71 + (readerStatus, tagType) = MFIAREReader.MFRC522_Request(MFIAREReader.PICC_REQIDL)
57 - ############################################################## 72 + (readerStatus, uid) = MFIAREReader.MFRC522_Anticoll() # uid = [1, 2, 3, 4, 5]
58 - # 73 + if readerStatus == MFIAREReader.MI_OK: # if RFID 태그가 됨:
59 - # 복잡한 것 같아 수도코드를 첨부합니다. 74 + deviceId = "" # 방금 태그된 RFID 장치의 ID.
60 - # 75 + for i in uid:
61 - # success = False 76 + deviceId += str(i) # deviceId = 12345
62 - # if RFID 태그가 됨: 77 +
63 - # deviceId = 방금 태그된 RFID 장치의 ID 78 + # devices = callApi(GET /api/device) # 기기 조회
64 - # devices = callApi(GET /api/device) 79 + response = requests.get(BASE_URL+"/api/device")
80 + deviceList = [] # 기기 목록
81 + if response.status_code == 200:
82 + deviceList = (response.json()['deviceList'])
83 +
65 # state = getFromIPC(원격 잠금해제 여부) 84 # state = getFromIPC(원격 잠금해제 여부)
66 - # 85 + target = Lock.objects.get(id=1) # 장고 모델에서 잠금 상태 모델(Lock) 객체 가져옴
67 - # if state == 원격 잠금해제: 86 + serializer = LockSerializer(target, many=False) # python 데이터타입으로 변환
68 - # try: 87 + state = serializer.data['state'] # state에 저장(boolean)
69 - # if devices.find(deviceId): 88 +
70 - # raise 이미 등록된 RFID 장치 89 + findDevice = False # 기기 등록 여부
71 - # else: 90 + for i in deviceList:
72 - # callApi(POST /api/device, {rfid_id:deviceId}) 91 + if deviceId in i["rfid"]:
73 - # (가능하다면) 완료됐다는 소리 출력 (딩동댕 정도?) 92 + findDevice = True
74 - # except: 93 +
75 - # (가능하다면) 경고음 출력 (삑!) 94 + if state == False: # if state == 원격 잠금해제:
76 - # finally: 95 + try:
77 - # setToIPC(원격 잠금해제 여부, 원격 잠금해제 아님) 96 + if findDevice: # if devices.find(deviceId):
78 - # else: # 원격 잠금해제 상태가 아님 = 도어락 해제 프로세스 97 + print("이미 등록된 RFID 장치") # raise
79 - # try: 98 + pass
80 - # if not devices.find(deviceId): 99 + else:
81 - # raise 등록되지 않은 RFID 장치 100 + # callApi(POST /api/device, {rfid_id:deviceId}) # 기기 추가
82 - # else: 101 + requests.post(BASE_URL+"/api/device", data={"rfid_id": deviceId})
83 - # success = True 102 + print("딩동댕 ~ 완료하였습니다") # 소리 출력
84 - # except: 103 + pass
85 - # (가능하다면) 경고음 출력 (삑!) 104 + except:
86 - # 105 + print("경고음 삑 -!")
87 - ############################################################## 106 + pass
107 + finally: # setToIPC(원격 잠금해제 여부, 원격 잠금해제 아님)
108 + target.state = True
109 + target.save()
110 + else: # 원격 잠금해제 상태가 아님 = 도어락 해제 프로세스
111 + try:
112 + if not findDevice: # if not devices.find(deviceId)
113 + print("등록되지 않은 RFID 장치") # raise
114 + pass
115 + else:
116 + success = True
117 + except:
118 + print("경고음 삑 -!") # 소리 출력
119 + pass
120 +
88 if success: 121 if success:
89 print("등록된 RFID ID가 확인됨") 122 print("등록된 RFID ID가 확인됨")
90 signalQueue.put("RFID") 123 signalQueue.put("RFID")
124 + except KeyboardInterrupt:
125 + pass
126 + # GPIO.cleanup()
127 +
91 128
92 def RemoteProcess(signalQueue): 129 def RemoteProcess(signalQueue):
93 while True: 130 while True:
94 - ################## 이곳을 지우고 코드를 작성해주세요 ################ 131 + """
95 # 원격 잠금해제 요청이 들어온 경우 success에 True를 넣습니다. 132 # 원격 잠금해제 요청이 들어온 경우 success에 True를 넣습니다.
96 # 원격 잠금해제 요청은 IPC로 처리합니다. 133 # 원격 잠금해제 요청은 IPC로 처리합니다.
97 # 지우님과 협업하여 작업해주세요. 134 # 지우님과 협업하여 작업해주세요.
...@@ -101,15 +138,20 @@ def RemoteProcess(signalQueue): ...@@ -101,15 +138,20 @@ def RemoteProcess(signalQueue):
101 # 원격 잠금해제 요청이 들어온 경우 API에서 write하도록 하면 되겠죠..? 138 # 원격 잠금해제 요청이 들어온 경우 API에서 write하도록 하면 되겠죠..?
102 # 139 #
103 # success가 True인 경우 모터가 회전합니다. 140 # success가 True인 경우 모터가 회전합니다.
104 - # 141 + """
105 - # 아래 코드는 테스트를 위한 코드입니다. 아래 코드까지 지우고 작성해주세요. 142 + success = False
106 - time.sleep(13) 143 + target = Lock.objects.get(id=1) # 장고 모델에서 잠금 상태 모델(Lock) 객체 가져옴
144 + serializer = LockSerializer(target, many=False) # python 데이터타입으로 변환
145 + state = serializer.data['state'] # state에 저장(boolean)
146 + if state == False: # 잠금 해제 요청이 왔을 경우
147 + print(">> 원격 잠금해제 요청이 들어옴")
107 success = True 148 success = True
108 - ############################################################## 149 + target.state = True # 다시 잠금 상태로
150 + target.save() # 바꾼 값으로 db에 저장
109 if success: 151 if success:
110 - print("원격 잠금해제 요청이 들어옴")
111 signalQueue.put("Remote") 152 signalQueue.put("Remote")
112 153
154 +
113 def signalProcess(signalQueue): 155 def signalProcess(signalQueue):
114 pid = os.fork() 156 pid = os.fork()
115 if pid == 0: 157 if pid == 0:
...@@ -117,6 +159,7 @@ def signalProcess(signalQueue): ...@@ -117,6 +159,7 @@ def signalProcess(signalQueue):
117 else: 159 else:
118 RemoteProcess(signalQueue) 160 RemoteProcess(signalQueue)
119 161
162 +
120 def doorProcess(doorQueue): 163 def doorProcess(doorQueue):
121 motor = Motor() 164 motor = Motor()
122 while True: 165 while True:
...@@ -133,11 +176,12 @@ def doorProcess(doorQueue): ...@@ -133,11 +176,12 @@ def doorProcess(doorQueue):
133 time.sleep(0.5) 176 time.sleep(0.5)
134 motor.stop() 177 motor.stop()
135 178
179 +
136 if __name__ == '__main__': 180 if __name__ == '__main__':
137 try: 181 try:
138 - GPIO.setmode(GPIO.BCM) 182 + # GPIO.setmode(GPIO.BCM)
139 - GPIO.setup(PIN['Motor_MT_N'], GPIO.OUT, initial=GPIO.LOW) 183 + # GPIO.setup(PIN['Motor_MT_N'], GPIO.OUT, initial=GPIO.LOW)
140 - GPIO.setup(PIN['Motor_MT_P'], GPIO.OUT, initial=GPIO.LOW) 184 + # GPIO.setup(PIN['Motor_MT_P'], GPIO.OUT, initial=GPIO.LOW)
141 185
142 signalQueue = Queue() 186 signalQueue = Queue()
143 pid = os.fork() 187 pid = os.fork()
...@@ -148,7 +192,9 @@ if __name__ == '__main__': ...@@ -148,7 +192,9 @@ if __name__ == '__main__':
148 while True: 192 while True:
149 signal = signalQueue.get() 193 signal = signalQueue.get()
150 print("{} 신호가 들어와 전달 준비".format(signal)) 194 print("{} 신호가 들어와 전달 준비".format(signal))
195 + print(signal)
151 if signal is not None: 196 if signal is not None:
197 + print("signal is not None")
152 doorQueue.put(signal) 198 doorQueue.put(signal)
153 else: 199 else:
154 doorProcess(doorQueue) 200 doorProcess(doorQueue)
...@@ -157,4 +203,5 @@ if __name__ == '__main__': ...@@ -157,4 +203,5 @@ if __name__ == '__main__':
157 except Exception as e: 203 except Exception as e:
158 print(e) 204 print(e)
159 finally: 205 finally:
160 - GPIO.cleanup()
...\ No newline at end of file ...\ No newline at end of file
206 + pass
207 + # GPIO.cleanup()
......
...@@ -24,4 +24,8 @@ urlpatterns = [ ...@@ -24,4 +24,8 @@ urlpatterns = [
24 path('api/video/<str:vid_name>', views.VideoDownload.as_view()), 24 path('api/video/<str:vid_name>', views.VideoDownload.as_view()),
25 path('auto/checkDate', views.CheckDate.as_view()), 25 path('auto/checkDate', views.CheckDate.as_view()),
26 path('api/setting', views.Recording.as_view()), 26 path('api/setting', views.Recording.as_view()),
27 + path('api/auth', views.Login.as_view()),
28 + path('api/device', views.Devices.as_view()),
29 + path('api/device/<str:device_id>', views.Devices.as_view()),
30 + path('api/remote', views.Remote.as_view()),
27 ] 31 ]
......