-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
292 lines (250 loc) · 8.03 KB
/
app.py
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
from threading import Lock
from flask import Flask, render_template, session, request, jsonify, url_for
from flask_socketio import SocketIO, emit, disconnect
import time
import random
import math
import smbus
import os
import RPi.GPIO as GPIO
import MySQLdb
import ConfigParser
import subprocess
startf=open("static/files/run.txt","r")
startt=(startf.read(4))
startf.close()
if startt=="aaaa":
time.sleep(0.5)
print('StartApp.py, drive.py je uz spusteny')
else:
startf=open("static/files/run.txt","w")
startf.write("aaaa")
startf.close()
time.sleep(0.5)
print('StartApp.py')
def stop():
stopf= open("static/files/run.txt", "w")
stopf.write("stop")
stopf.close()
def stoptest():
stopf= open("static/files/run.txt", "r")
stopt=(stopf.read(4))
stopf.close()
if stopt=="stop":
istop=1;
else:
istop=0
return istop
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO_TRIGGER = 24
GPIO_ECHO = 21
GPIO.setup(24, GPIO.OUT)
GPIO.setup(21, GPIO.IN)
def distance():
# set Trigger to HIGH
GPIO.output(GPIO_TRIGGER, True)
# set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
StartTime = time.time()
StopTime = time.time()
# save StartTime
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()
# save time of arrival
while GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()
# time difference between start and arrival
TimeElapsed = StopTime - StartTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2
return distance
# Register
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
def read_byte(reg):
return bus.read_byte_data(address, reg)
def read_word(reg):
h = bus.read_byte_data(address, reg)
l = bus.read_byte_data(address, reg+1)
value = (h << 8) + l
return value
def read_word_2c(reg):
val = read_word(reg)
if (val >= 0x8000):
return -((65535 - val) + 1)
else:
return val
bus = smbus.SMBus(1)
address = 0x68
bus.write_byte_data(address, power_mgmt_1, 0)
def MPU_9265_getdata():
gxout = read_word_2c(0x43)
gyout = read_word_2c(0x45)
gzout = read_word_2c(0x47)
xout = read_word_2c(0x3b)
yout = read_word_2c(0x3d)
zout = read_word_2c(0x3f)
xout=xout/ 16384.0
yout = yout / 16384.0
zout = zout / 16384.0
return gxout,gyout,gzout,xout,yout,zout
async_mode = None
app = Flask(__name__)
config = ConfigParser.ConfigParser()
config.read('config.cfg')
myhost = config.get('mysqlDB', 'host')
myuser = config.get('mysqlDB', 'user')
mypasswd = config.get('mysqlDB', 'passwd')
mydb = config.get('mysqlDB', 'db')
print myhost
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()
runvariable='nieco'
dbV='nieco'
def background_thread(args):
dataList = []
db = MySQLdb.connect(host=myhost,user=myuser,passwd=mypasswd,db=mydb)
uholx=0
uholy=0
count=0
countemit=0
dtime=0.01
dist=50
dist1=50
dist2=50
## put ka in range 0 to 1 better near 0
ka=0.2
while True:
if stoptest():
print('Drive.py called to stop')
os._exit(0)
socketio.sleep(dtime)
if runvariable=="start":
gx,gy,gz,ax,ay,az=MPU_9265_getdata()
uholx=ka*(uholx+gy*dtime)+(1-ka)*(math.atan(ay/(math.sqrt(ax*ax+az*az)))*180/math.pi)-5.4
uholy=-ka*(uholy+gx*dtime)-(1-ka)*(math.atan(ax/(math.sqrt(ay*ay+az*az)))*180/math.pi)-14.5
count += 1
countemit +=1
if (countemit == 20):
dist=distance();
if dist>40:
dist=40;
socketio.emit('my_response',
{'anglex': round(uholx),'angley': round(uholy),'dist': (round(40-(dist+dist1+dist2)/3)),'gx': gx,'gy': gy,'gz': gz, 'count': count},
namespace='/test')
countemit=0;
dist2=dist1;
dist1=dist;
if dbV == 'start':
print('zapisujem do suboru')
dataDict = {
"N": count/20,
"Ax": round(uholx),
"Ay": round(uholy),
"Dist": (round(40-(dist+dist1+dist2)/3))}
dataList.append(dataDict)
else:
if len(dataList)>0:
print (str(dataList))
fuj = str(dataList).replace("'", "\"")
print fuj
fo = open("static/files/test.txt","a+")
fo.write(str(fuj)+"\r\n")
fo.close()
cursor = db.cursor()
cursor.execute("SELECT MAX(id) FROM graph")
maxid = cursor.fetchone()
cursor.execute("INSERT INTO graph (id, hodnoty) VALUES (%s, %s)", (maxid[0] + 1, fuj))
db.commit()
print('zapisane do suboru a do databazy')
dataList = []
dataCounter = 0
@app.route('/', methods=['GET', 'POST'])
def graphlive():
return render_template('index.html', async_mode=socketio.async_mode)
@socketio.on('disconnect_request', namespace='/test')
def disconnect_request():
print('Client has Disconnected, ending script')
stop()
time.sleep(0.5)
os._exit(0)
@app.route('/graph', methods=['GET', 'POST'])
def graph():
return render_template('graph.html', async_mode=socketio.async_mode)
@app.route('/dbdata/<string:num>', methods=['GET', 'POST'])
def dbdata(num):
db = MySQLdb.connect(host=myhost,user=myuser,passwd=mypasswd,db=mydb)
cursor = db.cursor()
if num=="last":
cursor.execute("SELECT hodnoty FROM graph WHERE id=(SELECT MAX(id) FROM graph)")
else:
cursor.execute("SELECT MAX(id) FROM graph")
maxdb=cursor.fetchone()
num = int(num)
if num>(maxdb[0]-1):
cursor.execute("SELECT hodnoty FROM graph WHERE id=(SELECT MAX(id) FROM graph)")
print('Maximalny riadok databazy je:')
print(maxdb[0]-1)
else:
numstr1 = str(int((num + 1)/10))
numstr2 = str((num + 1) - int((num + 1)/10)*10)
cursor.execute("SELECT hodnoty FROM graph WHERE id=%s%s" % (numstr1, numstr2))
rv = cursor.fetchone()
return str(rv[0])
@app.route('/db')
def db():
db = MySQLdb.connect(host=myhost,user=myuser,passwd=mypasswd,db=mydb)
cursor = db.cursor()
cursor.execute('SELECT hodnoty FROM graph WHERE id=(SELECT MAX(id) FROM graph)')
rv = cursor.fetchall()
return str(rv)
@app.route('/text')
def text():
fo = open("static/files/test.txt","r")
rows = fo.readlines()
fo.close()
line = len(rows)
return rows[line-1]
@app.route('/graphtxt', methods=['GET', 'POST'])
def graphtxt():
return render_template('graphtxt.html', async_mode=socketio.async_mode)
@app.route('/read/<string:num>')
def readmyfile(num):
fo = open("static/files/test.txt","r")
rows = fo.readlines()
fo.close()
line = len(rows)
if (num=="last") or (int(num)>line):
tmpfile=line
print('Maximalny riadok je:')
print(line)
else:
tmpfile=int(num)
return rows[tmpfile-1]
@socketio.on('connect', namespace='/test')
def test_connect():
global thread
with thread_lock:
if thread is None:
thread = socketio.start_background_task(target=background_thread, args=session._get_current_object())
print('zaciatok spojenia')
@socketio.on('db_event', namespace='/test')
def db_message(message):
global dbV
dbV = message['value']
print(dbV)
@socketio.on('start_event', namespace='/test')
def run_message(message):
global runvariable
runvariable = message['value']
if runvariable=="start":
print(runvariable)
else:
print('nemeriam veliciny')
if __name__ == '__main__':
socketio.run(app, host="0.0.0.0", port=80, debug=True)