-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
212 lines (167 loc) · 5.57 KB
/
main.py
File metadata and controls
212 lines (167 loc) · 5.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#TCP server Code
import time
import socket
import threading
import struct
import requests
import multiprocessing as mp
from pymongo import MongoClient
from queue import Queue
from threading import Lock
from call.Call import *
import ssl
MONGODB_URI = "mongodb+srv://SK:PickHacks@pickhacks.s50jyfl.mongodb.net/?retryWrites=true&w=majority&appName=PickHacks"
DB_NAME = "messages"
COLLECTION_NAME = "messages"
db_lock = Lock()
apikey = 'AIzaSyAvEcUwJvMn0mXPBx1g66Xlu-QCLI5OmB0'
def listConvert(listInput):
new = filtered_bytes = [byte for byte in listInput if byte != b'\x00']
ret = b''.join(filtered_bytes).decode('utf-8')
return ret
def policeLocation(latitude, longitude, apikey):
url = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json'
params = {
"fields": "formatted_address,name,geometry,place_id",
"input": "police",
"inputtype": "textquery",
"locationbias": f"circle:2000@{latitude}, {longitude}",
"key": apikey
}
response = requests.get(url, params=params)
data = response.json()
if data['status'] == 'OK' and data['candidates']:
place_id = data['candidates'][0].get('place_id')
return place_id
def policeDetails(placeid, apikey):
url2 = 'https://maps.googleapis.com/maps/api/place/details/json'
params2 = {
"fields": "name,formatted_phone_number",
"place_id": placeid,
"key": apikey
}
response2 = requests.get(url2, params=params2)
data2 = response2.json()
if data2['status'] == 'OK':
phone = data2['result'].get('formatted_phone_number')
name = data2['result'].get('name')
return phone, name
def numFormat(phoneNumber):
formattedNum = "+1"
if phoneNumber != None:
for x in list(phoneNumber):
if x.isdigit():
formattedNum += x
return formattedNum
def newClient(clientsocket, port):
maxCallTime = 60
client = MongoClient(MONGODB_URI, tlsInsecure=True)
db = client[DB_NAME]
namesend, receivedsend, stationID, stationNum, stationName, numsend = None, [], None, None, None, None
alertMsgRcvd = False
while not alertMsgRcvd:
data = clientsocket.recv(1024)
if not data:
break
alertMsgRcvd = True
s = struct.unpack("I128cff", data[0:140])
name = s[1: 129]
lat = float(s[129])
log = float(s[130])
received = " "
if (s[0] - 140 > 0):
received = struct.unpack(f"{s[0] - 140}c", data[140:])
namesend = listConvert(name)
receivedsend.append(listConvert(received))
stationID = policeLocation(lat, log, apikey)
stationNum, stationName = policeDetails(stationID, apikey)
numsend = numFormat(stationNum)
mngr = mp.Manager()
outboundLock = threading.Lock()
outboundMsg = mngr.list([])
inboundLock = threading.Lock()
inboundMsg = mngr.list([])
outboundMsg.append(f"Emergency Call from Alert App: Name is {namesend} Location: {lat} latitude and {log} longitude. Communicate with me and messaged will be transcribed to user")
print(f"Received message from {namesend}: ")
defaultNumber = "+15733032511"
# while db_lock.locked():
# time.sleep(0.001)
# with db_lock:
# collection = db[COLLECTION_NAME]
# messageData = {
# "Name: ": namesend,
# "Latitude: ": lat,
# "Longitude: ": log,
# "Alert Message: ": receivedsend,
# "Nearest Station Name: ": stationName,
# "Nearest Station Phone Number: ": numsend
# }
# print(f"Stuck in collection insertion")
# collection.insert_one(messageData)
# print("Data in MongoDB")
# sleep(1)
callThread = threading.Thread(target=Call, args=(defaultNumber, outboundMsg, inboundMsg, outboundLock, inboundLock, port, maxCallTime))
callThread.start()
init_time = perf_counter()
while perf_counter() - init_time < maxCallTime:
data = clientsocket.recv(1024)
if data:
s = struct.unpack("I128cff", data[0:140])
received = " "
if (s[0] - 140 > 0):
received = struct.unpack(f"{s[0] - 140}c", data[140:])
namesend = listConvert(name)
received = listConvert(received)
receivedsend.append(received)
while outboundLock.locked():
sleep(0.001)
with outboundLock:
outboundMsg.append(received)
print(f"Main Thread Outbound Msgs:\n{outboundMsg}")
#print(f'Arrived at inbound')
rcvdMessage = None
if len(inboundMsg) > 0:
while inboundLock.locked():
sleep(0.001)
with inboundLock:
rcvdMessage = ''.join([i for i in inboundMsg])
inboundMsg[:] = []
if (rcvdMessage != None):
rcvdMessageByte = [*rcvdMessage]
rcvdMessageByte = [char.encode("utf-8") for char in rcvdMessageByte]
msgSize = len(rcvdMessage)+4
msg = struct.pack(f"I{msgSize - 4}c", msgSize, *rcvdMessageByte)
clientsocket.send(msg)
receivedsend.append(rcvdMessage)
print(f"Main Thread Cur Inbound Msg:\n{rcvdMessage}")
sleep(2)
clientsocket.close()
while db_lock.locked():
time.sleep(0.001)
with db_lock:
collection = db[COLLECTION_NAME]
messageData = {
"Name: ": namesend,
"Latitude: ": lat,
"Longitude: ": log,
"Alert Message: ": receivedsend,
"Nearest Station Name: ": stationName,
"Nearest Station Phone Number: ": numsend
}
print(f"Stuck in collection insertion")
collection.insert_one(messageData)
print("Data in MongoDB")
def startServer():
portList = [ i for i in range(4950, 4980)]
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind(('172.28.39.248', 4760))
serverSocket.listen(5)
print("Server started. Waiting for connections...")
while True:
clientsocket, clientaddress = serverSocket.accept()
print(f"Connection from {clientaddress} established.")
clientThread = threading.Thread(target=newClient, args = (clientsocket,portList.pop(0)))
clientThread.start()
print("Client Thread Started")
if __name__ == "__main__":
startServer()