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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Definitions of tsts, for de/serialization and manipulation.

use std::default;

use crate::uuid;
use enum_dispatch::enum_dispatch;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;

mod consts;

//  __  __ _            ____  _                   _
// |  \/  (_)___  ___  / ___|| |_ _ __ _   _  ___| |_ _   _ _ __ ___  ___
// | |\/| | / __|/ __| \___ \| __| '__| | | |/ __| __| | | | '__/ _ \/ __|
// | |  | | \__ \ (__   ___) | |_| |  | |_| | (__| |_| |_| | | |  __/\__ \
// |_|  |_|_|___/\___| |____/ \__|_|   \__,_|\___|\__|\__,_|_|  \___||___/

/// Represent a geographic point in the world
#[derive(Serialize, Deserialize, Debug, Default, PartialEq, Clone)]
pub struct GeoPoint
{
  /// longitude of the point
  pub longitude: f32,
  /// latitude of the point
  pub latitude: f32,
  /// altitude of the point
  pub altitude: f32,
}

/// Represent a speed in a tst, some of the values are platform specific
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
pub enum Speed
{
  /// A fast speed
  #[serde(rename = "fast")]
  Fast,
  /// The standard speed for the platform, a balance between speed and fuel efficiency
  #[serde(rename = "standard")]
  #[default]
  Standard,
  /// A slow speed
  #[serde(rename = "slow")]
  Slow,
  /// A maximum speed specified as m/s
  #[serde(rename = "max-speed")]
  MaxSpeed(f32),
}

//  _   _           _
// | \ | | ___   __| | ___
// |  \| |/ _ \ / _` |/ _ \
// | |\  | (_) | (_| |  __/
// |_| \_|\___/ \__,_|\___|

/// Represent a TST node
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "name")]
#[enum_dispatch(NodeTrait)]
pub enum Node
{
  /// Noop node
  #[serde(rename = "noop")]
  Noop(Noop),
  /// Sequential node
  #[serde(rename = "seq")]
  Seq(Seq),
  /// Concurrent node
  #[serde(rename = "conc")]
  Conc(Conc),
  /// MoveTo node
  #[serde(rename = "move-to")]
  MoveTo(MoveTo),
  /// SearchArea node
  #[serde(rename = "search-area")]
  SearchArea(SearchArea),
}

impl Node
{
  /// Convenient function to convert a node to a JSON string
  pub fn to_json_string(&self) -> serde_json::Result<String>
  {
    serde_json::to_string(self)
  }
  /// Convenient function to convert a JSON string to a node
  pub fn from_json_string(def: &String) -> serde_json::Result<Node>
  {
    serde_json::from_str(def)
  }
}

impl Default for Node
{
  fn default() -> Self
  {
    Self::Noop(Noop::default())
  }
}

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

/// Parameters common to all the nodes
#[skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct CommonParameters
{
  /// Unique identifier for the node
  pub node_uuid: uuid::Uuid,
  /// Execution unit
  pub execunit: Option<String>,
}

/// Parameters for the move to tst
#[skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct MoveToParameters
{
  /// Destination
  pub waypoint: GeoPoint,
  /// Optional speed
  pub speed: Option<Speed>,
}

/// Parmeters for the search area test
#[skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct SearchAreaParameters
{
  /// Polygon to explore
  pub area: Vec<GeoPoint>,
  /// Optional speed
  pub speed: Option<Speed>,
}

/// Use for nodes without parameters
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct NoParameters {}

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

/// This class is used to build tsts
#[allow(private_bounds)]
#[derive(Debug, Clone)]
pub struct NodeBuilder<T: CompositeNode, P: NodeBuilderTrait>
{
  t: std::rc::Rc<std::cell::RefCell<T>>,
  p: Option<P>,
}

/// Root null builder
#[derive(Clone)]
pub struct NullNodeBuilder;

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

trait NodeBuilderTrait: Clone
{
  fn append_child(&mut self, node: impl Into<Node>);
}

/// Base trait for nodes
#[enum_dispatch]
pub trait NodeTrait: Clone + Into<Node> + Default
{
  fn common_params_ref(&self) -> &CommonParameters;
  fn set_common_params(&mut self, params: CommonParameters);
}

trait CompositeNode: NodeTrait
{
  fn append_child(&mut self, node: impl Into<Node>);
}

trait LeafNode: NodeTrait
{
  type ParametersType: Clone + Default;
  fn set_params(&mut self, params: Self::ParametersType);
}

trait LeafNodeParameters
{
  type NodeType: Default + LeafNode + Into<Node>;
}

// Nodes

macro_rules! define_composite_node {
  ($node_type:ident, $node_enum_type:path) => {
    /// Node for $node_type
    #[derive(Serialize, Deserialize, Debug, Clone, Default)]
    pub struct $node_type
    {
      /// Common parameters
      pub common_params: CommonParameters,
      /// Childrent of the composite node
      pub children: Vec<Node>,
    }
    impl $node_type
    {
      /// Create a builder with optional common params
      #[allow(private_interfaces)]
      pub fn build(
        common_params: Option<CommonParameters>,
      ) -> NodeBuilder<$node_type, NullNodeBuilder>
      {
        let mut t = $node_type::default();
        if let Some(common_params) = common_params
        {
          t.common_params = common_params;
        }

        NodeBuilder::<$node_type, NullNodeBuilder> {
          t: std::rc::Rc::new(std::cell::RefCell::new(t)),
          p: None,
        }
      }
    }
    impl NodeTrait for $node_type
    {
      fn common_params_ref(&self) -> &CommonParameters
      {
        &self.common_params
      }
      fn set_common_params(&mut self, common_params: CommonParameters)
      {
        self.common_params = common_params;
      }
    }
    impl CompositeNode for $node_type
    {
      fn append_child(&mut self, node: impl Into<Node>)
      {
        self.children.push(node.into());
      }
    }
  };
}

macro_rules! define_leaf_node {
  ($node_type:ident, $node_parameters_type:ident, $node_enum_type:path) => {
    #[derive(Serialize, Deserialize, Debug, Clone, Default)]
    /// Node for $node_type
    pub struct $node_type
    {
      /// Common parameters
      pub common_params: CommonParameters,
      /// Parameters specific to the node
      pub params: $node_parameters_type,
    }
    impl NodeTrait for $node_type
    {
      fn common_params_ref(&self) -> &CommonParameters
      {
        &self.common_params
      }
      fn set_common_params(&mut self, common_params: CommonParameters)
      {
        self.common_params = common_params;
      }
    }
    impl LeafNode for $node_type
    {
      type ParametersType = $node_parameters_type;
      fn set_params(&mut self, params: Self::ParametersType)
      {
        self.params = params;
      }
    }
    impl LeafNodeParameters for $node_parameters_type
    {
      type NodeType = $node_type;
    }
  };
}

define_composite_node!(Seq, Node::Seq);
define_composite_node!(Conc, Node::Conc);

define_leaf_node!(MoveTo, MoveToParameters, Node::MoveTo);
define_leaf_node!(SearchArea, SearchAreaParameters, Node::SearchArea);
define_leaf_node!(Noop, NoParameters, Node::Noop);

// Implementation

/// Trait used to compute the velocity
pub trait SpeedCompute
{
  /// Compute the actual velocity based on the maximum velocity of the platform
  fn compute_velocity(&self, max_velocity: f32) -> f32;
}

impl SpeedCompute for Option<Speed>
{
  fn compute_velocity(&self, max_velocity: f32) -> f32
  {
    match self
    {
      Some(v) => match v
      {
        Speed::Slow => consts::VELOCITY_SLOW_RATIO * max_velocity,
        Speed::Standard => consts::VELOCITY_STANDARD_RATIO * max_velocity,
        Speed::Fast => consts::VELOCITY_FAST_RATIO * max_velocity,
        Speed::MaxSpeed(s) => s.min(max_velocity),
      },
      None => consts::VELOCITY_STANDARD_RATIO * max_velocity,
    }
  }
}

#[allow(missing_docs)]
#[inline]
pub fn default<T: Default>() -> T
{
  Default::default()
}

impl NodeBuilderTrait for NullNodeBuilder
{
  fn append_child(&mut self, _node: impl Into<Node>)
  {
    panic!("Cannot add child to null builder.");
  }
}

impl<T: CompositeNode, P: NodeBuilderTrait> NodeBuilderTrait for NodeBuilder<T, P>
{
  fn append_child(&mut self, node: impl Into<Node>)
  {
    self.t.borrow_mut().append_child(node);
  }
}

#[allow(private_bounds)]
impl<T: CompositeNode, P: NodeBuilderTrait> NodeBuilder<T, P>
{
  /// Start a composite node, must be followed by end
  pub fn start<U: CompositeNode>(
    self,
    cp: Option<CommonParameters>,
  ) -> NodeBuilder<U, NodeBuilder<T, P>>
  {
    let mut t = U::default();
    if let Some(cp) = cp
    {
      t.set_common_params(cp);
    }
    NodeBuilder::<U, NodeBuilder<T, P>> {
      t: std::rc::Rc::new(std::cell::RefCell::new(t)),
      p: Some(self),
    }
  }
  /// end a composite node
  pub fn end(self) -> P
  {
    let mut p = self.p.unwrap();
    p.append_child(self.t.borrow().to_owned());
    p
  }
  /// Add a leaf node
  #[allow(private_interfaces)]
  pub fn add<U>(self, p: U, cp: Option<CommonParameters>) -> Self
  where
    U: LeafNodeParameters + Into<<<U as LeafNodeParameters>::NodeType as LeafNode>::ParametersType>,
  {
    let mut t = U::NodeType::default();
    t.set_params(p.into());
    if let Some(cp) = cp
    {
      t.set_common_params(cp);
    }
    self.t.borrow_mut().append_child(t);
    self
  }
  fn to_t(&self) -> T
  {
    self.t.borrow().clone()
  }
}

impl<T: CompositeNode, U: NodeBuilderTrait> From<NodeBuilder<T, U>> for Node
where
  T: Into<Node>,
{
  fn from(value: NodeBuilder<T, U>) -> Self
  {
    value.to_t().into()
  }
}

// Tests

#[cfg(test)]
mod tests
{
  use crate::definitions::tst::CommonParameters;

  use super::GeoPoint;

  macro_rules! get_tst_node {
    ($value:expr, $variant:path) => {
      match $value
      {
        $variant(x) => x,
        _ => panic!("Unexpected TST Node."),
      }
    };
  }

  macro_rules! check_speed {
    ($value:expr, $variant:path) => {
      match $value.params.speed.as_ref().unwrap()
      {
        $variant => (),
        _ => panic!("Wrong speed"),
      }
    };
  }

  macro_rules! check_max_speed {
    ($value:expr, $max_speed:expr) => {
      match $value.params.speed.as_ref().unwrap()
      {
        super::Speed::MaxSpeed(v) => assert_eq!(*v, $max_speed),
        _ => panic!("Wrong speed"),
      }
    };
  }

  fn mgp(longitude: f32, latitude: f32, altitude: f32) -> GeoPoint
  {
    GeoPoint {
      longitude: longitude,
      latitude: latitude,
      altitude: altitude,
    }
  }
  #[test]
  fn parse_test_tst()
  {
    let mut d = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    d.push("data/test_tst.json");
    let message: String = std::fs::read_to_string(d).unwrap();
    let node: super::Node = serde_json::from_str(&message).unwrap();
    let node_seq = get_tst_node!(node, super::Node::Seq);

    // First move
    let seq_move_to_0 = get_tst_node!(&node_seq.children[0], super::Node::MoveTo);
    assert_eq!(
      seq_move_to_0.params.waypoint,
      mgp(15.570883999999998, 58.394741999999994, 100.8)
    );
    check_speed!(seq_move_to_0, super::Speed::Standard);

    // Concurrent
    let seq_conc = get_tst_node!(&node_seq.children[1], super::Node::Conc);
    let conc_searc_area = get_tst_node!(&seq_conc.children[0], super::Node::SearchArea);
    assert_eq!(
      conc_searc_area.params.area[0],
      mgp(15.570883999999998, 58.394741999999994, 100.8)
    );
    assert_eq!(
      conc_searc_area.params.area[1],
      mgp(15.570883999999998, 58.304741999999994, 100.8)
    );
    assert_eq!(
      conc_searc_area.params.area[2],
      mgp(15.500883999999998, 58.304741999999994, 100.8)
    );
    check_max_speed!(conc_searc_area, 10.0);

    let conc_move_to = get_tst_node!(&seq_conc.children[1], super::Node::MoveTo);
    assert_eq!(
      conc_move_to.params.waypoint,
      mgp(15.571883999999998, 58.394742999999994, 100.8)
    );
    assert!(conc_move_to.params.speed.is_none());

    // Second move
    let seq_move_to_2 = get_tst_node!(&node_seq.children[2], super::Node::MoveTo);
    assert_eq!(
      seq_move_to_2.params.waypoint,
      mgp(16.572883999999998, 59.394741999999994, 110.8)
    );
    check_speed!(seq_move_to_2, super::Speed::Fast);
  }
  #[test]
  fn gen_tst()
  {
    let node = super::Node::Seq(super::Seq {
      common_params: CommonParameters {
        node_uuid: crate::uuid::Uuid::from_string("f3bab5e0-a861-4f6e-bf28-37c9e3470181").unwrap(),
        ..Default::default()
      },
      ..Default::default()
    });
    assert_eq!(
      serde_json::to_string(&node).unwrap(),
      r#"{"name":"seq","common_params":{"node_uuid":"f3bab5e0-a861-4f6e-bf28-37c9e3470181"},"children":[]}"#
    );
  }
  #[test]
  fn test_builder()
  {
    let node: super::Node = super::Conc::build(Some(CommonParameters {
      node_uuid: crate::uuid::Uuid::from_string("68eb7e83-cc44-4404-bdb1-2fd66ffcbf1c").unwrap(),
      ..Default::default()
    }))
    .start::<super::Seq>(Some(CommonParameters {
      node_uuid: crate::uuid::Uuid::from_string("a5665c27-e2c6-442f-8ab3-357aa4427945").unwrap(),
      ..Default::default()
    }))
    .add(
      super::MoveToParameters {
        waypoint: GeoPoint {
          longitude: 16.4,
          latitude: 59.3,
          altitude: 110.8,
        },

        ..super::default()
      },
      Some(CommonParameters {
        node_uuid: crate::uuid::Uuid::from_string("0cd50294-611a-4da6-b398-73b0f2e0ee7c").unwrap(),
        ..Default::default()
      }),
    )
    .add(
      super::MoveToParameters {
        waypoint: GeoPoint {
          longitude: 16.5,
          latitude: 59.5,
          altitude: 110.7,
        },
        ..super::default()
      },
      Some(CommonParameters {
        node_uuid: crate::uuid::Uuid::from_string("47288783-cfbd-48ad-9bb9-734fae54d2be").unwrap(),
        ..Default::default()
      }),
    )
    .end()
    .add(
      super::MoveToParameters {
        waypoint: GeoPoint {
          longitude: 16.6,
          latitude: 59.4,
          altitude: 110.9,
        },
        ..super::default()
      },
      Some(CommonParameters {
        node_uuid: crate::uuid::Uuid::from_string("88eae25f-473f-4185-bfcb-ca3ee0ed2247").unwrap(),
        ..Default::default()
      }),
    )
    .into();
    assert_eq!(
      serde_json::to_string(&node).unwrap(),
      r#"{"name":"conc","common_params":{"node_uuid":"68eb7e83-cc44-4404-bdb1-2fd66ffcbf1c"},"children":[{"name":"seq","common_params":{"node_uuid":"a5665c27-e2c6-442f-8ab3-357aa4427945"},"children":[{"name":"move-to","common_params":{"node_uuid":"0cd50294-611a-4da6-b398-73b0f2e0ee7c"},"params":{"waypoint":{"longitude":16.4,"latitude":59.3,"altitude":110.8}}},{"name":"move-to","common_params":{"node_uuid":"47288783-cfbd-48ad-9bb9-734fae54d2be"},"params":{"waypoint":{"longitude":16.5,"latitude":59.5,"altitude":110.7}}}]},{"name":"move-to","common_params":{"node_uuid":"88eae25f-473f-4185-bfcb-ca3ee0ed2247"},"params":{"waypoint":{"longitude":16.6,"latitude":59.4,"altitude":110.9}}}]}"#
    );
  }
}