-
Notifications
You must be signed in to change notification settings - Fork 1
/
seed_sqlite.py
345 lines (302 loc) · 10.7 KB
/
seed_sqlite.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Created On: 2023-06-18
# SPDX-FileCopyrightText: Copyright (c) 2023 Shanghai Bosch Rexroth Hydraulics & Automation Ltd.
# SPDX-License-Identifier: MIT
#
# https://realpython.com/intro-to-python-threading/#producer-consumer-using-lock
import socket
import struct
import argparse
from datetime import datetime
import time
import logging
import requests
import sqlite3
import json
import concurrent.futures
# import threading
# Locator
config = {
"user_name": "admin",
"password": "admin",
"locator_host": "127.0.0.1",
"locator_pose_port": 9011,
"locator_json_rpc_port": 8080,
}
# ClientLocalizationPoseDatagram data structure (see API manual)
unpacker = struct.Struct("<ddQiQQddddddddddddddQddd")
# print(datetime.now())
id = 0
pose = {}
def get_client_localization_pose():
"""Receive localization poses from ROKIT Locator and save them to a global variable, pose"""
global pose
# Creating a TCP/IP socket
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server
server_address = (config["locator_host"], config["locator_pose_port"])
client_sock.connect(server_address)
logging.info(
f"Connected to {config['locator_host']} on port {config['locator_pose_port']}"
)
try:
while True:
# read the socket
data = client_sock.recv(unpacker.size)
# upack the data (= interpret the datagram)
if not data:
continue
unpacked_data = unpacker.unpack(data)
# create a json row
pose = {
"timestamp": datetime.fromtimestamp(unpacked_data[1]).strftime(
"%d-%m-%Y-%H-%M-%S"
),
"x": unpacked_data[6],
"y": unpacked_data[7],
# 'yaw': math.degrees(unpacked_data[8]),
"yaw": unpacked_data[8],
"localization_state": unpacked_data[3],
}
# logging.debug(pose)
finally:
client_sock.close()
def clientLocalizationSetSeed(
sessionId: str,
x: float,
y: float,
a: float,
enforceSeed: bool = False,
uncertainSeed: bool = False,
):
global id
payload = {
"id": id,
"jsonrpc": "2.0",
"method": "clientLocalizationSetSeed",
"params": {
"query": {
"sessionId": sessionId,
"enforceSeed": enforceSeed,
"uncertainSeed": uncertainSeed,
"seedPose": {"x": x, "y": y, "a": a},
}
},
}
id = id + 1
logging.debug(payload)
logging.info(f"x={x}, y={y}, a={a}")
response = requests.post(url=url, json=payload)
# print(response.json())
def sessionLogin() -> str:
global id
payload = {
"id": id,
"jsonrpc": "2.0",
"method": "sessionLogin",
"params": {
"query": {
"timeout": { # timeout, not timestamp
"valid": True,
"time": 60, # Integer64
"resolution": 1, # real_time = time / resolution
},
"userName": config["user_name"],
"password": config["password"],
}
},
}
id = id + 1
logging.debug(payload)
response = requests.post(url=url, json=payload)
logging.debug(response.json())
sessionId = response.json()["result"]["response"]["sessionId"]
return sessionId
def sessionLogout(sessionId: str = None):
global id
# headers = {
# "Content-Type": "application/json; charset=utf-8",
# }
payload = {
"id": id,
"jsonrpc": "2.0",
"method": "sessionLogout",
"params": {"query": {"sessionId": sessionId}},
}
id = id + 1
response = requests.post(url=url, json=payload)
logging.debug(response.json())
def update_seed_1():
"""Update the first seed in table seeds of locator.db"""
global pose
# Connect to the database
connection = sqlite3.connect("locator.db")
# Create a cursor object
cursor = connection.cursor()
try:
while True:
if "localization_state" in pose and pose["localization_state"] >= 2:
pose_a = pose
# Define the update query
query = "UPDATE seeds SET x = ?, y=?, yaw=? WHERE id =1"
# Define the values to update and the condition
values = (pose_a["x"], pose_a["y"], pose_a["yaw"])
# Execute the query
cursor.execute(query, values)
# Commit the changes
connection.commit()
logging.debug(f"last pose updated to {values}")
break
else:
time.sleep(0.5)
continue
while True:
time.sleep(0.5)
if "localization_state" in pose and pose["localization_state"] >= 2:
pose_b = pose
# update last pose on the first row of table seeds
# units: meter and radian, 0.0087 radians = 0.5 degrees
if (
abs(pose_b["x"] - pose_a["x"]) > 0.005
or abs(pose_b["y"] - pose_a["y"]) > 0.005
or abs(pose_b["yaw"] - pose_a["yaw"]) > 0.0087
):
# Define the update query
query = "UPDATE seeds SET x = ?, y=?, yaw=? WHERE id =1"
# Define the values to update and the condition
values = (pose_b["x"], pose_b["y"], pose_b["yaw"])
# Execute the query
cursor.execute(query, values)
# Commit the changes
connection.commit()
logging.debug(f"seed 1 updated to {values}")
pose_a = pose_b
finally:
cursor.close()
connection.close()
def teach_or_set_seed():
global pose
# Connect to the database
connection = sqlite3.connect("locator.db")
# Create a cursor object
cursor = connection.cursor()
# Retrieve the data
seeds_a = cursor.execute("SELECT * FROM seeds").fetchall()
try:
while True:
time.sleep(0.5)
seeds_b = cursor.execute("SELECT * FROM seeds").fetchall()
for i in range(len(seeds_b)):
# teach seed
if not seeds_a[i][7] and seeds_b[i][7]:
# read current pose from Locator and write it to pose i in the data block
# pose = get_client_localization_pose()
assert pose["localization_state"] >= 2, "NOT_LOCALIZED"
# Define the update query
query = "UPDATE seeds SET x = ?, y=?, yaw=?, teach=? WHERE id =?"
# Define the values to update and the condition
values = (pose["x"], pose["y"], pose["yaw"], 0, i + 1)
# Execute the query
cursor.execute(query, values)
# Commit the changes
connection.commit()
logging.info(
f"Seed taught, id {seeds_b[i][0]}, name {seeds_b[i][1]}, {values[:3]}"
)
break
# set seed
if not seeds_a[i][8] and seeds_b[i][8]:
session_id = sessionLogin()
clientLocalizationSetSeed(
sessionId=session_id,
x=seeds_b[i][2],
y=seeds_b[i][3],
a=seeds_b[i][4],
enforceSeed=bool(seeds_b[i][5]),
uncertainSeed=bool(seeds_b[i][6]),
)
sessionLogout(session_id)
# reset field set in DB table seeds
cursor.execute("UPDATE seeds SET 'set'=? WHERE id=?", (0, i + 1))
# Commit the changes
connection.commit()
logging.info(
f"Seed set, id {seeds_b[i][0]}, name {seeds_b[i][1]}, x={seeds_b[i][2]}, y={seeds_b[i][3]}, yaw={seeds_b[i][4]}"
)
break
seeds_a = seeds_b
finally:
cursor.close()
connection.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="a program to teach and set seeds for ROKIT Locator",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"-c",
"--config",
type=str,
help="The path to the configuration file",
)
parser.add_argument(
"--user_name",
type=str,
default=config["user_name"],
help="User name of ROKIT Locator client",
)
parser.add_argument(
"--password",
type=str,
default=config["password"],
help="Password of ROKIT Locator client",
)
parser.add_argument(
"--locator_host",
type=str,
default=config["locator_host"],
help="IP of ROKIT Locator client",
)
parser.add_argument(
"--locator_pose_port",
type=int,
default=config["locator_pose_port"],
help="Port of binary ClientLocalizationPose",
)
parser.add_argument(
"--locator_json_rpc_port",
type=int,
default=config["locator_json_rpc_port"],
help="Port of JSON RPC ROKIT Locator Client",
)
args = parser.parse_args()
# config.json has the highest priority and it will overide other command-line arguments
if args.config:
with open(args.config, "r") as f:
config.update(json.load(f))
else:
config.update(vars(args))
# parser.print_help()
print(config)
url = (
"http://" + config["locator_host"] + ":" + str(config["locator_json_rpc_port"])
)
# format = "%(asctime)s [%(levelname)s] %(threadName)s %(message)s"
format = "%(asctime)s [%(levelname)s] %(funcName)s(), %(message)s"
logging.basicConfig(format=format, level=logging.DEBUG, datefmt="%Y-%m-%d %H:%M:%S")
# x = threading.Thread(target=get_client_localization_pose, daemon=True)
# logging.info("start thread get_client_localization_pose")
# x.start()
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
executor.submit(get_client_localization_pose)
executor.submit(update_seed_1)
executor.submit(teach_or_set_seed)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("Main thread received KeyboardInterrupt")
executor.shutdown(wait=True)
print("All threads completed")