-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxdr_api.py
More file actions
executable file
·342 lines (300 loc) · 12.1 KB
/
xdr_api.py
File metadata and controls
executable file
·342 lines (300 loc) · 12.1 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request, make_response
from functools import wraps
import os
import json
def add_cors_headers(response):
response.headers.add('Access-Control-Allow-Origin', '*')
if request.method == 'OPTIONS':
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
return response
# Import XDR core functions directly
from xdr_core import (
xdr_status, xdr_scan, xdr_tune, xdr_bandwidth,
xdr_mode, xdr_volume, xdr_deemp,xdr_agc, xdr_antenna, xdr_gain,
xdr_daa, xdr_squelch, xdr_rotator, xdr_interval, xdr_init_cmd,
xdr_shutdown, xdr_state
)
app = Flask(__name__)
# CORS middleware
@app.after_request
def after_request(response):
return add_cors_headers(response)
# Configuration
DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 5000
# Default configuration for up to 4 XDRD hosts
XDRD_CONFIG = [
{"host": "xdrd1", "port": 7371, "name": "XDR-1", "password": "123qwe"}, # Default first host
]
if os.environ.get("XDRD_CONFIG"):
try:
XDRD_CONFIG = json.loads(os.environ["XDRD_CONFIG"])
except json.JSONDecodeError:
print("Error parsing XDRD_CONFIG environment variable, using default.")
# cambiar a env, default en 1
MAX_XDR = len(XDRD_CONFIG)
# Get configuration from environment variables
HOST = os.environ.get("HOST", DEFAULT_HOST)
PORT = int(os.environ.get("PORT", DEFAULT_PORT))
# Load XDRD configurations from environment
XDRD_CONFIGS = []
for i in range(MAX_XDR):
idx = i + 1 # 1-based index for environment variables
if i < len(XDRD_CONFIG):
if XDRD_CONFIG[i]["host"]:
XDRD_CONFIGS.append({
"id": idx,
"host": XDRD_CONFIG[i]["host"],
"port": XDRD_CONFIG[i]["port"],
"name": XDRD_CONFIG[i]["name"],
"password": XDRD_CONFIG[i]["password"]
})
if not XDRD_CONFIGS:
raise ValueError("At least one XDRD host must be configured")
# XDR Context Manager
class XDRContext:
_instances = {}
@classmethod
def get_context(cls, host_id):
"""Get or create an XDR context for the specified host ID"""
if host_id not in cls._instances:
config = next((c for c in XDRD_CONFIGS if c["id"] == host_id), None)
if not config:
raise ValueError(f"No configuration found for XDRD host ID {host_id}")
cls._instances[host_id] = cls._create_context(config)
return cls._instances[host_id]
@classmethod
def _create_context(cls, config):
"""Create a new XDR context from config"""
ctx = XDRContext()
ctx.obj = {
'host': config["host"],
'port': config["port"],
'password': config["password"],
'id': config["id"],
'name': config["name"]
}
return ctx
@classmethod
def list_contexts(cls):
"""List all configured XDR contexts"""
return [{
'id': ctx.obj['id'],
'name': ctx.obj['name'],
'host': ctx.obj['host'],
'port': ctx.obj['port']
} for ctx in cls._instances.values()]
def __init__(self):
self.obj = {}
# Initialize contexts for all configured hosts
for config in XDRD_CONFIGS:
XDRContext.get_context(config["id"])
# API Endpoints
@app.route('/api/xdrs', methods=['GET'])
def list_xdrs():
"""List all configured XDR receivers"""
return jsonify({
'xdrs': XDRContext.list_contexts(),
'count': len(XDRContext.list_contexts())
})
@app.route(f'/api/status/<int(min=1, max={MAX_XDR}):xdrid>', methods=['GET', 'OPTIONS'])
def get_status(xdrid):
if request.method == 'OPTIONS':
return make_response()
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 1.0))
as_json = False
result = xdr_status(xdr_ctx, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route(f'/api/state/<int(min=1, max={MAX_XDR}):xdrid>', methods=['GET', 'OPTIONS'])
def get_state(xdrid):
if request.method == 'OPTIONS':
return make_response()
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 1.0))
as_json = True
result = xdr_state(xdr_ctx, read_seconds, as_json)
return result
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/tune/<int:khz>', methods=['POST', 'OPTIONS'])
@app.route('/api/tune/<int:khz>', methods=['POST', 'OPTIONS'], defaults={'xdrid': 1})
def tune(xdrid, khz):
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_tune(xdr_ctx, khz, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/bandwidth/<int:code>', methods=['POST', 'OPTIONS'])
@app.route('/api/bandwidth/<int:code>', methods=['POST', 'OPTIONS'], defaults={'xdrid': 1})
def set_bandwidth(xdrid, code):
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_bandwidth(xdr_ctx, code, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/mode/<int:mode>', methods=['POST'])
@app.route('/api/mode/<int:mode>', methods=['POST'], defaults={'xdrid': 1})
def set_mode(xdrid, mode):
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_mode(xdr_ctx, mode, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/volume/<int:value>', methods=['POST'])
@app.route('/api/volume/<int:value>', methods=['POST'], defaults={'xdrid': 1})
def set_volume(xdrid, value):
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_volume(xdr_ctx, value, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/deemp/<int:value>', methods=['POST'])
@app.route('/api/deemp/<int:value>', methods=['POST'], defaults={'xdrid': 1})
def set_deemp(xdrid, value):
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_deemp(xdr_ctx, value, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/agc/<int:value>', methods=['POST'])
@app.route('/api/agc/<int:value>', methods=['POST'], defaults={'xdrid': 1})
def set_agc(xdrid, value):
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_agc(xdr_ctx, value, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/antenna/<int:value>', methods=['POST'])
@app.route('/api/antenna/<int:value>', methods=['POST'], defaults={'xdrid': 1})
def set_antenna(xdrid, value):
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_antenna(xdr_ctx, value, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/gain/<int:value>', methods=['POST'])
@app.route('/api/gain/<int:value>', methods=['POST'], defaults={'xdrid': 1})
def set_gain(xdrid, value):
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_gain(xdr_ctx, value, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/daa/<int:value>', methods=['POST'])
@app.route('/api/daa/<int:value>', methods=['POST'], defaults={'xdrid': 1})
def set_daa(xdrid, value):
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_daa(xdr_ctx, value, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/squelch/<int:value>', methods=['POST'])
@app.route('/api/squelch/<int:value>', methods=['POST'], defaults={'xdrid': 1})
def set_squelch(xdrid, value):
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_squelch(xdr_ctx, value, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/rotator/<int:value>', methods=['POST'])
@app.route('/api/rotator/<int:value>', methods=['POST'], defaults={'xdrid': 1})
def set_rotator(xdrid, value):
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_rotator(xdr_ctx, value, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/interval', methods=['POST'])
@app.route('/api/interval', methods=['POST'], defaults={'xdrid': 1})
def set_interval(xdrid):
try:
xdr_ctx = XDRContext.get_context(xdrid)
data = request.get_json()
if not data or 'interval' not in data:
return jsonify({"error": "Missing interval parameter"}), 400
interval = int(data['interval'])
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_interval(xdr_ctx, interval, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/init', methods=['POST'])
@app.route('/api/init', methods=['POST'], defaults={'xdrid': 1})
def init(xdrid):
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_init_cmd(xdr_ctx, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/<int:xdrid>/shutdown', methods=['POST'])
@app.route('/api/shutdown', methods=['POST'], defaults={'xdrid': 1})
def shutdown(xdrid):
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_shutdown(xdr_ctx, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
@app.route('/api/scan/<int(min=1, max={MAX_XDR}):xdrid>', methods=['GET', 'OPTIONS'])
def scan(xdrid):
if request.method == 'OPTIONS':
return make_response()
try:
xdr_ctx = XDRContext.get_context(xdrid)
read_seconds = float(request.args.get('read_seconds', 0.6))
as_json = False
result = xdr_scan(xdr_ctx, read_seconds, as_json)
return jsonify(result)
except ValueError as e:
return jsonify({"error": str(e)}), 404
if __name__ == '__main__':
app.run(host=HOST,
port=PORT,
debug=os.environ.get('DEBUG', 'false').lower() == 'true')