Skip to content

Commit

Permalink
Switch to new EDDN schemas
Browse files Browse the repository at this point in the history
  • Loading branch information
Marginal committed Aug 16, 2016
1 parent 69242b6 commit 7c22657
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 68 deletions.
2 changes: 1 addition & 1 deletion EDMC.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def versioncmp(versionstring):

if data['lastStarport'].get('commodities'):
# Fixup anomalies in the commodity data
session.fixup(data['lastStarport']['commodities'])
data = session.fixup(data['lastStarport']['commodities'])

# stuff we can do when not docked
if args.d:
Expand Down
8 changes: 4 additions & 4 deletions EDMarketConnector.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,14 +422,14 @@ def getandsend(self, event=None, retrying=False):
else:
if data['lastStarport'].get('commodities'):
# Fixup anomalies in the commodity data
self.session.fixup(data['lastStarport']['commodities'])
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']
Expand Down
32 changes: 16 additions & 16 deletions companion.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,11 +267,10 @@ def close(self):
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
Expand All @@ -293,28 +292,29 @@ def fixup(self, commodities):
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__:
Expand Down
76 changes: 29 additions & 47 deletions eddn.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# 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

Expand All @@ -16,17 +18,8 @@
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'] = {
Expand All @@ -49,61 +42,50 @@ 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']]
for commodity in data['lastStarport'].get('commodities') or []:
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']

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'])]),
}
})

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')]),
}
})

Expand Down

0 comments on commit 7c22657

Please sign in to comment.