Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Condition.js « condition « plugins « src - github.com/nasa/openmct.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9896e9746c5122f40049b1ffc226f5410ba7303e (plain)
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
/*****************************************************************************
 * Open MCT, Copyright (c) 2014-2022, United States Government
 * as represented by the Administrator of the National Aeronautics and Space
 * Administration. All rights reserved.
 *
 * Open MCT is licensed under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 *
 * Open MCT includes source code licensed under additional open source
 * licenses. See the Open Source Licenses file (LICENSES.md) included with
 * this source code distribution or the Licensing information page available
 * at runtime from the About dialog for additional information.
 *****************************************************************************/

import EventEmitter from 'EventEmitter';
import { v4 as uuid } from 'uuid';
import TelemetryCriterion from "./criterion/TelemetryCriterion";
import { evaluateResults } from './utils/evaluator';
import { getLatestTimestamp } from './utils/time';
import AllTelemetryCriterion from "./criterion/AllTelemetryCriterion";
import {TRIGGER_CONJUNCTION, TRIGGER_LABEL} from "./utils/constants";

/*
* conditionConfiguration = {
*   id: uuid,
*   trigger: 'any'/'all'/'not','xor',
*   criteria: [
*       {
*           telemetry: '',
*           operation: '',
*           input: [],
*           metadata: ''
*       }
*   ]
* }
*/
export default class Condition extends EventEmitter {

    /**
     * Manages criteria and emits the result of - true or false - based on criteria evaluated.
     * @constructor
     * @param conditionConfiguration: {id: uuid,trigger: enum, criteria: Array of {id: uuid, operation: enum, input: Array, metaDataKey: string, key: {domainObject.identifier} }
     * @param openmct
     * @param conditionManager
     */
    constructor(conditionConfiguration, openmct, conditionManager) {
        super();

        this.openmct = openmct;
        this.conditionManager = conditionManager;
        this.id = conditionConfiguration.id;
        this.criteria = [];
        this.result = undefined;
        this.timeSystems = this.openmct.time.getAllTimeSystems();
        if (conditionConfiguration.configuration.criteria) {
            this.createCriteria(conditionConfiguration.configuration.criteria);
        }

        this.trigger = conditionConfiguration.configuration.trigger;
        this.summary = '';
    }

    updateResult(datum) {
        if (!datum || !datum.id) {
            console.log('no data received');

            return;
        }

        // if all the criteria in this condition have no telemetry, we want to force the condition result to evaluate
        if (this.hasNoTelemetry() || this.isTelemetryUsed(datum.id)) {

            this.criteria.forEach(criterion => {
                if (this.isAnyOrAllTelemetry(criterion)) {
                    criterion.updateResult(datum, this.conditionManager.telemetryObjects);
                } else {
                    if (criterion.usesTelemetry(datum.id)) {
                        criterion.updateResult(datum);
                    }
                }
            });

            this.result = evaluateResults(this.criteria.map(criterion => criterion.result), this.trigger);
        }
    }

    isAnyOrAllTelemetry(criterion) {
        return (criterion.telemetry && (criterion.telemetry === 'all' || criterion.telemetry === 'any'));
    }

    hasNoTelemetry() {
        return this.criteria.every((criterion) => {
            return !this.isAnyOrAllTelemetry(criterion) && criterion.telemetry === '';
        });
    }

    isTelemetryUsed(id) {
        return this.criteria.some(criterion => {
            return this.isAnyOrAllTelemetry(criterion) || criterion.usesTelemetry(id);
        });
    }

    update(conditionConfiguration) {
        this.updateTrigger(conditionConfiguration.configuration.trigger);
        this.updateCriteria(conditionConfiguration.configuration.criteria);
    }

    updateTrigger(trigger) {
        if (this.trigger !== trigger) {
            this.trigger = trigger;
        }
    }

    generateCriterion(criterionConfiguration) {
        return {
            id: criterionConfiguration.id || uuid(),
            telemetry: criterionConfiguration.telemetry || '',
            telemetryObjects: this.conditionManager.telemetryObjects,
            operation: criterionConfiguration.operation || '',
            input: criterionConfiguration.input === undefined ? [] : criterionConfiguration.input,
            metadata: criterionConfiguration.metadata || ''
        };
    }

    createCriteria(criterionConfigurations) {
        criterionConfigurations.forEach((criterionConfiguration) => {
            this.addCriterion(criterionConfiguration);
        });
    }

    updateCriteria(criterionConfigurations) {
        this.destroyCriteria();
        this.createCriteria(criterionConfigurations);
    }

    updateTelemetryObjects() {
        this.criteria.forEach((criterion) => {
            criterion.updateTelemetryObjects(this.conditionManager.telemetryObjects);
        });
    }

    /**
     *  adds criterion to the condition.
     */
    addCriterion(criterionConfiguration) {
        let criterion;
        let criterionConfigurationWithId = this.generateCriterion(criterionConfiguration || null);
        if (criterionConfiguration.telemetry && (criterionConfiguration.telemetry === 'any' || criterionConfiguration.telemetry === 'all')) {
            criterion = new AllTelemetryCriterion(criterionConfigurationWithId, this.openmct);
        } else {
            criterion = new TelemetryCriterion(criterionConfigurationWithId, this.openmct);
        }

        criterion.on('criterionUpdated', (obj) => this.handleCriterionUpdated(obj));
        criterion.on('telemetryIsStale', (obj) => this.handleStaleCriterion(obj));
        if (!this.criteria) {
            this.criteria = [];
        }

        this.criteria.push(criterion);

        return criterionConfigurationWithId.id;
    }

    findCriterion(id) {
        let criterion;

        for (let i = 0, ii = this.criteria.length; i < ii; i++) {
            if (this.criteria[i].id === id) {
                criterion = {
                    item: this.criteria[i],
                    index: i
                };
            }
        }

        return criterion;
    }

    updateCriterion(id, criterionConfiguration) {
        let found = this.findCriterion(id);
        if (found) {
            const newCriterionConfiguration = this.generateCriterion(criterionConfiguration);
            let newCriterion = new TelemetryCriterion(newCriterionConfiguration, this.openmct);
            newCriterion.on('criterionUpdated', (obj) => this.handleCriterionUpdated(obj));
            newCriterion.on('telemetryIsStale', (obj) => this.handleStaleCriterion(obj));

            let criterion = found.item;
            criterion.unsubscribe();
            criterion.off('criterionUpdated', (obj) => this.handleCriterionUpdated(obj));
            criterion.off('telemetryIsStale', (obj) => this.handleStaleCriterion(obj));
            this.criteria.splice(found.index, 1, newCriterion);
        }
    }

    destroyCriterion(id) {
        let found = this.findCriterion(id);
        if (found) {
            let criterion = found.item;
            criterion.off('criterionUpdated', (obj) => {
                this.handleCriterionUpdated(obj);
            });
            criterion.off('telemetryIsStale', (obj) => {
                this.handleStaleCriterion(obj);
            });
            criterion.destroy();
            this.criteria.splice(found.index, 1);

            return true;
        }

        return false;
    }

    handleCriterionUpdated(criterion) {
        let found = this.findCriterion(criterion.id);
        if (found) {
            this.criteria[found.index] = criterion.data;
        }
    }

    handleStaleCriterion(updatedCriterion) {
        this.result = evaluateResults(this.criteria.map(criterion => criterion.result), this.trigger);
        let latestTimestamp = {};
        latestTimestamp = getLatestTimestamp(
            latestTimestamp,
            updatedCriterion.data,
            this.timeSystems,
            this.openmct.time.timeSystem()
        );
        this.conditionManager.updateCurrentCondition(latestTimestamp);
    }

    updateDescription() {
        const triggerDescription = this.getTriggerDescription();
        let description = '';
        this.criteria.forEach((criterion, index) => {
            if (!index) {
                description = `Match if ${triggerDescription.prefix}`;
            }

            description = `${description} ${criterion.getDescription()} ${(index < this.criteria.length - 1) ? triggerDescription.conjunction : ''}`;
        });
        this.summary = description;
    }

    getTriggerDescription() {
        if (this.trigger) {
            return {
                conjunction: TRIGGER_CONJUNCTION[this.trigger],
                prefix: `${TRIGGER_LABEL[this.trigger]}: `
            };
        } else {
            return {
                conjunction: '',
                prefix: ''
            };
        }
    }

    requestLADConditionResult(options) {
        let latestTimestamp;
        let criteriaResults = {};
        const criteriaRequests = this.criteria
            .map(criterion => criterion.requestLAD(this.conditionManager.telemetryObjects, options));

        return Promise.all(criteriaRequests)
            .then(results => {
                results.forEach(resultObj => {
                    const { id, data, data: { result } } = resultObj;
                    if (this.findCriterion(id)) {
                        criteriaResults[id] = Boolean(result);
                    }

                    latestTimestamp = getLatestTimestamp(
                        latestTimestamp,
                        data,
                        this.timeSystems,
                        this.openmct.time.timeSystem()
                    );
                });

                return {
                    id: this.id,
                    data: Object.assign(
                        {},
                        latestTimestamp,
                        { result: evaluateResults(Object.values(criteriaResults), this.trigger) }
                    )
                };
            });
    }

    getCriteria() {
        return this.criteria;
    }

    destroyCriteria() {
        let success = true;
        //looping through the array backwards since destroyCriterion modifies the criteria array
        for (let i = this.criteria.length - 1; i >= 0; i--) {
            success = success && this.destroyCriterion(this.criteria[i].id);
        }

        return success;
    }

    destroy() {
        this.destroyCriteria();
    }
}