-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
executable file
·1692 lines (1384 loc) · 80.5 KB
/
main.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 customtkinter
import cv2
import os
import tkinter
import time
import socket
import socket
import pyproj
import pymoos
from collections import deque
from geopy.distance import geodesic as GD
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
#from auvlib.data_tools import jsf_data, utils
from tkintermapview import TkinterMapView
from PIL import Image, ImageTk
from pyais import decode
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
from mission_control import MissionControl
#mpl.style.use('seaborn')
plt.style.use('dark_background')
# Configurations to access Moos server
IP_MOOS = "127.0.0.1" # Local
#IP_MOOS = "100.67.139.83" # Vessel's server
#IP_MOOS = "192.168.14.138" # Ekren
#IP_MOOS = "172.18.14.98" # Rasp WIFI
#IP_MOOS = "100.93.183.81" # Raspberry Pi 4 Tailscale
PORTA_MOOS = 9000
#LOCATION = "Salvador"
LOCATION = "Rio de Janeiro"
#LOCATION = "MIT"
"""
xdiff =
ydiff =
"""
# AIS configuration
ip_address = '201.76.184.242'
port = 8000
# Create a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server
#sock.connect((ip_address, port))
"""
Thrust limit for changing gear ###
The gear will only be changed if thrust < thrust_gear_limit
"""
thrust_gear_limit = 1
AUTONOMOUS_SPEED = 5 # knots
MAX_AUTONOMOUS_SPEED = 10 # knots
DEGREES_SECONDS = False # GPS notation in Degrees, Minutes, Seconds if True
"""
Variables for Kp, Ki and Kd control
"""
MAX_HEADING_KP = 2
MAX_HEADING_KI = 0.5
MAX_HEADING_KD = 1
MAX_SPEED_KP = 20
MAX_SPEED_KI = 5
MAX_SPEED_KD = 2
CONNECTION_OK_COLOR = "#56a152"
CONNECTION_NOT_OK_COLOR = "#bf7258"
customtkinter.set_default_color_theme("blue")
customtkinter.set_appearance_mode("Dark")
class App(customtkinter.CTk):
APP_NAME = "AVP-MOOS v0.2"
WIDTH = 1600
HEIGHT = 1000
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.title(App.APP_NAME)
self.geometry(str(App.WIDTH) + "x" + str(App.HEIGHT))
self.minsize(App.WIDTH, App.HEIGHT)
self.protocol("WM_DELETE_WINDOW", self.on_closing)
self.bind("<Command-q>", self.on_closing)
self.bind("<Command-w>", self.on_closing)
self.createcommand('tk::mac::Quit', self.on_closing)
#Auxiliar para plotagem dos pontos da derrota autonoma
self.marker_autonomous_list = []
#Socket para conectar ao sonar
self.sonar_ip = "127.0.0.1"
self.sonar_port = 3000
self.sonar_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sonar_socket.bind((self.sonar_ip, self.sonar_port))
# Convert Lat Long to minutes and seconds Option
self.minutes_seconds = DEGREES_SECONDS
# Create mission controller with Moos
self.controller = MissionControl(IP_MOOS,PORTA_MOOS,LOCATION)
self.__init_main_variables()
self.__init_GUI()
self.__main_loop()
self.centralize_ship()
def __init_GUI(self):
"""
Inits main components of the User interface
"""
#Carrego imagens para os ícones
self.current_path = os.path.join(os.path.dirname(os.path.abspath(__file__)))
#Imagem do meu navio
self.ship_imagefile = Image.open(os.path.join(self.current_path, "images", "ship_red0.png"))
ship_image = ImageTk.PhotoImage(self.ship_imagefile)
# ============ create two CTkFrames ============
self.grid_columnconfigure(0, weight=0)
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(0, weight=1)
self.frame_left = customtkinter.CTkFrame(master=self, width=150, corner_radius=0, fg_color=None)
self.frame_left.grid(row=0, column=0, padx=0, pady=0, sticky="nsew")
self.frame_right = customtkinter.CTkFrame(master=self, corner_radius=0)
self.frame_right.grid(row=0, column=1, rowspan=1, pady=0, padx=0, sticky="nsew")
# ============ frame_left ============
self.frame_left.grid_rowconfigure(8, weight=1) #Para deixar igualmente espaçados
self.frame_left.grid_rowconfigure(9, weight=1)
self.frame_left.grid_rowconfigure(10, weight=1)
self.frame_left.grid_rowconfigure(11, weight=1)
self.frame_left.grid_rowconfigure(12, weight=1)
self.frame_left.grid_rowconfigure(13, weight=1)
self.frame_left.grid_rowconfigure(14, weight=1)
self.frame_left.grid_rowconfigure(15, weight=1)
self.frame_left.grid_rowconfigure(16, weight=1)
self.frame_left.grid_rowconfigure(17, weight=1)
self.button_1 = customtkinter.CTkButton(master=self.frame_left,
text="Colocar Marcador",
command=self.set_marker_event)
self.button_1.grid(pady=(20, 0), padx=(20, 20), row=0, column=0)
self.button_2 = customtkinter.CTkButton(master=self.frame_left,
text="Limpar Marcadores",
command=self.clear_marker_event)
self.button_2.grid(pady=(20, 0), padx=(20, 20), row=1, column=0)
self.button_3 = customtkinter.CTkButton(master=self.frame_left,
text="Câmera",
command=self.open_camera)
self.button_3.grid(pady=(20, 0), padx=(20, 20), row=2, column=0)
self.button_4 = customtkinter.CTkButton(master=self.frame_left,
text="Desativar Mapas",
command=self.destroy_maps)
self.button_4.grid(pady=(20, 0), padx=(20, 20), row=3, column=0)
self.button_5 = customtkinter.CTkButton(master=self.frame_left,
text="Controle Remoto",
command=self.activate_remote_control)
self.button_5.grid(pady=(20, 0), padx=(20, 20), row=4, column=0)
self.button_controle_autonomo = customtkinter.CTkButton(master=self.frame_left,
text="Controle Autônomo",
command=self.update_autonomous)
self.button_controle_autonomo.grid(pady=(20, 0), padx=(20, 20), row=5, column=0)
self.trajectory_button = customtkinter.CTkButton(master=self.frame_left,
text="Plot Trajetória",
command=self.trajectory_plot)
self.trajectory_button.grid(pady=(20, 0), padx=(20, 20), row=6, column=0)
self.plot_sonar_button = customtkinter.CTkButton(master=self.frame_left,
text="Sonar Plot",
command=self.receive_sonar)
self.plot_sonar_button.grid(pady=(20, 0), padx=(20, 20), row=7, column=0)
#Texto da Latitude
self.label_lat = customtkinter.CTkLabel(master=self.frame_left, text="Latitude: "+str(self.controller.nav_lat))
self.label_lat.configure(font=("Segoe UI", 15))
self.label_lat.grid(row=8, column=0, padx=(20,20), pady=(50,0), sticky="")
#Texto da Longitude
self.label_long = customtkinter.CTkLabel(master=self.frame_left, text="Longitude: "+str(self.controller.nav_long))
self.label_long.configure(font=("Segoe UI", 15))
self.label_long.grid(row=9, column=0, padx=(20,20), pady=(0,20), sticky="")
#Texto do rumo
self.label_heading = customtkinter.CTkLabel(master=self.frame_left, text="Rumo: "+str(self.controller.nav_heading))
self.label_heading.configure(font=("Segoe UI", 25))
self.label_heading.grid(row=10, column=0, padx=(20,20), pady=(20,20), sticky="")
#Texto da veloc
self.label_speed = customtkinter.CTkLabel(master=self.frame_left, text=f"Velocidade: {self.controller.nav_speed:.2f} knots",)
self.label_speed.configure(font=("Segoe UI", 25))
self.label_speed.grid(row=11, column=0, padx=(20,20), pady=(20,20), sticky="")
#Texto do angulo do leme
self.label_yaw = customtkinter.CTkLabel(master=self.frame_left, text="Ângulo do Leme: "+str(round(self.controller.nav_yaw,2)))
self.label_yaw.configure(font=("Segoe UI", 20))
self.label_yaw.grid(row=12, column=0, padx=(20,20), pady=(20,20), sticky="")
#Connection Text
if self.connection_ok:
self.label_connection = customtkinter.CTkLabel(master=self.frame_left, text=f"Conexão: {self.connection_ok}",fg_color=(CONNECTION_OK_COLOR))
else:
self.label_connection = customtkinter.CTkLabel(master=self.frame_left, text=f"Conexão: {self.connection_ok}",fg_color=(CONNECTION_NOT_OK_COLOR))
self.label_connection.configure(font=("Segoe UI", 20))
self.label_connection.grid(row=13, column=0, padx=(20,20), pady=(20,20), sticky="")
#MAP
self.map_label = customtkinter.CTkLabel(self.frame_left, text="Servidor de Mapas:", anchor="w")
self.map_label.grid(row=14, column=0, padx=(20, 20), pady=(20, 0))
self.map_option_menu = customtkinter.CTkOptionMenu(self.frame_left, values=["OpenStreetMap", "Google normal", "Google satellite"],
command=self.change_map)
self.map_option_menu.grid(row=15, column=0, padx=(20, 20), pady=(10, 0))
self.appearance_mode_label = customtkinter.CTkLabel(self.frame_left, text="Aparência:", anchor="w")
self.appearance_mode_label.grid(row=16, column=0, padx=(20, 20), pady=(20, 0))
self.appearance_mode_optionemenu = customtkinter.CTkOptionMenu(self.frame_left, values=["Light", "Dark", "System"],
command=self.change_appearance_mode)
self.appearance_mode_optionemenu.grid(row=17, column=0, padx=(20, 20), pady=(10, 20))
# ============ frame_right ============f
self.frame_right.grid_rowconfigure(1, weight=1)
self.frame_right.grid_rowconfigure(0, weight=0)
self.frame_right.grid_columnconfigure(0, weight=1)
self.frame_right.grid_columnconfigure(1, weight=0)
self.frame_right.grid_columnconfigure(2, weight=1)
#Criação do mapa inicial
self.script_directory = os.path.dirname(os.path.abspath(__file__))
self.database_path = os.path.join(self.script_directory, "offline_tiles_rio.db")
#Mapas offline
self.map_widget = TkinterMapView(self.frame_right, corner_radius=0,use_database_only=True,database_path=self.database_path)
#Mapas online
#self.map_widget = TkinterMapView(self.frame_right, corner_radius=0)
self.map_widget.grid(row=1, rowspan=1, column=0, columnspan=3, sticky="nswe", padx=(0, 0), pady=(0, 0))
self.map_widget.set_overlay_tile_server("http://tiles.openseamap.org/seamark//{z}/{x}/{y}.png")
self.entry = customtkinter.CTkEntry(master=self.frame_right,
placeholder_text="Digite Endereço")
self.entry.grid(row=0, column=0, sticky="we", padx=(12, 0), pady=12)
self.entry.bind("<Return>", self.search_event)
self.button_6 = customtkinter.CTkButton(master=self.frame_right,
text="Buscar",
width=90,
command=self.search_event)
self.button_6.grid(row=0, column=1, sticky="w", padx=(12, 0), pady=12)
self.botao_centralizar_navio = customtkinter.CTkButton(master=self.frame_right,
text="Centralizar Navio",
width=90,
command=self.centralize_ship)
self.botao_centralizar_navio.grid(row=0, column=2, sticky="w", padx=(12, 0), pady=12)
#Funções no mapa inicial
self.map_widget.add_right_click_menu_command(label="Adicionar mina",
command=self.add_mine,
pass_coords=True)
#Ponto de derrota autônoma
self.map_widget.add_right_click_menu_command(label="Adicionar ponto de derrota autônoma",
command=self.add_autonomous_point,
pass_coords=True)
#Varredura sonar
self.map_widget.add_right_click_menu_command(label="Adicionar varredura sonar",
command=self.add_sonar_sweep,
pass_coords=True)
#Botão que liga/desliga AIS da praticagem
self.checkbox = customtkinter.CTkCheckBox(master=self.frame_left, text="AIS Praticagem", command=self.update_lista_praticagem(),variable=self.check_var, onvalue="on", offvalue="off")
self.checkbox.grid(row=18, column=0, padx=(20, 20), pady=(10, 20))
###Imagem da camera
self.vid = cv2.VideoCapture('teste.mp4')
"""
rtsp_url = 'rtsp://172.18.14.214/axis-media/media.amp' #Para usar na lancha
self.vid = cv2.VideoCapture(rtsp_url)
self.camera_width , self.camera_height = 800,600
# Set the width and height
self.vid.set(cv2.CAP_PROP_FRAME_WIDTH, self.camera_width)
self.vid.set(cv2.CAP_PROP_FRAME_HEIGHT, self.camera_height)
"""
# Create a label and display it on app
self.text_var = tkinter.StringVar(value="")
self.label_widget = customtkinter.CTkLabel(self,textvariable=self.text_var)
self.label_widget.grid(row=0,column=2,sticky="nsew",rowspan=1,columnspan=3)
# Set default values
self.map_widget.set_position(self.controller.LatOrigin, self.controller.LongOrigin) #Posição inicial do mapa
self.map_widget.set_zoom(15)
#self.map_widget.set_address("Rio de Janeiro")
self.map_option_menu.set("Google normal")
self.appearance_mode_optionemenu.set("Dark")
#Teste de marcadores
self.marker_1 = self.map_widget.set_marker(self.controller.LatOrigin, self.controller.LongOrigin, text="VSNT-Lab", icon=ship_image, command=self.marker_callback)
def __init_main_variables(self):
# Variables for plotting the trajectory
self.autonomous_points = []
self.pontos_sonar = []
self.autonomous_speed = AUTONOMOUS_SPEED # meters/s
self.max_autonomous_speed = MAX_AUTONOMOUS_SPEED
self.visited_points = []
#Variables for control parameters
self.max_heading_kp = MAX_HEADING_KP
self.max_heading_ki = MAX_HEADING_KI
self.max_heading_kd = MAX_HEADING_KD
self.max_speed_kp = MAX_SPEED_KP
self.max_speed_ki = MAX_SPEED_KI
self.max_speed_kd = MAX_SPEED_KD
#Variável auxiliar para ligar AIS da praticagem
self.check_var = tkinter.StringVar(self,"off")
self.check_var_constantheading = tkinter.StringVar(self,"off")
#Auxilio na plotagem dos AIS
self.marker_list = []
#Variáveis auxiliares
self.mmsi_list = []
self.markers_ais = {} #Dicionário para colocar os marcadores
self.markers_image = {} #Dicionário para imagens dos navios AIS
self.camera_on = False
self.last_ais_msg = None
self.manual_control = False
self.control_activation_counter = 0
self.view_seglist = None
self.view_point = None
self.activate_point_marker = None
self.station_keep_marker = None
self.deploy = None
self.return_var = None
self.bhv_settings = None #Comportamento ativo no momento
self.ivphelm_bhv_active = None
self.maximum_msg_time = 3 # seconds
self.connection_ok = True
self.trajectory_plot_is_toggled = False
self.autonomous_control = False
self.make_variables_plot = False
self.active_animations = []
self.selected_plot_variables = []
def __main_loop(self):
"""
Main functions to run in the loop
"""
self.update_ship_position()
self.update_gui()
self.update_ais_contacts()
#self.update_station_keep()
#self.update_lista_praticagem()
#
self.check_connection()
def check_connection(self):
"""
Checks the last time a messagem was received from MOOS, and if it is greater than the
maximum defined time, a display is set to show that there is no connection
"""
try:
if pymoos.time() - self.controller.last_msg_time > self.maximum_msg_time:
self.connection_ok = False
else:
self.connection_ok = True
except AttributeError:
self.connection_ok = False
print(f"\nConnection is {self.connection_ok}")
self.after(1000,self.check_connection)
def trajectory_plot(self):
"""
Plots the previous trajectory of the vessel
"""
if len(self.visited_points) > 1:
if self.trajectory_plot_is_toggled:
self.trajectory_button.configure(text="Plot Trajetória")
self.trajectory_plot_is_toggled = False
self.path_trajectory.delete()
else:
self.trajectory_button.configure(text="Remove Trajetória")
self.trajectory_plot_is_toggled = True
self.path_trajectory = self.map_widget.set_path(self.visited_points, color='yellow',width=0.5)
def centralize_ship(self):
"""
Centers the map on the Ship's location
"""
self.map_widget.set_position(self.controller.nav_lat,self.controller.nav_long)
def decimal_degrees_to_dms(self,latitude):
"""
Converts degrees to degrees, minutes and seconds
"""
degrees = int(latitude)
decimal_minutes = (latitude - degrees) * 60
minutes = int(decimal_minutes)
seconds = (decimal_minutes - minutes) * 60
return degrees, minutes, seconds
#Atualiza o station_keep
def update_station_keep(self):
if self.bhv_settings is not None and self.ivphelm_bhv_active == "end-station":
vars_station = self.bhv_settings.split(",") #Divido variáveis
x = float(vars_station[2][2:]) #Pego o valor de x do station keep
y = float(vars_station[3][2:]) #Pego o valor de y do station keep
#Converto x e y para lat e long
inv_longitude, inv_latitude = pyproj.transform(self.projection_local, self.projection_global, x-self.diff_x, y-self.diff_y)
station_keep_image = ImageTk.PhotoImage(Image.open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "images", "circle_station_keep.png")).resize((70, 70)))
if self.station_keep_marker is None:
self.station_keep_marker = self.map_widget.set_marker(inv_latitude, inv_longitude, icon=station_keep_image)
else:
self.station_keep_marker.set_position(inv_latitude,inv_longitude)
else:
if self.station_keep_marker is not None:
self.station_keep_marker.delete() #Deleto o marker
self.station_keep_marker = None
self.after(1000,self.update_station_keep)
#Atualiza o ponto ativo no momento
def update_active_autonomous_point(self):
if self.view_point is not None:
data_point = self.view_point.split(",")
x = float(data_point[0][2:]) #Pego o valor de x do ponto ativo
y = float(data_point[1][2:]) #Pego o valor de y do ponto ativo
#Converto x e y para lat e long
inv_longitude, inv_latitude = pyproj.transform(self.projection_local, self.projection_global, x-self.diff_x, y-self.diff_y)
#Ploto o marker do ponto ativo
ponto_ativo_image = ImageTk.PhotoImage(Image.open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "images", "hit_marker.png")).resize((70, 70)))
if self.activate_point_marker is None:
self.activate_point_marker = self.map_widget.set_marker(inv_latitude, inv_longitude, icon=ponto_ativo_image)
else:
self.activate_point_marker.set_position(inv_latitude,inv_longitude)
self.after(1000,self.update_active_autonomous_point)
else:
print("Variable VIEW_POINT is None \n")
#Atualiza a derrota autônoma - Executar apenas quando ativar a opção de controle autônomo
def update_autonomous(self):
self.create_menu_autonomous()
if self.view_seglist is not None: #Checa se a lista não está vazia
#Extrair coordenadas da self.view_seglist
start_index = self.view_seglist.find("pts={") + len("pts={")
end_index = self.view_seglist.find("}")
pts_string = self.view_seglist[start_index:end_index]
points = pts_string.split(":")
# Converte os pontos para coordenadas de mapa e armazena
for match in points:
match = match.split(",")
#Conversão de coordenadas locais para globais
#inv_longitude, inv_latitude = pyproj.transform(self.projection_local, self.projection_global, float(match[0])-self.diff_x, float(match[1])-self.diff_y)
inv_longitude, inv_latitude = pyproj.transform(self.projection_local, self.projection_global, float(match[0]), float(match[1]))
print(inv_latitude, inv_longitude)
#Adiciono os pontos na lista
self.autonomous_points.append((inv_latitude, inv_longitude))
# Pontos para debug
print(f"Autonomous Points: {self.autonomous_points}")
#Defino o caminho
#self.path_autonomous = self.map_widget.set_path(self.autonomous_points)
self.path_autonomous.set_position_list(self.autonomous_points)
#Definindo pontos da derrota como markers
for ponto in self.autonomous_points:
#self.marker_autonomous_list.append(self.map_widget.set_marker(ponto[0], ponto[1], text="#"+str(self.autonomous_points.index(ponto)+1)+" Ponto de derrota autônoma"))
self.marker_autonomous_list.append(self.map_widget.set_marker(ponto[0], ponto[1], text=f"#{self.autonomous_points.index(ponto)+1} Pt"))
# Ploto a derrota no mapa
#path_1 = self.map_widget.set_path([self.marker_autonomous_list[0].position, self.marker_autonomous_list[1].position, (-43.15947614659043, -22.911947446774985), (-43.15947564792508, -22.908967568090326)])
#Adiciona a varredura sonar no mapa
def add_sonar_sweep(self,coords):
#Transformo coordenadas globais em locais
x, y = pyproj.transform(self.projection_global, self.projection_local, coords[1], coords[0])
string_varredura_inicial='points=format=lawnmower,x='+str(round(x,2))+',y='+str(round(y,2))+',degs=0,height=500,width=1800,lane_width=150'
print(string_varredura_inicial)
#Envia a varredura sonar para o MOOS
self.controller.notify('WPT_UPDATE', string_varredura_inicial,pymoos.time())
print("Enviado para o MOOS -> WPT_UPDATE="+string_varredura_inicial)
#Inicia e depois para
if self.deploy == 'false' or self.return_var == 'true':
self.controller.notify('DEPLOY', 'true',pymoos.time())
self.controller.notify('MOOS_MANUAL_OVERIDE', 'false',pymoos.time())
self.controller.notify('RETURN', 'false',pymoos.time())
self.controller.notify('END', 'false',pymoos.time())
#Caso não atualize a varredura, aumentar o delay aqui
time.sleep(1)
self.controller.notify('END', 'true',pymoos.time())
#Após enviar atualiza os pontos na tela
#Deleta pontos de indicação da derrota
for marker in self.marker_autonomous_list:
marker.delete()
#Deleta o caminho do mapa
self.map_widget.delete_all_path()
#Limpo a lista self.pontos_autonomos
self.autonomous_points = []
#Pega os pontos da variável e cria a nova derrota
if self.view_seglist is not None: #Checa se a lista não está vazia
#Extrair coordenadas da self.view_seglist
start_index = self.view_seglist.find("pts={") + len("pts={")
end_index = self.view_seglist.find("}")
pts_string = self.view_seglist[start_index:end_index]
points = pts_string.split(":")
# Converte os pontos para coordenadas de mapa e armazena
for match in points:
match = match.split(",")
#Conversão de coordenadas locais para globais
inv_longitude, inv_latitude = pyproj.transform(self.projection_local, self.projection_global, float(match[0])-self.diff_x, float(match[1])-self.diff_y)
#Adiciono os pontos na lista
self.autonomous_points.append((inv_latitude, inv_longitude))
#Defino o caminho
self.path_autonomous = self.map_widget.set_path(self.autonomous_points)
#Definindo pontos da derrota como markers
for ponto in self.autonomous_points:
self.marker_autonomous_list.append(self.map_widget.set_marker(ponto[0], ponto[1], text="#"+str(self.autonomous_points.index(ponto)+1)+" Ponto de derrota autônoma"))
def add_autonomous_point(self,coords):
"""
Adds points for the autonomous navigation trajectory
"""
print("Adicionar ponto de derrota:", coords)
#Adiciona ponto na lista de pontos
self.autonomous_points.append(coords)
#Defino o caminho
if len(self.autonomous_points) > 1: #Para não criar o caminho c/ 1 ponto só
try:
self.path_autonomous.set_position_list(self.autonomous_points)
except AttributeError:
self.path_autonomous = self.map_widget.set_path(self.autonomous_points)
#Definindo pontos da derrota como markers
#Só adiciona pontos que não estão na lista
for ponto in self.autonomous_points:
if ponto not in self.marker_autonomous_list:
self.marker_autonomous_list.append(self.map_widget.set_marker(ponto[0], ponto[1], text="#"+str(self.autonomous_points.index(ponto)+1)+" Ponto de derrota autônoma"))
def destroy_autonomous(self):
"""
Destroys the GUI for the autonomous navigation
"""
self.autonomous_control = False
#Deleto toda a derrota do mapa
self.map_widget.delete_all_path()
#Deleto os pontos do mapa
for marker in self.marker_autonomous_list:
marker.delete()
#Alterar a função do botão
self.button_controle_autonomo.configure(command=self.update_autonomous,text="Controle Autônomo")
self.slider_progressbar_frame1.destroy()
self.label_machine1.destroy()
self.activate_point_marker.destroy()
self.controller.stop_autonomous_navigation()
def create_menu_autonomous(self):
"""
Create the GUI Menu for setting the desired autonomous trajectory and speed
If the desired speed changes the Init button must be hit again
"""
#Altero o texto do botão
self.autonomous_control = True
self.button_controle_autonomo.configure(command=self.destroy_autonomous,text="Desativar Controle Autônomo")
#Crio o frame com o controle autônomo
# create slider and progressbar frame
self.slider_progressbar_frame1 = customtkinter.CTkFrame(self, fg_color="transparent",width=400,height=200)
self.slider_progressbar_frame1.grid(row=0, column=5, padx=(20, 0), pady=(90, 0), sticky="nsew") #Mexer no pady se quiser abaixar mais o frame
self.slider_progressbar_frame1.grid_columnconfigure(0, weight=1)
self.slider_progressbar_frame1.grid_rowconfigure(24, weight=1)
#Label do Controle Autônomo
self.label_machine1 = customtkinter.CTkLabel(master=self.slider_progressbar_frame1, text="Controle Autônomo")
self.label_machine1.configure(font=("Segoe UI", 30))
self.label_machine1.grid(row=0, column=0, columnspan=2, padx=(50,50), pady=(10,5), sticky="")
#Botão para iniciar
self.button_inicio_autonomo = customtkinter.CTkButton(master=self.slider_progressbar_frame1,
text="Iniciar",
command=self.activate_autonomous)
self.button_inicio_autonomo.grid(pady=(5, 5), padx=(5, 5), row=1, column=0)
self.button_parada_autonomo = customtkinter.CTkButton(master=self.slider_progressbar_frame1,
text="Parar",
command=self.stop_autonomous)
self.button_parada_autonomo.grid(pady=(5, 5), padx=(5, 35), row=1, column=1)
self.button_parada_autonomo = customtkinter.CTkButton(master=self.slider_progressbar_frame1,
text="Limpar Derrota",
command=self.clean_autonomous)
self.button_parada_autonomo.grid(pady=(15, 5), padx=(35, 35), row=2, column=0)
self.button_remove_ultimo = customtkinter.CTkButton(master=self.slider_progressbar_frame1,
text="Remover Último Ponto",
command=self.clean_last_autonomous)
self.button_remove_ultimo.grid(pady=(15, 5), padx=(35, 60), row=2, column=1)
# Set desired speed for autonomous controller
self.label_desired_speed = customtkinter.CTkLabel(master=self.slider_progressbar_frame1, text=f"Desired Speed: {float(self.autonomous_speed)}knots")
self.label_desired_speed.configure(font=("Segoe UI", 20))
self.label_desired_speed.grid(row=3, column=0, columnspan=2, padx=0, pady=(15,5), sticky="")
self.slider_speed = customtkinter.CTkSlider(self.slider_progressbar_frame1, from_=0,
to=self.max_autonomous_speed,
number_of_steps=self.max_autonomous_speed*2)
self.slider_speed.grid(row=4, column=0, columnspan=2, padx=(50, 50), pady=(15, 5), sticky="ew")
self.slider_speed.configure(command=self.update_desired_speed)
self.slider_speed.set(self.autonomous_speed)
self.speed_progressbar = customtkinter.CTkProgressBar(master=self.slider_progressbar_frame1,width=300)
self.speed_progressbar.grid(row=5, column=0, columnspan=2, padx=(50, 50), pady=(15, 15), sticky="ew")
self.speed_progressbar.set(self.controller.nav_speed/self.max_autonomous_speed)
# Set option for Plotting Variables
self.button_plot_variables = customtkinter.CTkButton(master=self.slider_progressbar_frame1,
text="Plot Variables",
command=self.toggle_plot_variables)
self.button_plot_variables.grid(pady=(5, 5), padx=(5, 5), row=6, column=0)
# Creates a listbox for selecting multiple variables to plot
self.listbox_selection = ('RUDDER PLOT',
'HEADING PLOT',
'SPEED PLOT',
'DEPTH PLOT')
var = tkinter.Variable(value=self.listbox_selection)
# selecmode can be MULTIPLE, SINGLE
self.select_list = tkinter.Listbox(master=self.slider_progressbar_frame1,
listvariable=var,
height=len(self.listbox_selection),
selectmode=tkinter.SINGLE)
self.select_list.configure(background="#265aad",foreground="white",font=("Segoe UI", 10))
self.select_list.grid(pady=(5, 5), padx=(5, 5), row=6, column=1)
# Binds the variables chosen to an action
self.select_list.bind('<<ListboxSelect>>', self.items_selected)
#Heading automático
self.checkbox_heading = customtkinter.CTkCheckBox(master=self.slider_progressbar_frame1, text="Heading Constante", variable=self.check_var_constantheading, onvalue="on", offvalue="off")
self.checkbox_heading.grid(row=7, column=0, columnspan=2, padx=(20, 20), pady=(5, 5))
self.checkbox_heading.configure(command=self.update_auto_heading)
self.label_setpoint_heading = customtkinter.CTkLabel(master=self.slider_progressbar_frame1, text=f"Rumo: {round(float(self.controller.setpoint_heading),2)}")
self.label_setpoint_heading.configure(font=("Segoe UI", 20))
self.label_setpoint_heading.grid(row=8, column=0, columnspan=2, padx=(10,0), pady=(0,5), sticky="")
self.slider_setpoint_heading = customtkinter.CTkSlider(self.slider_progressbar_frame1, from_=0, to=360, number_of_steps=360)
self.slider_setpoint_heading.grid(row=9, column=0, columnspan=2, padx=0, pady=(5, 5), sticky="ew")
self.slider_setpoint_heading.configure(command=self.update_setpoint_heading)
self.slider_setpoint_heading.set(self.controller.heading_kp)
#Parâmetros do controle PID
#Label de cima
self.label_machine1 = customtkinter.CTkLabel(master=self.slider_progressbar_frame1, text="Controle PID Heading")
self.label_machine1.configure(font=("Segoe UI", 25))
self.label_machine1.grid(row=10, column=0, columnspan=2, padx=(10,20), pady=(10,5), sticky="n")
self.label_heading_kp = customtkinter.CTkLabel(master=self.slider_progressbar_frame1, text=f"KP: {self.controller.heading_kp:.2f}")
self.label_heading_kp.configure(font=("Segoe UI", 20))
self.label_heading_kp.grid(row=11, column=0, columnspan=2, padx=(10,0), pady=(0,5), sticky="n")
self.slider_heading_kp = customtkinter.CTkSlider(self.slider_progressbar_frame1, from_=0, to=self.max_heading_kp, number_of_steps=200)
self.slider_heading_kp.grid(row=12, column=0, columnspan=2, padx=0, pady=(5, 5), sticky="")
self.slider_heading_kp.configure(command=self.update_heading_kp)
self.slider_heading_kp.set(self.controller.heading_kp)
self.label_heading_ki = customtkinter.CTkLabel(master=self.slider_progressbar_frame1, text=f"KI: {round(float(self.controller.heading_ki),2)}")
self.label_heading_ki.configure(font=("Segoe UI", 20))
self.label_heading_ki.grid(row=13, column=0, columnspan=2, padx=0, pady=(5,5), sticky="")
self.slider_heading_ki = customtkinter.CTkSlider(self.slider_progressbar_frame1, from_=0, to=self.max_heading_ki, number_of_steps=200)
self.slider_heading_ki.grid(row=14, column=0, columnspan=2, padx=0, pady=(5, 5), sticky="")
self.slider_heading_ki.configure(command=self.update_heading_ki)
self.slider_heading_ki.set(self.controller.heading_ki)
self.label_heading_kd = customtkinter.CTkLabel(master=self.slider_progressbar_frame1, text=f"KD: {round(float(self.controller.heading_kd),2)}")
self.label_heading_kd.configure(font=("Segoe UI", 20))
self.label_heading_kd.grid(row=15, column=0, columnspan=2, padx=0, pady=(5,5), sticky="")
self.slider_heading_kd = customtkinter.CTkSlider(self.slider_progressbar_frame1, from_=0, to=self.max_heading_kd, number_of_steps=200)
self.slider_heading_kd.grid(row=16, column=0, columnspan=2, padx=0, pady=(5, 5), sticky="")
self.slider_heading_kd.configure(command=self.update_heading_kd)
self.slider_heading_kd.set(self.controller.heading_kd)
self.label_machine1 = customtkinter.CTkLabel(master=self.slider_progressbar_frame1, text="Controle PID Speed")
self.label_machine1.configure(font=("Segoe UI", 25))
self.label_machine1.grid(row=17, column=0, columnspan=2, padx=(10,20), pady=(5,5), sticky="n")
self.label_speed_kp = customtkinter.CTkLabel(master=self.slider_progressbar_frame1, text=f"KP: {round(float(self.controller.speed_kp),2)}")
self.label_speed_kp.configure(font=("Segoe UI", 20))
self.label_speed_kp.grid(row=18, column=0, columnspan=2, padx=(10,0), pady=(0,5), sticky="n")
self.slider_speed_kp = customtkinter.CTkSlider(self.slider_progressbar_frame1, from_=0, to=self.max_speed_kp, number_of_steps=200)
self.slider_speed_kp.grid(row=19, column=0, columnspan=2, padx=0, pady=(5, 5), sticky="")
self.slider_speed_kp.configure(command=self.update_speed_kp)
self.slider_speed_kp.set(self.controller.speed_kp)
self.label_speed_ki = customtkinter.CTkLabel(master=self.slider_progressbar_frame1, text=f"KI: {round(float(self.controller.speed_ki),2)}")
self.label_speed_ki.configure(font=("Segoe UI", 20))
self.label_speed_ki.grid(row=20, column=0, columnspan=2, padx=0, pady=(5,5), sticky="")
self.slider_speed_ki = customtkinter.CTkSlider(self.slider_progressbar_frame1, from_=0, to=self.max_speed_ki, number_of_steps=200)
self.slider_speed_ki.grid(row=21, column=0, columnspan=2, padx=0, pady=(5, 5), sticky="")
self.slider_speed_ki.configure(command=self.update_speed_ki)
self.slider_speed_ki.set(self.controller.speed_ki)
self.label_speed_kd = customtkinter.CTkLabel(master=self.slider_progressbar_frame1, text=f"KD: {round(float(self.controller.speed_kd),2)}")
self.label_speed_kd.configure(font=("Segoe UI", 20))
self.label_speed_kd.grid(row=22, column=0, columnspan=2, padx=0, pady=(5,5), sticky="")
self.slider_speed_kd = customtkinter.CTkSlider(self.slider_progressbar_frame1, from_=0, to=self.max_speed_kd, number_of_steps=200)
self.slider_speed_kd.grid(row=23, column=0, columnspan=2, padx=0, pady=(5, 5), sticky="")
self.slider_speed_kd.configure(command=self.update_speed_kd)
self.slider_speed_kd.set(self.controller.speed_kd)
def toggle_plot_variables(self):
"""
Check if USER asked to plot variables
"""
if self.make_variables_plot: # End plot
self.button_plot_variables.configure(text=f"Plot Variables")
self.make_variables_plot = False
for animation in self.active_animations:
animation.pause()
plt.close()
self.active_animations = []
else: # Start plot
if len(self.selected_plot_variables) > 0:
self.make_variables_plot = True
self.button_plot_variables.configure(text=f"Close Plot Variables")
if len(self.active_animations) > 0:
for animation in self.active_animations:
animation.resume()
else:
for plot_type in self.selected_plot_variables:
self.plot_variables(plot_type=plot_type)
def items_selected(self, event):
"""
Updates the selected variables to plot from the list
"""
selected_indices = self.select_list.curselection()
self.selected_plot_variables = [self.listbox_selection[i] for i in selected_indices]
print(self.selected_plot_variables)
def plot_variables(self, plot_type):
"""
Plot Two Variables: var_des, intended for desired control variables
var_nav, the real value for the vessel
""" # Clear the previous plot and plot the updated data
MAXLEN = 100 # maximum stored values in the queue
ALPHA = 0.1 # transparency of plot
LINEWIDTH = 1 # line width of plot
PLOT_INTERVAL = 200 # ms
def animate_heading(i,heading_x_data,
heading_y_des_data,
heading_y_nav_data,
heading_y_out_data):
x = time.time() - heading_init_time
nav = self.controller.nav_heading
if (self.controller.constant_heading == True) or (self.check_var_constantheading.get() == "on"):
des = self.controller.setpoint_heading
else:
des = self.controller.desired_heading
out = self.controller.desired_rudder
heading_x_data.append(x)
heading_y_des_data.append(des)
heading_y_nav_data.append(nav)
heading_y_out_data.append(out)
plt.cla()
axu.clear()
axd.clear()
axu.plot(heading_x_data, heading_y_nav_data,label="NAV_HEADING")
axu.plot(heading_x_data, heading_y_des_data,label="DESIRED_HEADING")
axd.set_xlabel('Time [s]')
axu.set_ylabel('Value [°]')
axu.set_ylim([0,365])
axu.legend()
axd.plot(heading_x_data, heading_y_out_data,label="PID OUTPUT")
axd.set_ylabel('Value [°]')
axd.set_ylim([-40,40])
axd.legend()
axu.set_title('Real-time Heading Plot')
axd.grid(alpha=ALPHA,linewidth=LINEWIDTH)
axu.grid(alpha=ALPHA,linewidth=LINEWIDTH)
plt.tight_layout()
def animate_rudder(i):
x = time.time() - rudder_init_time
nav = self.controller.nav_yaw
des = self.controller.desired_rudder
rudder_x_data.append(x)
rudder_y_des_data.append(des)
rudder_y_nav_data.append(nav)
plt.cla()
plt.plot(rudder_x_data, rudder_y_nav_data,label="NAV_RUDDER")
plt.plot(rudder_x_data, rudder_y_des_data,label="DESIRED_RUDDER")
plt.xlabel('Time [s]')
plt.ylabel('Value [°]')
plt.ylim([-45,45])
plt.legend()
plt.grid(alpha=ALPHA,linewidth=LINEWIDTH)
plt.title('Real-time Rudder Plot')
def animate_speed(i,speed_x_data,
speed_y_des_data,
speed_y_nav_data,
speed_y_out_data):
x = time.time() - speed_init_time
nav = self.controller.nav_speed
des = self.controller.desired_speed
out = self.controller.desired_thrust
speed_x_data.append(x)
speed_y_des_data.append(des)
speed_y_nav_data.append(nav)
speed_y_out_data.append(out)
plt.cla()
axu.clear()
axd.clear()
axu.plot(speed_x_data, speed_y_nav_data,label="NAV_SPEED")
axu.plot(speed_x_data, speed_y_des_data,label="DESIRED_SPEED")
axu.set_ylabel('Value [knots]')
axu.set_ylim([0,10])
axu.grid(alpha=ALPHA,linewidth=LINEWIDTH)
axu.legend()
axd.set_xlabel('Time [s]')
axd.plot(speed_x_data, speed_y_out_data,label="PID OUTPUT")
axd.set_ylabel('Value %')
axd.set_ylim([0,100])
axd.legend()
axd.grid(alpha=ALPHA,linewidth=LINEWIDTH)
axu.set_title('Real-time Speed Plot')
def animate_depth(i):
x = time.time() - depth_init_time
nav = self.controller.nav_depth
depth_x_data.append(x)
depth_y_nav_data.append(nav)
plt.cla()
plt.plot(depth_x_data, depth_y_nav_data,label="NAV_DEPTH")
plt.xlabel('Time [s]')
plt.ylabel('Value [m]')
plt.legend()
plt.grid(alpha=ALPHA,linewidth=LINEWIDTH)
plt.title('Real-time Depth Plot')
if plot_type == "RUDDER PLOT":
print("\nMaking RUDDER PLOT\n")
rudder_x_data = deque(maxlen=MAXLEN)
rudder_y_des_data = deque(maxlen=MAXLEN)
rudder_y_nav_data = deque(maxlen=MAXLEN)
rudder_fig, ax = plt.subplots()
rudder_init_time = time.time()
self.rudder_plot_animation = FuncAnimation(rudder_fig, animate_rudder, interval=PLOT_INTERVAL)
self.active_animations.append(self.rudder_plot_animation)
plt.show()
elif plot_type == "SPEED PLOT":
print("\nMaking SPEED PLOT\n")
speed_x_data = deque(maxlen=MAXLEN)
speed_y_des_data = deque(maxlen=MAXLEN)
speed_y_nav_data = deque(maxlen=MAXLEN)
speed_y_out_data = deque(maxlen=MAXLEN)
speed_fig, (axu,axd) = plt.subplots(nrows=2,sharex=True)
speed_init_time = time.time()
self.speed_plot_animation = FuncAnimation(speed_fig, animate_speed, fargs=(speed_x_data,
speed_y_des_data,
speed_y_nav_data,
speed_y_out_data),interval=PLOT_INTERVAL)
self.active_animations.append(self.speed_plot_animation)
plt.show()
elif plot_type == "HEADING PLOT":
print("\nMaking HEADING PLOT\n")
heading_x_data = deque(maxlen=MAXLEN)
heading_y_des_data = deque(maxlen=MAXLEN)
heading_y_nav_data = deque(maxlen=MAXLEN)
heading_y_out_data = deque(maxlen=MAXLEN)
heading_fig, (axu,axd) = plt.subplots(nrows=2,sharex=True)
heading_init_time = time.time()
self.heading_plot_animation = FuncAnimation(heading_fig, animate_heading, fargs=(heading_x_data,
heading_y_des_data,
heading_y_nav_data,
heading_y_out_data),interval=PLOT_INTERVAL)
self.active_animations.append(self.heading_plot_animation)
plt.show()
elif plot_type == "DEPTH PLOT":
print("\nMaking DEPTH PLOT\n")
depth_x_data = deque(maxlen=MAXLEN)
depth_y_nav_data = deque(maxlen=MAXLEN)
depth_fig, ax = plt.subplots()
depth_init_time = time.time()
self.depth_plot_animation = FuncAnimation(depth_fig, animate_depth, interval=PLOT_INTERVAL)
self.active_animations.append(self.depth_plot_animation)
plt.show()
#TODO
def update_desired_speed(self,_):
"""
Updates GUI of desired speed in the autonomous menu and notifies the controller
of the new desired speed for the autonomous path
"""
desired_speed = self.slider_speed.get()
self.autonomous_speed = desired_speed
#TODO ver se vai fazer funcionar só mandar a velocidade fixa
#self.controller.set_desired_speed(desired_speed)
self.label_desired_speed.configure(text=f"Desired Speed: {self.autonomous_speed}knots")
def update_heading_kp(self,value):
"""
Updates kp value in the control
"""
#Envio para o MOOS o valor da variável
self.controller.notify('HEADING_KP',value,pymoos.time())
#Update da label
self.label_heading_kp.configure(text=f"KP: {self.controller.heading_kp:.3f}")
def update_heading_ki(self,value):
"""
Updates ki value in the control
"""
#Envio para o MOOS o valor da variável