· 7 years ago · Feb 19, 2019, 10:46 PM
1'''
2Original Author: Dichong Song
3Creation date: Jan 10, 2019
4Contents of file:
5 1. Flask framework (main thread)
6 1.1 render static html source
7 1.2 communicate with frontend web page
8 1.3 always on
9 2. Xml fetcher (sub-thread)
10 2.1 parse content from given url
11 2.2 output in json format
12 2.3 repeat every hour
13'''
14from flask import Flask,render_template,jsonify,request,session,redirect,url_for
15from xml.dom import minidom
16from urllib.request import urlopen
17import sched, time, _thread,json,io,shlex,subprocess,datetime,hashlib,sqlite3
18from pyfingerprint.pyfingerprint import PyFingerprint
19from watchdog.observers import Observer
20from watchdog.events import *
21
22app=Flask(__name__)
23s = sched.scheduler(time.time, time.sleep)
24userID = "-1"
25isupdated = 0
26conn = sqlite3.connect('users.db')
27c = conn.cursor()
28c.execute('''
29CREATE TABLE IF NOT EXISTS User(
30findex int primary key,
31username text,
32email text,
33preference text)
34''')
35findex = 1
36username = "dichong"
37email = "dichong@gmail.com"
38preference = "111111"
39
40c.execute('''
41INSERT INTO User(findex,username,email,preference)VALUES(?,?,?,?)
42''',(findex,username,email,preference))
43
44
45class FileEventHandler(FileSystemEventHandler):
46 def __init__(self):
47 FileSystemEventHandler.__init__(self)
48
49 def on_moved(self, event):
50 if event.is_directory:
51 print("directory moved from {0} to {1}".format(event.src_path,event.dest_path))
52 else:
53 print("file moved from {0} to {1}".format(event.src_path,event.dest_path))
54
55 def on_created(self, event):
56 if event.is_directory:
57 print("directory created:{0}".format(event.src_path))
58 else:
59 print("file created:{0}".format(event.src_path))
60
61 def on_deleted(self, event):
62 if event.is_directory:
63 print("directory deleted:{0}".format(event.src_path))
64 else:
65 print("file deleted:{0}".format(event.src_path))
66
67 def on_modified(self, event):
68 global isupdated
69 if event.is_directory:
70 print("directory modified:{0}".format(event.src_path))
71 else:
72 isupdated = 1
73 print("file modified:{0}".format(event.src_path))
74
75def xmlfetcher(urllink):
76 xml_file = urlopen(urllink)
77 mydoc = minidom.parse(xml_file)
78 items = mydoc.getElementsByTagName('title')
79 result = []
80 for item in items:
81 result.append(item.firstChild.data)
82 return result
83
84def write_to_json():
85 my_list = xmlfetcher("https://www.cbc.ca/cmlink/rss-topstories")
86 f1 = open("./static/upload/newsfeed/news.json","w")
87 with io.open('./static/upload/newsfeed/news.json', 'w', encoding='utf-8') as f:
88 f.write(json.dumps(my_list, ensure_ascii=False))
89 s.enter(3600, 1, write_to_json)
90 s.run()
91
92def execute_cmd(cmd):
93 args = shlex.split(cmd)
94 p = subprocess.run(args,stdout = subprocess.PIPE)
95 result = p.stdout
96 return result
97
98def update_userID():
99 global userID,isupdated
100 observer = Observer()
101 event_handler = FileEventHandler()
102 observer.schedule(event_handler,'/home/pi',True)
103 observer.start()
104 while True:
105 with open('loginstate.txt', 'r') as f:
106 if isupdated == 1:
107 try:
108 lines = f.read().splitlines()
109 last_line = lines[-1]
110 if last_line == userID:
111 pass
112 else:
113 userID = last_line
114 isupdated = 0
115 except Exception:
116 pass
117 time.sleep(1)
118
119
120@app.route('/',methods=['GET','POST'])
121def index():
122 global userID
123 if request.method == "POST":
124 data = request.form['request'].encode('utf-8')
125 if int(data) == 1:
126 #successfully login
127 t = (userID,)
128 c.execute('SELECT * FROM User WHERE findex=?',t)
129 print(c.fetchone())
130
131
132 return jsonify({"username":username})
133 elif int(data) == 2:
134 try:
135 execute_cmd("mkdir -p " + username)
136 filename = username + "_" + datetime.datetime.now().strftime("%B_%d_%Y_%H:%M:%S")+".jpg"
137 msg = execute_cmd("raspistill -n -o "+"./"+username +"/"+filename)
138 return jsonify({"status":msg})
139 except Exception:
140 print("some error happens 1")
141 return render_template("specialUserPage.html")
142 return render_template('mainPage.html')
143def search_fingerprint():
144 ## Tries to initialize the sensor
145 try:
146 f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)
147 file1 = open("loginstate.txt","a+")
148 if ( f.verifyPassword() == False ):
149 raise ValueError('The given fingerprint sensor password is wrong!')
150
151 except Exception as e:
152 print('The fingerprint sensor could not be initialized!')
153 print('Exception message: ' + str(e))
154 #~ exit(1)
155
156
157
158 ## Gets some sensor information
159 print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))
160
161 ## Tries to search the finger and calculate hash
162 try:
163 print('Waiting for finger...')
164
165 ## Wait that finger is read
166 while ( f.readImage() == False ):
167 pass
168
169 ## Converts read image to characteristics and stores it in charbuffer 1
170 f.convertImage(0x01)
171
172 ## Searchs template
173 result = f.searchTemplate()
174 print (result)
175 positionNumber = result[0]
176 accuracyScore = result[1]
177
178 if ( positionNumber == -1 ):
179 print('No match found!')
180 #~ search_fingerprint()
181 #~ exit(0)
182 else:
183 print('Found template at position #' + str(positionNumber))
184 print('The accuracy score is: ' + str(accuracyScore))
185 file1.write(str(positionNumber)+'\n')
186 file1.flush()
187 ## OPTIONAL stuff
188 ##
189 ## Loads the found template to charbuffer 1
190 f.loadTemplate(positionNumber, 0x01)
191 print("1")
192 print(result)
193 ## Downloads the characteristics of template loaded in charbuffer 1
194 characterics = str(f.downloadCharacteristics(0x01)).encode('utf-8')
195 print("2")
196 print(result)
197 ## Hashes characteristics of template
198 print('SHA-2 hash of template: ' + hashlib.sha256(characterics).hexdigest())
199 time.sleep(1)
200
201 except Exception as e:
202 print('Operation failed!')
203 print('Exception message: ' + str(e))
204 #~ exit(1)
205 time.sleep(1)
206 search_fingerprint()
207
208
209@app.route('/signup',methods=['POST'])
210def signup():
211 print(1234)
212 if request.method == "POST":
213 print('GMAIL:'+request.form['gml'])
214 print('UserName:'+request.form['uname'])
215
216 return render_template('mainPage.html')
217
218@app.route('/specialUserPage',methods = ['GET','POST'])
219def specialUserPage():
220 if request.method == "POST":
221 data = request.form['request'].encode('utf-8')
222 if int(data) == 2:
223 try:
224 execute_cmd("mkdir -p " + username)
225 msg = execute_cmd("raspistill -o "+"./"+username +"/"+ username + "_"+ datetime.date.today().strftime("%B_%d_%Y") +".jpg")
226 return jsonify({"status":msg})
227 except Exception:
228 print("some error happens 2")
229 return render_template("specialUserPage.html")
230
231 return render_template("specialUserPage.html")
232
233def print_global():
234 global userID
235 while True:
236 print(userID)
237 time.sleep(1)
238
239if __name__=="__main__":
240 _thread.start_new_thread(write_to_json,())
241 #~ _thread.start_new_thread(search_fingerprint,())
242 _thread.start_new_thread(update_userID,())
243 _thread.start_new_thread(print_global,())
244 app.debug=True
245 app.run(host='0.0.0.0',port=4310)