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
// Copyright (c) 2022-2023, Radu Racariu.

use crate::base::block::{Block, BlockDesc, BlockProps, BlockStaticDesc};
use crate::base::input::InputProps;

use crate::base::engine::Engine;
use crate::blocks::control::Pid;
use crate::blocks::logic::{
    And, Equal, GreaterThan, GreaterThanEq, LessThan, LessThanEq, Not, NotEqual, Or, Xor,
};
use crate::blocks::math::{Abs, Add, ArcTan, Cos, Sub};
use crate::blocks::math::{
    ArcCos, ArcSin, Average, Div, Even, Exp, Log10, Logn, Max, Median, Min, Mod, Mul, Neg, Odd,
    Pow, Sin, Sqrt,
};
use crate::blocks::misc::{Random, SineWave};
use crate::blocks::string::StrLen;

use anyhow::{anyhow, Result};
use lazy_static::lazy_static;
use std::collections::BTreeMap;
use std::sync::Mutex;

use super::misc::ParseNumber;
use super::InputImpl;

pub(crate) type DynBlockProps = dyn BlockProps<
    Reader = <InputImpl as InputProps>::Reader,
    Writer = <InputImpl as InputProps>::Writer,
>;
type MapType = BTreeMap<String, BlockEntry>;
type BlockRegistry = Mutex<MapType>;

/// Register a block in the registry
pub struct BlockEntry {
    pub desc: BlockDesc,
    pub make: Option<fn() -> Box<DynBlockProps>>,
}

/// Macro for statically registering all the blocks that are
/// available in the system.
#[macro_export]
macro_rules! register_blocks{
    ( $( $x:ty ),* ) => {
		lazy_static! {
			/// The block registry
			/// This is a static variable that is initialized once and then
			/// used throughout the lifetime of the program.
			pub static ref  BLOCKS: BlockRegistry = {
				let mut reg = BTreeMap::new();

				$(
					register_impl::<$x>(&mut reg);
				)*

				reg.into()
			};
		}

		/// Schedule a block by name.
		/// If the block name is valid, it will be scheduled on the engine.
		/// The engine will execute the block if the engine is running.
		/// This requires that the block is statically registered.
		///
		/// # Arguments
		/// - name: The name of the block to schedule
		/// - eng: The engine to schedule the block on
		/// # Returns
		/// A result indicating success or failure
		pub fn schedule_block<E>(name: &str, eng: &mut E) -> Result<uuid::Uuid>
		where E : Engine<Reader = <InputImpl as InputProps>::Reader, Writer = <InputImpl as InputProps>::Writer> {

			match name {
				$(
					stringify!($x) => {
						let block = <$x>::new();
						let uuid = *block.id();
						eng.schedule(block);
						Ok(uuid)
					}
				)*
				_ => {
					return Err(anyhow!("Block not found"));
				}
			}

		}

		/// Schedule a block by name and UUID.
		/// See [`schedule_block`] for more details.
		pub fn schedule_block_with_uuid<E>(name: &str, uuid: uuid::Uuid, eng: &mut E) -> Result<uuid::Uuid>
		where E : Engine<Reader = <InputImpl as InputProps>::Reader, Writer = <InputImpl as InputProps>::Writer> {

			match name {
				$(
					stringify!($x) => {
						let block = <$x>::new_uuid(uuid);
						eng.schedule(block);
						Ok(uuid)
					}
				)*
				_ => {
					return Err(anyhow!("Block not found"));
				}
			}

		}
    };
}

register_blocks!(
    // Logic blocks
    And,
    Or,
    Not,
    Equal,
    NotEqual,
    Xor,
    GreaterThan,
    GreaterThanEq,
    LessThan,
    LessThanEq,
    // Math blocks
    Abs,
    Add,
    ArcCos,
    ArcTan,
    Average,
    Median,
    Even,
    Odd,
    Sub,
    Mul,
    Div,
    Exp,
    Cos,
    ArcSin,
    Sin,
    Log10,
    Logn,
    Sqrt,
    Pow,
    Mod,
    Min,
    Max,
    Neg,
    // Control blocks
    Pid,
    // String blocks
    StrLen,
    // Misc blocks
    Random,
    SineWave,
    ParseNumber
);

/// Construct a block properties from the registry
/// # Arguments
/// - name: The name of the block to get
/// # Returns
/// A boxed block
pub fn make(name: &str) -> Option<Box<DynBlockProps>> {
    let reg = BLOCKS.lock().expect("Block registry is locked");

    if let Some(data) = reg.get(name) {
        data.make.map(|make| make())
    } else {
        None
    }
}

/// Register a block with the registry
/// # Arguments
/// - B: The block type to register
/// # Panics
/// Panics if the block registry is already locked
pub fn register<
    B: Block<
            Reader = <InputImpl as InputProps>::Reader,
            Writer = <InputImpl as InputProps>::Writer,
        > + Default
        + 'static,
>() {
    let mut reg = BLOCKS.lock().expect("Block registry is locked");

    register_impl::<B>(&mut reg);
}

fn register_impl<
    B: Block<
            Reader = <InputImpl as InputProps>::Reader,
            Writer = <InputImpl as InputProps>::Writer,
        > + Default
        + 'static,
>(
    reg: &mut MapType,
) {
    reg.insert(<B as BlockStaticDesc>::desc().name.clone(), {
        let desc = <B as BlockStaticDesc>::desc();
        let make = || -> Box<DynBlockProps> {
            let block = B::default();
            Box::new(block)
        };

        BlockEntry {
            desc: desc.clone(),
            make: Some(make),
        }
    });
}

#[cfg(test)]
mod test {

    use crate::base::block::connect::connect_output;

    use super::*;

    #[test]
    fn test_registry() {
        let mut add = make("Add").expect("Add block not found");
        let mut random = make("Random").expect("Random block not found");
        let sine = make("SineWave").expect("SineWave block not found");

        assert_eq!(add.desc().name, "Add");
        assert_eq!(random.desc().name, "Random");
        assert_eq!(sine.desc().name, "SineWave");

        let mut outs = random.outputs_mut();
        let mut ins = add.inputs_mut();

        let out = outs.first_mut().unwrap();
        let input = ins.first_mut().unwrap();

        connect_output(*out, *input).unwrap();

        let mut eng = crate::single_threaded::SingleThreadedEngine::new();

        schedule_block("Add", &mut eng).expect("Block");

        assert!(eng.blocks().iter().any(|b| b.desc().name == "Add"));
    }
}