summaryrefslogtreecommitdiff
path: root/web-timeplot/src/data/csv-replay-source.js
blob: c4e6a666f6f46c1a568e7cb8d0b014111403ad5f (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
import { BaseSource } from './base-source.js';

function clamp(value, min, max) {
    return Math.min(max, Math.max(min, value));
}

export class CsvReplaySource extends BaseSource {
    constructor(config = {}) {
        super({
            replayRate: 1,
            dataset: [],
            ...config,
        });
        this.sourceType = 'csv-replay';
        this.nextPointIndex = 0;
    }

    start(startTimeMs = 0) {
        super.start();
        this.reset(startTimeMs);
    }

    reset() {
        this.nextPointIndex = 0;
    }

    updateConfig(nextConfig) {
        const datasetChanged = nextConfig.dataset !== this.config.dataset;
        super.updateConfig(nextConfig);
        if (datasetChanged) {
            this.reset();
        }
    }

    update(currentPlotTimeMs) {
        if (!this.running || !Array.isArray(this.config.dataset) || this.config.dataset.length === 0) {
            return [];
        }

        const replayRate = clamp(this.config.replayRate ?? 1, 0.1, 8);
        const targetDatasetTimeMs = currentPlotTimeMs * replayRate;
        const points = [];

        while (this.nextPointIndex < this.config.dataset.length) {
            const datasetPoint = this.config.dataset[this.nextPointIndex];
            if (datasetPoint.timeMs > targetDatasetTimeMs) {
                break;
            }

            points.push({
                timeMs: datasetPoint.timeMs / replayRate,
                value: datasetPoint.value,
                sourceId: this.config.id ?? 'csv-replay',
            });
            this.nextPointIndex += 1;
        }

        return points;
    }
}