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
//! Automation service.
//!
//! Automation _is not_ a special core functionality. Instead, it's implemented as a service,
//! that listens to other services messages and reacts by emitting its own messages.
//!
//! The latter ones, automator-generated messages, are treated in the same way, allowing those to be
//! displayed on the dashboard or caught by other services.
//!
//! Basically, this is a case of "multi-producer multi-consumer" pattern.

use crate::prelude::*;
use crate::supervisor;
use crossbeam_channel::Sender;
use log::{debug, info};
use serde::Deserialize;
use std::sync::{Arc, Mutex};

/// Automator settings.
#[derive(Deserialize, Debug, Clone)]
pub struct Settings {
    scenarios: Vec<Scenario>,
}

pub fn spawn(
    service_id: &str,
    settings: &Settings,
    db: &Arc<Mutex<Db>>,
    outbox_tx: &Sender<Message>,
) -> Result<Vec<Sender<Message>>> {
    let outbox_tx = outbox_tx.clone();
    let db = db.clone();
    let service_id = service_id.to_string();
    let settings = settings.clone();

    let (inbox_tx, inbox_rx) = crossbeam_channel::unbounded::<Message>();

    supervisor::spawn(
        format!("my-iot::automator::{}", &service_id),
        outbox_tx.clone(),
        move || {
            for message in &inbox_rx {
                for scenario in settings.scenarios.iter() {
                    if scenario.conditions.iter().all(|c| c.is_met(&message)) {
                        info!(r"{} triggered scenario: {}", &message.sensor, scenario.description);
                        for action in scenario.actions.iter() {
                            action.execute(&service_id, &db, &message, &outbox_tx).unwrap();
                        }
                    } else {
                        debug!("Skipped: {}", &message.sensor);
                    }
                }
            }
            unreachable!();
        },
    )?;

    Ok(vec![inbox_tx])
}

/// Single automation scenario.
#[derive(Deserialize, Debug, Clone)]
pub struct Scenario {
    /// User-defined description. Brings no functional effect, but helps to debug scenarios.
    #[serde(default = "String::new")]
    description: String,

    /// Conditions which trigger a scenario to run. All of them must be met in order to trigger
    /// the scenario.
    #[serde(default = "Vec::new")]
    conditions: Vec<Condition>,

    /// Actions executed when scenario is run.
    #[serde(default = "Vec::new")]
    actions: Vec<Action>,
}

#[derive(Deserialize, Debug, Clone)]
pub enum Condition {
    /// Sensor matches a specified string.
    Sensor(String),

    /// Sensor ends with a specified string.
    SensorEndsWith(String),

    /// Sensor starts with a specified string.
    SensorStartsWith(String),

    /// Sensor contains a specified string.
    SensorContains(String),

    /// At least one of conditions is met.
    Or(Vec<Condition>),
}

impl Condition {
    pub fn is_met(&self, message: &Message) -> bool {
        match self {
            Condition::Sensor(sensor) => &message.sensor == sensor,
            Condition::SensorEndsWith(suffix) => message.sensor.ends_with(suffix),
            Condition::SensorStartsWith(prefix) => message.sensor.starts_with(prefix),
            Condition::SensorContains(infix) => message.sensor.contains(infix),
            Condition::Or(conditions) => conditions.iter().any(|c| c.is_met(&message)),
        }
    }
}

#[derive(Deserialize, Debug, Clone)]
#[serde(tag = "action")]
pub enum Action {
    /// Emit a message with the original value and custom message type and sensor.
    Repeat(RepeatParameters),

    /// Read the last sensor value and emit a message with the same value but custom sensor and type.
    /// If the former is missing, then no message will be sent.
    ReadSensor(ReadSensorParameters),
}

#[derive(Deserialize, Debug, Clone)]
pub struct RepeatParameters {
    target_type: MessageType,
    target_sensor: String,
}

#[derive(Deserialize, Debug, Clone)]
pub struct ReadSensorParameters {
    source_sensor: String,
    target_type: MessageType,
    target_sensor: String,
}

impl Action {
    pub fn execute(
        &self,
        _service_id: &str,
        db: &Arc<Mutex<Db>>,
        message: &Message,
        tx: &Sender<Message>,
    ) -> Result<()> {
        match self {
            Action::Repeat(parameters) => {
                tx.send(
                    Composer::new(&parameters.target_sensor)
                        .type_(parameters.target_type)
                        .value(message.value.clone())
                        .into(),
                )?;
                Ok(())
            }
            Action::ReadSensor(parameters) => {
                if let Some(source) = db.lock().unwrap().select_last_reading(&parameters.source_sensor)? {
                    tx.send(
                        Composer::new(&parameters.target_sensor)
                            .type_(parameters.target_type)
                            .value(source.value.clone())
                            .into(),
                    )?
                }
                Ok(())
            }
        }
    }
}