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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
//! Support for executing tst.

use futures::future::FutureExt;

/// Result of executing a TST
pub type ExecutionResult<'a> = futures::future::BoxFuture<'a, Result<()>>;

use crate::definitions::tst as definitions_tst;
use crate::{utils, Error, Result};

// Error

// Traits

/// Trait representing the executors, used for dispatch
pub trait Executors: Sync
{
  /// Execute a sequential action
  fn execute_seq(&self, tst_node: definitions_tst::Seq) -> ExecutionResult;
  /// Execute a sequential action
  fn execute_conc(&self, tst_node: definitions_tst::Conc) -> ExecutionResult;
  /// Execute a move to action
  fn execute_move_to(&self, tst_node: definitions_tst::MoveTo) -> ExecutionResult;
  /// Execute a search area action
  fn execute_search_area(&self, tst_node: definitions_tst::SearchArea) -> ExecutionResult;
}

/// Executor trait
pub trait Executor<T>: Send
{
  /// Execute the node t
  fn execute<'a, 'b>(&'a self, executors: &'b impl Executors, t: T) -> ExecutionResult<'b>;
}

// Dispatch

fn dispatch_execution(
  executors: &impl Executors,
  tst_node: definitions_tst::Node,
) -> ExecutionResult
{
  match tst_node
  {
    definitions_tst::Node::Noop(noop) => async { Ok(()) }.boxed(),
    definitions_tst::Node::Seq(seq) => executors.execute_seq(seq),
    definitions_tst::Node::Conc(conc) => executors.execute_conc(conc),
    definitions_tst::Node::MoveTo(move_to) => executors.execute_move_to(move_to),
    definitions_tst::Node::SearchArea(search_area) => executors.execute_search_area(search_area),
  }
}

/// Sequential Executor
pub struct SeqExecutor;

impl Executor<definitions_tst::Seq> for SeqExecutor
{
  fn execute<'a, 'b>(
    &'a self,
    executors: &'b impl Executors,
    t: definitions_tst::Seq,
  ) -> ExecutionResult<'b>
  {
    async move {
      for sub_task in t.children.iter()
      {
        dispatch_execution(executors, sub_task.to_owned()).await?;
      }
      Ok::<(), Error>(())
    }
    .boxed()
  }
}

/// Concurrent Executor
pub struct ConcExecutor;

impl Executor<definitions_tst::Conc> for ConcExecutor
{
  fn execute<'a, 'b>(
    &'a self,
    executors: &'b impl Executors,
    t: definitions_tst::Conc,
  ) -> ExecutionResult<'b>
  {
    async move {
      let mut futures = vec![];
      for sub_task in t.children.iter()
      {
        futures.push(dispatch_execution(executors, sub_task.to_owned()));
      }
      futures::future::try_join_all(futures).await?;
      Ok::<(), Error>(())
    }
    .boxed()
  }
}

/// No Executor, it can be used for agent that don't implement some of the executors
pub struct NoExecutor<T: Send>
{
  ghost: std::marker::PhantomData<T>,
}

impl<T: Send> Executor<T> for NoExecutor<T>
{
  fn execute<'a, 'b>(&'a self, _executors: &'b impl Executors, _t: T) -> ExecutionResult<'b>
  {
    async move { Err::<(), Error>(Error::NoExecutor()) }.boxed()
  }
}

/// Agent trait for TST execution
pub trait Agent {}

/// Trait for creating executor for an agent
pub trait CreatableFromAgent<TAgent, T>
{
  /// Create an executor from an agent
  fn from_agent(agent: &TAgent) -> T;
}

impl<TAgent> CreatableFromAgent<TAgent, SeqExecutor> for SeqExecutor
{
  fn from_agent(_agent: &TAgent) -> SeqExecutor
  {
    SeqExecutor {}
  }
}
impl<TAgent> CreatableFromAgent<TAgent, ConcExecutor> for ConcExecutor
{
  fn from_agent(_agent: &TAgent) -> ConcExecutor
  {
    ConcExecutor {}
  }
}

impl<TAgent, T: Send> CreatableFromAgent<TAgent, NoExecutor<T>> for NoExecutor<T>
{
  fn from_agent(_agent: &TAgent) -> NoExecutor<T>
  {
    NoExecutor {
      ghost: Default::default(),
    }
  }
}

//     _                    _   _____                     _            _____            _ _
//    / \   __ _  ___ _ __ | |_| ____|_  _____  ___ _   _| |_ ___  _ _|_   _| __   __ _(_) |_
//   / _ \ / _` |/ _ \ '_ \| __|  _| \ \/ / _ \/ __| | | | __/ _ \| '__|| || '__| / _` | | __|
//  / ___ \ (_| |  __/ | | | |_| |___ >  <  __/ (__| |_| | || (_) | |   | || |   | (_| | | |_
// /_/   \_\__, |\___|_| |_|\__|_____/_/\_\___|\___|\__,_|\__\___/|_|   |_||_|    \__,_|_|\__|
//      |___/

/// Base trait for the AgentExecutor
pub trait AgentExecutorTrait
{
  /// Executor for sequential nodes
  type SeqExecutor: Executor<definitions_tst::Seq>;
  /// Executor for concurrent nodes
  type ConcExecutor: Executor<definitions_tst::Conc>;
  /// Executor for move_to nodes
  type MoveToExecutor: Executor<definitions_tst::MoveTo>;
  /// Executor for search area nodes
  type SearchAreaExecutor: Executor<definitions_tst::SearchArea>;

  /// Create a new executor for the given agent
  fn from_agent<TAgent>(agent: &TAgent) -> Self
  where
    Self::SeqExecutor: CreatableFromAgent<TAgent, Self::SeqExecutor>,
    Self::ConcExecutor: CreatableFromAgent<TAgent, Self::ConcExecutor>,
    Self::MoveToExecutor: CreatableFromAgent<TAgent, Self::MoveToExecutor>,
    Self::SearchAreaExecutor: CreatableFromAgent<TAgent, Self::SearchAreaExecutor>;
  /// Execute the tst
  fn execute(&self, t: definitions_tst::Node) -> ExecutionResult;
}

//     _                    _   _____                     _
//    / \   __ _  ___ _ __ | |_| ____|_  _____  ___ _   _| |_ ___  _ __
//   / _ \ / _` |/ _ \ '_ \| __|  _| \ \/ / _ \/ __| | | | __/ _ \| '__|
//  / ___ | (_| |  __/ | | | |_| |___ >  |  __/ (__| |_| | || (_) | |
// /_/   \_\__, |\___|_| |_|\__|_____/_/\_\___|\___|\__,_|\__\___/|_|
//         |___/

/// Executor of TST for an agent
pub struct AgentExecutor<
  TSeqExecutor: Executor<definitions_tst::Seq>,
  TConcExecutor: Executor<definitions_tst::Conc>,
  TMoveToExecutor: Executor<definitions_tst::MoveTo>,
  TSearchAreaExecutor: Executor<definitions_tst::SearchArea>,
> {
  seq_executor: utils::ArcMutex<TSeqExecutor>,
  conc_executor: utils::ArcMutex<TConcExecutor>,
  move_to_executor: utils::ArcMutex<TMoveToExecutor>,
  search_area_executor: utils::ArcMutex<TSearchAreaExecutor>,
}

impl<
    TSeqExecutor: Executor<definitions_tst::Seq>,
    TConcExecutor: Executor<definitions_tst::Conc>,
    TMoveToExecutor: Executor<definitions_tst::MoveTo>,
    TSearchAreaExecutor: Executor<definitions_tst::SearchArea>,
  > AgentExecutorTrait
  for AgentExecutor<TSeqExecutor, TConcExecutor, TMoveToExecutor, TSearchAreaExecutor>
{
  type SeqExecutor = TSeqExecutor;
  type ConcExecutor = TConcExecutor;
  type MoveToExecutor = TMoveToExecutor;
  type SearchAreaExecutor = TSearchAreaExecutor;
  fn from_agent<TAgent>(agent: &TAgent) -> Self
  where
    TSeqExecutor: CreatableFromAgent<TAgent, TSeqExecutor>,
    TConcExecutor: CreatableFromAgent<TAgent, TConcExecutor>,
    TMoveToExecutor: CreatableFromAgent<TAgent, TMoveToExecutor>,
    TSearchAreaExecutor: CreatableFromAgent<TAgent, TSearchAreaExecutor>,
  {
    Self {
      seq_executor: utils::arc_mutex_new(TSeqExecutor::from_agent(agent)),
      conc_executor: utils::arc_mutex_new(TConcExecutor::from_agent(agent)),
      move_to_executor: utils::arc_mutex_new(TMoveToExecutor::from_agent(agent)),
      search_area_executor: utils::arc_mutex_new(TSearchAreaExecutor::from_agent(agent)),
    }
  }
  fn execute(&self, t: definitions_tst::Node) -> ExecutionResult
  {
    dispatch_execution(self, t)
  }
}

impl<
    TSeqExecutor: Executor<definitions_tst::Seq>,
    TConcExecutor: Executor<definitions_tst::Conc>,
    TMoveToExecutor: Executor<definitions_tst::MoveTo>,
    TSearchAreaExecutor: Executor<definitions_tst::SearchArea>,
  > Executors for AgentExecutor<TSeqExecutor, TConcExecutor, TMoveToExecutor, TSearchAreaExecutor>
{
  fn execute_seq(&self, tst_node: definitions_tst::Seq) -> ExecutionResult
  {
    self.seq_executor.lock().unwrap().execute(self, tst_node)
  }
  fn execute_conc(&self, tst_node: definitions_tst::Conc) -> ExecutionResult
  {
    self.conc_executor.lock().unwrap().execute(self, tst_node)
  }
  fn execute_move_to(&self, tst_node: definitions_tst::MoveTo) -> ExecutionResult
  {
    self
      .move_to_executor
      .lock()
      .unwrap()
      .execute(self, tst_node)
  }
  fn execute_search_area(&self, tst_node: definitions_tst::SearchArea) -> ExecutionResult
  {
    self
      .search_area_executor
      .lock()
      .unwrap()
      .execute(self, tst_node)
  }
}

/// Agent executor with default for Sequence and Concurrent
pub type DefaultAgentExecutor<TMoveToExecutor, TSearchAreaExecutor> =
  AgentExecutor<SeqExecutor, ConcExecutor, TMoveToExecutor, TSearchAreaExecutor>;

#[cfg(test)]
mod tests
{
  struct FakeAgentPosition
  {
    longitude: f32,
    latitude: f32,
    altitude: f32,
  }
  struct FakeAgent
  {
    position: utils::ArcMutex<FakeAgentPosition>,
  }
  impl Agent for FakeAgent {}
  struct FakeAgentMoveToExecutor
  {
    position: utils::ArcMutex<FakeAgentPosition>,
  }
  impl CreatableFromAgent<FakeAgent, FakeAgentMoveToExecutor> for FakeAgentMoveToExecutor
  {
    fn from_agent(_agent: &FakeAgent) -> FakeAgentMoveToExecutor
    {
      FakeAgentMoveToExecutor {
        position: _agent.position.clone(),
      }
    }
  }
  impl Executor<definitions_tst::MoveTo> for FakeAgentMoveToExecutor
  {
    fn execute<'a, 'b>(
      &'a self,
      _executors: &'b impl Executors,
      t: definitions_tst::MoveTo,
    ) -> ExecutionResult<'b>
    {
      let pos = self.position.clone();
      async move {
        let mut p = pos.lock().unwrap();
        p.longitude = t.params.waypoint.longitude;
        p.latitude = t.params.waypoint.latitude;
        p.altitude = t.params.waypoint.altitude;
        Ok::<(), Error>(())
      }
      .boxed()
    }
  }
  use super::*;

  #[test]
  fn execute()
  {
    let node: definitions_tst::Node = definitions_tst::Seq::build(None)
      .add(
        definitions_tst::MoveToParameters {
          waypoint: definitions_tst::GeoPoint {
            longitude: 16.4,
            latitude: 59.3,
            altitude: 110.8,
          },
          ..Default::default()
        },
        None,
      )
      .add(
        definitions_tst::MoveToParameters {
          waypoint: definitions_tst::GeoPoint {
            longitude: 16.5,
            latitude: 59.5,
            altitude: 110.7,
          },
          ..Default::default()
        },
        None,
      )
      .into();

    let agent = FakeAgent {
      position: utils::arc_mutex_new(FakeAgentPosition {
        longitude: 0.0,
        latitude: 0.0,
        altitude: 0.0,
      }),
    };
    let executor = AgentExecutor::<
      SeqExecutor,
      ConcExecutor,
      FakeAgentMoveToExecutor,
      NoExecutor<definitions_tst::SearchArea>,
    >::from_agent(&agent);
    let r = executor.execute(node);
    let res = futures::executor::block_on(r);
    assert!(res.is_ok());
    let p = agent.position.lock().unwrap();
    assert_eq!(p.longitude, 16.5);
    assert_eq!(p.latitude, 59.5);
    assert_eq!(p.altitude, 110.7);
  }
}