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
use crate::adsb::{
decode_altitude, decode_cpr, get_adsb_icao_address, get_adsb_message_type, ADSB_SIZE_BYTES,
};
use crate::cache::pool::RedisPool;
use crate::cache::RedisPools;
use crate::grpc::client::GrpcClients;
use adsb_deku::adsb::ME::AirbornePositionBaroAltitude as Position;
use adsb_deku::deku::DekuContainerRead;
use adsb_deku::CPRFormat;
use lib_common::time::datetime_to_timestamp;
use svc_gis_client_grpc::client::{AircraftPosition, Coordinates};
use svc_storage_client_grpc::resources::adsb;
use svc_storage_client_grpc::SimpleClient;
use axum::{body::Bytes, extract::Extension, Json};
use chrono::Utc;
use hyper::StatusCode;
use std::cmp::Ordering;
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
const CACHE_EXPIRE_MS_AIRCRAFT_ADSB: u32 = 10000;
const CACHE_EXPIRE_MS_AIRCRAFT_CPR: u32 = 1000;
const N_REPORTERS_NEEDED: u32 = 1;
pub async fn gis_position_push(
icao: u32,
lat_cpr: u32,
lon_cpr: u32,
alt: u16,
odd_flag: CPRFormat,
mut pool: RedisPool,
ring: Arc<Mutex<VecDeque<AircraftPosition>>>,
) -> Result<(), ()> {
if odd_flag == CPRFormat::Odd {
rest_info!("(gis_position_push) received an odd flag CPR format message.");
return Ok(()); }
let keys = vec![
format!("{:x}:lat_cpr:{}", icao, CPRFormat::Odd as u8),
format!("{:x}:lon_cpr:{}", icao, CPRFormat::Odd as u8),
];
let n_expected_results = keys.len();
let Ok(results) = pool.multiple_get::<u32>(keys).await else {
rest_warn!("(gis_position_push) could not get packet from cache.");
return Err(());
};
if results.len() != n_expected_results {
rest_warn!("(gis_position_push) unexpected result from cache.");
return Err(());
}
let (e_lat_cpr, e_lon_cpr) = (results[0], results[1]);
let Ok((latitude, longitude)) = decode_cpr(e_lat_cpr, e_lon_cpr, lat_cpr, lon_cpr) else {
rest_warn!("(gis_position_push) could not decode CPR.");
return Err(());
};
let Some(time) = datetime_to_timestamp(&Utc::now()) else {
rest_warn!("(gis_position_push) could not get current time.");
return Err(());
};
let item = AircraftPosition {
callsign: format!("{:x}", icao),
location: Some(Coordinates {
latitude: latitude as f32,
longitude: longitude as f32,
}),
altitude_meters: decode_altitude(alt),
time: Some(time),
uuid: None,
};
match ring.lock() {
Ok(mut ring) => {
rest_debug!(
"(handle_adsb) pushing to ring buffer (items: {})",
ring.len()
);
ring.push_back(item);
Ok(())
}
_ => {
rest_warn!("(handle_adsb) could not push to ring buffer.");
Err(())
}
}
}
#[utoipa::path(
post,
path = "/telemetry/aircraft/adsb",
tag = "svc-telemetry",
request_body = Vec<u8>,
responses(
(status = 200, description = "Telemetry received."),
(status = 400, description = "Malformed packet."),
(status = 500, description = "Something went wrong."),
(status = 503, description = "Dependencies of svc-telemetry were down."),
)
)]
pub async fn aircraft_adsb(
Extension(mut pools): Extension<RedisPools>,
Extension(mq_channel): Extension<lapin::Channel>,
Extension(grpc_clients): Extension<GrpcClients>,
Extension(ring): Extension<Arc<Mutex<VecDeque<AircraftPosition>>>>,
payload: Bytes,
) -> Result<Json<u32>, StatusCode> {
rest_info!("(aircraft_adsb) entry.");
let Ok(key) = std::str::from_utf8(&payload[..]) else {
rest_error!("(aircraft_adsb) could not convert payload to string.");
return Err(StatusCode::BAD_REQUEST);
};
let result = pools
.adsb
.increment(key, CACHE_EXPIRE_MS_AIRCRAFT_ADSB)
.await;
let Ok(count) = result else {
rest_error!("(aircraft_adsb) {}", result.unwrap_err());
return Err(StatusCode::INTERNAL_SERVER_ERROR);
};
match count.cmp(&N_REPORTERS_NEEDED) {
Ordering::Less => {
rest_error!("(aircraft_adsb) ADS-B reporter count should be impossible: {count}.");
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
Ordering::Greater => {
rest_info!("(aircraft_adsb) ADS-B reporter count is greater than needed: {count}.");
return Ok(Json(count));
}
_ => (), }
let Ok(payload) = <[u8; ADSB_SIZE_BYTES]>::try_from(payload.as_ref()) else {
rest_info!("(aircraft_adsb) received ads-b message not {ADSB_SIZE_BYTES} bytes.");
return Err(StatusCode::BAD_REQUEST);
};
let Ok(frame) = adsb_deku::Frame::from_bytes((&payload, 0)) else {
rest_info!("(aircraft_adsb) could not parse ads-b message.");
return Err(StatusCode::BAD_REQUEST);
};
let frame = frame.1;
let adsb_deku::DF::ADSB(msg) = &frame.df else {
rest_info!("(aircraft_adsb) received a non-ADSB format message.");
return Err(StatusCode::BAD_REQUEST);
};
let icao = get_adsb_icao_address(&msg.icao.0);
match msg.me {
Position(adsb_deku::Altitude {
odd_flag,
lat_cpr,
lon_cpr,
alt,
..
}) => {
let Some(alt) = alt else {
rest_info!("(aircraft_adsb) no altitude in packet.");
return Err(StatusCode::BAD_REQUEST);
};
let keyvals = vec![
(
format!("{:x}:lat_cpr:{}", icao, odd_flag),
lat_cpr.to_string(),
),
(
format!("{:x}:lon_cpr:{}", icao, odd_flag),
lon_cpr.to_string(),
),
];
match pools
.adsb
.multiple_set(keyvals, CACHE_EXPIRE_MS_AIRCRAFT_CPR)
.await
{
Ok(_) => rest_info!("(aircraft_adsb) added lat/lon to cache."),
Err(e) => {
rest_error!("(aircraft_adsb) could not add lat/lon to cache: {}.", e);
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
}
match gis_position_push(icao, lat_cpr, lon_cpr, alt, odd_flag, pools.adsb, ring).await {
Ok(_) => rest_info!("(aircraft_adsb) pushed position to ring buffer."),
Err(_) => {
rest_error!("(aircraft_adsb) could not push position to ring buffer.");
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
}
}
_ => {
rest_info!("(aircraft_adsb) received an unrecognized message.");
return Err(StatusCode::BAD_REQUEST);
}
};
let result = mq_channel
.basic_publish(
crate::amqp::EXCHANGE_NAME_TELEMETRY,
crate::amqp::ROUTING_KEY_ADSB,
lapin::options::BasicPublishOptions::default(),
&payload,
lapin::BasicProperties::default(),
)
.await;
match result {
Ok(_) => rest_info!("(aircraft_adsb) telemetry pushed to RabbitMQ."),
Err(e) => rest_error!("(aircraft_adsb) telemetry push to RabbitMQ failed: {e}."),
}
let data = adsb::Data {
icao_address: icao as i64,
message_type: get_adsb_message_type(&payload),
network_timestamp: Some(Utc::now().into()),
payload: payload.to_vec(),
};
let request = data;
let client = &grpc_clients.storage.adsb;
match client.insert(request).await {
Ok(_) => rest_info!("(aircraft_adsb) telemetry pushed to svc-storage."),
Err(e) => {
rest_error!(
"(aircraft_adsb) telemetry push to svc-storage failed: {}.",
e
);
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
}
Ok(Json(count))
}