forked from owoalex/botd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
botd_client.py
executable file
·406 lines (361 loc) · 16.8 KB
/
botd_client.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#!/bin/python3
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
import json
from io import BytesIO
import re
import sys
import os
import base64
import requests
import threading
#define global variables
current_order = None
bot_definition = None
video_devices = {}
video_buffers = {}
class BotClient(threading.Thread):
#initialise BotClient
def __init__(self, thread_name, thread_ID):
threading.Thread.__init__(self)
self.thread_name = thread_name
self.thread_ID = thread_ID
# helper function to execute the threads
def run(self):
global current_order
global bot_definition
global video_devices
global video_buffers
time.sleep(1)
print("Connecting to server @ %s" % (remote_server))
remote_server_base_uri = "http://" + remote_server
bot_definition["port"] = local_server_port
request = requests.post(url = remote_server_base_uri + "/register", json = bot_definition)
data = request.json()
#print(data)
if (bot_definition["type"] == "CONTROLLER"):
print("Setting remote to bot0")
bot_definition["remote_bot_id"] = "bot0"
current_order = None
while True:
if not (current_order == None):
#if current_order has expired, set current_order to None
if (current_order["expiry"] < time.time()):
current_order = None
#Set all actuators pins GPIOs to low
for actuator in bot_definition["actuators"]:
for pin in actuator["motor_pins"]:
GPIO.output(actuator["motor_pins"][pin], GPIO.LOW)
else:
output_motor_levels = {}
for actuator in bot_definition["actuators"]:
output_motor_levels[actuator["name"]] = 0
print(current_order)
if "x_vel" in current_order:
for motor in bot_definition["intents"]["x"]:
output_motor_levels[motor] += bot_definition["intents"]["x"][motor] * current_order["x_vel"]
if "y_vel" in current_order:
print("MOVE Y")
if "yaw_vel" in current_order:
for motor in bot_definition["intents"]["yaw"]:
output_motor_levels[motor] += bot_definition["intents"]["yaw"][motor] * current_order["yaw_vel"]
#print(output_motor_levels)
for actuator in bot_definition["actuators"]:
if actuator["type"] == "BRUSHED":
if output_motor_levels[actuator["name"]] > 0.1:
GPIO.output(actuator["motor_pins"]["cw"], GPIO.HIGH)
GPIO.output(actuator["motor_pins"]["ccw"], GPIO.LOW)
elif output_motor_levels[actuator["name"]] < -0.1:
GPIO.output(actuator["motor_pins"]["cw"], GPIO.LOW)
GPIO.output(actuator["motor_pins"]["ccw"], GPIO.HIGH)
else:
GPIO.output(actuator["motor_pins"]["cw"], GPIO.LOW)
GPIO.output(actuator["motor_pins"]["ccw"], GPIO.LOW)
#
if "cameras" in bot_definition:
for camera in bot_definition["cameras"]:
if video_devices[camera["name"]].isOpened():
ret, frame = video_devices[camera["name"]].read()
#cv2.imshow("uwu", frame)
#cv2.waitKey()
#cv2.imwrite("test.jpg", frame)
frame_encode = cv2.imencode(".jpg", frame)[1]
data_encode = numpy.array(frame_encode)
byte_encode = data_encode.tobytes()
video_buffers[camera["name"]] = byte_encode
else:
print("COULD NOT READ CAMERA (NOT OPENED)")
time.sleep(0.1)
#print(str(self.thread_name) +" "+ str(self.thread_ID));
class BotServerHost(threading.Thread):
def __init__(self, thread_name, thread_ID):
threading.Thread.__init__(self)
self.thread_name = thread_name
self.thread_ID = thread_ID
# helper function to execute the threads
def run(self):
global current_order
global bot_definition
client_thread = BotClient("main_client", 128);
client_thread.start()
web_server = HTTPServer((host_name, local_server_port), BotServer)
if host_name == "":
print("Client responder starting on port %s" % (local_server_port))
else:
print("Client responder starting http://%s:%s" % (host_name, local_server_port))
try:
web_server.serve_forever()
except KeyboardInterrupt:
pass
web_server.server_close()
print("Client stopped.")
class BotServer(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def do_POST(self):
global current_order
global bot_definition
path_components = self.path.split("/")
if (len(path_components) >= 1):
if (path_components[0] == ""):
path_components.pop(0)
if (len(path_components) == 0):
path_components.push("")
if (self.headers['Content-Length'] == None):
self.do_GET()
return
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length).decode("utf-8")
try:
body = json.loads(body)
except ValueError: # includes simplejson.decoder.JSONDecodeError
self.send_response(401)
self.send_header("Content-type", "application/json")
self.end_headers()
reply_body = json.dumps({
"status": "INVALID_JSON_PAYLOAD"
}, indent=4)
self.wfile.write((reply_body + "\n").encode("utf-8"))
return
if (re.compile("^motor[0-9]+$").match(path_components[0])):
self.send_response(200)
self.end_headers()
reply_body = json.dumps({
"status": "OK",
"request": body
}, indent=4)
self.wfile.write((reply_body + "\n").encode("utf-8"))
elif (path_components[0] == "cmd"):
#print("INTENT:")
#print(body)
self.send_response(200)
self.end_headers()
reply_body = json.dumps({
"status": "OK",
"intent": body
}, indent=4)
self.wfile.write((reply_body + "\n").encode("utf-8"))
current_order = body
current_order["expiry"] = current_order["expiry"] + time.time()
## TODO : PARSE INTENT
else:
self.do_GET()
def do_PUT(self):
global current_order
global bot_definition
path_components = self.path.split("/")
if (len(path_components) >= 1):
if (path_components[0] == ""):
path_components.pop(0)
if (len(path_components) == 0):
path_components.push("")
if (re.compile("^screen[0-9]+$").match(path_components[0])):
timestamp = time.time()
filename = "display/" + path_components[1] + "-" + str(timestamp) + ".jpeg"
file_length = int(self.headers['Content-Length'])
with open(filename, 'wb') as output_file:
output_file.write(self.rfile.read(file_length))
self.send_response(201, "Created")
self.end_headers()
reply_body = json.dumps({
"status": "OK"
}, indent=4)
self.wfile.write((reply_body + "\n").encode("utf-8"))
else:
self.send_response(404)
self.send_header("Content-type", "application/json")
self.end_headers()
reply_body = json.dumps({
"status": "INVALID_PUT_LOCATION"
}, indent=4)
self.wfile.write((reply_body + "\n").encode("utf-8"))
def do_GET(self):
global current_order
global bot_definition
global video_buffers
path_components = self.path.split("/")
if (len(path_components) >= 1):
if (path_components[0] == ""):
path_components.pop(0)
if (len(path_components) == 0):
path_components.push("")
if (path_components[0] == ""):
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
reply_body = json.dumps({
"status": "OK"
}, indent=4)
self.wfile.write((reply_body + "\n").encode("utf-8"))
elif (re.compile("^camera[0-9]+$").match(path_components[0])):
if (len(path_components) >= 2):
if (path_components[1] == "latest.jpg"):
cameraidx = int(re.search(r'\d{0,3}$', path_components[0]).group())
self.send_response(200)
self.end_headers()
reply_body = bytes(video_buffers[bot_definition["cameras"][cameraidx]["name"]])
self.wfile.write(reply_body)
else:
self.send_response(404)
self.send_header("Content-type", "application/json")
self.end_headers()
reply_body = json.dumps({
"status": "ENDPOINT_NOT_FOUND",
"error_at": path_components[1]
}, indent=4)
self.wfile.write((reply_body + "\n").encode("utf-8"))
else:
cameraidx = int(re.search(r'\d{0,3}$', path_components[0]).group())
self.send_response(200)
self.end_headers()
try:
reply_body = json.dumps({
"status": "OK",
"camera_index": cameraidx,
"camera_name": bot_definition["cameras"][cameraidx]["name"],
"buffer": base64.b64encode(video_buffers[bot_definition["cameras"][cameraidx]["name"]]).decode("utf-8")
}, indent=4)
except IndexError:
reply_body = json.dumps({
"status": "INVALID_CAMERA_INDEX",
"camera_index": cameraidx
}, indent=4)
self.wfile.write((reply_body + "\n").encode("utf-8"))
else:
self.send_response(404)
self.send_header("Content-type", "application/json")
self.end_headers()
reply_body = json.dumps({
"status": "ENDPOINT_NOT_FOUND"
}, indent=4)
self.wfile.write((reply_body + "\n").encode("utf-8"))
if __name__ == "__main__":
switch_name = "PYFILE"
host_name = ""
remote_server = None
config_file = None
local_server_port = 8081
for arg in sys.argv:
if switch_name == None:
if (arg.startswith("-")):
if (arg.startswith("--")):
if (arg == "--port"):
switch_name = "PORT"
if (arg == "--remote"):
switch_name = "REMOTE_SERVER"
else:
if (arg == "-p"):
switch_name = "PORT"
if (arg == "-r"):
switch_name = "REMOTE_SERVER"
else:
config_file = arg
elif switch_name == "PORT":
local_server_port = int(arg)
switch_name = None
elif switch_name == "REMOTE_SERVER":
remote_server = arg
switch_name = None
elif switch_name == "PYFILE":
switch_name = None
else:
print("Argument parse error!")
if remote_server == None:
print("No remote server supplied!")
elif config_file == None:
print("No config file supplied!")
print("python3 botd_client.py --remote <ip_address>[:port] <config_file>")
else:
f = open(config_file)
bot_definition = json.load(f)
f.close()
server_thread = BotServerHost("main_server", 64);
server_thread.start()
if (bot_definition["type"] == "BOT"):
if "cameras" in bot_definition:
import cv2
import numpy
for camera in bot_definition["cameras"]:
videodev = os.readlink(camera["path"]).split("/")[-1]
videodevidx = re.search(r'\d{0,3}$', videodev).group()
videodevpath = "/dev/video" + str(videodevidx)
print("Camera %s at OpenCV path %s" % (camera["name"], videodevpath))
video_buffers[camera["name"]] = bytearray()
video_devices[camera["name"]] = cv2.VideoCapture(videodevpath)
if not video_devices[camera["name"]].isOpened():
print("FAILED TO OPEN CAMERA")
if (bot_definition["control_scheme"] == "TELEMETRY_ONLY"):
print("Telemetry-only robot")
if (bot_definition["control_scheme"] == "RPI_ONBOARD_GPIO"):
try:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
#GPIO.setup(36, GPIO.OUT)
#GPIO.setup(38, GPIO.OUT)
#GPIO.setup(40, GPIO.OUT)
for actuator in bot_definition["actuators"]:
for pin in actuator["motor_pins"]:
print("Activating motor pin %s" % (actuator["motor_pins"][pin]))
GPIO.setup(actuator["motor_pins"][pin], GPIO.OUT)
GPIO.output(actuator["motor_pins"][pin], GPIO.LOW)
#for pin in actuator["encoder_pins"]:
# print("Activating encoder pin %s" % (pin))
# GPIO.setup(pin, GPIO.INPUT)
bot_definition["motors_active"] = True
except ImportError:
print("CANNOT START RPI CONTROL WITHOUT RPI MODULE")
print("Try: pip install RPi.GPIO")
elif (bot_definition["type"] == "CONTROLLER"):
if (bot_definition["control_scheme"] == "VIRTUAL_KEYBOARD"):
try:
import keyboard
print("Starting virtual controller!")
while True:
key = keyboard.read_key()
intents = []
expiry = 0
for keymap in bot_definition["keymap"]:
if (keymap["key"] == key):
intents = intents + keymap["intents"]
if expiry < keymap["expiry"]:
expiry = keymap["expiry"]
built_intent = {"expiry": expiry}
send_intent = False
for intent in intents:
send_intent = True
if intent["axis"] in built_intent:
built_intent[intent["axis"]] = intent["rate"] + built_intent[intent["axis"]]
else:
built_intent[intent["axis"]] = intent["rate"]
if send_intent:
if "remote_bot_id" in bot_definition:
remote_server_base_uri = "http://" + remote_server
bot_definition["port"] = local_server_port
request = requests.post(url = remote_server_base_uri + "/" + bot_definition["remote_bot_id"] + "/cmd", json = built_intent)
data = request.json()
else:
print("NO REMOTE BOT")
except ImportError:
print("CANNOT START VIRTUAL CONTROLLER WITHOUT KEYBOARD MODULE")
print("Try: pip install keyboard")
print("Note: On linux this script requires root")