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
//! A bin that outputs the values of a XIO job run.
//!
//! ```text
//!   ┌────[xiosource]────┐
//!   │         <output 0>│⇒
//!   │         <output 1>│⇒
//!   │         <output 2>│⇒
//!   ┊         …         ┊⇒
//!   │         <output n>│⇒
//!   └───────────────────┘
//! ```

use crate::bins::{
    BinDescription, Iteration, SourceBin, SourceId, SourceNames,
    SourceOnlyBin, SourceOnlyBinDescription,
};
use crate::{error, GetCalibration, Item, Proceed, Result, Scope};
use crossbeam_channel::Receiver;
use indexmap::{IndexMap, IndexSet};
use snafu::ensure;
use snafu::OptionExt;

/// The current internal state of the bin.
#[derive(Clone, Debug)]
pub enum BinState {
    /// Initialized, waiting for the `Started` event.
    Initialized,
    /// Job was Started, waiting for the `MeasurementData` or `Finished`
    /// event.
    WaitingForData {
        /// The tags received by the `Started` event.
        tags: IndexMap<String, Vec<String>>,
    },
    /// Already received some data, waiting for more `MeasurementData`
    /// events or a `Finished` event.
    Running {
        /// The tags received by the `Started` event.
        tags: IndexMap<String, Vec<String>>,
        /// The last measurement data row.
        data: IndexMap<String, Item>,
    },
    /// Finished state, the measurement was successfully finished.
    Finished,
    /// Failed state, something went wrong.
    Failed,
}

/// Description of the xiosource bin.
#[derive(Debug)]
pub struct Description {
    /// The mapping of `MeasurementData` tags to the output sources.
    pub mapping: IndexMap<String, IndexMap<String, String>>,
    /// The receiver from which the job events get fetched.
    pub receiver: Receiver<xio_webapi::JobEvent>,
}

#[derive(Debug)]
struct XioDataSource {
    tag: String,
    field: String,
}

/// A bin that outputs the values of a XIO job run.
#[derive(Debug)]
pub struct Bin {
    scope: Scope,
    xio_sources: IndexMap<String, XioDataSource>,
    receiver: Receiver<xio_webapi::JobEvent>,
    state: BinState,
}

static BIN_TYPE: &str = "xio_arnalisa";

impl BinDescription for Description {
    type Bin = Bin;

    fn check_validity(
        &self,
        _scope: &Scope,
        _get_calibration: &mut dyn GetCalibration,
    ) -> Result<()> {
        // TODO: implement validity check
        Ok(())
    }

    fn bin_type(&self) -> &'static str {
        BIN_TYPE
    }
}

impl SourceNames for Description {
    fn source_names(&self) -> Result<IndexSet<String>> {
        Ok(self
            .mapping
            .iter()
            .map(|(_k, v)| v.iter())
            .flatten()
            .map(|(_k, v)| v.to_string())
            .collect())
    }
}

impl Description {
    fn build_xio_sources(
        &self,
    ) -> Result<IndexMap<String, XioDataSource>> {
        let mut s = IndexMap::new();

        for (tag, mapping) in self.mapping.iter() {
            for (xio_source, arnalisa_sink) in mapping {
                let entry = s.entry(arnalisa_sink.to_string());
                use indexmap::map::Entry as E;
                match entry {
                    E::Occupied(_) => {
                        error::XioMappingDuplicateSource {
                            mapping: self.mapping.clone(),
                            name: arnalisa_sink.to_string(),
                        }
                        .fail()?;
                    }
                    E::Vacant(v) => {
                        v.insert(XioDataSource {
                            tag: tag.to_string(),
                            field: xio_source.to_string(),
                        });
                    }
                }
            }
        }

        Ok(s)
    }
}

impl SourceOnlyBinDescription for Description {
    fn build_bin(&self, scope: &Scope) -> Result<Self::Bin> {
        // TODO: add required
        Ok(Bin {
            scope: scope.clone(),
            xio_sources: self.build_xio_sources()?,
            receiver: self.receiver.clone(),
            state: BinState::Initialized,
        })
    }
}

impl SourceBin for Bin {
    fn get_source_data(&self, source: &SourceId) -> Result<Item> {
        match &self.state {
            BinState::Running { data, .. } => data
                .get(&source.id)
                .context(error::InvalidSourceName {
                    scope: self.scope.clone(),
                    name: source.id.to_string(),
                    bin_type: BIN_TYPE.to_string(),
                })
                .map(|item| item.clone()),
            current_state => error::XioGettingDataWhileNotInRunningState {
                current_state: current_state.clone(),
            }
            .fail(),
        }
    }
}

impl Bin {
    fn build_data(
        &self,
        tags: &IndexMap<String, Vec<String>>,
        tag: String,
        data: Vec<xio_base_datatypes::DataValueDescriptive>,
    ) -> Result<IndexMap<String, Item>> {
        let column_names =
            tags.get(&tag).context(error::XioTagNotAvailable {
                tag: tag.to_string(),
                available: tags
                    .keys()
                    .cloned()
                    .collect::<IndexSet<String>>(),
            })?;
        ensure!(
            data.len() == column_names.len(),
            error::XioColumnCountMismatch {
                tag: tag.to_string(),
                expected: column_names.len(),
                received: data.len()
            }
        );

        let index = column_names
            .iter()
            .zip(data.into_iter())
            .map(|(k, dv)| {
                use xio_base_datatypes::DataValue as DV;
                let v = match dv {
                    DV::Boolean(v) => Item::from(v),
                    DV::UInt8(v) => Item::from(v),
                    DV::UInt16(v) => Item::from(v),
                    DV::UInt32(v) => Item::from(v),
                    DV::UInt64(v) => Item::from(v),
                    DV::Int8(v) => Item::from(v),
                    DV::Int16(v) => Item::from(v),
                    DV::Int32(v) => Item::from(v),
                    DV::Int64(v) => Item::from(v),
                    DV::ParameterMask(_m) => Item::Nothing,
                };
                (k, v)
            })
            .collect::<IndexMap<_, _>>();
        let row = self
            .xio_sources
            .iter()
            .map(|(k, reference)| {
                (
                    k.to_string(),
                    if reference.tag == tag {
                        index
                            .get(&reference.field)
                            .cloned()
                            .unwrap_or_else(|| Item::Nothing)
                    } else {
                        Item::Nothing
                    },
                )
            })
            .collect();
        Ok(row)
    }
}

impl SourceOnlyBin for Bin {
    fn fetch_next(&mut self, _iteration: &Iteration) -> Result<Proceed> {
        for event in self.receiver.iter() {
            use xio_webapi::JobEvent as E;
            use BinState as S;
            match (self.state.clone(), event) {
                (S::Initialized, E::Started { tags, .. }) => {
                    self.state = S::WaitingForData { tags };
                }
                (
                    S::WaitingForData { tags },
                    E::Data { tag, values, .. },
                ) => {
                    let data = self.build_data(&tags, tag, values)?;
                    self.state = S::Running { tags, data };
                    return Ok(Proceed::Continue);
                }
                (S::WaitingForData { .. }, E::Position { .. }) => {}
                (S::Running { tags, .. }, E::Data { tag, values, .. }) => {
                    let data = self.build_data(&tags, tag, values)?;
                    self.state = S::Running { tags, data };
                    return Ok(Proceed::Continue);
                }
                (S::Running { .. }, E::Position { .. }) => {}
                (S::Running { .. }, E::Stopped { .. }) => {
                    self.state = S::Finished;
                    return Ok(Proceed::Stop);
                }
                (state, event) => {
                    return error::XioReceivedUnexpectedEventInState {
                        state: state.clone(),
                        event,
                    }
                    .fail();
                }
            }
        }
        Ok(Proceed::Stop)
    }
}