Skip to content

Commit 1b5a245

Browse files
committed
Cleaned up code
1 parent c28c21d commit 1b5a245

File tree

3 files changed

+66
-160
lines changed

3 files changed

+66
-160
lines changed

functions.py

Lines changed: 47 additions & 132 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,55 @@
11
from threading import Thread
22
import logging
33
import time
4-
# import sys
54
import socket
65
import datetime
76
import firebase_admin
87
from firebase_admin import credentials
98
from firebase_admin import firestore
10-
#logging.basicConfig(filename='event_log.log',level=logging.DEBUG)
11-
messageList = []
12-
'''
13-
SEND MESSAGE:
14-
in_module
15-
in_method
16-
check_args
17-
send
18-
'''
19-
# import subprocess
9+
10+
class listen_class:
11+
def __init__(self, listenList):
12+
self.messageList = listenList
13+
14+
def get_list(self):
15+
return self.messageList
16+
17+
def reset_list(self):
18+
self.messageList = []
19+
20+
def start_listen(self):
21+
t1 = Thread(target=self.listen, args=())
22+
t1.daemon = True
23+
t1.start()
24+
25+
def listen_test(self): # FOR TESTING
26+
while True:
27+
message = input("What is your message?")
28+
self.messageList.append(message)
29+
print(self.messageList)
30+
31+
def listen(self):
32+
UDP_IP = "127.0.0.1"
33+
RX_PORT = 5557
34+
while True:
35+
msg_lstn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
36+
msg_lstn.bind((UDP_IP, RX_PORT))
37+
ack, addr = msg_lstn.recvfrom(1024)
38+
if "to SATT4" in str(ack): #checks if message received was the one we just sent
39+
print("RX: ", end="")
40+
print(ack)
41+
self.messageList.append(ack)
42+
timestamp = get_time()
43+
city_ref = db.collection(u'Log').document(u'Listen')
44+
city_ref.update({
45+
timestamp : ack,
46+
})
47+
checksum = generate_checksum(ack)
48+
time.sleep(1)
2049
cred = credentials.Certificate("groundstation-listen-log-firebase-adminsdk-h2jfr-9d71ce0bdb.json")
2150
firebase_admin.initialize_app(cred)
22-
2351
db = firestore.client()
52+
2453
tx_port = 5555
2554
udp_ip = "127.0.0.1"
2655

@@ -69,24 +98,17 @@
6998
'_init_': _init_
7099
}
71100

72-
73101
def get_time(): # get_time()
74102
ts = time.time()
75103
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
76104
return (st)
77105

78-
79-
#def get_logger():
80-
#return (logging.getLogger("CI"))
81-
82-
83106
def print_arg(list):
84107
string = ""
85108
for arg in list:
86109
string += str(arg) + ","
87110
return (string[:-1])
88111

89-
90112
def generate_checksum(body: str):
91113
"""
92114
Given a message body, generate its checksum
@@ -97,190 +119,83 @@ def generate_checksum(body: str):
97119
sum1 = sum([ord(x) for x in body[0:-7]])
98120
sum1 %= 26
99121
sum1 += 65
100-
#logger = get_logger()
101-
#logger.debug('CHECKOUT :' + chr(sum1) + ";")
102122
return chr(sum1)
103123

104124
def check_checksum (body: str):
105125
body2 = body[:-1]
106126
checksum = generate_checksum(body2)
107127
if (checksum == body[-1]):
108128
return True;
109-
else: return False;
110-
class listen_class:
111-
def __init__(self, listenList):
112-
self.messageList = listenList
113-
# self.messageList.append(messageList)
129+
else:
130+
return False;
114131

115-
def get_list(self):
116-
return self.messageList
117-
118-
def reset_list(self):
119-
self.messageList = []
120-
121-
def start_listen(self):
122-
t1 = Thread(target=self.listen_test, args=())
123-
t1.daemon = True
124-
t1.start()
125-
126-
def listen_test(self): # FOR TESTING
127-
while True:
128-
message = input("What is your message?")
129-
self.messageList.append(message)
130-
print(self.messageList)
131-
132-
def listen(self):
133-
UDP_IP = "127.0.0.1"
134-
RX_PORT = 5557
135-
while True:
136-
msg_lstn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
137-
msg_lstn.bind((UDP_IP, RX_PORT))
138-
ack, addr = msg_lstn.recvfrom(1024)
139-
#print (ack)
140-
#time.sleep(1)
141-
#REDUDANCY CHECK
142-
if "to SATT4" in str(ack):
143-
# getTime()
144-
print("RX: ", end="")
145-
print(ack)
146-
self.messageList.append(ack)
147-
timestamp = get_time()
148-
city_ref = db.collection(u'Log').document(u'Listen')
149-
city_ref.update({
150-
timestamp : ack,
151-
})
152-
checksum = generate_checksum(ack)
153-
time.sleep(1)
154-
#self.messageList.append(ack)
155-
# return(str(ack))
156-
#print ("RX: " + get_time(), end="")
157-
#print (ack)
158-
# print(ack)
159-
# self.messageList.append(ack)
160132
def in_module(module):
161-
# get_time()
162-
# submod = input("UI: Which Module?\n")
163-
# while(submod not in submodules):
164-
# get_time()
165-
# submod = input("UI: Which Module?\n")
166-
# return(submod)
167133
if (module in submodules):
168134
return True
169135
return False
170136

171-
172-
def print_Methods(submodule):
173-
methods = "<font color=green></br>"
174-
for i in submodules[submodule].keys():
175-
print(i)
176-
methods += i + "</br>"
177-
methods += "</font>"
178-
return (methods)
179-
180-
181137
def in_method(submod, method):
182-
'''method = input("UI: Which method?\n")
183-
while(method not in submodules[submod]):
184-
get_time()
185-
method = input("UI: Which method?\n")
186-
return(method)'''
187138
if (method in submodules[submod]):
188139
return True
189140
return False
190141

191-
192142
def check_int(num):
193143
return (num.isdigit())
194144

195-
196145
def check_bool(booleanVar):
197-
# takes in str
198146
if (booleanVar == "True" or booleanVar == "False"):
199147
return (True)
200148
return (False)
201149

202-
203-
# def send_message()
204-
205150
def check_float(floatVar):
206151
try:
207152
float(floatVar)
208153
return (True)
209154
except ValueError:
210155
return (False)
211156

212-
213157
def check_char(charVal):
214158
if (charVal.isalpha() == True and len(charVal) <= 1):
215159
return (True)
216160
return False
217161

218-
219-
def arg_length(module, method):
220-
return (len(submodules[module][method]))
221-
222-
223-
def get_arg(module, method):
224-
argStr = "<font color=green></br>Args: ["
225-
for i in (submodules[module][method]):
226-
argStr += i + ", "
227-
argStr += "]<font>"
228-
return (argStr)
229-
230-
231162
def check_args(module, method, argList):
232163
argumentlist = submodules[module][method]
233164
if (len(argumentlist) != len(argList)):
234165
return (False)
235166
count = 0
236167
for i in argumentlist:
237-
# print(count)
238-
# print(argList[count])
239168
if (i == "int"):
240169
if (check_int(argList[count]) == False):
241-
# print("int")
242170
return (False)
243171
count += 1
244172
elif (i == "bool"):
245173
if (check_bool(argList[count]) == False):
246-
# print("bool")
247174
return (False)
248175
count += 1
249176
elif (i == "float"):
250177
if (check_float(argList[count]) == False):
251-
# print("float")
252178
return (False)
253179
count += 1
254180
elif (i == "char"):
255181
if (check_char(argList[count]) == False):
256-
# print("char")
257182
return (False)
258183
count += 1
259184
else:
260185
count += 1
261186
return (True)
262187

263-
264-
def get_message(module, method, argList):
265-
checksum = generate_checksum(
266-
'TJ' + module + ',' + method + ',' + print_arg(argList))
267-
msg = "TJ" + module + "," + method + "," + print_arg(argList) + checksum
268-
return (msg)
269-
270-
271188
def send(module, method, argList): # ASSUMES EVERYTHING HAS BEEN CHECKED
272-
log = open("event_log.log", "a")
273189
checksum = generate_checksum('TJ' + module + ',' + method + ',' + print_arg(argList))
274190
msg = "TJ" + module + "," + method + "," + print_arg(argList) + checksum
275191
try: # Message successfully sent
276192
msg_snd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
277193
msg_snd.sendto(msg.encode(), (udp_ip, tx_port))
278-
city_ref = db.collection(u'Log').document(u'Send')
194+
city_ref = db.collection(u'Log').document(u'Send')#
279195
timestamp = get_time()
280-
city_ref.update({
281-
timestamp : msg,
282-
})
196+
city_ref.update({#
197+
timestamp : msg,#
198+
})#
283199
return True
284200
except:
285-
log.write("ERROR: MESSAGE FAILED TO SEND. MESSAGE: " + msg)
286201
return False

main.py

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@
44
import functions
55

66
app = Flask(__name__)
7-
log = logging.getLogger('werkzeug')
8-
log.disabled = True
97
message = []
108
failed_msg = [] #list of every message that has an incorrect checksum
119
@app.route("/send", methods=["POST"])
@@ -21,35 +19,27 @@ def handle_send():
2119
else:
2220
return "incorrect parameters", 405
2321

24-
2522
@app.route("/")
26-
def send():
23+
def template():
2724
return render_template("index.html")
2825

2926

3027
@app.route("/listen", methods=['GET'])
3128
def listen():
32-
listen_list = myobject.get_list()
33-
for i in listen_list:
34-
if (listen_list[i].check_checksum is not True):
35-
failed_msg.append(i)
36-
myobject.reset_list()
29+
listen_list = listenObject.get_list()
30+
#for i in listen_list:
31+
#if (listen_list[i].check_checksum is not True):
32+
#failed_msg.append(i)
33+
listenObject.reset_list()
3734
return jsonify(listen_list)
3835

3936
@app.route("/failed", methods=['GET'])
4037
def checksum():
4138
return_list = failed_msg
4239
failed_msg.clear()
4340
return return_list
44-
#returns all elements of failed_msg
45-
#clears failed_msg
41+
4642
if __name__ == '__main__':
47-
'''t1 = Thread(target = listen_thread, args = ())
48-
t1.daemon = True
49-
t1.start()'''
50-
myobject = functions.listen_class([])
51-
myobject.start_listen()
52-
'''functions.start_listen()
53-
print(functions.get_time(), "yes")
54-
print("done")'''
43+
listenObject = functions.listen_class([])
44+
listenObject.start_listen()
5545
app.run()

0 commit comments

Comments
 (0)