forked from SumZer0-git/EDAPGui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMarketParser.py
More file actions
233 lines (207 loc) · 7.78 KB
/
MarketParser.py
File metadata and controls
233 lines (207 loc) · 7.78 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
from __future__ import annotations
import json
import os
import time
from datetime import datetime, timedelta
import queue
from sys import platform
import threading
from time import sleep
from EDlogger import logger
from WindowsKnownPaths import *
class MarketParser:
""" Parses the Market.json file generated by the game. """
def __init__(self, file_path=None):
if platform != "win32":
self.file_path = file_path if file_path else "./linux_ed/Market.json"
else:
from WindowsKnownPaths import get_path, FOLDERID, UserHandle
self.file_path = file_path if file_path else (get_path(FOLDERID.SavedGames, UserHandle.current)
+ "/Frontier Developments/Elite Dangerous/Market.json")
self.last_mod_time = None
# Read json file data
self.current_data = self.get_market_data()
# self.watch_thread = threading.Thread(target=self._watch_file_thread, daemon=True)
# self.watch_thread.start()
# self.status_queue = queue.Queue()
# def _watch_file_thread(self):
# backoff = 1
# while True:
# try:
# self._watch_file()
# except Exception as e:
# logger.debug('An error occurred when reading status file')
# sleep(backoff)
# logger.debug('Attempting to restart status file reader after failure')
# backoff *= 2
#
# def _watch_file(self):
# """Detects changes in the Status.json file."""
# while True:
# status = self.get_cleaned_data()
# if status != self.current_data:
# self.status_queue.put(status)
# self.current_data = status
# sleep(1)
def get_file_modified_time(self) -> float:
return os.path.getmtime(self.file_path)
def get_market_data(self):
"""Loads data from the JSON file and returns the data.
{
"timestamp": "2024-09-21T14:53:38Z",
"event": "Market",
"MarketID": 129019775,
"StationName": "Rescue Ship Cornwallis",
"StationType": "MegaShip",
"StarSystem": "V886 Centauri",
"Items": [
{
"id": 128049152,
"Name": "$platinum_name;",
"Name_Localised": "Platinum",
"Category": "$MARKET_category_metals;",
"Category_Localised": "Metals",
"BuyPrice": 3485,
"SellPrice": 3450,
"MeanPrice": 58272,
"StockBracket": 0,
"DemandBracket": 0,
"Stock": 0,
"Demand": 0,
"Consumer": false,
"Producer": false,
"Rare": false
}, { etc. } ]
"""
# Check if file changed
if self.get_file_modified_time() == self.last_mod_time:
#logger.debug(f'Market.json mod timestamp {self.last_mod_time} unchanged.')
return self.current_data
# Read file
backoff = 1
while True:
try:
with open(self.file_path, 'r') as file:
data = json.load(file)
break
except Exception as e:
logger.debug('An error occurred when reading Market.json file')
sleep(backoff)
logger.debug('Attempting to restart status file reader after failure')
backoff *= 2
# Store data
self.current_data = data
self.last_mod_time = self.get_file_modified_time()
#logger.debug(f'Market.json mod timestamp {self.last_mod_time} updated.')
# print(json.dumps(data, indent=4))
return data
def get_sellable_items(self):
""" Get a list of items that can be sold to the station.
Will trigger a read of the json file.
{
"id": 128049154,
"Name": "$gold_name;",
"Name_Localised": "Gold",
"Category": "$MARKET_category_metals;",
"Category_Localised": "Metals",
"BuyPrice": 49118,
"SellPrice": 48558,
"MeanPrice": 47609,
"StockBracket": 2,
"DemandBracket": 0,
"Stock": 89,
"Demand": 1,
"Consumer": true,
"Producer": false,
"Rare": false
}
"""
data = self.get_market_data()
sellable_items = [x for x in data['Items'] if x['Consumer'] or x['Demand'] > 0]
# print(json.dumps(newlist, indent=4))
return sellable_items
def get_buyable_items(self):
""" Get a list of items that can be bought from the station.
Will trigger a read of the json file.
{
"id": 128049154,
"Name": "$gold_name;",
"Name_Localised": "Gold",
"Category": "$MARKET_category_metals;",
"Category_Localised": "Metals",
"BuyPrice": 49118,
"SellPrice": 48558,
"MeanPrice": 47609,
"StockBracket": 2,
"DemandBracket": 0,
"Stock": 89,
"Demand": 1,
"Consumer": false,
"Producer": true,
"Rare": false
}
"""
data = self.get_market_data()
buyable_items = [x for x in data['Items'] if x['Producer'] and x['Stock'] > 0]
# print(json.dumps(newlist, indent=4))
return buyable_items
def get_market_name(self) -> str:
""" Gets the current market (station) name.
Will not trigger a read of the json file.
"""
return self.current_data['StationName']
def get_item(self, item_name) -> dict[any] | None:
""" Get details of one item. Returns the item detail as below, or None if item does not exist.
Will not trigger a read of the json file.
{
"id": 128049154,
"Name": "$gold_name;",
"Name_Localised": "Gold",
"Category": "$MARKET_category_metals;",
"Category_Localised": "Metals",
"BuyPrice": 49118,
"SellPrice": 48558,
"MeanPrice": 47609,
"StockBracket": 2,
"DemandBracket": 0,
"Stock": 89,
"Demand": 1,
"Consumer": false,
"Producer": true,
"Rare": false
}
"""
for good in self.current_data['Items']:
if good['Name_Localised'].upper() == item_name.upper():
# print(json.dumps(good, indent=4))
return good
return None
def can_buy_item(self, item_name: str) -> bool:
""" Can the item be bought from the market (is it sold and is there stock).
Will not trigger a read of the json file.
"""
good = self.get_item(item_name)
if good is None:
return False
return ((good['Stock'] > 0 and good['Producer'] and not good['Rare'])
or (good['Stock'] > 0 and good['Rare'])) # Need producer in for non-Rares?
def can_sell_item(self, item_name: str) -> bool:
""" Can the item be sold to the market (is it bought, regardless of demand).
Will not trigger a read of the json file.
"""
good = self.get_item(item_name)
if good is None:
return False
return good['Consumer'] or good['Demand'] > 0 or good['Rare']
# Usage Example
if __name__ == "__main__":
parser = MarketParser()
while True:
cleaned_data = parser.get_market_data()
#item = parser.get_item('water')
sell = parser.can_sell_item('water')
#buy = parser.can_buy_item('water')
print(f"Curr Time: {time.time()}")
print(f"Sell water: {sell}")
# print(json.dumps(cleaned_data, indent=4))
time.sleep(1)