-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrobot.py
2294 lines (1707 loc) · 73.3 KB
/
robot.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import serial
import sys
import time
import struct
import threading
import math
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import csv
import slam
import rutil
import config
import logging
import os
import socket
import imdraw_util as imdraw
from behavior_defn import beh_def_list, Beh
from bbr import Arbiter, Behavior
from kinect import Kinect
from openni import openni2
from playsound import playsound
from serial.tools import list_ports
from kinematic import Trajectory
from sklearn.neighbors import NearestNeighbors
# Opcodes
START = chr(128)
SAFE_MODE = chr(131)
FULL_MODE = chr(132)
SENSORS = chr(142)
DRIVE_DIRECT = chr(145)
DRIVE = chr(137)
# Packets
PKT_MOTION = chr(2) # Group Packet 2, includes Packets 17 to 20.
PKT_STATUS = chr(3) # Group Packet 3, includes Packets 21 to 26.
PKT_BUMP = chr(7)
PKT_DISTANCE = chr(19)
PKT_ANGLE = chr(20)
PKT_BATT_CHG = chr(25)
PKT_BATT_CAP = chr(26)
# Packet bytes
PKT_BYTES = { }
PKT_BYTES[PKT_MOTION] = 6
PKT_BYTES[PKT_STATUS] = 10
PKT_BYTES[PKT_BUMP] = 1
PKT_BYTES[PKT_DISTANCE] = 2
PKT_BYTES[PKT_ANGLE] = 2
# Threads
THREAD_SLAM = 0
THREAD_SENSE_HUMAN = 1
MOTION_STATIC = 0
MOTION_EXPLORE = 1
MOTION_APPROACH = 2
MOTION_ESCAPE = 3
# Special radius values for DRIVE command.
DRIVE_RADIUS_STRAIGHT = 32768
DRIVE_RADIUS_COUNTER_CLOCKWISE = 1
DRIVE_RADIUS_CLOCKWISE = 65535
# Keyboard keys.
KEY_SPACE = ord(' ')
KEY_F2 = 191
KEY_ESC = 27
KEY_W = 119
KEY_A = 97
KEY_S = 115
KEY_D = 100
WINDOW_MAP = 'Display'
class PIDController:
def __init__(self, kp, ki, kd):
self.kp, self.ki, self.kd = kp, ki, kd
self.__prev_error = 0
self.__error = 0
self.__setpoint = 0
self.__integral = 0
def e(self, sp, pv, mod=None):
self.__prev_error = self.__error
if mod is None:
self.__error = sp - pv
else:
self.__error = (sp - pv) % mod
def P(self):
return self.kp * self.__error
def I(self, dt):
self.__integral = (self.__integral + self.__error * dt)
return self.ki * self.__integral
def D(self, dt):
derivative = (self.__error - self.__prev_error) / dt
return self.kd * derivative
class StaticPlotter:
def __init__(self, n, init_pos, style='b-', on_off=None):
self.__n = n
self.__theta = [0] * n
self.__pos_x = [p[0] for p in init_pos]
self.__pos_y = [p[1] for p in init_pos]
self.__dis_x = []
self.__dis_y = []
for i in range(n):
self.__dis_x.append([self.__pos_x[i]])
self.__dis_y.append([self.__pos_y[i]])
self.__styles = ['b-']
if style == 'b-':
self.__styles = ['b-'] * n
else:
self.__styles = style
if on_off is not None:
self.__on_off = on_off
for i in range(n):
if i not in self.__on_off:
self.__on_off[i] = '111'
else:
self.__on_off = {}
for i in range(n):
self.__on_off[i] = '111'
self.__min_x = min(self.__pos_x)
self.__max_x = max(self.__pos_x)
self.__min_y = min(self.__pos_y)
self.__max_y = min(self.__pos_y)
self.__min_v = 999
self.__max_v = -999
self.__min_w = 999
self.__max_w = -999
self.__time = [0] * n
self.__timestep = []
for i in range(n):
self.__timestep.append([])
self.__linear_velocity = []
self.__angular_velocity = []
for i in range(n):
self.__linear_velocity.append([])
self.__angular_velocity.append([])
gs = gridspec.GridSpec(2, 2)
self.__fig = plt.figure()
# Subplot for velocity-time graph.
self.__ax1 = self.__fig.add_subplot(
gs[0, 0],
ylim=[self.__min_v, self.__max_v])
# Subplot for angular-velocity-time graph.
self.__ax2 = self.__fig.add_subplot(
gs[0, 1],
ylim=[self.__min_w, self.__max_w])
# Subplot for displacement.
self.__ax3 = self.__fig.add_subplot(
gs[1, :],
xlim=[self.__min_x, self.__max_x],
ylim=[self.__min_y, self.__max_y])
def __plot(self, ax, i):
return ax.plot(self.__pos_x[i], self.__pos_y[i],\
self.__styles[i])[0]
def set_waypoints(self, waypoints):
self.__waypoints_x = [0] * len(waypoints)
self.__waypoints_y = [0] * len(waypoints)
for i, (x, y) in enumerate(waypoints):
self.__waypoints_x[i] = x
self.__waypoints_y[i] = y
def add_plot(self, i, timestamp, x, y, v, w):
if i < 0 or i > self.__n:
raise ValueError('Invalid line index given.')
self.__pos_x[i] = x
self.__pos_y[i] = y
if i in self.__on_off and self.__on_off[i][2] == '1':
if self.__pos_x[i] < self.__min_x:
self.__min_x = self.__pos_x[i]
if self.__pos_x[i] > self.__max_x:
self.__max_x = self.__pos_x[i]
if self.__pos_y[i] < self.__min_y:
self.__min_y = self.__pos_y[i]
if self.__pos_y[i] > self.__max_y:
self.__max_y = self.__pos_y[i]
if i in self.__on_off and self.__on_off[i][0] == '1':
if v < self.__min_v:
self.__min_v = v
if v > self.__max_v:
self.__max_v = v
if i in self.__on_off and self.__on_off[i][1] == '1':
if w < self.__min_w:
self.__min_w = w
if w > self.__max_w:
self.__max_w = w
self.__dis_x[i].append(self.__pos_x[i])
self.__dis_y[i].append(self.__pos_y[i])
self.__timestep[i].append(self.__time[i])
self.__time[i] = timestamp
self.__linear_velocity[i].append(v)
self.__angular_velocity[i].append(w)
def update_plot(self, i, delta_time, delta_distance, delta_angle, v, w):
if i < 0 or i > self.__n:
raise ValueError('Invalid line index given.')
delta_angle = math.radians(delta_angle)
self.__theta[i] = self.__theta[i] + delta_angle
self.__pos_x[i] = self.__pos_x[i] +\
delta_distance * math.cos(self.__theta[i])
self.__pos_y[i] = self.__pos_y[i] +\
delta_distance * math.sin(self.__theta[i])
self.__timestep[i].append(self.__time[i])
self.__time[i] = self.__time[i] + delta_time
self.__linear_velocity[i].append(v)
self.__angular_velocity[i].append(w)
# print('v:', len(self.__linear_velocity[i]))
# print('t:', len(self.__timestep[i]))
if i in self.__on_off and self.__on_off[i][2] == '1':
if self.__pos_x[i] < self.__min_x:
self.__min_x = self.__pos_x[i]
if self.__pos_x[i] > self.__max_x:
self.__max_x = self.__pos_x[i]
if self.__pos_y[i] < self.__min_y:
self.__min_y = self.__pos_y[i]
if self.__pos_y[i] > self.__max_y:
self.__max_y = self.__pos_y[i]
if i in self.__on_off and self.__on_off[i][0] == '1':
if v < self.__min_v:
self.__min_v = v
if v > self.__max_v:
self.__max_v = v
if i in self.__on_off and self.__on_off[i][1] == '1':
if w < self.__min_w:
self.__min_w = w
if w > self.__max_w:
self.__max_w = w
self.__dis_x[i].append(self.__pos_x[i])
self.__dis_y[i].append(self.__pos_y[i])
def draw(self):
v_margin = 0.05 * (self.__max_v - self.__min_v)
w_margin = 0.05 * (self.__max_w - self.__min_w)
x_margin = 0.05 * (self.__max_x - self.__min_x)
y_margin = 0.05 * (self.__max_y - self.__min_y)
self.__ax1.set_ylim(ymin=self.__min_v - v_margin,
ymax=self.__max_v + v_margin)
self.__ax2.set_ylim(ymin=self.__min_w - w_margin,
ymax=self.__max_w + w_margin)
self.__ax3.set_xlim(xmin=self.__min_x - x_margin,
xmax=self.__max_x + x_margin)
self.__ax3.set_ylim(ymin=self.__min_y - y_margin,
ymax=self.__max_y + y_margin)
self.__ax1.set_xlabel('Time')
self.__ax1.set_ylabel('Linear velocity')
self.__ax2.set_xlabel('Time')
self.__ax2.set_ylabel('Angular velocity')
self.__ax3.set_xlabel('X-displacement')
self.__ax3.set_ylabel('Y-displacement')
for i in range(self.__n):
if i in self.__on_off:
if self.__on_off[i][0] == '1':
self.__ax1.plot(self.__timestep[i],
self.__linear_velocity[i], self.__styles[i])
if self.__on_off[i][1] == '1':
self.__ax2.plot(self.__timestep[i],
self.__angular_velocity[i], self.__styles[i])
if self.__on_off[i][2] == '1':
self.__ax3.plot(self.__dis_x[i], self.__dis_y[i],
self.__styles[i])
# Waypoints.
if self.__waypoints_x is not None and\
self.__waypoints_y is not None:
self.__ax3.plot(self.__waypoints_x, self.__waypoints_y, 'bo-')
plt.grid()
plt.show()
class Robot:
def __init__(self, b=26, port='', max_speed=10,
pid_v=(0, 0, 0), pid_w=(0, 0, 0), setting={}):
"""
Initialize the Robot class.
port: The serial port to connect with the iRobot Create e.g.
'/dev/ttyUSB0'.
@param b:
The axial distance between the wheels in cm.
@param port:
The serial port used to send messages to the robot.
@param max_speed:
The maximum speed each wheel can attain in cm/s.
"""
self.__init_logging()
logger = logging.getLogger('robot')
self.cmd_snd_semaphore = threading.Semaphore(value=1)
self.cmd_rcv_semaphore = threading.Semaphore(value=1)
##################################################
# Initialize connection.
##################################################
# Serial variables.
self.baudrate=57600
# If port is not explicitly given, do an automatic port look-up of
# a USB serial port.
if port == '':
try:
ports = self.ports_lookup()
usb_ports = []
for p in ports:
if 'USB' in p:
usb_ports.append(p)
port = usb_ports[0]
logger.info('Found port: {0}'.format(port))
except:
logger.error('No USB serial port found.')
sys.exit(-1)
self.__b = b
self.__serial_port = port
self.__client_port = 9000
self.ser = serial.Serial(port, baudrate=self.baudrate, timeout=1)
# Setting for this robot.
self.setting = {}
self.setting['disable_auto'] = False
self.setting['enable_human_tracking'] = False
self.setting['show_display'] = False
self.setting['record_frames'] = False
# Overwrite default setting.
for k in setting.keys():
if k in self.setting.keys():
self.setting[k] = setting[k]
# Run start command.
self.start()
self.full_mode()
# Store issued command variables.
self.issued_v = 0
self.issued_w = 0
# Reading of linear and angular velocity of the robot chassis.
self.__v = 0
self.__w = 0
self.__delta_distance = 0
self.__delta_angle = 0
self.__motion_update_counter_ = 0
self.__motion_update_counter = 0
# Kinematics variables.
self.max_speed = max_speed # in cm/s
# The position and orientation of the robot w.r.t global reference
# frame.
self.__pose = np.array([0, 0, 0])
self.__prev_pose = np.array([0, 0, 0])
# Flags.
self.is_pid_enable = True
self.is_autonomous = False
###################################################
# SSH flag.
###################################################
self.__conn_ssh = 'SSH_CONNECTION' in os.environ
if self.__conn_ssh:
print('SSH connection detected.')
# Autonomous driving variables.
self.auto_trajectory = None
self.auto_timestep = 0
self.auto_end_time = 0
self.auto_t0 = 0
self.motion_state = MOTION_STATIC
self.plotter = StaticPlotter(
3, # Plot 3 lines for each graph.
[self.get_odom_pose()[:2]] * 3,
['kx-', 'cx--', 'g^--'],
{0: '111',
1: '111',
2: '000'}) # Plot number 2 is not drawn
self.kin = Kinect(config.PRIMESENSE_REDIST_PATH,\
enable_color_stream=False)
###################################################
# Status.
###################################################
self.battery_perc = self.battery_charge()
###################################################
# SLAM related.
###################################################
self.camera_image = None
self.occ_grid_map = np.full(config.GRID_MAP_SIZE, 0.5)
self.hum_grid_map = np.full(config.GRID_MAP_SIZE, 0.5)
self.raw_occ_grid_map = np.full(config.GRID_MAP_SIZE, 0.5)
local_map = self.__init_local_map()
self.fast_slam = slam.FastSLAM(\
self.occ_grid_map.shape,
config.GRID_MAP_RESOLUTION,
np.copy(local_map),
num_particles=config.PF_NUM_PARTICLES,
motion_noise=config.MOTION_NOISE)
self.path = []
self.u_t = None
self.z_t = None
self.h_t = []
self.rgb_t = None
self.goal_cell = None
self.nearest_human = None
self.current_solution = []
self.__distance_traveled = 0
self.scan_locations = []
if self.setting['record_frames']:
filename = rutil.now_file_name()
filename = './saves/vid/' + filename + '.avi'
self.video_writer = cv2.VideoWriter(\
filename, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 30,
(config.GRID_MAP_SIZE[1]*2, config.GRID_MAP_SIZE[0]))
###################################################
# Behavior based robotic.
###################################################
self.arbiter = Arbiter(self)
self.behaviors = {}
for name, priority, func in beh_def_list:
self.behaviors[name] = Behavior(name, self.arbiter, priority, func)
###################################################
# Speak.
###################################################
# playsound(config.SND_INIT)
###################################################
# Manual control.
###################################################
if not self.__conn_ssh:
cv2.namedWindow(WINDOW_MAP)
cv2.setMouseCallback(WINDOW_MAP, Robot.mouse_input_callback,\
self)
self.__manual_goal = (-1, -1)
self.__manual_v = 0
self.__manual_w = 0
self.__client_keyboard = 0
self.__display_map = np.full(\
(config.GRID_MAP_SIZE[0], config.GRID_MAP_SIZE[1], 3), 255,\
np.uint8)
self.__display_human_map = np.full(\
(config.GRID_MAP_SIZE[0], config.GRID_MAP_SIZE[1], 3), 255,\
np.uint8)
print('battery: {0}%'.format(self.battery_charge() * 100))
logger.info('Battery percentage on startup: {0}'.format(\
self.battery_charge() * 100))
def __init_logging(self):
FORMAT = '[%(name)s :: %(asctime)s] %(filename)s '\
'(line %(lineno)d, %(funcName)s): \n '\
'%(levelname)s: %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
logger = logging.getLogger('robot')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('robot.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter(FORMAT)
fh.setFormatter(formatter)
logger.addHandler(fh)
def __init_local_map(self, iterations=30):
local_map = np.full(config.GRID_MAP_SIZE, 0.5)
logger = logging.getLogger('robot')
# Initialize the map for fastSLAM.
logger.info('Initializing FastSLAM map.')
for _ in range(iterations):
depth_map = self.kin.get_depth()
world_xy = self.kin.depth_map_to_world(depth_map, clean=True)
end_cells = slam.world_frame_to_cell_pos(world_xy,\
config.GRID_MAP_SIZE, config.GRID_MAP_RESOLUTION)
mid = np.array(np.array(config.GRID_MAP_SIZE) // 2).astype(int)
obs_dict = slam.observed_cells(mid, end_cells)
obs_mat = slam.observation_matrix(\
obs_dict, config.GRID_MAP_SIZE, occu=0.9, free=-0.7)
slam.update_occupancy_grid_map(local_map, obs_mat)
time.sleep(1.0 / self.kin.get_depth_fps())
logger.info('Finished initializing FastSLAM map.')
return local_map
def ports_lookup(self):
"""
Automatic lookup of the roomba serial port device. If no USB serial port
device is found, return False. Otherwise, the USB serial port(s) found
will be returned in a list.
"""
roomba_ports = [
p.device
for p in list_ports.comports()
]
if len(roomba_ports) == 0:
raise
return roomba_ports
def __init_threads(self):
"""
Initialize all threads.
"""
logger = logging.getLogger('robot')
self.threads = [
threading.Thread(target=Robot.thread_slam, args=(self,),\
name='SLAM'),\
threading.Thread(target=Robot.thread_sense_human, args=(self,),\
name='SenseHuman'),\
threading.Thread(target=Robot.thread_remote_input, args=(self,),\
name='RemoteInput')
]
# A list of flag to maintain thread stop request
# via stop_thread() function.
self.is_thread_stop_requested = [False] * len(self.threads)
for thread in self.threads:
if thread.is_alive():
logger.info('Thread {0} is started before initialization.'\
.format(thread.name))
else:
thread.start()
logger.info('Thread {0} has started.'.format(thread.name))
time.sleep(0.1)
def clean_up(self):
self.drive_velocity(0, 0)
time.sleep(0.05)
self.stop_all_threads()
self.kin.clean_up()
def start(self):
"""
Start the iRobot Create.
"""
self.send_code(START)
def safe_mode(self):
"""
Set the robot to safe mode.
"""
self.send_code(SAFE_MODE)
def full_mode(self):
"""
Set the robot to full mode.
"""
self.send_code(FULL_MODE)
def send_msg(self, opcode, byte_data):
"""
Deprecated. I think using send_codes is sufficient. For now.
"""
successful = False
while not successful:
try:
self.send_code(opcode + byte_data)
successful = True
print('Success!')
except serial.SerialException as e:
print('Error:', e)
def send_code(self, code):
"""
Send a byte to the iRobot Create. To send a code, say, 128, to start
the iRobot, you may pass chr(128).
"""
logger = logging.getLogger('robot')
try:
self.ser.write(bytes(code, encoding='Latin-1'))
except serial.SerialException as e:
logger.error('Error sending code {0}: {1}'.format(code, e))
def send_codes(self, codes):
"""
Send a list of 1 byte binary datum to the iRobot Create.
See send_code.
"""
self.cmd_snd_semaphore.acquire()
for c in codes:
self.send_code(c)
self.cmd_snd_semaphore.release()
def recv_code(self, packet_id):
"""
Read from sensor. Pass the packet_id to get the buffer returned from
requesting the sensor reading. The packet_id is a 1 byte binary.
"""
codes = [SENSORS, packet_id]
self.send_codes(codes)
self.cmd_rcv_semaphore.acquire()
read_buf = self.ser.read(PKT_BYTES[packet_id])
self.cmd_rcv_semaphore.release()
return read_buf
def interpret_code(self, packet_id, read_buf):
"""
Interpret a buffer. Refer the manual on how the buffer for each sensor
packet buffer should be interpreted.
"""
try:
if packet_id == PKT_MOTION:
distance = struct.unpack('>i',
b'\x00\x00' + read_buf[2:4])[0]
angle = struct.unpack('>i',
b'\x00\x00' + read_buf[4:6])[0]
# Distance in mm, angle in degrees.
distance = rutil.from_twos_comp_to_signed_int(distance, byte=2)
angle = rutil.from_twos_comp_to_signed_int(angle, byte=2)
distance = rutil.mm_to_cm(distance)
return distance, angle
if packet_id == PKT_STATUS:
charge = struct.unpack('>I',
b'\x00\x00' + read_buf[6:8])[0]
capacity = struct.unpack('>I',
b'\x00\x00' + read_buf[8:10])[0]
# charge = int(charge, 2)
# capacity = int(capacity, 2)
return charge, capacity
if packet_id == PKT_BUMP:
left_bump = struct.unpack('>I',
b'\x00\x00\x00' + read_buf)[0]
right_bump = struct.unpack('>I',
b'\x00\x00\x00' + read_buf)[0]
return left_bump, right_bump
if packet_id == PKT_DISTANCE:
# The buffer received from PKT_DISTANCE is 2 bytes, but
# struct.unpack requires 4 bytes to convert it to integer
# (hence it's prepended with b'\x00\x00').
# Convert the 2 bytes binary data to integer data. This integer
# data represents distance in mm.
#
# ">i" means the buffer is read as signed int, big endian.
i = struct.unpack('>i', b'\x00\x00' + read_buf)[0]
# Maximum of the integer value replied for this packet.
# Since i is a signed integer, we perform two's complement
# and get its actual value.
i = rutil.from_twos_comp_to_signed_int(i, byte=2)
# Convert from mm/s to cm/s
return rutil.mm_to_cm(i)
if packet_id == PKT_ANGLE:
i = struct.unpack('>i', b'\x00\x00' + read_buf)[0]
i = rutil.from_twos_comp_to_signed_int(i, byte=2)
return i
if packet_id == PKT_BATT_CHG:
# ">I" means the buffer is read as unsigned int, big endian.
i = struct.unpack('>I', b'\x00\x00' + read_buf)[0]
return i
if packet_id == PKT_BATT_CAP:
i = struct.unpack('>I', b'\x00\x00' + read_buf)[0]
return i
else:
pass
except struct.error as e:
pass
# print(e)
# print('read_buf:', read_buf)
# print('length:', len(read_buf))
return 0.0
def drive_direct(self, lw, rw):
"""
Drive each left wheel (lw) and right wheel (rw) in cm/s.
"""
# Convert variables from cm/s to mm/s.
max_speed = rutil.cm_to_mm(self.max_speed)
lw = rutil.cm_to_mm(lw)
rw = rutil.cm_to_mm(rw)
# Cap linear speed of each wheel.
lw = rutil.cap(lw, -max_speed, +max_speed)
rw = rutil.cap(rw, -max_speed, +max_speed)
rw_high, rw_low = rutil.to_twos_comp_2(int(rw))
lw_high, lw_low = rutil.to_twos_comp_2(int(lw))
codes = [START, FULL_MODE,
DRIVE_DIRECT,
chr(rw_high), chr(rw_low),
chr(lw_high), chr(lw_low)]
self.send_codes(codes)
def drive_radius(self, v, r):
"""
Drive the robot using control the following control values:
v for the forward velocity.
r for the radius of turn.
"""
max_speed = rutil.cm_to_mm(self.max_speed)
v = rutil.cm_to_mm(v)
r = rutil.cm_to_mm(r)
v = rutil.cap(v, -max_speed, +max_speed)
v_high, v_low = rutil.to_twos_comp_2(int(v))
r_high, r_low = rutil.to_twos_comp_2(int(r))
codes = [START, FULL_MODE,
DRIVE,
chr(v_high), chr(v_low),
chr(r_high), chr(r_low)]
self.send_codes(codes)
def drive(self, vel_forward, vel_angular, is_feedback=False):
"""
Drive the robot given its local forward velocity and its angular
velocity (in radian per seconds.).
NOTE: This only update the issued_v and issued_w of the robot. The
actual command is issued in thread_motion().
"""
if not is_feedback:
self.issued_v = vel_forward
self.issued_w = vel_angular
# v1 = vel_forward - self.__b * vel_angular
# v2 = vel_forward + self.__b * vel_angular
# self.drive_direct(v1, v2)
def drive_velocity(self, v, w):
v1 = v - self.__b * w
v2 = v + self.__b * w
self.drive_direct(v1, v2)
def drive_to(self, speed, next_pos, targ_orientation=None):
"""
This method is the same as drive_trajectory, except that this takes in
only the next waypoint instead of a series of waypoints.
"""
print('Drive from (%.2f, %.2f, %.2f) to (%.2f, %.2f, %.2f).' %\
(self.__pose[0], self.__pose[1], self.__pose[2],
targ_pos[0], next_pos[1], targ_orientation))
self.auto_trajectory = Trajectory(speed,
self.__pose[:2], self.__pose[2],
next_pos, targ_orientation)
print('Start autonomous driving.')
self.is_autonomous = True
self.auto_timestep = 0
self.auto_t0 = 0
def drive_trajectory(self, speed, waypoints, targ_orientation=None):
"""
Drive the robot at a set speed through a set of waypoints. By default,
the orientation of the robot is automatically calculated from the last
two waypoints. The speed will is used to determine the magnitude of the
set of velocities at each point of the calculated trajectory produced by
interpolation of the robot's velocity at each waypoint.
"""
self.auto_trajectory = Trajectory(speed,
self.__pose[:2], self.__pose[2],
waypoints[0], targ_orientation)
if len(waypoints) > 1:
for i in range(1, len(waypoints)):
x, y = waypoints[i]
self.auto_trajectory.add_waypoint(x, y)
time_estimate =\
self.auto_trajectory.estimate_time_between_points(
self.auto_trajectory.get_speed(),
self.auto_trajectory.current())
self.auto_end_time = time_estimate
self.is_autonomous = True
self.auto_timestep = 0
self.auto_t0 = 0
self.auto_speed = speed
def stop_thread(self, i):
"""
Stop the i-th thread in the self.threads list. The robot object maintain
a list of flag corresponding the each thread in self.threads list called
is_thread_stop_requested. When is_thread_stop_requested[i] is set to
True, the loop that runs in that thread is stopped, stopping the thread.
Note that the function that the thread run is responsible to set the
flag back to false.
"""
self.is_thread_stop_requested[i] = True
def stop_all_threads(self):
"""
Simply stop all threads. See stop_thread.
"""
for i in range(0, len(self.threads)):
self.stop_thread(i)
def show_running_threads(self):
"""
Return a list of thread by their names. Only threads that is running
(i.e. thread.is_live() is True) is included in the list.
"""
running_threads = []
for t in self.threads:
if t.is_alive():
running_threads.append(t.name)
return running_threads
def start_thread(self, i):
"""
Start the i-th thread from self.threads list.
"""
if not self.threads[i].is_alive():
self.threads[i].start()
def next_cell(self, grid_map, curr_pos, goal_pos):
robot_cell = slam.world_to_cell_pos(curr_pos,\
config.GRID_MAP_SIZE, config.GRID_MAP_RESOLUTION)
goal_cell = slam.nearest_unexplored_cell(\
slam.entropy_map(grid_map), robot_cell)
next_cell = slam.shortest_path(robot_cell, goal_cell,
grid_map, 0.75)[0]
return next_cell
def thread_remote_input(self):
host = ''
port = self.__client_port
print('Waiting for client connection...')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print('Connected by {0}:{1}'.format(addr[0], addr[1]))
with conn:
while True:
# Send map data to client.
data = self.__display_map.tobytes()
try:
conn.sendall(data)
except BrokenPipeError as e:
print(e)
# Send human map data to client.
data = self.__display_human_map.tobytes()
try:
conn.sendall(data)