-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheddn_client.py
executable file
·265 lines (222 loc) · 8.32 KB
/
eddn_client.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
#!/usr/bin/env python
# ----------------------------------------------------------------
# Simple EDDN client for debug purposes. Based on the example at
# https://github.com/jamesremuscat/EDDN
# ----------------------------------------------------------------
import argparse
import datetime
import simplejson
import sys
import time
import traceback
import zlib
import zmq
__version_info__ = ('3', '4', '0')
__version__ = '.'.join(__version_info__)
# ----------------------------------------------------------------
# Functions.
# ----------------------------------------------------------------
def parse_args():
'''
Parse arguments.
'''
# Basic argument parsing.
parser = argparse.ArgumentParser(
description='EDDN Test Client.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
# Version
parser.add_argument('--version',
action='version',
version='%(prog)s '+__version__)
# Debug
parser.add_argument("--debug",
action="store_true",
default=False,
help="Output additional debug info, and use test\
schema.")
# relay
parser.add_argument("--relay",
default="tcp://eddn-relay.elite-markets.net:9500",
help='EDDN relay to connect to.')
# timeout
parser.add_argument("--timeout",
default=600000,
type=int,
help='Connection timeout.')
# Software
parser.add_argument("--software",
default=[
"EDAPI",
"EDAPI Trade Dangerous Plugin",
],
nargs='+',
help="A list of white listed software. Use \"all\" to\
see all messages.")
# Parse the command line.
args = parser.parse_args()
return args
def date(format):
'''
Date format helper.
'''
d = datetime.datetime.utcnow()
return d.strftime(format)
def echoLog(line):
'''
Format console output.
'''
if (echoLog.oldTime is False) or (echoLog.oldTime != date('%H:%M:%S')):
echoLog.oldTime = date('%H:%M:%S')
line = str(echoLog.oldTime) + ' | ' + str(line)
else:
line = ' ' + ' | ' + str(line)
print(line)
sys.stdout.flush()
echoLog.oldTime = False
def Main():
'''
Main()
'''
# These are the schemas we will decode.
allowed_schemas = {
'http://schemas.elite-markets.net/eddn/commodity/2': 'commodity-v2',
'http://schemas.elite-markets.net/eddn/shipyard/1': 'shipyard-v1',
'http://schemas.elite-markets.net/eddn/outfitting/1': 'outfitting-v1',
}
# If debug, only listen for test type messages.
if args.debug:
for key, name in allowed_schemas.items():
del allowed_schemas[key]
key += '/test'
allowed_schemas[key] = name
echoLog('Starting EDDN Subscriber...')
echoLog('')
# Some info
echoLog('Software white list:')
for soft in args.software:
echoLog('\t' + soft)
echoLog('')
echoLog('Schema white list:')
for schema in allowed_schemas:
echoLog('\t' + schema)
echoLog('')
# Configure the zmq subscriber.
context = zmq.Context()
subscriber = context.socket(zmq.SUB)
subscriber.setsockopt(zmq.SUBSCRIBE, b"")
subscriber.setsockopt(zmq.RCVTIMEO, args.timeout)
# Do this forever.
while True:
try:
# Connect.
subscriber.connect(args.relay)
echoLog('Connected to ' + args.relay)
echoLog('')
echoLog('')
# Keep reading until disconnected.
while True:
message = subscriber.recv()
# We were disconnected.
if message is False:
subscriber.disconnect(args.relay)
echoLog('Disconnected from ' + args.relay)
echoLog('')
echoLog('')
break
# Decode the JSON message.
message = simplejson.loads(zlib.decompress(message))
# ID the schema.
schema = "Unknown"
if message['$schemaRef'] in allowed_schemas:
schema = allowed_schemas[message['$schemaRef']]
else:
schema += ': ' + message['$schemaRef']
uploaderID = message['header']['uploaderID']
uploaderID = uploaderID[:16]+'...' if len(uploaderID)>16 else uploaderID
echoLog(
'Received ' + schema +
' ' + message['header']['softwareName'] +
' / ' + message['header']['softwareVersion'] +
' (' + uploaderID + ')' +
' : ' + message['message']['systemName'] +
' / ' + message['message']['stationName']
)
# Check if the software is white listed.
if (
(
message['header']['softwareName'] in args.software or
args.software == ['all']
) and
not schema.startswith("Unknown")
):
pass
else:
continue
# Log common info.
echoLog('\t- Schema: ' + message['$schemaRef'])
echoLog('\t- Software: ' + message['header']['softwareName'] + ' / ' + message['header']['softwareVersion']) # NOQA
echoLog('\t- Timestamp: ' + message['message']['timestamp'])
echoLog('\t- Uploader ID: ' + message['header']['uploaderID'])
echoLog('\t\t- System Name: ' + message['message']['systemName']) # NOQA
echoLog('\t\t- Station Name: ' + message['message']['stationName']) # NOQA
# Handle commodity v2
if schema == 'commodity-v2':
for com in message['message']['commodities']:
echoLog('\t\t\t- Name: ' + com['name'])
echoLog('\t\t\t\t- Buy Price: ' + str(com['buyPrice']))
echoLog(
'\t\t\t\t- Supply: ' +
str(com['supply']) +
' (' + com.get('supplyLevel', 'N/A') + ')'
)
echoLog('\t\t\t\t- Sell Price: ' + str(com['sellPrice'])) # NOQA
echoLog(
'\t\t\t\t- Demand: ' +
str(com['demand']) +
' (' + com.get('demandLevel', 'N/A') + ')'
)
echoLog('')
echoLog('')
# Handle shipyard v1
if schema == 'shipyard-v1':
for ship in message['message']['ships']:
echoLog('\t\t\t- Ship: ' + ship)
echoLog('')
echoLog('')
# Handle outfitting v1
if schema == 'outfitting-v1':
for module in message['message']['modules']:
echoLog('\t\t\t- Module: ' + module['name'])
echoLog('')
echoLog('')
# Connect error... Retry...
except zmq.ZMQError as e:
echoLog('')
echoLog('ZMQSocketException: ' + str(e))
echoLog('')
time.sleep(10)
if __name__ == '__main__':
'''
Command line invocation.
'''
try:
# Parse any command line arguments.
args = parse_args()
# Command line overrides
if args.debug is True:
print('***** Debug mode *****')
print(args)
# Execute the Main() function and return results.
sys.exit(Main())
except KeyboardInterrupt as e:
print("Disconnecting...")
sys.exit(0)
except SystemExit as e:
# Clean exit, provide a return code.
sys.exit(e.code)
except:
# Handle all other exceptions.
ErrStr = traceback.format_exc()
print('Exception in main loop. Exception info below:')
sys.exit(ErrStr)