-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodbuskeres.py
374 lines (289 loc) · 11 KB
/
modbuskeres.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
import sys
import serial
import numpy as np
import RPi.GPIO as GPIO
import time
from pymodbus.client.sync import ModbusTcpClient
from helper import Edge, Filter
from statemachine import StateMapElement, StateMachine
from datetime import datetime
from ujkeres import ujkeres
from korkeres import findCircle
from enum import Enum
from collections import defaultdict
#######################################################################################################
class Msg:
msg = ""
cnt = 0
cursorup = '\033[F'
erase = '\033[K'
en = 1
def printMsg(self, msg):
if (self.en == 0):
return
print(msg)
#if (self.msg is msg):
# if (self.cnt > 1) :
# print(self.cursorup+self.erase)
# self.cnt += 1
#print(msg + " ({})".format(self.cnt))
#else:
# self.cnt = 0
#self.msg = msg
#print(msg)
#y 30 110
#x 360 440
#z 25
#406-33
class State(Enum):
SignalWait = 1
GetPosition = 2
CheckPositionList = 3
CalculateNewPosition = 4
WaitScanReady = 5
ReturnMovement = 6
CalculateCenter = 7
Stop = 8
StopAll = 9
def setNeg(n):
if (n < 0):
return n+pow(2,16)
else:
return n
def getSigned16bit(a):
if (a >> 15) & 1:
return a - (1 << 16)
return a
def readID(port):
line = port.readline().rstrip().replace("\x02","").replace("\x03","")
if (len(line)==12):
return line
else:
return ""
def log(s):
with open(f, "a+") as myfile:
myfile.write(s)
return
def changeState(current, next):
msg.printMsg("\n Changing from '{}' to '{}'...".format(current, next))
return next
###############################################################################################
# Raspberry config
GPIO.setmode (GPIO.BCM)
GPIO.setup(4, GPIO.IN)
serialPort = serial.Serial('/dev/ttyS0', 9600, timeout = 0.4)
# Communication registers
dataReadyReg = 500
dataXReg = 1000
dataYReg = 1002
newDataReadyReg = 1006
scanReadyReg = 1008
dataRead = 0
id1RegX = 520
id1RegY = 522
id2RegX = 524
id2RegY = 526
startIdSwayReg = 530
ip = '192.168.0.104'
client = ModbusTcpClient(ip, 502)
conn = client.connect()
SignalFilter = Filter(16)
SignalEdge = Edge()
ReadyEdge = Edge()
msg = Msg()
edgeDetected = 0
dataReadyEdgeDetected = 0
currPos = []
t = datetime.now().time().strftime("%H%M%S")
f = "./meres/40keresKozep"+t+".txt"
idsToSearch = 2
scanPoints = []
isScanning = False
pointsx = defaultdict(list)
pointsy = defaultdict(list)
iterationCounter = 0
maxIterations = 1
pointDict = defaultdict(list)
centerDict = defaultdict(list)
latestID = ""
scanningID = ""
finishedIDs = []
currentState = State.SignalWait
client.write_register(500, 0)
client.write_register(510, 0)
client.write_register(530, 0)
client.write_register(1008,0)
client.write_register(1006,0)
while 1:
signalType = ""
# Waits for RFID signal edge
if (currentState == State.SignalWait):
input_v = GPIO.input(4)
signal = SignalFilter.step(input_v)
signalEdge = SignalEdge.chk(signal)
signalType = signalEdge['type']
# Notify robot of RFID signal change
if (signalEdge['value'] == 1):
if (signalEdge['type'] == "rising"):
print("rising edge")
latestID = readID(serialPort)
print("latest id: {}".format(latestID))
print("scanning id: {}".format(scanningID))
print("finishedIDs: {}".format(finishedIDs))
if (scanningID == "" and latestID not in finishedIDs and latestID != ""):
scanningID = latestID
if (isScanning == True and scanningID != latestID):
continue
if (signalEdge['type'] == "falling"):
print("falling edge")
if (len(finishedIDs) == 1 and (scanningID == "" or scanningID in finishedIDs)):
continue
msg.printMsg("\n Edge detected, setting Reg500 to 1")
client.write_register(newDataReadyReg, 0)
client.write_register(dataReadyReg, 1)
currentState = changeState(currentState,State.GetPosition)
continue
# Gets robot's current position data
elif (currentState == State.GetPosition):
dataReady = client.read_holding_registers(newDataReadyReg,1)
#msg.printMsg("\n Checking if data is ready: {}".format(dataReady))
if (dataReady == None):
msg.printMsg("dataready none")
continue
dataReady = dataReady.registers[0]
readyEdge = ReadyEdge.chk(dataReady)
#if (readyEdge['value'] == 1 and readyEdge['type'] == "rising"):
if (dataReady == 1):
client.write_register(newDataReadyReg,0)
time.sleep(0.5)
xy = client.read_holding_registers(dataXReg,4)
x = getSigned16bit(xy.registers[0])
y = getSigned16bit(xy.registers[2])
# If the point is too close to the latest one, disregard
if (len(currPos)>0):
d = np.linalg.norm(np.array([x,y])-np.array(currPos))
if (d < 40):
currentState = changeState(currentState,State.ReturnMovement)
continue
currPos = [x,y]
pointsx[scanningID].append(float(x))
pointsy[scanningID].append(float(y))
log("\n {},{}".format(x,y))
pointDict[scanningID].append(currPos)
#pointArray.append(currPos)
msg.printMsg("\n Data ready signal changed to {}".format(dataReady))
#
client.write_register(newDataReadyReg,0)
currentState = changeState(currentState,State.CheckPositionList)
continue
# Check if we already have two position data and can calculate next one
elif (currentState == State.CheckPositionList):
msg.printMsg("\n Scanning: {}".format(isScanning))
#print("{}, length: {} ".format(pointArray,len(pointArray)))
if (isScanning):
msg.printMsg("\n scanPoints length: {}".format(len(scanPoints)))
msg.printMsg("\n pointDict[{}][-1:][0]: {}".format(scanningID,pointDict[scanningID][-1:][0]))
scanPoints.append(pointDict[scanningID][-1:][0])
msg.printMsg("\n len(scanPoints): {}".format(len(scanPoints)))
if (len(scanPoints) < 2):
currentState = changeState(currentState,State.ReturnMovement)
else:
scanPoints = []
msg.printMsg("\nIterationCounter: {} | max iterations: {}".format(iterationCounter,maxIterations))
if (iterationCounter >= maxIterations):
iterationCounter = 0
print("getting center")
currentState = changeState(currentState, State.CalculateCenter)
continue
#if (len(pointArray) < 2):
msg.printMsg("\n len(pointDict[scanningID]) {}".format(len(pointDict[scanningID])))
if (len(pointDict[scanningID]) < 2 or len(scanPoints) % 2 == 1):
currentState = changeState(currentState, State.ReturnMovement)
else:
currentState = changeState(currentState, State.CalculateNewPosition)
# Need to find more points, return robot movement as it were
elif (currentState == State.ReturnMovement):
client.write_register(500,2)
currentState = changeState(currentState,State.SignalWait)
# Calculates new position data and sends it to robot
elif (currentState == State.CalculateNewPosition):
newPointData = ujkeres(pointsx[scanningID],pointsy[scanningID],30)
iterationCounter += 1
newStart = newPointData["kezdo"]
newEnd = newPointData["veg"]
log("\n {},{}, start".format(newStart.astype(int)[0],newStart.astype(int)[1]))
log("\n {},{}, end".format(newEnd.astype(int)[0],newEnd.astype(int)[1]))
newSd = newStart - currPos
newEd = newEnd - currPos
nxd = newSd.astype(int)[0]
nyd = newSd.astype(int)[1]
nexd = newEd.astype(int)[0]
neyd = newEd.astype(int)[1]
print("Scan positions: {} -> {} ".format(newStart,newEnd))
#print("nxd nyd {} {}".format(nxd,nyd))
#print("nexd neyd {} {}".format(nexd,neyd))
nxd = setNeg(nxd)
nyd = setNeg(nyd)
nexd = setNeg(nexd)
neyd = setNeg(neyd)
client.write_register(502, nxd)
client.write_register(504, nyd)
client.write_register(506, nexd)
client.write_register(508, neyd)
client.write_register(500, 0)
client.write_register(newDataReadyReg,0)
isScanning = True
currentState = changeState(currentState,State.WaitScanReady)
#Calculates and moves to center
elif (currentState == State.CalculateCenter):
c = findCircle(pointsx[scanningID],pointsy[scanningID])
print("findcircle: {}, current pos: {}".format(c,currPos))
c = np.array(c)
cd = c - currPos
cx = setNeg(cd.astype(int)[0])
cy = setNeg(cd.astype(int)[1])
client.write_register(512, cx)
client.write_register(514, cy)
time.sleep(0.5)
#client.write_register(500, 5)
#client.write_register(510, 1)
centerDict[scanningID].append(c)
finishedIDs.append(scanningID)
scanningID = ""
if (len(centerDict) == 1):
client.write_register(500, 3)
currentState = changeState(currentState, State.SignalWait)
else:
currentState = changeState(currentState, State.Stop)
elif (currentState == State.Stop):
id1 = finishedIDs[0]
id2 = finishedIDs[1]
#print("\nIDs:\n\t{}\n\t{}".format(id1,
c1 = centerDict[id1][0]
c2 = centerDict[id2][0]
log("\nCenters: {} - {}".format(c1,c2))
c1 = c1 - currPos
c2 = c2 - currPos
c1x = setNeg(c1.astype(int)[0])
c1y = setNeg(c1.astype(int)[1])
c2x = setNeg(c2.astype(int)[0])
c2y = setNeg(c2.astype(int)[1])
client.write_register(id1RegX, c1x)
client.write_register(id1RegY, c1y)
client.write_register(id2RegX, c2x)
client.write_register(id2RegY, c2y)
client.write_register(500, 3)
client.write_register(startIdSwayReg, 1)
currentState = changeState(currentState,State.StopAll)
elif (currentState == State.StopAll):
jkl = 0
elif (currentState == State.WaitScanReady):
dataReady = client.read_holding_registers(1008,1)
dataReady = dataReady.registers[0]
if (dataReady == 2):
client.write_register(1008, 0)
client.write_register(newDataReadyReg, 0)
currentState = changeState(currentState,State.SignalWait)
#stateMachine.event("ScanReady")
#msg.printMsg("input: {} | filtered: {} | edge: {} ".format(input_v,signal,signalEdge))
client.close()