-
Notifications
You must be signed in to change notification settings - Fork 23
/
ED_AP.py
1886 lines (1549 loc) · 77.8 KB
/
ED_AP.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
from pickletools import read_unicodestring1
import traceback
from math import atan, degrees
import json
import random
import cv2
from PIL import Image
from pathlib import Path
from EDAP_data import *
from EDlogger import logger, logging
import Image_Templates
import Screen
import Screen_Regions
from EDWayPoint import *
from EDJournal import *
from EDKeys import *
from EDafk_combat import AFK_Combat
from Overlay import *
from StatusParser import StatusParser
from Voice import *
from Robigo import *
"""
File:EDAP.py EDAutopilot
Description:
Note:
Ideas taken from: https://github.com/skai2/EDAutopilot
Author: [email protected]
"""
# Exception class used to unroll the call tree to to stop execution
class EDAP_Interrupt(Exception):
pass
class EDAutopilot:
def __init__(self, cb, doThread=True):
self.config = {
"DSSButton": "Primary", # if anything other than "Primary", it will use the Secondary Fire button for DSS
"JumpTries": 3, #
"NavAlignTries": 3, #
"RefuelThreshold": 65, # if fuel level get below this level, it will attempt refuel
"FuelThreasholdAbortAP": 10, # level at which AP will terminate, because we are not scooping well
"WaitForAutoDockTimer": 120, # After docking granted, wait this amount of time for us to get docked with autodocking
"SunBrightThreshold": 125, # The low level for brightness detection, range 0-255, want to mask out darker items
"FuelScoopTimeOut": 35, # number of second to wait for full tank, might mean we are not scooping well or got a small scooper
"DockingRetries": 30, # number of time to attempt docking
"HotKey_StartFSD": "home", # if going to use other keys, need to look at the python keyboard package
"HotKey_StartSC": "ins", # to determine other keynames, make sure these keys are not used in ED bindings
"HotKey_StartRobigo": "pgup", #
"HotKey_StopAllAssists": "end",
"Robigo_Single_Loop": False, # True means only 1 loop will executed and then terminate the Robigo, will not perform mission processing
"EnableRandomness": False, # add some additional random sleep times to avoid AP detection (0-3sec at specific locations)
"ActivateEliteEachKey": False, # Activate Elite window before each key or group of keys
"OverlayTextEnable": False, # Experimental at this stage
"OverlayTextYOffset": 400, # offset down the screen to start place overlay text
"OverlayTextXOffset": 50, # offset left the screen to start place overlay text
"OverlayTextFont": "Eurostyle",
"OverlayTextFontSize": 14,
"OverlayGraphicEnable": False, # not implemented yet
"DiscordWebhook": False, # discord not implemented yet
"DiscordWebhookURL": "",
"DiscordUserID": "",
"VoiceEnable": False,
"VoiceID": 1, # my Windows only have 3 defined (0-2)
"ElwScannerEnable": False,
"LogDEBUG": False, # enable for debug messages
"LogINFO": True,
"Enable_CV_View": 0, # Should CV View be enabled by default
"ShipConfigFile": None # Ship config to load on start
}
# used this to write the self.config table to the json file
# self.write_config(self.config)
cnf = self.read_config()
# if we read it then point to it, otherwise use the default table above
if cnf is not None:
if len(cnf) != len(self.config):
self.write_config(self.config)
else:
self.config = cnf
logger.debug("read AP json:"+str(cnf))
# Specific test since new entry
if 'SunBrightThreshold' not in self.config:
self.config['SunBrightThreshold'] = 125
else:
self.write_config(self.config)
# config the voice interface
self.vce = Voice()
self.vce.v_enabled = self.config['VoiceEnable']
self.vce.set_voice_id(self.config['VoiceID'])
self.vce.say("Welcome to Autopilot")
# set log level based on config input
if self.config['LogINFO']:
logger.setLevel(logging.INFO)
if self.config['LogDEBUG']:
logger.setLevel(logging.DEBUG)
# initialize all to false
self.fsd_assist_enabled = False
self.sc_assist_enabled = False
self.afk_combat_assist_enabled = False
self.waypoint_assist_enabled = False
self.robigo_assist_enabled = False
# Create instance of each of the needed Classes
self.scr = Screen.Screen()
self.templ = Image_Templates.Image_Templates(self.scr.scaleX, self.scr.scaleY)
self.scrReg = Screen_Regions.Screen_Regions(self.scr, self.templ)
self.jn = EDJournal()
self.keys = EDKeys()
self.afk_combat = AFK_Combat(self.keys, self.jn, self.vce)
self.waypoint = EDWayPoint(self.jn.ship_state()['odyssey'])
self.robigo = Robigo(self)
self.status = StatusParser()
# rate as ship dependent. Can be found on the outfitting page for the ship. However, it looks like supercruise
# has worse performance for these rates
# see: https://forums.frontier.co.uk/threads/supercruise-handling-of-ships.396845/
#
# If you find that you are overshoot in pitch or roll, need to adjust these numbers.
# Algorithm will roll the vehicle for the nav point to be north or south and then pitch to get the nave point
# to center
self.yawrate = 8.0
self.rollrate = 80.0
self.pitchrate = 33.0
self.sunpitchuptime = 0.0
self.jump_cnt = 0
self.total_dist_jumped = 0
self.total_jumps = 0
self.refuel_cnt = 0
self.ap_ckb = cb
# Overlay vars
self.ap_state = "Idle"
self.fss_detected = "nothing found"
# Initialize the Overlay class
self.overlay = Overlay("", elite=1)
self.overlay.overlay_setfont(self.config['OverlayTextFont'], self.config['OverlayTextFontSize'])
self.overlay.overlay_set_pos(self.config['OverlayTextXOffset'], self.config['OverlayTextYOffset'])
# must be called after we initialized the objects above
self.update_overlay()
# debug window
self.cv_view = False
self.cv_view_x = 10
self.cv_view_y = 10
#start the engine thread
self.terminate = False # terminate used by the thread to exit its loop
if doThread:
self.ap_thread = kthread.KThread(target=self.engine_loop, name="EDAutopilot")
self.ap_thread.start()
# Loads the configuration file
#
def read_config(self, fileName='./configs/AP.json'):
s = None
try:
with open(fileName, "r") as fp:
s = json.load(fp)
except Exception as e:
logger.warning("EDAPGui.py read_config error :"+str(e))
return s
def update_config(self):
self.write_config(self.config)
def write_config(self, data, fileName='./configs/AP.json'):
try:
with open(fileName, "w") as fp:
json.dump(data, fp, indent=4)
except Exception as e:
logger.warning("EDAPGui.py write_config error:"+str(e))
# draw the overlay data on the ED Window
#
def update_overlay(self):
if self.config['OverlayTextEnable']:
ap_mode = "Offline"
if self.fsd_assist_enabled == True:
ap_mode = "FSD Route Assist"
elif self.robigo_assist_enabled == True:
ap_mode = "Robigo Assist"
elif self.sc_assist_enabled == True:
ap_mode = "SC Assist"
elif self.waypoint_assist_enabled == True:
ap_mode = "Waypoint Assist"
elif self.afk_combat_assist_enabled == True:
ap_mode = "AFK Combat Assist"
ship_state = self.jn.ship_state()['status']
if ship_state == None:
ship_state = '<init>'
sclass = self.jn.ship_state()['star_class']
if sclass == None:
sclass = "<init>"
location = self.jn.ship_state()['location']
if location == None:
location = "<init>"
self.overlay.overlay_text('1', "AP MODE: "+ap_mode, 1, 1, (136, 53, 0))
self.overlay.overlay_text('2', "AP STATUS: "+self.ap_state, 2, 1, (136, 53, 0))
self.overlay.overlay_text('3', "SHIP STATUS: "+ship_state, 3, 1, (136, 53, 0))
self.overlay.overlay_text('4', "CURRENT SYSTEM: "+location+", "+sclass, 4, 1, (136, 53, 0))
self.overlay.overlay_text('5', "JUMPS: {} of {}".format(self.jump_cnt, self.total_jumps), 5, 1, (136, 53, 0))
if self.config["ElwScannerEnable"] == True:
self.overlay.overlay_text('6', "ELW SCANNER: "+self.fss_detected, 6, 1, (136, 53, 0))
self.overlay.overlay_paint()
def update_ap_status(self, txt):
self.ap_state = txt
self.update_overlay()
self.ap_ckb('statusline', txt)
# draws the matching rectangle within the image
#
def draw_match_rect(self, img, pt1, pt2, color, thick):
wid = pt2[0]-pt1[0]
hgt = pt2[1]-pt1[1]
if wid < 20:
#cv2.rectangle(screen, pt, (pt[0] + compass_width, pt[1] + compass_height), (0,0,255), 2)
cv2.rectangle(img, pt1, pt2, color, thick)
else:
len_wid = wid/5
len_hgt = hgt/5
half_wid = wid/2
half_hgt = hgt/2
tic_len = thick-1
# top
cv2.line(img, (int(pt1[0]), int(pt1[1])), (int(pt1[0]+len_wid), int(pt1[1])), color, thick)
cv2.line(img, (int(pt1[0]+(2*len_wid)), int(pt1[1])), (int(pt1[0]+(3*len_wid)), int(pt1[1])), color, 1)
cv2.line(img, (int(pt1[0]+(4*len_wid)), int(pt1[1])), (int(pt2[0]), int(pt1[1])), color, thick)
# top tic
cv2.line(img, (int(pt1[0]+half_wid), int(pt1[1])), (int(pt1[0]+half_wid), int(pt1[1])-tic_len), color, thick)
# bot
cv2.line(img, (int(pt1[0]), int(pt2[1])), (int(pt1[0]+len_wid), int(pt2[1])), color, thick)
cv2.line(img, (int(pt1[0]+(2*len_wid)), int(pt2[1])), (int(pt1[0]+(3*len_wid)), int(pt2[1])), color, 1)
cv2.line(img, (int(pt1[0]+(4*len_wid)), int(pt2[1])), (int(pt2[0]), int(pt2[1])), color, thick)
# bot tic
cv2.line(img, (int(pt1[0]+half_wid), int(pt2[1])), (int(pt1[0]+half_wid), int(pt2[1])+tic_len), color, thick)
# left
cv2.line(img, (int(pt1[0]), int(pt1[1])), (int(pt1[0]), int(pt1[1]+len_hgt)), color, thick)
cv2.line(img, (int(pt1[0]), int(pt1[1]+(2*len_hgt))), (int(pt1[0]), int(pt1[1]+(3*len_hgt))), color, 1)
cv2.line(img, (int(pt1[0]), int(pt1[1]+(4*len_hgt))), (int(pt1[0]), int(pt2[1])), color, thick)
# left tic
cv2.line(img, (int(pt1[0]), int(pt1[1]+half_hgt)), (int(pt1[0]-tic_len), int(pt1[1]+half_hgt)), color, thick)
# right
cv2.line(img, (int(pt2[0]), int(pt1[1])), (int(pt2[0]), int(pt1[1]+len_hgt)), color, thick)
cv2.line(img, (int(pt2[0]), int(pt1[1]+(2*len_hgt))), (int(pt2[0]), int(pt1[1]+(3*len_hgt))), color, 1)
cv2.line(img, (int(pt2[0]), int(pt1[1]+(4*len_hgt))), (int(pt2[0]), int(pt2[1])), color, thick)
# right tic
cv2.line(img, (int(pt2[0]), int(pt1[1]+half_hgt)), (int(pt2[0]+tic_len), int(pt1[1]+half_hgt)), color, thick)
# find the best scale value in the given range of scales with the passed in threshold
#
def calibrate_range(self, range_low, range_high, threshold):
#print("--- new range ---")
scale = 0
max_pick = 0
for i in range(range_low, range_high):
self.scr.scaleX = float(i/100)
self.scr.scaleY = self.scr.scaleX
# must reload the templates with this scale value
self.templ.reload_templates(self.scr.scaleX, self.scr.scaleY)
# do image matching on the compass and the target
compass_image, (minVal, maxVal, minLoc, maxLoc), match = self.scrReg.match_template_in_region('compass', 'compass')
dst_image, (minVal1, maxVal1, minLoc1, maxLoc1), match = self.scrReg.match_template_in_region('target', 'target')
border = 10 # border to prevent the box from interfering with future matches
reg_compass_pos = self.scrReg.reg['compass']['rect']
comp_width = self.scrReg.templates.template['compass']['width'] + border + border
comp_height = self.scrReg.templates.template['compass']['height'] + border + border
comp_left = reg_compass_pos[0] + maxLoc[0] - border
comp_top = reg_compass_pos[1] + maxLoc[1] - border
reg_target_pos = self.scrReg.reg['target']['rect']
targ_width = self.scrReg.templates.template['target']['width'] + border + border
targ_height = self.scrReg.templates.template['target']['height'] + border + border
targ_left = reg_target_pos[0] + maxLoc1[0] - border
targ_top = reg_target_pos[1] + maxLoc1[1] - border
if maxVal > threshold and maxVal1 > threshold and maxVal > max_pick:
# Draw box around compass
self.overlay.overlay_rect(20, (comp_left, comp_top),(comp_left + comp_width, comp_top + comp_height), (0, 255, 0), 2)
self.overlay.overlay_floating_text(20, f'Match: {maxVal:5.2f}', comp_left, comp_top - 25, (0, 255, 0))
# Draw box around target
self.overlay.overlay_rect(22, (targ_left, targ_top), (targ_left + targ_width, targ_top + targ_height), (0, 255, 0), 2)
self.overlay.overlay_floating_text(22, f'Match: {maxVal1:5.2f}', targ_left, targ_top - 25, (0, 255, 0))
else:
# Draw box around compass
self.overlay.overlay_rect(21, (comp_left, comp_top),(comp_left + comp_width, comp_top + comp_height), (255, 0, 0), 2)
self.overlay.overlay_floating_text(21, f'Match: {maxVal:5.2f}', comp_left, comp_top - 25, (255, 0, 0))
# Draw box around target
self.overlay.overlay_rect(23, (targ_left, targ_top), (targ_left + targ_width, targ_top + targ_height), (255, 0, 0), 2)
self.overlay.overlay_floating_text(23, f'Match: {maxVal1:5.2f}', targ_left, targ_top - 25, (255, 0, 0))
self.overlay.overlay_paint()
#print("Looping i:"+str(i)+ ' scale:'+str(self.scr.scaleX)+ " maxVal:"+str(maxVal)+" maxVal1:"+str(maxVal1))
# Show the bounding box
self.get_nav_offset(self.scrReg)
self.get_destination_offset(self.scrReg)
if maxVal > threshold and maxVal1 > threshold:
#print("met criteria:"+f'{self.scr.scaleX:5.2f} '+str(threshold))
if maxVal > max_pick:
max_pick = maxVal
scale = i
self.ap_ckb('log', 'Cal: Found match:' + f'{max_pick:5.2f}' + "% with scale:" + f'{self.scr.scaleX:5.2f}')
return scale, max_pick
# Routine to find the optimal scaling values for the tempalte images
def calibrate(self):
self.set_focus_elite_window()
# Draw the target and compass regions on the screen
for i, key in enumerate(self.scrReg.reg):
if key == 'target' or key == 'compass':
targ_region = self.scrReg.reg[key]
self.overlay.overlay_rect(key, (targ_region['rect'][0], targ_region['rect'][1]),
(targ_region['rect'][2], targ_region['rect'][3]),(0, 0, 255), 2)
self.overlay.overlay_floating_text(key, key, targ_region['rect'][0],
targ_region['rect'][1], (0, 0, 255))
self.overlay.overlay_paint()
range_low = 30
range_high = 200
match_level = 0.5
scale_max = 0
max_val = 0
# loop through thresholds from 50 to 90% in 5% increments. Find out which scale factor
# meets the highest threshold value
#
for i in range(50, 90, 5):
threshold = float(i/100)
scale, max_pick = self.calibrate_range(range_low, range_high, threshold) # match from 50-> 100 by 5
#print("i:"+str(i)+" scale:"+str(scale)+ " threshold:"+str(threshold))
if scale != 0:
scale_max = scale
max_val = max_pick
range_low = scale-2
range_high = scale+2
if range_high > 100:
range_high = 100
else:
break # no match found with threshold
if scale_max == 99:
scale_max = 100
# if we found a scaling factor that meets our criteria, then save it to the resolution.json file
if max_val != 0:
self.scr.scaleX = float(scale_max/100)
self.scr.scaleY = self.scr.scaleX
self.ap_ckb('log', 'Cal: Max best match:'+f'{max_val:5.2f}'+"% with scale:"+f'{self.scr.scaleX:5.2f}')
self.scr.scales['Calibrated'] = [self.scr.scaleX, self.scr.scaleY]
self.scr.write_config(data=None) # None means the writer will use its own scales variable which we modified
else:
self.ap_ckb('log', 'Cal: Insufficient matching to meet reliability, max % match:'+str(max_val))
# Wait, then clean up
sleep(3)
self.overlay.overlay_clear()
self.overlay.overlay_paint()
# Go into FSS, check to see if we have a signal waveform in the Earth, Water or Ammonia zone
# if so, announce finding and log the type of world found
#
def fss_detect_elw(self, scr_reg):
#open fss
self.keys.send('SetSpeedZero')
sleep(0.1)
self.keys.send('ExplorationFSSEnter')
sleep(2.5)
# look for a circle or signal in this region
elw_image, (minVal, maxVal, minLoc, maxLoc), match = scr_reg.match_template_in_region('fss', 'elw')
elw_sig_image, (minVal1, maxVal1, minLoc1, maxLoc1), match = scr_reg.match_template_in_image(elw_image, 'elw_sig')
# dvide the region in thirds. Earth, then Water, then Ammonio
wid_div3 = scr_reg.reg['fss']['width']/3
# Exit out of FSS, we got the images we need to process
self.keys.send('ExplorationFSSQuit')
# Uncomment this to show on the ED Window where the region is define. Must run this file as an App, so uncomment out
# the main at the bottom of file
#self.overlay.overlay_rect('fss', (scr_reg.reg['fss']['rect'][0], scr_reg.reg['fss']['rect'][1]),
# (scr_reg.reg['fss']['rect'][2], scr_reg.reg['fss']['rect'][3]), (120, 255, 0),2)
#self.overlay.overlay_paint()
if self.cv_view:
elw_image_d = elw_image.copy()
elw_image_d = cv2.cvtColor(elw_image_d, cv2.COLOR_GRAY2RGB)
#self.draw_match_rect(elw_image_d, maxLoc, (maxLoc[0]+15,maxLoc[1]+15), (255,255,255), 1)
self.draw_match_rect(elw_image_d, maxLoc1, (maxLoc1[0]+15, maxLoc1[1]+25), (0, 0, 255), 1)
cv2.putText(elw_image_d, f'{maxVal1:5.2f}> .70', (1, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.30, (255, 255, 255), 1, cv2.LINE_AA)
cv2.imshow('fss', elw_image_d)
cv2.moveWindow('fss', self.cv_view_x, self.cv_view_y+100)
cv2.waitKey(30)
logger.info("elw detected:{0:6.2f} ".format(maxVal)+" sig:{0:6.2f}".format(maxVal1))
# check if the circle or the signal meets probability number, if so, determine which type by its region
#if (maxVal > 0.65 or (maxVal1 > 0.60 and maxLoc1[1] < 30) ):
# only check for singal
if (maxVal1 > 0.70 and maxLoc1[1] < 30):
if maxLoc1[0] < wid_div3:
sstr = "Earth"
elif maxLoc1[0] > (wid_div3*2):
sstr = "Water"
else:
sstr = "Ammonia"
# log the entry into the elw.txt file
f = open("elw.txt", 'a')
f.write(self.jn.ship_state()["location"]+", Type: "+sstr+
", Probabilty: {0:3.0f}% ".format((maxVal1*100))+
", Date: "+str(datetime.now())+str("\n"))
f.close
self.vce.say(sstr+" like world detected ")
self.fss_detected = sstr+" like world detected "
logger.info(sstr+" world at: "+str(self.jn.ship_state()["location"]))
else:
self.fss_detected = "nothing found"
self.keys.send('SetSpeed100')
return
def have_destination(self, scr_reg) -> bool:
""" Check to see if the compass is on the screen. """
icompass_image, (minVal, maxVal, minLoc, maxLoc), match = scr_reg.match_template_in_region('compass', 'compass')
logger.debug("has_destination:"+str(maxVal))
# need > x in the match to say we do have a destination
if maxVal < scr_reg.compass_match_thresh:
return False
else:
return True
def interdiction_check(self) -> bool:
""" Checks if we are being interdicted. This can occur in SC and maybe in system jump by Thargoids
(needs to be verified). Returns False if not interdicted, True after interdiction is detected and we
get away. Use return result to determine the next action (continue, or do something else).
"""
# Return if we are not being interdicted.
if not self.status.get_flag(FlagsBeingInterdicted):
return False
# Interdiction detected.
self.vce.say("Danger. Interdiction detected.")
self.ap_ckb('log', 'Interdiction detected.')
# Keep setting speed to zero to submit while in supercruise or system jump.
while self.status.get_flag(FlagsSupercruise) or self.status.get_flag2(Flags2FsdHyperdriveCharging):
self.keys.send('SetSpeedZero') # Submit.
sleep(0.5)
# Set speed to 100%.
self.keys.send('SetSpeed100')
# Wait for cooldown to start.
self.status.wait_for_flag_on(FlagsFsdCooldown)
# Boost while waiting for cooldown to complete.
while not self.status.wait_for_flag_off(FlagsFsdCooldown, timeout=2):
self.keys.send('UseBoostJuice')
# Cooldown over, get us out of here.
self.keys.send('HyperSuperCombination', hold=0.001)
# Wait for supercruise, keep boosting.
while not self.status.wait_for_flag_on(FlagsSupercruise, timeout=2):
self.keys.send('UseBoostJuice')
# Update journal flag.
self.jn.ship_state()['interdicted'] = False # reset flag
return True
def get_nav_offset(self, scr_reg):
""" Determine the x,y offset from center of the compass of the nav point. """
icompass_image, (minVal, maxVal, minLoc, maxLoc), match = (
scr_reg.match_template_in_region('compass', 'compass'))
pt = maxLoc
# get wid/hgt of templates
c_wid = scr_reg.templates.template['compass']['width']
c_hgt = scr_reg.templates.template['compass']['height']
wid = scr_reg.templates.template['navpoint']['width']
hgt = scr_reg.templates.template['navpoint']['height']
# cut out the compass from the region
pad = 5
compass_image = icompass_image[abs(pt[1]-pad): pt[1]+c_hgt+pad, abs(pt[0]-pad): pt[0]+c_wid+pad].copy()
# find the nav point within the compass box
navpt_image, (n_minVal, n_maxVal, n_minLoc, n_maxLoc), match = (
scr_reg.match_template_in_image(compass_image, 'navpoint'))
n_pt = n_maxLoc
# must be > x to have solid hit, otherwise we are facing wrong way (empty circle)
if n_maxVal < scr_reg.navpoint_match_thresh:
final_x = 0.0
final_y = 0.0
final_z = -1.0 # Behind
result = {'x': final_x, 'y': final_y, 'z': final_z}
else:
final_x = ((n_pt[0]+((1/2)*wid))-((1/2)*c_wid))-5.5
final_y = (((1/2)*c_hgt)-(n_pt[1]+((1/2)*hgt)))+6.5
final_z = 1.0 # Ahead
logger.debug(("maxVal="+str(n_maxVal)+" x:"+str(final_x)+" y:"+str(final_y)))
result = {'x': final_x, 'y': final_y, 'z': final_z}
if self.cv_view:
icompass_image_d = cv2.cvtColor(icompass_image, cv2.COLOR_GRAY2RGB)
self.draw_match_rect(icompass_image_d, pt, (pt[0]+c_wid, pt[1]+c_hgt), (0, 0, 255), 2)
#cv2.rectangle(icompass_image_display, pt, (pt[0]+c_wid, pt[1]+c_hgt), (0, 0, 255), 2)
#self.draw_match_rect(compass_image, n_pt, (n_pt[0] + wid, n_pt[1] + hgt), (255,255,255), 2)
self.draw_match_rect(icompass_image_d, (pt[0]+n_pt[0]-pad, pt[1]+n_pt[1]-pad), (pt[0]+n_pt[0]+wid-pad, pt[1]+n_pt[1]+hgt-pad), (0, 255, 0), 1)
#cv2.rectangle(icompass_image_display, (pt[0]+n_pt[0]-pad, pt[1]+n_pt[1]-pad), (pt[0]+n_pt[0] + wid-pad, pt[1]+n_pt[1] + hgt-pad), (0, 0, 255), 2)
# dim = (int(destination_width/3), int(destination_height/3))
# img = cv2.resize(dst_image, dim, interpolation =cv2.INTER_AREA)
cv2.putText(icompass_image_d, f'Compass: {maxVal:5.2f} > {scr_reg.compass_match_thresh:5.2f}', (1, 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 255, 255), 1, cv2.LINE_AA)
cv2.putText(icompass_image_d, f'Nav Point: {n_maxVal:5.2f} > {scr_reg.navpoint_match_thresh:5.2f}', (1, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (255, 255, 255), 1, cv2.LINE_AA)
#cv2.circle(icompass_image_display, (pt[0]+n_pt[0], pt[1]+n_pt[1]), 5, (0, 255, 0), 3)
cv2.imshow('compass', icompass_image_d)
#cv2.imshow('nav', navpt_image)
cv2.moveWindow('compass', self.cv_view_x, self.cv_view_y)
#cv2.moveWindow('nav', self.cv_view_x, self.cv_view_y)
cv2.waitKey(30)
return result
# Looks to see if the 'dashed' line of the target is present indicating the target is occluded by the planet
# return True if meets threshold
#
def is_destination_occluded(self, scr_reg) -> bool:
dst_image, (minVal, maxVal, minLoc, maxLoc), match = scr_reg.match_template_in_region('target_occluded', 'target_occluded')
pt = maxLoc
if self.cv_view:
dst_image_d = cv2.cvtColor(dst_image, cv2.COLOR_GRAY2RGB)
destination_width = scr_reg.reg['target']['width']
destination_height = scr_reg.reg['target']['height']
width = scr_reg.templates.template['target_occluded']['width']
height = scr_reg.templates.template['target_occluded']['height']
try:
self.draw_match_rect(dst_image_d, pt, (pt[0]+width, pt[1]+height), (0, 0, 255), 2)
dim = (int(destination_width/2), int(destination_height/2))
img = cv2.resize(dst_image_d, dim, interpolation=cv2.INTER_AREA)
cv2.putText(img, f'{maxVal:5.2f} > {scr_reg.target_occluded_thresh:5.2f}', (1, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA)
cv2.imshow('occluded', img)
cv2.moveWindow('occluded', self.cv_view_x, self.cv_view_y+650)
except Exception as e:
print("exception in getdest: "+str(e))
cv2.waitKey(30)
if maxVal > scr_reg.target_occluded_thresh:
return True
else:
return False
def get_destination_offset(self, scr_reg):
""" Determine how far off we are from the target being in the middle of the screen
(in this case the specified region). """
dst_image, (minVal, maxVal, minLoc, maxLoc), match = scr_reg.match_template_in_region('target', 'target')
pt = maxLoc
destination_width = scr_reg.reg['target']['width']
destination_height = scr_reg.reg['target']['height']
width = scr_reg.templates.template['target']['width']
height = scr_reg.templates.template['target']['height']
# need some fug numbers since our template is not symetric to determine center
final_x = ((pt[0]+((1/2)*width))-((1/2)*destination_width))-7
final_y = (((1/2)*destination_height)-(pt[1]+((1/2)*height)))+22
# print("get dest, final:" + str(final_x)+ " "+str(final_y))
# print(destination_width, destination_height, width, height)
# print(maxLoc)
if self.cv_view:
dst_image_d = cv2.cvtColor(dst_image, cv2.COLOR_GRAY2RGB)
try:
self.draw_match_rect(dst_image_d, pt, (pt[0]+width, pt[1]+height), (0, 0, 255), 2)
dim = (int(destination_width/2), int(destination_height/2))
img = cv2.resize(dst_image_d, dim, interpolation=cv2.INTER_AREA)
cv2.putText(img, f'{maxVal:5.2f} > {scr_reg.target_thresh:5.2f}', (1, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA)
cv2.imshow('target', img)
#cv2.imshow('tt', scr_reg.templates.template['target']['image'])
cv2.moveWindow('target', self.cv_view_x+500, self.cv_view_y)
except Exception as e:
print("exception in getdest: "+str(e))
cv2.waitKey(30)
#print (maxVal)
# must be > x to have solid hit, otherwise we are facing wrong way (empty circle)
if maxVal < scr_reg.target_thresh:
result = None
else:
result = {'x': final_x, 'y': final_y}
return result
# look for the "PRESS [J] TO DISENGAGE", if in this region then return true
#
def sc_disengage(self, scr_reg) -> bool:
dis_image, (minVal, maxVal, minLoc, maxLoc), match = scr_reg.match_template_in_region('disengage', 'disengage')
pt = maxLoc
width = scr_reg.templates.template['disengage']['width']
height = scr_reg.templates.template['disengage']['height']
if self.cv_view:
self.draw_match_rect(dis_image, pt, (pt[0] + width, pt[1] + height), (0,255,0), 2)
cv2.putText(dis_image, f'{maxVal:5.2f} > {scr_reg.disengage_thresh}', (1, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1, cv2.LINE_AA)
cv2.imshow('disengage', dis_image)
cv2.moveWindow('disengage', self.cv_view_x-460,self.cv_view_y+575)
cv2.waitKey(1)
logger.debug("Disenage = "+str(maxVal))
if (maxVal > scr_reg.disengage_thresh):
self.vce.say("Disengaging Supercruise")
return True
else:
return False
# Performs menu action to undock from Station
#
def undock(self):
# Assume we are in Star Port Services
# Now we are on initial menu, we go up to top (which is Refuel)
self.keys.send('UI_Up', repeat=3)
# down to Auto Undock and Select it...
self.keys.send('UI_Down')
self.keys.send('UI_Down')
self.keys.send('UI_Select')
self.keys.send('SetSpeedZero', repeat=2)
# Performs left menu ops to request docking
# Required that the left menu is on the "NAVIGATION" tab otherwise this doesn't work
#
def request_docking(self, toCONTACT):
self.keys.send('UI_Back', repeat=10)
self.keys.send('HeadLookReset')
self.keys.send('UIFocus', state=1)
self.keys.send('UI_Left')
self.keys.send('UIFocus', state=0)
sleep(0.5)
# we start with the Left Panel having "NAVIGATION" highlighted, we then need to right
# right twice to "CONTACTS". Notice of a FSD run, the LEFT panel is reset to "NAVIGATION"
# otherwise it is on the last tab you selected. Thus must start AP with "NAVIGATION" selected
if (toCONTACT == 1):
self.keys.send('CycleNextPanel', hold=0.2)
sleep(0.2)
self.keys.send('CycleNextPanel', hold=0.2)
# On the CONTACT TAB, go to top selection, do this 4 seconds to ensure at top
# then go right, which will be "REQUEST DOCKING" and select it
self.keys.send('UI_Up', hold=4)
self.keys.send('UI_Right')
self.keys.send('UI_Select')
sleep(0.3)
self.keys.send('UI_Back')
self.keys.send('HeadLookReset')
# Docking sequence. Assumes in normal space, will get closer to the Station
# then zero the velocity and execute menu commands to request docking, when granted
# will wait a configurable time for dock. Perform Refueling and Repair
#
def dock(self):
# if not in normal space, give a few more sections as at times it will take a little bit
if self.jn.ship_state()['status'] != "in_space":
sleep(3) # sleep a little longer
if self.jn.ship_state()['status'] != "in_space":
logger.error('In dock(), after wait, but still not in_space')
sleep(5) # wait 5 seconds to get to 7.5km to request docking
self.keys.send('SetSpeed50')
if self.jn.ship_state()['status'] != "in_space":
self.keys.send('SetSpeedZero')
logger.error('In dock(), after long wait, but still not in_space')
raise Exception('Docking error')
sleep(12)
# At this point (of sleep()) we should be < 7.5km from the station. Go 0 speed
# if we get docking granted ED's docking computer will take over
self.keys.send('SetSpeedZero', repeat=2)
self.request_docking(1)
sleep(1)
tries = self.config['DockingRetries']
granted = False
if self.jn.ship_state()['status'] == "dockinggranted":
granted = True
else:
for i in range(tries):
if self.jn.ship_state()['no_dock_reason'] == "Distance":
self.keys.send('SetSpeed50')
sleep(5)
self.keys.send('SetSpeedZero', repeat=2)
self.request_docking(0)
self.keys.send('SetSpeedZero', repeat=2)
sleep(1.5)
if self.jn.ship_state()['status'] == "dockinggranted":
granted = True
break
if self.jn.ship_state()['status'] == "dockingdenied":
pass
if not granted:
self.ap_ckb('log', 'Docking denied: '+str(self.jn.ship_state()['no_dock_reason']))
logger.warning('Did not get docking authorization, reason:'+str(self.jn.ship_state()['no_dock_reason']))
else:
# allow auto dock to take over
for i in range(self.config['WaitForAutoDockTimer']):
sleep(1)
if self.jn.ship_state()['status'] == "in_station":
# go to top item, select (which should be refuel)
self.keys.send('UI_Up', hold=3)
self.keys.send('UI_Select') # Refuel
sleep(0.5)
self.keys.send('UI_Right') # Repair
self.keys.send('UI_Select')
sleep(0.5)
self.keys.send('UI_Right') # Ammo
self.keys.send('UI_Select')
sleep(0.5)
self.keys.send("UI_Left", repeat=2) # back to fuel
break
def is_sun_dead_ahead(self, scr_reg):
return scr_reg.sun_percent(scr_reg.screen) > 5
# use to orient the ship to not be pointing right at the Sun
# Checks brightness in the region in front of us, if brightness exceeds a threshold
# then will pitch up until below threshold.
#
def sun_avoid(self, scr_reg):
logger.debug('align= avoid sun')
sleep(0.5)
# close to core the 'sky' is very bright with close stars, if we are pitch due to a non-scoopable star
# which is dull red, the star field is 'brighter' than the sun, so our sun avoidance could pitch up
# endlessly. So we will have a fail_safe_timeout to kick us out of pitch up if we've pitch past 110 degrees, but
# we'll add 3 more second for pad in case the user has a higher pitch rate than the vehicle can do
fail_safe_timeout = (120/self.pitchrate)+3
starttime = time.time()
# if sun in front of us, then keep pitching up until it is below us
while self.is_sun_dead_ahead(scr_reg):
self.keys.send('PitchUpButton', state=1)
# check if we are being interdicted
interdicted = self.interdiction_check()
if interdicted:
# Continue journey after interdiction
self.keys.send('SetSpeedZero')
# if we are pitching more than N seconds break, may be in high density area star area (close to core)
if ((time.time()-starttime) > fail_safe_timeout):
logger.debug('sun avoid failsafe timeout')
print("sun avoid failsafe timeout")
break
sleep(0.35) # up slightly so not to overheat when scooping
sleep(self.sunpitchuptime) # some ships heat up too much and need pitch up a little further
self.keys.send('PitchUpButton', state=0)
# we know x, y offset of the nav point from center, use arc tan to determine the angle, convert to degrees
# we want the angle to the 90 (up) and 180 (down) axis
def x_angle(self, point=None):
if not point:
return None
if point['x'] == 0:
point['x'] = 0.1
result = degrees(atan(abs(point['y'])/abs(point['x'])))
return 90-result
def nav_align(self, scr_reg):
""" Use the compass to find the nav point position. Will then perform rotation and pitching
to put the nav point in the middle of the compass, i.e. target right in front of us """
close = 2
if not (self.jn.ship_state()['status'] == 'in_supercruise' or self.jn.ship_state()['status'] == 'in_space'):
logger.error('align=err1')
raise Exception('nav_align not in super or space')
self.vce.say("Navigation Align")
# get the x,y offset from center, or none, which means our point is behind us
off = self.get_nav_offset(scr_reg)
# check to see if we are already converged, if so return
if off['z'] > 0 and abs(off['x']) < close and abs(off['y']) < close:
return
# nav point must be behind us, pitch up until somewhat in front of us
while off['z'] < 0:
if off['y'] >= 0:
self.pitchUp(90)
if off['y'] < 0:
self.pitchDown(90)
off = self.get_nav_offset(scr_reg)
# check if converged, unlikely at this point
if off['z'] > 0 and abs(off['x']) < close and abs(off['y']) < close:
return
# try multiple times to get aligned. If the sun is shining on console, this it will be hard to match
# the vehicle should be positioned with the sun below us via the sun_avoid() routine after a jump
for ii in range(self.config['NavAlignTries']):
off = self.get_nav_offset(scr_reg)
if off['z'] > 0 and abs(off['x']) < close and abs(off['y']) < close:
break
while off['z'] < 0:
if off['y'] >= 0:
self.pitchUp(45)
if off['y'] < 0:
self.pitchDown(45)
off = self.get_nav_offset(scr_reg)
# determine the angle and the hold time to keep the button pressed to roll that number of degrees
ang = self.x_angle(off)%90
htime = ang/self.rollrate
logger.debug("Angle:"+str(ang)+" x: "+str(off['x'])+" rolltime:"+str(htime))
# first roll to get the nav point at the vertical position
if (abs(off['x']) > close):
# top right quad, then roll right to get to 90 up
if (off['x'] > 0 and off['y'] > 0):
self.keys.send('RollRightButton', hold=htime)
# bottom right quad, then roll left
elif (off['x'] > 0 and off['y'] < 0):
self.keys.send('RollLeftButton', hold=htime)
# top left quad, then roll left
elif (off['x'] < 0 and off['y'] > 0):
self.keys.send('RollLeftButton', hold=htime)
# bottom left quad, then roll right
else:
self.keys.send('RollRightButton', hold=htime)
else:
#print("X is <= "+str(close))
pass
sleep(0.15) # wait for image to stablize
off = self.get_nav_offset(scr_reg)
while off['z'] < 0:
if off['y'] >= 0:
self.pitchUp(45)
if off['y'] < 0:
self.pitchDown(45)
off = self.get_nav_offset(scr_reg)
# calc pitch time based on nav point location
# this is assuming 40 offset is max displacement on the Y axis. So get percentage we are offset
#
utime = (abs(off['y'])/40.)*(90./self.pitchrate)
logger.debug("ptichtime:"+str(utime)+" x:"+str(off['x'])+" y:"+str(off['y']))
if (abs(off['y']) > close):
if (off['y'] < 0):
self.keys.send('PitchDownButton', hold=utime)
else:
self.keys.send('PitchUpButton', hold=utime)
else:
#print("Y is <= "+str(close))
pass
sleep(.1)
logger.debug("final x:"+str(off['x'])+" y:"+str(off['y']))
def target_align(self, scr_reg):
""" Coarse align to the target to support FSD jumping """
self.vce.say("Target Align")
logger.debug('align= fine align')
close = 50
# TODO: should use Pitch Rates to calculate, but this seems to work fine with all ships
hold_pitch = 0.150
hold_yaw = 0.300
for i in range(5):
new = self.get_destination_offset(scr_reg)
if new:
off = new
break
sleep(0.25)
# try one more time to align
if new is None:
self.nav_align(scr_reg)
new = self.get_destination_offset(scr_reg)
if new:
off = new
else:
logger.debug(' out of fine -not off-'+'\n')
return
#
while (off['x'] > close) or \
(off['x'] < -close) or \
(off['y'] > close) or \
(off['y'] < -close):
#print("off:"+str(new))
if off['x'] > close:
self.keys.send('YawRightButton', hold=hold_yaw)
if off['x'] < -close:
self.keys.send('YawLeftButton', hold=hold_yaw)
if off['y'] > close:
self.keys.send('PitchUpButton', hold=hold_pitch)
if off['y'] < -close:
self.keys.send('PitchDownButton', hold=hold_pitch)
if self.jn.ship_state()['status'] == 'starting_hyperspace':
return
for i in range(5):
sleep(0.1)
new = self.get_destination_offset(scr_reg)
if new:
off = new
break
sleep(0.25)
if not off:
return
logger.debug('align=complete')
def mnvr_to_target(self, scr_reg):
logger.debug('align')
if not (self.jn.ship_state()['status'] == 'in_supercruise' or self.jn.ship_state()['status'] == 'in_space'):
logger.error('align() not in sc or space')
raise Exception('align() not in sc or space')
self.sun_avoid(scr_reg)
self.nav_align(scr_reg)
self.keys.send('SetSpeed100')
self.target_align(scr_reg)
def sc_target_align(self, scr_reg) -> bool:
""" Stays tight on the target, monitors for disengage and obscured.
If target could not be found, return false."""
close = 6
off = None