forked from skai2/EDAutopilot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dev_autopilot.py
1312 lines (977 loc) · 41.9 KB
/
dev_autopilot.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
#!/usr/bin/env python
# coding: utf-8
# <h1>Elite Dangerous Autopilot v2<span class="tocSkip"></span></h1>
# <div class="toc"><ul class="toc-item"><li><span><a href="#References" data-toc-modified-id="References-1"><span class="toc-item-num">1 </span>References</a></span></li><li><span><a href="#Imports" data-toc-modified-id="Imports-2"><span class="toc-item-num">2 </span>Imports</a></span></li><li><span><a href="#Logging" data-toc-modified-id="Logging-3"><span class="toc-item-num">3 </span>Logging</a></span></li><li><span><a href="#Constants" data-toc-modified-id="Constants-4"><span class="toc-item-num">4 </span>Constants</a></span></li><li><span><a href="#Read-ED-logs" data-toc-modified-id="Read-ED-logs-5"><span class="toc-item-num">5 </span>Read ED logs</a></span><ul class="toc-item"><li><span><a href="#Get-latest-log-file" data-toc-modified-id="Get-latest-log-file-5.1"><span class="toc-item-num">5.1 </span>Get latest log file</a></span></li><li><span><a href="#Extract-ship-info-from-log" data-toc-modified-id="Extract-ship-info-from-log-5.2"><span class="toc-item-num">5.2 </span>Extract ship info from log</a></span></li></ul></li><li><span><a href="#Control-ED-with-direct-input" data-toc-modified-id="Control-ED-with-direct-input-6"><span class="toc-item-num">6 </span>Control ED with direct input</a></span><ul class="toc-item"><li><span><a href="#Get-latest-keybinds-file" data-toc-modified-id="Get-latest-keybinds-file-6.1"><span class="toc-item-num">6.1 </span>Get latest keybinds file</a></span></li><li><span><a href="#Extract-necessary-keys" data-toc-modified-id="Extract-necessary-keys-6.2"><span class="toc-item-num">6.2 </span>Extract necessary keys</a></span></li></ul></li><li><span><a href="#Direct-input-function" data-toc-modified-id="Direct-input-function-7"><span class="toc-item-num">7 </span>Direct input function</a></span><ul class="toc-item"><li><span><a href="#Send-input" data-toc-modified-id="Send-input-7.1"><span class="toc-item-num">7.1 </span>Send input</a></span></li><li><span><a href="#Clear-input" data-toc-modified-id="Clear-input-7.2"><span class="toc-item-num">7.2 </span>Clear input</a></span></li></ul></li><li><span><a href="#Autopilot-UI" data-toc-modified-id="Autopilot-UI-8"><span class="toc-item-num">8 </span>Autopilot UI</a></span><ul class="toc-item"><li><span><a href="#Tkinter-test" data-toc-modified-id="Tkinter-test-8.1"><span class="toc-item-num">8.1 </span>Tkinter test</a></span></li></ul></li><li><span><a href="#OpenCV" data-toc-modified-id="OpenCV-9"><span class="toc-item-num">9 </span>OpenCV</a></span><ul class="toc-item"><li><span><a href="#Get-screen" data-toc-modified-id="Get-screen-9.1"><span class="toc-item-num">9.1 </span>Get screen</a></span></li><li><span><a href="#HSV-slider-tool" data-toc-modified-id="HSV-slider-tool-9.2"><span class="toc-item-num">9.2 </span>HSV slider tool</a></span></li><li><span><a href="#Equalization" data-toc-modified-id="Equalization-9.3"><span class="toc-item-num">9.3 </span>Equalization</a></span></li><li><span><a href="#Filter-bright" data-toc-modified-id="Filter-bright-9.4"><span class="toc-item-num">9.4 </span>Filter bright</a></span></li><li><span><a href="#Filter-sun" data-toc-modified-id="Filter-sun-9.5"><span class="toc-item-num">9.5 </span>Filter sun</a></span></li><li><span><a href="#Filter-orange" data-toc-modified-id="Filter-orange-9.6"><span class="toc-item-num">9.6 </span>Filter orange</a></span></li><li><span><a href="#Filter-orange2" data-toc-modified-id="Filter-orange2-9.7"><span class="toc-item-num">9.7 </span>Filter orange2</a></span></li><li><span><a href="#Filter-blue" data-toc-modified-id="Filter-blue-9.8"><span class="toc-item-num">9.8 </span>Filter blue</a></span></li><li><span><a href="#Get-sun" data-toc-modified-id="Get-sun-9.9"><span class="toc-item-num">9.9 </span>Get sun</a></span></li><li><span><a href="#Get-compass-image" data-toc-modified-id="Get-compass-image-9.10"><span class="toc-item-num">9.10 </span>Get compass image</a></span></li><li><span><a href="#Get-navpoint-offset" data-toc-modified-id="Get-navpoint-offset-9.11"><span class="toc-item-num">9.11 </span>Get navpoint offset</a></span></li><li><span><a href="#Get-destination-offset" data-toc-modified-id="Get-destination-offset-9.12"><span class="toc-item-num">9.12 </span>Get destination offset</a></span></li></ul></li><li><span><a href="#Autopilot-routines" data-toc-modified-id="Autopilot-routines-10"><span class="toc-item-num">10 </span>Autopilot routines</a></span><ul class="toc-item"><li><span><a href="#Undock" data-toc-modified-id="Undock-10.1"><span class="toc-item-num">10.1 </span>Undock</a></span></li><li><span><a href="#Dock" data-toc-modified-id="Dock-10.2"><span class="toc-item-num">10.2 </span>Dock</a></span></li><li><span><a href="#Align" data-toc-modified-id="Align-10.3"><span class="toc-item-num">10.3 </span>Align</a></span></li><li><span><a href="#Jump" data-toc-modified-id="Jump-10.4"><span class="toc-item-num">10.4 </span>Jump</a></span></li><li><span><a href="#Refuel" data-toc-modified-id="Refuel-10.5"><span class="toc-item-num">10.5 </span>Refuel</a></span></li><li><span><a href="#Discovery-scanner" data-toc-modified-id="Discovery-scanner-10.6"><span class="toc-item-num">10.6 </span>Discovery scanner</a></span></li><li><span><a href="#Position" data-toc-modified-id="Position-10.7"><span class="toc-item-num">10.7 </span>Position</a></span></li></ul></li><li><span><a href="#Autopilot-main" data-toc-modified-id="Autopilot-main-11"><span class="toc-item-num">11 </span>Autopilot main</a></span><ul class="toc-item"><li><span><a href="#status-reference" data-toc-modified-id="status-reference-11.1"><span class="toc-item-num">11.1 </span>status reference</a></span></li></ul></li></ul></div>
# ## References
# Useful docs / articles / etc
#
# 1 - [A Python wrapper around AHK](https://pypi.org/project/ahk/)
#
# 2 - [OpenCV on Wheels](https://pypi.org/project/opencv-python/)
#
# 3 - [Autopilot for Elite Dangerous using OpenCV and thoughts on CV enabled bots in visual-to-keyboard loop](https://networkgeekstuff.com/projects/autopilot-for-elite-dangerous-using-opencv-and-thoughts-on-cv-enabled-bots-in-visual-to-keyboard-loop/)
#
# 4 - [Using PyInstaller to Easily Distribute Python Applications](https://realpython.com/pyinstaller-python/)
#
# 5 - [Direct Input to a Game - Python Plays GTA V](https://pythonprogramming.net/direct-input-game-python-plays-gta-v/)
#
# 6 - [Cross-platform GUI automation for human beings](https://pyautogui.readthedocs.io/en/latest/index.html)
# ## Imports
# In[181]:
import sys
import datetime
from os import environ, listdir
from os.path import join, isfile, getmtime, abspath
from json import loads
from math import degrees, atan
from random import random
from time import sleep
from numpy import array, sum, where
from PIL import ImageGrab
from datetime import datetime
from xml.etree.ElementTree import parse
import cv2 # see reference 2
from src.directinput import * # see reference 5
from pyautogui import size# see reference 6
import logging
import colorlog
# In[182]:
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = abspath(".")
return join(base_path, relative_path)
# ## Logging
# In[183]:
logging.basicConfig(filename='autopilot.log', level=logging.DEBUG)
logger = colorlog.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
handler.setFormatter(
colorlog.ColoredFormatter('%(log_color)s%(levelname)-8s%(reset)s %(white)s%(message)s',
log_colors={
'DEBUG': 'fg_bold_cyan',
'INFO': 'fg_bold_green',
'WARNING': 'bg_bold_yellow,fg_bold_blue',
'ERROR': 'bg_bold_red,fg_bold_white',
'CRITICAL': 'bg_bold_red,fg_bold_yellow',
},secondary_log_colors={}
))
logger.addHandler(handler)
logger.debug('This is a DEBUG message. These information is usually used for troubleshooting')
logger.info('This is an INFO message. These information is usually used for conveying information')
logger.warning('some warning message. These information is usually used for warning')
logger.error('some error message. These information is usually used for errors and should not happen')
logger.critical('some critical message. These information is usually used for critical error, and will usually result in an exception.')
# In[184]:
logging.info('\n'+200*'-'+'\n'+'---- AUTOPILOT DATA '+180*'-'+'\n'+200*'-')
# ## Constants
# In[185]:
RELEASE = 'v19.05.15-alpha-18'
PATH_LOG_FILES = None
PATH_KEYBINDINGS = None
KEY_MOD_DELAY = 0.010
KEY_DEFAULT_DELAY = 0.200
KEY_REPEAT_DELAY = 0.100
FUNCTION_DEFAULT_DELAY = 0.500
SCREEN_WIDTH, SCREEN_HEIGHT = size()
logging.info('RELEASE='+str(RELEASE))
logging.info('PATH_LOG_FILES='+str(PATH_LOG_FILES))
logging.info('PATH_KEYBINDINGS='+str(PATH_KEYBINDINGS))
logging.info('KEY_MOD_DELAY='+str(KEY_MOD_DELAY))
logging.info('KEY_DEFAULT_DELAY='+str(KEY_DEFAULT_DELAY))
logging.info('KEY_REPEAT_DELAY='+str(KEY_REPEAT_DELAY))
logging.info('FUNCTION_DEFAULT_DELAY='+str(FUNCTION_DEFAULT_DELAY))
logging.info('SCREEN_WIDTH='+str(SCREEN_WIDTH))
logging.info('SCREEN_HEIGHT='+str(SCREEN_HEIGHT))
# ## Read ED logs
# ### Get latest log file
# In[186]:
def get_latest_log(path_logs=None):
"""Returns the full path of the latest (most recent) elite log file (journal) from specified path"""
if not path_logs:
path_logs = environ['USERPROFILE'] + "\Saved Games\Frontier Developments\Elite Dangerous"
list_of_logs = [join(path_logs, f) for f in listdir(path_logs) if isfile(join(path_logs, f)) and f.startswith('Journal.')]
if not list_of_logs:
return None
latest_log = max(list_of_logs, key=getmtime)
return latest_log
# In[187]:
logging.info('get_latest_log='+str(get_latest_log(PATH_LOG_FILES)))
# ### Extract ship info from log
# In[188]:
def ship():
"""Returns a 'status' dict containing relevant game status information (state, fuel, ...)"""
latest_log = get_latest_log(PATH_LOG_FILES)
ship = {
'time': (datetime.now() - datetime.fromtimestamp(getmtime(latest_log))).seconds,
'status': None,
'type': None,
'location': None,
'star_class': None,
'target': None,
'fuel_capacity': None,
'fuel_level': None,
'fuel_percent': None,
'is_scooping': False,
}
# Read log line by line and parse data
with open(latest_log, encoding="utf-8") as f:
for line in f:
log = loads(line)
# parse data
try:
# parse ship status
log_event = log['event']
if log_event == 'StartJump':
ship['status'] = str('starting_'+log['JumpType']).lower()
if log['JumpType'] == 'Hyperspace':
ship['star_class'] = log['StarClass']
elif log_event == 'SupercruiseEntry' or log_event == 'FSDJump':
ship['status'] = 'in_supercruise'
elif log_event == 'SupercruiseExit' or log_event == 'DockingCancelled' or (log_event == 'Music' and ship['status'] == 'in_undocking') or (log_event == 'Location' and log['Docked'] == False):
ship['status'] = 'in_space'
elif log_event == 'Undocked':
# ship['status'] = 'starting_undocking'
ship['status'] = 'in_space'
elif log_event == 'DockingRequested':
ship['status'] = 'starting_docking'
elif log_event == "Music" and log['MusicTrack'] == "DockingComputer":
if ship['status'] == 'starting_undocking':
ship['status'] = 'in_undocking'
elif ship['status'] == 'starting_docking':
ship['status'] = 'in_docking'
elif log_event == 'Docked':
ship['status'] = 'in_station'
# parse ship type
if log_event == 'LoadGame' or log_event == 'Loadout':
ship['type'] = log['Ship']
# parse fuel
if 'FuelLevel' in log and ship['type'] != 'TestBuggy':
ship['fuel_level'] = log['FuelLevel']
if 'FuelCapacity' in log and ship['type'] != 'TestBuggy':
try:
ship['fuel_capacity'] = log['FuelCapacity']['Main']
except:
ship['fuel_capacity'] = log['FuelCapacity']
if log_event == 'FuelScoop' and 'Total' in log:
ship['fuel_level'] = log['Total']
if ship['fuel_level'] and ship['fuel_capacity']:
ship['fuel_percent'] = round((ship['fuel_level'] / ship['fuel_capacity'])*100)
else:
ship['fuel_percent'] = 10
# parse scoop
if log_event == 'FuelScoop' and ship['time'] < 10 and ship['fuel_percent'] < 100:
ship['is_scooping'] = True
else:
ship['is_scooping'] = False
# parse location
if (log_event == 'Location' or log_event == 'FSDJump') and 'StarSystem' in log:
ship['location'] = log['StarSystem']
# parse target
if log_event == 'FSDTarget':
if log['Name'] == ship['location']:
ship['target'] = None
else:
ship['target'] = log['Name']
elif log_event == 'FSDJump':
if ship['location'] == ship['target']:
ship['target'] = None
# exceptions
except Exception as e:
logging.exception("Exception occurred")
print(e)
# logging.debug('ship='+str(ship))
return ship
# In[189]:
logging.debug('ship='+str(ship()))
# ## Control ED with direct input
# ### Get latest keybinds file
# In[190]:
def get_latest_keybinds(path_bindings=None):
if not path_bindings:
path_bindings = environ['LOCALAPPDATA'] + "\Frontier Developments\Elite Dangerous\Options\Bindings"
list_of_bindings = [join(path_bindings, f) for f in listdir(path_bindings) if (isfile(join(path_bindings, f)) and join(path_bindings, f).endswith("binds"))]
if not list_of_bindings:
return None
latest_bindings = max(list_of_bindings, key=getmtime)
return latest_bindings
# In[191]:
logging.info("get_latest_keybinds="+str(get_latest_keybinds()))
# ### Extract necessary keys
# In[192]:
keys_to_obtain = [
'YawLeftButton',
'YawRightButton',
'RollLeftButton',
'RollRightButton',
'PitchUpButton',
'PitchDownButton',
'SetSpeedZero',
'SetSpeed100',
'HyperSuperCombination',
'UIFocus',
'UI_Up',
'UI_Down',
'UI_Left',
'UI_Right',
'UI_Select',
'UI_Back',
'CycleNextPanel',
'HeadLookReset',
'PrimaryFire',
'SecondaryFire',
'MouseReset'
]
def get_bindings(keys_to_obtain=keys_to_obtain):
"""Returns a dict struct with the direct input equivalent of the necessary elite keybindings"""
direct_input_keys = {}
convert_to_direct_keys = {
'Key_LeftShift':'LShift',
'Key_RightShift':'RShift',
'Key_LeftAlt':'LAlt',
'Key_RightAlt':'RAlt',
'Key_LeftControl':'LControl',
'Key_RightControl':'RControl'
}
latest_bindings = get_latest_keybinds()
bindings_tree = parse(latest_bindings)
bindings_root = bindings_tree.getroot()
for item in bindings_root:
if item.tag in keys_to_obtain:
key = None
mod = None
# Check primary
if item[0].attrib['Device'].strip() == "Keyboard":
key = item[0].attrib['Key']
if len(item[0]) > 0:
mod = item[0][0].attrib['Key']
# Check secondary (and prefer secondary)
if item[1].attrib['Device'].strip() == "Keyboard":
key = item[1].attrib['Key']
if len(item[1]) > 0:
mod = item[1][0].attrib['Key']
# Adequate key to SCANCODE dict standard
if key in convert_to_direct_keys:
key = convert_to_direct_keys[key]
elif key is not None:
key = key[4:]
# Adequate mod to SCANCODE dict standard
if mod in convert_to_direct_keys:
mod = convert_to_direct_keys[mod]
elif mod is not None:
mod = mod[4:]
# Prepare final binding
binding = None
if key is not None:
binding = {}
binding['pre_key'] = 'DIK_'+key.upper()
binding['key'] = SCANCODE[binding['pre_key']]
if mod is not None:
binding['pre_mod'] = 'DIK_'+mod.upper()
binding['mod'] = SCANCODE[binding['pre_mod']]
if binding is not None:
direct_input_keys[item.tag] = binding
# else:
# logging.warning("get_bindings_<"+item.tag+">= does not have a valid keyboard keybind.")
if len(list(direct_input_keys.keys())) < 1:
return None
else:
return direct_input_keys
# In[193]:
keys = get_bindings()
for key in keys_to_obtain:
try:
logging.info('get_bindings_<'+str(key)+'>='+str(keys[key]))
except Exception as e:
logging.warning(str("get_bindings_<"+key+">= does not have a valid keyboard keybind.").upper())
# ## Direct input function
# ### Send input
# In[194]:
def send(key, hold=None, repeat=1, repeat_delay=None, state=None):
global KEY_MOD_DELAY, KEY_DEFAULT_DELAY, KEY_REPEAT_DELAY
if key is None:
logging.warning('SEND=NONE !!!!!!!!')
return
logging.debug('send=key:'+str(key)+',hold:'+str(hold)+',repeat:'+str(repeat)+',repeat_delay:'+str(repeat_delay)+',state:'+str(state))
for i in range(repeat):
if state is None or state == 1:
if 'mod' in key:
PressKey(key['mod'])
sleep(KEY_MOD_DELAY)
PressKey(key['key'])
if state is None:
if hold:
sleep(hold)
else:
sleep(KEY_DEFAULT_DELAY)
if state is None or state == 0:
ReleaseKey(key['key'])
if 'mod' in key:
sleep(KEY_MOD_DELAY)
ReleaseKey(key['mod'])
if repeat_delay:
sleep(repeat_delay)
else:
sleep(KEY_REPEAT_DELAY)
# In[195]:
# sleep(3)
# send(keys['UIFocus'], state=1)
# ### Clear input
# In[196]:
def clear_input(to_clear=None):
logging.info('\n'+200*'-'+'\n'+'---- CLEAR INPUT '+183*'-'+'\n'+200*'-')
send(to_clear['SetSpeedZero'])
send(to_clear['MouseReset'])
for key in to_clear.keys():
if key in keys:
send(to_clear[key], state=0)
logging.debug('clear_input')
# In[197]:
# clear_input(keys)
# ## Autopilot UI
# ### Tkinter test
# In[198]:
# import tkinter as tk
# from tkinter import messagebox
# root = tk.Tk()
# root.title("EDAutopilot")
# root.overrideredirect(True)
# label = tk.Label(root, text="Hello World")
# label.config(bg='lightgreen', font=('times', 24, 'italic'))
# label.pack(side="top", fill="both", expand=True, padx=20, pady=20)
# button = tk.Button(root, text="OK", command=lambda: root.destroy())
# button.pack(side="bottom", fill="none", expand=True)
# root.mainloop()
# ## OpenCV
# ### Get screen
# In[199]:
def get_screen(x_left, y_top, x_right, y_bot):
screen = array(ImageGrab.grab(bbox=(x_left, y_top, x_right, y_bot)))
screen = cv2.cvtColor(screen, cv2.COLOR_RGB2BGR)
return screen
# ### HSV slider tool
# In[200]:
def callback(x):
pass
def hsv_slider(bandw=False):
cv2.namedWindow('image')
ilowH = 0
ihighH = 179
ilowS = 0
ihighS = 255
ilowV = 0
ihighV = 255
# create trackbars for color change
cv2.createTrackbar('lowH','image',ilowH,179,callback)
cv2.createTrackbar('highH','image',ihighH,179,callback)
cv2.createTrackbar('lowS','image',ilowS,255,callback)
cv2.createTrackbar('highS','image',ihighS,255,callback)
cv2.createTrackbar('lowV','image',ilowV,255,callback)
cv2.createTrackbar('highV','image',ihighV,255,callback)
while(True):
# grab the frame
frame = get_screen((5/16)*SCREEN_WIDTH, (5/8)*SCREEN_HEIGHT,(2/4)*SCREEN_WIDTH, (15/16)*SCREEN_HEIGHT)
if bandw:
frame = equalize(frame)
frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
# get trackbar positions
ilowH = cv2.getTrackbarPos('lowH', 'image')
ihighH = cv2.getTrackbarPos('highH', 'image')
ilowS = cv2.getTrackbarPos('lowS', 'image')
ihighS = cv2.getTrackbarPos('highS', 'image')
ilowV = cv2.getTrackbarPos('lowV', 'image')
ihighV = cv2.getTrackbarPos('highV', 'image')
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_hsv = array([ilowH, ilowS, ilowV])
higher_hsv = array([ihighH, ihighS, ihighV])
mask = cv2.inRange(hsv, lower_hsv, higher_hsv)
frame = cv2.bitwise_and(frame, frame, mask=mask)
# show thresholded image
cv2.imshow('image', frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
# In[201]:
# hsv_slider()
# ### Equalization
# In[202]:
def equalize(image=None, testing=False):
while True:
if testing:
img = get_screen((5/16)*SCREEN_WIDTH, (5/8)*SCREEN_HEIGHT,(2/4)*SCREEN_WIDTH, (15/16)*SCREEN_HEIGHT)
else:
img = image.copy()
# Load the image in greyscale
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# create a CLAHE object (Arguments are optional).
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
img_out = clahe.apply(img_gray)
if testing:
cv2.imshow('Equalized', img_out)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
else:
break
return img_out
# In[203]:
# equalize(testing=True)
# ### Filter bright
# In[204]:
def filter_bright(image=None, testing=False):
while True:
if testing:
img = get_screen((5/16)*SCREEN_WIDTH, (5/8)*SCREEN_HEIGHT,(2/4)*SCREEN_WIDTH, (15/16)*SCREEN_HEIGHT)
else:
img = image.copy()
equalized = equalize(img)
equalized = cv2.cvtColor(equalized, cv2.COLOR_GRAY2BGR)
equalized = cv2.cvtColor(equalized, cv2.COLOR_BGR2HSV)
filtered = cv2.inRange(equalized, array([0, 0, 215]), array([0, 0, 255]))
if testing:
cv2.imshow('Filtered', filtered)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
else:
break
return filtered
# In[205]:
# filter_bright(testing=True)
# ### Filter sun
# In[206]:
def filter_sun(image=None, testing=False):
while True:
if testing:
hsv = get_screen((1/3)*SCREEN_WIDTH, (1/3)*SCREEN_HEIGHT,(2/3)*SCREEN_WIDTH, (2/3)*SCREEN_HEIGHT)
else:
hsv = image.copy()
# converting from BGR to HSV color space
hsv = cv2.cvtColor(hsv, cv2.COLOR_BGR2HSV)
# filter Elite UI orange
filtered = cv2.inRange(hsv, array([0, 100, 240]), array([180, 255, 255]))
if testing:
cv2.imshow('Filtered', filtered)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
else:
break
return filtered
# In[207]:
# filter_sun(testing=True)
# ### Filter orange
# In[208]:
def filter_orange(image=None, testing=False):
while True:
if testing:
hsv = get_screen((1/3)*SCREEN_WIDTH, (1/3)*SCREEN_HEIGHT,(2/3)*SCREEN_WIDTH, (2/3)*SCREEN_HEIGHT)
else:
hsv = image.copy()
# converting from BGR to HSV color space
hsv = cv2.cvtColor(hsv, cv2.COLOR_BGR2HSV)
# filter Elite UI orange
filtered = cv2.inRange(hsv, array([0, 130, 123]), array([25, 235, 220]))
if testing:
cv2.imshow('Filtered', filtered)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
else:
break
return filtered
# In[209]:
# filter_orange(testing=True)
# ### Filter orange2
# In[210]:
def filter_orange2(image=None, testing=False):
while True:
if testing:
hsv = get_screen((1/3)*SCREEN_WIDTH, (1/3)*SCREEN_HEIGHT,(2/3)*SCREEN_WIDTH, (2/3)*SCREEN_HEIGHT)
else:
hsv = image.copy()
# converting from BGR to HSV color space
hsv = cv2.cvtColor(hsv, cv2.COLOR_BGR2HSV)
# filter Elite UI orange
filtered = cv2.inRange(hsv, array([15, 220, 220]), array([30, 255, 255]))
if testing:
cv2.imshow('Filtered', filtered)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
else:
break
return filtered
# In[211]:
# filter_orange2(testing=True)
# ### Filter blue
# In[212]:
def filter_blue(image=None, testing=False):
while True:
if testing:
hsv = get_screen((1/3)*SCREEN_WIDTH, (1/3)*SCREEN_HEIGHT,(2/3)*SCREEN_WIDTH, (2/3)*SCREEN_HEIGHT)
else:
hsv = image.copy()
# converting from BGR to HSV color space
hsv = cv2.cvtColor(hsv, cv2.COLOR_BGR2HSV)
# filter Elite UI orange
filtered = cv2.inRange(hsv, array([0, 0, 200]), array([180, 100, 255]))
if testing:
cv2.imshow('Filtered', filtered)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
else:
break
return filtered
# In[213]:
# filter_blue(testing=True)
# ### Get sun
# In[214]:
def sun_percent():
screen = get_screen((1/3)*SCREEN_WIDTH, (1/3)*SCREEN_HEIGHT,(2/3)*SCREEN_WIDTH, (2/3)*SCREEN_HEIGHT)
filtered = filter_sun(screen)
total = (1/3)*SCREEN_WIDTH*(1/3)*SCREEN_HEIGHT
white = sum(filtered == 255)
black = sum(filtered != 255)
result = white / black
return result * 100
# In[215]:
# sleep(3)
# sun_percent()
# ### Get compass image
# In[216]:
def get_compass_image(testing=False):
compass_template = cv2.imread(resource_path("templates/compass.png"), cv2.IMREAD_GRAYSCALE)
compass_width, compass_height = compass_template.shape[::-1]
compass_image = compass_template.copy()
doubt = 10
while True:
screen = get_screen((5/16)*SCREEN_WIDTH, (5/8)*SCREEN_HEIGHT,(2/4)*SCREEN_WIDTH, (15/16)*SCREEN_HEIGHT)
# mask_orange = filter_orange(screen)
equalized = equalize(screen)
match = cv2.matchTemplate(equalized, compass_template, cv2.TM_CCOEFF_NORMED)
threshold = 0.3
loc = where( match >= threshold)
pt = (doubt, doubt)
for point in zip(*loc[::-1]):
pt = point
compass_image = screen[pt[1]-doubt : pt[1]+compass_height+doubt, pt[0]-doubt : pt[0]+compass_width+doubt].copy()
if testing:
cv2.rectangle(screen, pt, (pt[0] + compass_width, pt[1] + compass_height), (0,0,255), 2)
cv2.imshow('Compass Found', screen)
cv2.imshow('Compass Mask', equalized)
cv2.imshow('Compass', compass_image)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
else:
break
return compass_image, compass_width+(2*doubt), compass_height+(2*doubt)
# In[217]:
# get_compass_image(testing=True)
# ### Get navpoint offset
# In[218]:
same_last_count = 0
last_last = {'x': 1, 'y': 100}
def get_navpoint_offset(testing=False, last=None):
global same_last_count, last_last
navpoint_template = cv2.imread(resource_path("templates/navpoint.png"), cv2.IMREAD_GRAYSCALE)
navpoint_width, navpoint_height = navpoint_template.shape[::-1]
pt = (0, 0)
while True:
compass_image, compass_width, compass_height = get_compass_image()
mask_blue = filter_blue(compass_image)
# filtered = filter_bright(compass_image)
match = cv2.matchTemplate(mask_blue, navpoint_template, cv2.TM_CCOEFF_NORMED)
threshold = 0.5
loc = where( match >= threshold)
for point in zip(*loc[::-1]):
pt = point
final_x = (pt[0] + ((1/2)*navpoint_width)) - ((1/2)*compass_width)
final_y = ((1/2)*compass_height) - (pt[1] + ((1/2)*navpoint_height))
if testing:
cv2.rectangle(compass_image, pt, (pt[0] + navpoint_width, pt[1] + navpoint_height), (0,0,255), 2)
cv2.imshow('Navpoint Found', compass_image)
cv2.imshow('Navpoint Mask', mask_blue)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
else:
break
if pt[0] == 0 and pt[1] == 0:
if last:
if last == last_last:
same_last_count = same_last_count + 1
else:
last_last = last
same_last_count = 0
if same_last_count > 5:
same_last_count = 0
if random() < .9:
result = {'x': 1, 'y': 100}
else:
result = {'x': 100, 'y': 1}
else:
result = last
else:
result = None
else:
result = {'x':final_x, 'y':final_y}
logging.debug('get_navpoint_offset='+str(result))
return result
# In[219]:
# get_navpoint_offset(testing=True)
# ### Get destination offset
# In[220]:
def get_destination_offset(testing=False):
destination_template = cv2.imread(resource_path("templates/destination.png"), cv2.IMREAD_GRAYSCALE)
destination_width, destination_height = destination_template.shape[::-1]
pt = (0, 0)
width = (1/3)*SCREEN_WIDTH
height = (1/3)*SCREEN_HEIGHT
while True:
screen = get_screen((1/3)*SCREEN_WIDTH, (1/3)*SCREEN_HEIGHT,(2/3)*SCREEN_WIDTH, (2/3)*SCREEN_HEIGHT)
mask_orange = filter_orange2(screen)
# equalized = equalize(screen)
match = cv2.matchTemplate(mask_orange, destination_template, cv2.TM_CCOEFF_NORMED)
threshold = 0.2
loc = where( match >= threshold)
for point in zip(*loc[::-1]):
pt = point
final_x = (pt[0] + ((1/2)*destination_width)) - ((1/2)*width)
final_y = ((1/2)*height) - (pt[1] + ((1/2)*destination_height))
if testing:
cv2.rectangle(screen, pt, (pt[0] + destination_width, pt[1] + destination_height), (0,0,255), 2)
cv2.imshow('Destination Found', screen)
cv2.imshow('Destination Mask', mask_orange)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
else:
break
if pt[0] == 0 and pt[1] == 0:
result = None
else:
result = {'x':final_x, 'y':final_y}
logging.debug('get_destination_offset='+str(result))
return result
# In[221]:
# get_destination_offset(testing=True)
# ## Autopilot routines
# ### Undock
# In[222]:
def undock():
logging.debug('undock')
if ship()['status'] != "in_station":
logging.error('undock=err1')
raise Exception('undock error 1')
send(keys['UI_Back'], repeat=10)
send(keys['HeadLookReset'])
send(keys['UI_Down'], hold=3)
send(keys['UI_Select'])
sleep(1)
if not (ship()['status'] == "starting_undock" or ship()['status'] == "in_undock"):
logging.error('undock=err2')
raise Exception("undock error 2")
send(keys['HeadLookReset'])
send(keys['SetSpeedZero'], repeat=2)
wait = 120
for i in range(wait):
sleep(1)
if i > wait - 1:
logging.error('undock=err3')
raise Exception('undock error 3')
if ship()['status'] == "in_space":
break
logging.debug('undock=complete')
return True
# In[223]:
# sleep(3)
# undock()
# ### Dock
# In[224]:
def dock():
logging.debug('dock')
if ship()['status'] != "in_space":
logging.error('dock=err1')
raise Exception('dock error 1')
tries = 3
for i in range(tries):
send(keys['UI_Back'], repeat=10)
send(keys['HeadLookReset'])
send(keys['UIFocus'], state=1)
send(keys['UI_Left'])
send(keys['UIFocus'], state=0)
send(keys['CycleNextPanel'], repeat=2)
send(keys['UI_Up'], hold=3)
send(keys['UI_Right'])
send(keys['UI_Select'])
sleep(1)
if ship()['status'] == "starting_dock" or ship()['status'] == "in_dock":
break
if i > tries-1:
logging.error('dock=err2')
raise Exception("dock error 2")
send(keys['UI_Back'])
send(keys['HeadLookReset'])
send(keys['SetSpeedZero'], repeat=2)
wait = 120
for i in range(wait):
sleep(1)
if i > wait-1:
logging.error('dock=err3')
raise Exception('dock error 3')
if ship()['status'] == "in_station":
break
send(keys['UI_Up'], hold=3)
send(keys['UI_Down'])
send(keys['UI_Select'])
logging.debug('dock=complete')
return True
# In[225]:
# sleep(3)
# dock()