1
0
mirror of https://github.com/EDCD/EDMarketConnector.git synced 2025-04-19 02:17:38 +03:00

Switch to new EDDN schemas

Ref https://github.com/jamesremuscat/EDDN/pull/47
This commit is contained in:
Jonathan Harris 2016-08-16 14:27:10 +01:00
parent a0e11354aa
commit a89ac59a04
4 changed files with 58 additions and 79 deletions

View File

@ -92,10 +92,6 @@ try:
sys.stderr.write('What are you flying?!\n') # Shouldn't happen
sys.exit(EXIT_SERVER)
if data['lastStarport'].get('commodities'):
# Fixup anomalies in the commodity data
session.fixup(data['lastStarport']['commodities'])
# stuff we can do when not docked
if args.d:
with open(args.d, 'wt') as h:
@ -133,6 +129,7 @@ try:
if args.m:
if data['lastStarport'].get('commodities'):
data = session.fixup(data) # Fixup anomalies in the commodity data
commodity.export(data, COMMODITY_DEFAULT, args.m)
else:
sys.stderr.write("Station doesn't have a market\n")

View File

@ -367,10 +367,6 @@ class AppWindow:
self.status['text'] = ''
self.edit_menu.entryconfigure(0, state=tk.NORMAL) # Copy
if data['lastStarport'].get('commodities'):
# Fixup anomalies in the commodity data
self.session.fixup(data['lastStarport']['commodities'])
# stuff we can do when not docked
plug.notify_newdata(data)
if config.getint('output') & config.OUT_SHIP_EDS:
@ -413,12 +409,15 @@ class AppWindow:
else:
if data['lastStarport'].get('commodities'):
# Fixup anomalies in the commodity data
fixed = self.session.fixup(data)
if config.getint('output') & config.OUT_MKT_CSV:
commodity.export(data, COMMODITY_CSV)
commodity.export(fixed, COMMODITY_CSV)
if config.getint('output') & config.OUT_MKT_TD:
td.export(data)
td.export(fixed)
if config.getint('output') & config.OUT_MKT_BPC:
commodity.export(data, COMMODITY_BPC)
commodity.export(fixed, COMMODITY_BPC)
if config.getint('output') & config.OUT_MKT_EDDN:
old_status = self.status['text']

View File

@ -267,11 +267,10 @@ class Session:
pass
self.session = None
# Fixup in-place anomalies in the recieved commodity data
def fixup(self, commodities):
i=0
while i<len(commodities):
commodity = commodities[i]
# Returns a shallow copy of the received data with anomalies in the commodity data fixed up
def fixup(self, data):
commodities = []
for commodity in data['lastStarport'].get('commodities') or []:
# Check all required numeric fields are present and are numeric
# Catches "demandBracket": "" for some phantom commodites in ED 1.3 - https://github.com/Marginal/EDMarketConnector/issues/2
@ -293,28 +292,29 @@ class Session:
if __debug__: print 'Invalid "stockBracket":"%s" for "%s"' % (commodity['stockBracket'], commodity['name'])
else:
# Rewrite text fields
commodity['categoryname'] = category_map.get(commodity['categoryname'], commodity['categoryname'])
new = dict(commodity) # shallow copy
new['categoryname'] = category_map.get(commodity['categoryname'], commodity['categoryname'])
fixed = commodity_map.get(commodity['name'])
if type(fixed) == tuple:
(commodity['categoryname'], commodity['name']) = fixed
(new['categoryname'], new['name']) = fixed
elif fixed:
commodity['name'] = fixed
new['name'] = fixed
# Force demand and stock to zero if their corresponding bracket is zero
# Fixes spurious "demand": 1 in ED 1.3
if not commodity['demandBracket']:
commodity['demand'] = 0
new['demand'] = 0
if not commodity['stockBracket']:
commodity['stock'] = 0
new['stock'] = 0
# We're good
i+=1
continue
commodities.append(new)
# Skip the commodity
commodities.pop(i)
return commodities
# return a shallow copy
datacopy = dict(data)
datacopy['lastStarport'] = dict(data['lastStarport'])
datacopy['lastStarport']['commodities'] = commodities
return datacopy
def dump(self, r):
if __debug__:

87
eddn.py
View File

@ -1,32 +1,25 @@
# Export to EDDN
from collections import OrderedDict
import hashlib
import json
import numbers
import requests
from platform import system
import re
import requests
from sys import platform
import time
from config import applongname, appversion, config
import companion
import outfitting
from companion import category_map
### upload = 'http://localhost:8081/upload/' # testing
upload = 'http://eddn-gateway.elite-markets.net:8080/upload/'
timeout= 10 # requests timeout
module_re = re.compile('^Hpt_|^Int_|_Armour_')
# Map API ship names to EDDN schema names
# https://raw.githubusercontent.com/jamesremuscat/EDDN/master/schemas/shipyard-v1.0.json
ship_map = dict(companion.ship_map)
ship_map['asp'] = 'Asp' # Pre E:D 1.5 name for backwards compatibility
ship_map['cobramkiii'] = 'Cobra Mk III' # ditto
ship_map['viper'] = 'Viper' # ditto
bracketmap = { 1: 'Low',
2: 'Med',
3: 'High', }
def send(cmdr, msg):
msg['header'] = {
@ -46,52 +39,42 @@ def send(cmdr, msg):
def export_commodities(data):
# Don't send empty commodities list - schema won't allow it
if data['lastStarport'].get('commodities'):
commodities = []
for commodity in data['lastStarport'].get('commodities', []):
commodities.append({
'name' : commodity['name'],
'buyPrice' : int(commodity['buyPrice']),
'supply' : int(commodity['stock']),
'sellPrice' : int(commodity['sellPrice']),
'demand' : int(commodity['demand']),
})
if commodity['stockBracket']:
commodities[-1]['supplyLevel'] = bracketmap[commodity['stockBracket']]
if commodity['demandBracket']:
commodities[-1]['demandLevel'] = bracketmap[commodity['demandBracket']]
commodities = []
for commodity in data['lastStarport'].get('commodities') or []:
if category_map.get(commodity['categoryname'], True): # Check marketable
commodities.append(OrderedDict([
('name', commodity['name']),
('meanPrice', int(commodity['meanPrice'])),
('buyPrice', int(commodity['buyPrice'])),
('stock', int(commodity['stock'])),
('stockBracket', commodity['stockBracket']),
('sellPrice', int(commodity['sellPrice'])),
('demand', int(commodity['demand'])),
('demandBracket', commodity['demandBracket']),
]))
if commodity['statusFlags']:
commodities[-1]['statusFlags'] = commodity['statusFlags']
# Don't send empty commodities list - schema won't allow it
if commodities:
send(data['commander']['name'], {
'$schemaRef' : 'http://schemas.elite-markets.net/eddn/commodity/2',
'$schemaRef' : 'http://schemas.elite-markets.net/eddn/commodity/3',
'message' : {
'systemName' : data['lastSystem']['name'].strip(),
'stationName' : data['lastStarport']['name'].strip(),
'systemName' : data['lastSystem']['name'],
'stationName' : data['lastStarport']['name'],
'commodities' : commodities,
}
})
def export_outfitting(data):
# Don't send empty modules list
# Don't send empty modules list - schema won't allow it
if data['lastStarport'].get('modules'):
schemakeys = ['category', 'name', 'mount', 'guidance', 'ship', 'class', 'rating']
modules = []
for v in data['lastStarport'].get('modules', {}).itervalues():
try:
module = outfitting.lookup(v, ship_map)
if module:
modules.append({ k: module[k] for k in schemakeys if k in module }) # just the relevant keys
except AssertionError as e:
if __debug__: print 'Outfitting: %s' % e # Silently skip unrecognized modules
except:
if __debug__: raise
send(data['commander']['name'], {
'$schemaRef' : 'http://schemas.elite-markets.net/eddn/outfitting/1',
'$schemaRef' : 'http://schemas.elite-markets.net/eddn/outfitting/2',
'message' : {
'systemName' : data['lastSystem']['name'].strip(),
'stationName' : data['lastStarport']['name'].strip(),
'modules' : modules,
'systemName' : data['lastSystem']['name'],
'stationName' : data['lastStarport']['name'],
'modules' : sorted([module['name'] for module in (data['lastStarport'].get('modules') or {}).values() if module_re.search(module['name']) and module.get('sku') in [None, 'ELITE_HORIZONS_V_PLANETARY_LANDINGS'] and module['name'] != 'Int_PlanetApproachSuite']),
}
})
@ -99,10 +82,10 @@ def export_shipyard(data):
# Don't send empty ships list - shipyard data is only guaranteed present if user has visited the shipyard.
if data['lastStarport'].get('ships'):
send(data['commander']['name'], {
'$schemaRef' : 'http://schemas.elite-markets.net/eddn/shipyard/1',
'$schemaRef' : 'http://schemas.elite-markets.net/eddn/shipyard/2',
'message' : {
'systemName' : data['lastSystem']['name'].strip(),
'stationName' : data['lastStarport']['name'].strip(),
'ships' : [ship_map[ship['name'].lower()] for ship in (data['lastStarport']['ships'].get('shipyard_list') or {}).values() + data['lastStarport']['ships'].get('unavailable_list') if ship['name'].lower() in ship_map],
'systemName' : data['lastSystem']['name'],
'stationName' : data['lastStarport']['name'],
'ships' : sorted([ship['name'] for ship in (data['lastStarport']['ships'].get('shipyard_list') or {}).values() + data['lastStarport']['ships'].get('unavailable_list')]),
}
})