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
//! Region implementation for the United States (US)

use crate::grpc::server::{
    FlightPlanRequest, FlightPlanResponse, FlightReleaseRequest, FlightReleaseResponse,
};

use crate::region::RegionInterface;
use crate::region::RestrictionDetails;
use chrono::{Duration, Utc};
use std::collections::HashMap;
use svc_gis_client_grpc::prelude::gis::{Coordinates, ZoneType};
use tonic::{Request, Response, Status};

impl Default for super::RegionImpl {
    fn default() -> Self {
        Self {
            region: String::from("us"),
        }
    }
}

/// Processes for submission to the US authorities
#[tonic::async_trait]
impl RegionInterface for super::RegionImpl {
    fn get_region(&self) -> &str {
        &self.region
    }

    fn submit_flight_plan(
        &self,
        request: FlightPlanRequest,
    ) -> Result<Response<FlightPlanResponse>, Status> {
        region_info!("(submit_flight_plan)[us] entry.");
        // TODO(R4) implement
        let flight_plan_id = request.flight_plan_id;
        Ok(Response::new(FlightPlanResponse {
            flight_plan_id,
            submitted: true,
            result: None,
        }))
    }

    fn request_flight_release(
        &self,
        request: Request<FlightReleaseRequest>,
    ) -> Result<Response<FlightReleaseResponse>, Status> {
        region_info!("(request_flight_release)[us] entry.");
        // TODO(R4) implement
        let flight_plan_id = request.into_inner().flight_plan_id;
        Ok(Response::new(FlightReleaseResponse {
            flight_plan_id,
            released: true,
            result: None,
        }))
    }

    async fn acquire_restrictions(&self, restrictions: &mut HashMap<String, RestrictionDetails>) {
        //
        // TODO(R4): This is currently hardcoded. This should be replaced with a call to
        //  an API.
        //
        let mut from_remote: HashMap<String, RestrictionDetails> = HashMap::new();

        let vertices = vec![
            (30.9310, -104.0424),
            (30.9316, -104.0399),
            (30.9301, -104.039),
            (30.9299, -104.0405),
            (30.9310, -104.0424),
        ];

        let Some(delta) = Duration::try_hours(1) else {
            region_error!("Failed to create duration");
            return;
        };

        from_remote.insert(
            "ARROW-USA-TFR-ZONE".to_string(),
            RestrictionDetails {
                vertices: vertices
                    .into_iter()
                    .map(|(latitude, longitude)| Coordinates {
                        latitude,
                        longitude,
                    })
                    .collect(),
                timestamp_end: Some(Utc::now() + delta),
                timestamp_start: Some(Utc::now()),
                altitude_meters_min: 0.0,
                altitude_meters_max: 2000.0,
                zone_type: ZoneType::Restriction,
            },
        );

        let vertices = vec![
            (30.9321, -104.0471),
            (30.9313, -104.0428),
            (30.9316, -104.042),
            (30.9332, -104.0399),
            (30.9319, -104.0398),
            (30.9326, -104.0374),
            (30.9352, -104.0394),
            (30.9341, -104.0465),
            (30.9321, -104.0471),
        ];

        from_remote.insert(
            "ARROW-USA-NOFLY-ZONE".to_string(),
            RestrictionDetails {
                vertices: vertices
                    .into_iter()
                    .map(|(latitude, longitude)| Coordinates {
                        latitude,
                        longitude,
                    })
                    .collect(),
                // altitude_meters_min: 0,
                // altitude_meters_max: 6000,
                timestamp_end: None,
                timestamp_start: None,
                altitude_meters_min: 0.0,
                altitude_meters_max: 200.0,
                zone_type: ZoneType::Restriction,
            },
        );

        //
        // END HARDCODE
        //

        restrictions.retain(|k, _| from_remote.contains_key(k));
        for (label, details) in from_remote.into_iter() {
            restrictions.insert(label, details);
        }
    }

    async fn acquire_waypoints(&self, waypoints: &mut HashMap<String, Coordinates>) {
        //
        // TODO(R4): This is currently hardcoded. This should be replaced with a call to an API
        //

        // West TX
        let from_remote: Vec<(f64, f64)> = vec![
            // Ideal waypoint around hardcoded flight restriction
            (30.9311, -104.0428),
            // waypoint within the hardcoded flight restriction
            (30.9308, -104.0412),
        ];

        let from_remote: HashMap<String, Coordinates> = from_remote
            .into_iter()
            .enumerate()
            .map(|(i, (longitude, latitude))| {
                (
                    format!("ARROW-WEG-{}", i),
                    Coordinates {
                        latitude,
                        longitude,
                    },
                )
            })
            .collect();

        //
        // END HARDCODE
        //

        waypoints.retain(|k, _| from_remote.contains_key(k));
        for (label, details) in from_remote.into_iter() {
            waypoints.insert(label, details);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::region::RegionImpl;

    #[tokio::test]
    async fn test_region_code() {
        crate::get_log_handle().await;
        ut_info!("(test_region_code)[us] Start.");

        let region_impl = RegionImpl::default();
        assert_eq!(region_impl.region, "us");

        ut_info!("(test_region_code)[us] Success.");
    }

    #[tokio::test]
    async fn test_submit_flight_plan() {
        crate::get_log_handle().await;
        ut_info!("(test_submit_flight_plan)[us] Start.");

        let region = RegionImpl::default();
        let result = region.submit_flight_plan(FlightPlanRequest {
            flight_plan_id: "".to_string(),
            data: "".to_string(),
        });

        assert!(result.is_ok());
        let result: FlightPlanResponse = result.unwrap().into_inner();
        ut_debug!("(test_submit_flight_plan)[us] Result: {:?}", result);
        assert_eq!(result.submitted, true);

        ut_info!("(test_submit_flight_plan)[us] Success.");
    }

    #[tokio::test]
    async fn test_request_flight_release() {
        crate::get_log_handle().await;
        ut_info!("(test_request_flight_release)[us] Start.");

        let region = RegionImpl::default();
        let result = region.request_flight_release(tonic::Request::new(FlightReleaseRequest {
            flight_plan_id: "".to_string(),
            data: "".to_string(),
        }));

        assert!(result.is_ok());
        let result: FlightReleaseResponse = result.unwrap().into_inner();
        ut_debug!("(test_request_flight_release)[us] Result: {:?}", result);
        assert_eq!(result.released, true);

        ut_info!("(test_request_flight_release)[us] Success.");
    }

    #[tokio::test]
    async fn test_acquire_restrictions() {
        crate::get_log_handle().await;
        ut_info!("(test_acquire_restrictions)[us] Start.");

        let region = RegionImpl::default();
        let mut cache = HashMap::<String, RestrictionDetails>::new();
        region.acquire_restrictions(&mut cache).await;
        ut_debug!("(test_acquire_restrictions)[us] Cache content: {:?}", cache);
        assert!(cache.keys().len() > 0);

        ut_info!("(test_acquire_restrictions)[us] Success.");
    }

    #[tokio::test]
    async fn test_refresh_waypoints() {
        crate::get_log_handle().await;
        ut_info!("(test_refresh_waypoints)[us] Start.");

        let region = RegionImpl::default();
        let mut cache = HashMap::<String, Coordinates>::new();
        region.acquire_waypoints(&mut cache).await;
        assert!(cache.keys().len() > 0);

        ut_info!("(test_refresh_waypoints)[us] Success.");
    }
}