logic_mesh/blocks/misc/
sinewave.rs

1// Copyright (c) 2022-2023, Radu Racariu.
2
3use std::time::Duration;
4
5use uuid::Uuid;
6
7use crate::base::output::props::OutputProps;
8use crate::{
9    base::{
10        block::{Block, BlockDesc, BlockProps, BlockState},
11        input::{input_reader::InputReader, Input, InputProps},
12        output::Output,
13    },
14    blocks::utils::{input_as_float_or_default, input_to_millis_or_default},
15};
16
17use libhaystack::val::kind::HaystackKind;
18
19use crate::blocks::{InputImpl, OutputImpl};
20
21/// Block that generates a sine wave based on
22/// the frequency and the amplitude inputs.
23#[block]
24#[derive(BlockProps, Debug)]
25#[category = "misc"]
26pub struct SineWave {
27    #[input(kind = "Number")]
28    pub freq: InputImpl,
29    #[input(kind = "Number")]
30    pub amplitude: InputImpl,
31    #[output(kind = "Number")]
32    pub out: OutputImpl,
33    count: f64,
34}
35
36impl Block for SineWave {
37    async fn execute(&mut self) {
38        let millis = input_to_millis_or_default(&self.freq.val);
39
40        self.wait_on_inputs(Duration::from_millis(millis)).await;
41
42        if !self.out.is_connected() {
43            return;
44        }
45
46        let millis = input_to_millis_or_default(&self.freq.val);
47
48        let amp = input_as_float_or_default(&self.amplitude);
49        let amp = if amp == 0.0 { 1.0 } else { amp };
50
51        let res = amp * (self.count / millis as f64).sin();
52
53        self.count += 1.0;
54        self.out.set(res.into());
55    }
56}