-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfinal_project_socket_last_version.py
392 lines (307 loc) · 9.6 KB
/
final_project_socket_last_version.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 14 10:16:41 2020
@author: mesut
"""
import os
import cv2
import numpy as np
import math
import time
import serial
import sys
import socket
import threading
font = cv2.FONT_HERSHEY_SIMPLEX
setPointY=120 #it will get from desktop or mobile for y axes
setPointX=160 #it will get from desktop or mobile for y axes
setPointH=15
_pre_errorH=0
_pre_errorY=0
_pre_errorX=0
_integralY=0
_integralX=0
_integralH=0
period=200
periodH=200
myTime=0
ser=""
mode ='0'
px = 0
py = 0
h = 0
motorAngels = ""
os.system('ip neigh show dev wlan0 > ip.txt')
with open('ip.txt') as f:
read_data = f.read()
f.close()
print("my server : "+ read_data)
ip = read_data.split()
print("ip : "+ ip[0])
host = str(ip[0])
port = 9000
port2=8000
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
def video(cap):
x_medium = 0
y_medium = 0
tmpX = 0
tmpY = 0
tmpD = 0
_, frame = cap.read()
hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
sensitivity = 15
low_red = np.array([2,84,80])
high_red = np.array([134,255,255])
red_mask = cv2.inRange(hsv_frame,low_red,high_red)
_ ,contours, _= cv2.findContours(red_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=lambda x:cv2.contourArea(x), reverse=True)
#x_medium = 0
#y_medium = 0
for cnt in contours:
(x,y,w,h) = cv2.boundingRect(cnt)
distancei = (2*3.14 * 180)/(w+h*360)*1000 + 3
#print distancei
distance = distancei *2.54
distance = math.floor(distancei/2)
#cv2.rectangle(frame,(x,y),(x+w,y+h), (0,255,0),2)
x_medium = int((x+x+w)/2)
y_medium = int((y+y+h)/2)
cv2.line(frame, (x_medium,0), (x_medium,480), (0,255,0),1)
cv2.line(frame, (780,y_medium), (0,y_medium), (0,255,0),1)
tmpX=x_medium
tmpY=y_medium
tmpD=distance
break
position = (3,30)
#tmpX = tmpX - 160
#tmpY = 120- tmpY
cv2.putText(frame,'Distance = ' + str(tmpD) + ' cm', (3,50),font,0.5,(255,255,255),1)
cv2.putText(
frame, #numpy array on which text is written
" x pos : "+str(tmpX)+" \n y pos : "+str(tmpY)+"", #text
position, #position at which writing has to start
cv2.FONT_HERSHEY_SIMPLEX, #font family
0.5, #font size
(255, 255, 0, 255),1)
#cv2.imshow("Frame",frame)
#cv2.imshow("", red_mask)
key = cv2.waitKey(1) # print calculate(setPoint,y_medium,100,0.1,0.01,0.5)
if key==27:
sys.exit()
#tmpX = tmpX - 160
#tmpY = tmpY - 120
return tmpX,tmpY,tmpD
def pid(tmpX,tmpY , kp , kd , ki , dt , _max , _min ):
global myTime
global setPointY#it will get from desktop or mobile for y axes
global setPointX #it will get from desktop or mobile for y axes
global _pre_errorY
global _pre_errorX
global _integralY
global _integralX
global period
global ser
global motorAngels
#print('pid is starting')
millis = 0
millis = int(round(time.time() * 1000))
dy = 0
dz = 0
if(millis > myTime + period):
myTime= int(round(time.time() * 1000))
errorY = setPointY - tmpY
errorX = setPointX - tmpX
PoutY = kp * errorY
PoutX= kp * errorX
_integralY += errorY * ki
_integralX += errorX * ki
IoutY = _integralY
IoutX = _integralX
derivativeY = (errorY - _pre_errorY) / dt
DoutY = kd * derivativeY
derivativeX = (errorX - _pre_errorX) / dt
DoutX = kd * derivativeX
# Calculate total output
if(errorY > -15 or errorY < 15):
IoutY = 0
if(errorX > -15 or errorX < 15):
IoutX = 0
outputY = PoutY + IoutY +DoutY
outputX = PoutX + IoutX +DoutX
_pre_errorY = errorY
_pre_errorX = errorX
axisX=10
axisY=-5
#print(str(outputY) +" :::: "+str(errorY)+"\n")
#print(str(outputX) +" :::: "+str(errorX)+"\n")
dy= int((outputY+10000)/(20000)*(_max*2)-_max)
dx= int((outputX+10000)/(20000)*(_max*2)-_max)
if(dy > _max):
dy=_max
if(dy < _min):
dy=_min
if(dx > _max):
dx=_max
if(dx < _min):
dx=_min
dz = -1*dy
da = -1*dx
#print("dy:" + str(dy)+"\n")
#print("dx:" + str(dx)+"\n")
code=(str(dy)+":"+str(dx)+":"+str(da)+":"+str(dz)+":30000:10000\n")
#print("encode code : "+code)
ser.write(str.encode(code))
motorAngels = str(dz)+ " " + str(dy)+ " " + str(dx) + " " + str(da)
data = "DATAS" + " " + str(px) + " " + str(py) + " " + str(h) + " " + motorAngels
sendData(data)
#motorların adımları
#dy ile dz (x ekseni) karşılıklı - da ile dx (y ekseni) karşılıklı
def sektirme(x,y,h,kp,kd,dt,_max):
global motorAngels
global myTime
global setPointH #it will get from desktop or mobile for y axes
global setPointY #it will get from desktop or mobile for y axes
global setPointX #it will get from desktop or mobile for y axes
global _pre_errorY
global _pre_errorX
global _pre_errorH
global _integralH
global periodH
global ser
millis = 0
millis = int(round(time.time() * 1000))
dh=0
_min = -1*_max
errorY = setPointY - y
errorX = setPointX - x
PoutY = kp * errorY
PoutX= kp * errorX
'''
errorH = setPointH - h
PoutH = kp * errorH
'''
derivativeY = (errorY - _pre_errorY) / dt
DoutY = kd * derivativeY
derivativeX = (errorX - _pre_errorX) / dt
DoutX = kd * derivativeX
'''
derivativeH = (errorH - _pre_errorH) / dt
DoutH = kd * derivativeH
'''
_pre_errorY = errorY
_pre_errorX = errorX
#_pre_errorH = errorH
outputY = PoutY + DoutY
outputX = PoutX + DoutX
#outputH = PoutH + DoutH
dy= (outputY+10000)/(20000)*(_max*2)-_max
dx= (outputX+10000)/(20000)*(_max*2)-_max
periodH= ((h-20)/(30))*(900)+100
#print ("periodH:" + periodH)
if (periodH < 70 ):
periodH = 50
if(millis > myTime + periodH):
myTime= int(round(time.time() * 1000))
#print('if 111111')
ser.write(str.encode(str(dy+dh)+":"+str(dx+dh)+":"+str(dh-dx)+":"+str(dh-dy)+":30000:6000\n"))
#ser.write(str.encode(str(10)+":"+str(10)+":"+str(10)+":"+str(10)+":30000:6000\n"))
if(millis > myTime + (periodH*0.5)):
#print('if 22222')
#ser.write(str.encode(str(0)+":"+str(0)+":"+str(0)+":"+str(0)+":30000:6000\n"))
ser.write(str.encode(str((dy+dh)*-1)+":"+str((dx+dh)*-1)+":"+str((dh-dx)*-1)+":"+str((dh-dy)*-1)+":30000:6000\n"))
def recv(x):
global mode
data2 = ""
while True:
#print("Receiver Started!")
# server'dan gelen veriyi tutan degisken ------------
data2 = sock.recv(1024).decode()
print (data2)
#if not data2: sys.exit(0)
if "DATAS" not in data2:
if "has connected" not in data2:
arr = data2.split()
if arr:
if str(arr[0])=='D':
mode = str(arr[1])
#print(str(arr[0]) + ", " + str(arr[1]) + ", " + str(arr[2]) + "," + str(arr[3]))
#time.sleep(.1)
def sendData(data):
#print(data)
sockSender = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockSender.connect((host, port2))
sockSender.send(data.encode())
sockSender.close()
def main(msg):
global ser
global mode
global px
global py
global h
dh=0
dx=3
dy=6
print("before video")
cap = cv2.VideoCapture(0)
print("after video")
cap.set(3,320)
cap.set(4,240)
ser = serial.Serial('/dev/ttyACM0', 9600)
ser.flush()
px = 0
py = 0
ki= 0.1
kp= 40
kd= 20
dt = 0.2
_max = 300
_min = -300
ready = 1
counter = 0
while True :
x , y , h = video(cap)
if(x != 0):
px = x
if(y != 0):
py = y
# ser.flush()
# print "hello"
# ser.write("-1:0:0:1:1000")
# time.sleep(2)
# ser.write("0:0:0:0:1000")
# time.sleep(2)
#print(str(px)+"\t"+str(py)+"\t"+str(h)+"\n")
if(mode == '1'): #
pid(px,py,kp,kd,ki,dt,_max,_min)
'''
elif(mode == '2'):
#print('sektirme ')
if(ready == 0):
pid(px,py,30,50,0.01,dt,_max,_min)
if(px < setPointX+100 and px >= setPointX-100 and py < setPointY+100 and py >= setPointY-100):
if(counter == 200):
#ser.write("0:0:0:0:10000\n")
#ser.write("-18:-18:-18:-18:10000\n")
ready = 1
counter = counter +1
else:
counter = 0
if(ready == 1):
sektirme(px,py,h,20,50,0.2,50)
'''
try:
#kilitle
#thread.start_new_thread(sendData, ('msg', ))
#kilidi ac
t= threading.Thread(target=main, args=(1,))
t2= threading.Thread(target=recv, args=(1,))
t.start()
t2.start()
t.join()
t2.join()
except:
print("Error: unable to start thread")
# if __name__== "__main__":
# main(1)