forked from SumZer0-git/EDAPGui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEDJournal.py
More file actions
442 lines (356 loc) · 17.3 KB
/
EDJournal.py
File metadata and controls
442 lines (356 loc) · 17.3 KB
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
from __future__ import annotations
import os
from os import environ, listdir
from os.path import join, isfile, getmtime, abspath
from json import loads
from time import sleep, time
from datetime import datetime
from EDAP_data import ship_size_map, ship_name_map
from EDlogger import logger
from WindowsKnownPaths import *
"""
File EDJournal.py (leveraged the EDAutopilot on github, turned into a
class and enhanced, see https://github.com/skai2/EDAutopilot
Description: This file perform journal file processing. It opens the latest updated Journal*
file in the Saved directory, loads in the entries. Specific entries are stored in a dictionary.
Every time the dictionary is access the file will be read and if new lines exist those will be loaded
and parsed.
The dictionary can be accesses via:
jn = EDJournal()
print("Ship = ", jn.ship_state())
... jn.ship_state()['shieldsup']
Design:
- open the file once
- when accessing a field in the ship_state() first see if more to read from open file, if so
process it
- also check if a new journal file present, if so close current one and open new one
Author: sumzer0@yahoo.com
"""
"""
TODO: thinking self.ship()[name] uses the same names as in the journal, so can lookup same construct
"""
def get_ship_size(ship: str) -> str:
""" Gets the ship size from the journal ship name.
@ship: The ship name from the journal (i.e. 'diamondbackxl').
@return: The ship size ('S', 'M', 'L' or '' if ship not found or size not valid).
"""
if ship.lower() in ship_size_map:
return ship_size_map[ship.lower()]
else:
return ''
def get_ship_fullname(ship: str) -> str:
""" Gets the ship full name from the journal ship name.
@ship: The ship name from the journal (i.e. 'diamondbackxl').
@return: The ship full name ('Diamondback Explorer' or '' if ship not found).
"""
if ship.lower() in ship_name_map:
return ship_name_map[ship.lower()]
else:
return ''
def check_fuel_scoop(modules: list[dict[str, any]] | None) -> bool:
""" Gets whether the ship has a fuel scoop.
"""
# Default to fuel scoop fitted if modules is None
if modules is None:
return True
# Check all modules. Could just check the internals, but this is easier.
for module in modules:
if "fuelscoop" in module['Item'].lower():
return True
return False
def check_adv_docking_computer(modules: list[dict[str, any]] | None) -> bool:
""" Gets whether the ship has an advanced docking computer.
Advanced docking computer will dock and undock automatically.
"""
# Default to docking computer fitted if modules is None
if modules is None:
return True
# Check all modules. Could just check the internals, but this is easier.
for module in modules:
if "dockingcomputer_advanced" in module['Item'].lower():
return True
return False
def check_std_docking_computer(modules: list[dict[str, any]] | None) -> bool:
""" Gets whether the ship has a standard docking computer.
Standard docking computer will dock automatically, but not undock.
"""
# Default to docking computer fitted if modules is None
if modules is None:
return True
# Check all modules. Could just check the internals, but this is easier.
for module in modules:
if "dockingcomputer_standard" in module['Item'].lower():
return True
return False
def check_sco_fsd(modules: list[dict[str, any]] | None) -> bool:
""" Gets whether the ship has an FSD with SCO.
"""
# Default to SCO fitted if modules is None
if modules is None:
return True
# Check all modules. Could just check the internals, but this is easier.
for module in modules:
if module['Slot'] == "FrameShiftDrive":
if "overcharge" in module['Item'].lower():
#print("FrameShiftDrive has SCO!")
return True
#print("FrameShiftDrive has no SCO")
return False
class EDJournal:
def __init__(self, cb):
self.ap_ckb = cb
self.last_mod_time = None
self.log_file = None
self.current_log = self.get_latest_log()
self.open_journal(self.current_log)
self.ship = {
'time': (datetime.now() - datetime.fromtimestamp(getmtime(self.current_log))).seconds,
'odyssey': True,
'status': 'in_space',
'type': None,
'location': None,
'star_class': None,
'target': None,
'fighter_destroyed': False,
'shieldsup': True,
'under_attack': None,
'interdicted': False,
'no_dock_reason': None,
'mission_completed': 0,
'mission_redirected': 0,
'body': None,
'dist_jumped': 0,
'jumps_remains': 0,
'fuel_capacity': None,
'fuel_level': None,
'fuel_percent': None,
'is_scooping': False,
'cur_star_system': "",
'cur_station': "",
'cur_station_type': "",
'cargo_capacity': None,
'ship_size': None,
'has_fuel_scoop': None,
'SupercruiseDestinationDrop_type': None,
'has_adv_dock_comp': None,
'has_std_dock_comp': None,
'has_sco_fsd': None,
'StationServices': None,
}
self.ship_state() # load up from file
self.reset_items()
def get_file_modified_time(self) -> float:
return os.path.getmtime(self.current_log)
# these items do not have respective log entries to clear them. After initial reading of log file, clear these items
# also the App will need to reset these to False after detecting they were True
def reset_items(self):
self.ship['under_attack'] = False
self.ship['fighter_destroyed'] = False
def get_latest_log(self, 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 = get_path(FOLDERID.SavedGames, UserHandle.current) + "\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
def open_journal(self, log_name):
# if journal file is open then close it
if self.log_file is not None:
self.log_file.close()
logger.info("Opening new Journal: "+log_name)
# open the latest journal
self.log_file = open(log_name, encoding="utf-8")
self.last_mod_time = None
def parse_line(self, log):
# parse data
try:
# parse ship status
log_event = log['event']
# If fileheader, pull whether running Odyssey or Horizons
if log_event == 'Fileheader':
#self.ship['odyssey'] = log['Odyssey']
self.ship['odyssey'] = True # hardset to true for ED 4.0 since menus now same for Horizon
elif log_event == 'ShieldState':
if log['ShieldsUp'] == True:
self.ship['shieldsup'] = True
else:
self.ship['shieldsup'] = False
elif log_event == 'UnderAttack':
self.ship['under_attack'] = True
elif log_event == 'FighterDestroyed':
self.ship['fighter_destroyed'] = True
elif log_event == 'MissionCompleted':
self.ship['mission_completed'] = self.ship['mission_completed'] + 1
elif log_event == 'MissionRedirected':
self.ship['mission_redirected'] = self.ship['mission_redirected'] + 1
elif log_event == 'StartJump':
self.ship['status'] = str('starting_'+log['JumpType']).lower()
self.ship['SupercruiseDestinationDrop_type'] = None
if log['JumpType'] == 'Hyperspace':
self.ship['star_class'] = log['StarClass']
elif log_event == 'SupercruiseEntry' or log_event == 'FSDJump':
self.ship['status'] = 'in_supercruise'
elif log_event == "DockingGranted":
self.ship['status'] = 'dockinggranted'
elif log_event == "DockingDenied":
self.ship['status'] = 'dockingdenied'
self.ship['no_dock_reason'] = log['Reason']
elif log_event == 'SupercruiseExit':
self.ship['status'] = 'in_space'
self.ship['body'] = log['Body']
elif log_event == 'SupercruiseDestinationDrop':
self.ship['SupercruiseDestinationDrop_type'] = log['Type']
elif log_event == 'DockingCancelled':
self.ship['status'] = 'in_space'
elif log_event == 'Undocked':
self.ship['status'] = 'starting_undocking'
#self.ship['status'] = 'in_space'
elif log_event == 'DockingRequested':
self.ship['status'] = 'starting_docking'
elif log_event == "Music" and log['MusicTrack'] == "DockingComputer":
if self.ship['status'] == 'starting_undocking':
self.ship['status'] = 'in_undocking'
elif self.ship['status'] == 'starting_docking':
self.ship['status'] = 'in_docking'
elif log_event == "Music" and log['MusicTrack'] == "NoTrack" and self.ship['status'] == 'in_undocking':
self.ship['status'] = 'in_space'
# for unodck from outpost
elif log_event == "Music" and log['MusicTrack'] == "Exploration" and self.ship['status'] == 'in_undocking':
self.ship['status'] = 'in_space'
elif log_event == 'Docked':
# {"timestamp": "2024-09-29T00:47:08Z", "event": "Docked", "StationName": "Filipchenko City",
# "StationType": "Coriolis", "Taxi": false, "Multicrew": false, "StarSystem": "G 139-50",
# "SystemAddress": 13864557225401, "MarketID": 3229027584,
# "StationFaction": {"Name": "Pixel Bandits Security Force"},
# "StationGovernment": "$government_Democracy;", "StationGovernment_Localised": "Democracy",
# "StationServices": ["dock", "autodock", "blackmarket", "commodities", "contacts", "exploration",
# "missions", "outfitting", "crewlounge", "rearm", "refuel", "repair", "shipyard",
# "tuning", "engineer", "missionsgenerated", "flightcontroller", "stationoperations",
# "powerplay", "searchrescue", "materialtrader", "stationMenu", "shop", "livery",
# "socialspace", "bartender", "vistagenomics", "pioneersupplies", "apexinterstellar",
# "frontlinesolutions"], "StationEconomy": "$economy_HighTech;",
# "StationEconomy_Localised": "High Tech", "StationEconomies": [
# {"Name": "$economy_HighTech;", "Name_Localised": "High Tech", "Proportion": 0.800000},
# {"Name": "$economy_Refinery;", "Name_Localised": "Refinery", "Proportion": 0.200000}],
# "DistFromStarLS": 6.950547, "LandingPads": {"Small": 6, "Medium": 12, "Large": 7}}
self.ship['status'] = 'in_station'
self.ship['location'] = log['StarSystem']
self.ship['cur_star_system'] = log['StarSystem']
self.ship['cur_station'] = log['StationName']
self.ship['cur_station_type'] = log['StationType']
self.ship['StationServices'] = log['StationServices']
# parse location
elif log_event == 'Location':
self.ship['location'] = log['StarSystem']
self.ship['cur_star_system'] = log['StarSystem']
self.ship['cur_station'] = log['StationName']
self.ship['cur_station_type'] = log['StationType']
if log['Docked'] == True:
self.ship['status'] = 'in_station'
elif log_event == 'Interdicted':
self.ship['interdicted'] = True
# parse ship type
elif log_event == 'LoadGame':
self.ship['type'] = log['Ship'].lower()
self.ship['ship_size'] = get_ship_size(log['Ship'])
# Parse Loadout
# When written: at startup, when loading from main menu, or when switching ships,
# or after changing the ship in Outfitting, or when docking SRV back in mothership
elif log_event == 'Loadout':
self.ship['type'] = log['Ship'].lower()
self.ship['ship_size'] = get_ship_size(log['Ship'])
self.ship['cargo_capacity'] = log['CargoCapacity']
self.ship['has_fuel_scoop'] = check_fuel_scoop(log['Modules'])
self.ship['has_adv_dock_comp'] = check_adv_docking_computer(log['Modules'])
self.ship['has_std_dock_comp'] = check_std_docking_computer(log['Modules'])
self.ship['has_sco_fsd'] = check_sco_fsd(log['Modules'])
# parse fuel
if 'FuelLevel' in log and self.ship['type'] != 'TestBuggy':
self.ship['fuel_level'] = log['FuelLevel']
if 'FuelCapacity' in log and self.ship['type'] != 'TestBuggy':
try:
self.ship['fuel_capacity'] = log['FuelCapacity']['Main']
except:
self.ship['fuel_capacity'] = log['FuelCapacity']
if log_event == 'FuelScoop' and 'Total' in log:
self.ship['fuel_level'] = log['Total']
if self.ship['fuel_level'] and self.ship['fuel_capacity']:
self.ship['fuel_percent'] = round((self.ship['fuel_level'] / self.ship['fuel_capacity'])*100)
else:
self.ship['fuel_percent'] = 10
# parse scoop
#
if log_event == 'FuelScoop' and self.ship['time'] < 10 and self.ship['fuel_percent'] < 100:
self.ship['is_scooping'] = True
else:
self.ship['is_scooping'] = False
if log_event == 'FSDJump':
self.ship['location'] = log['StarSystem']
self.ship['cur_star_system'] = log['StarSystem']
#TODO if 'StarClass' in log:
#TODO self.ship['star_class'] = log['StarClass']
# parse target
if log_event == 'FSDTarget':
if log['Name'] == self.ship['location']:
self.ship['target'] = None
self.ship['jumps_remains'] = 0
else:
self.ship['target'] = log['Name']
try:
self.ship['jumps_remains'] = log['RemainingJumpsInRoute']
except:
pass
#
# 'Log did not have jumps remaining. This happens most if you have less than .' +
# '3 jumps remaining. Jumps remaining will be inaccurate for this jump.')
elif log_event == 'FSDJump':
if self.ship['location'] == self.ship['target']:
self.ship['target'] = None
self.ship['dist_jumped'] = log["JumpDist"]
# parse nav route clear
elif log_event == 'NavRouteClear':
self.ship['target'] = None
self.ship['jumps_remains'] = 0
elif log_event == 'CarrierJump':
self.ship['location'] = log['StarSystem']
self.ship['cur_star_system'] = log['StarSystem']
self.ship['cur_station'] = log['StationName']
self.ship['cur_station_type'] = log['StationType']
# exceptions
except Exception as e:
#logger.exception("Exception occurred")
print(e)
def ship_state(self):
latest_log = self.get_latest_log()
# open journal file if not open yet or there is a more recent journal
if self.current_log is None or self.current_log != latest_log:
self.open_journal(latest_log)
# Check if file changed
if self.get_file_modified_time() == self.last_mod_time:
return self.ship
cnt = 0
while True:
line = self.log_file.readline()
# if end of file then break from while True
if not line:
break
else:
log = loads(line)
cnt = cnt + 1
current_jrnl = self.ship.copy()
self.parse_line(log)
if self.ship != current_jrnl:
logger.debug('Journal*.log: read: '+str(cnt)+' ship: '+str(self.ship))
self.last_mod_time = self.get_file_modified_time()
return self.ship
def dummy_cb(msg, body=None):
pass
def main():
jn = EDJournal(cb=dummy_cb)
while True:
sleep(5)
print("Ship = ", jn.ship_state())
if __name__ == "__main__":
main()