All files / src/app/components/signals-graph signals-graph.component.ts

85.06% Statements 188/221
66.95% Branches 77/115
77.77% Functions 28/36
84.72% Lines 183/216

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637                                        52x                 64x     12x   12x 12x     12x 12x                                     12x 12x   12x         12x 12x 12x 12x   12x     12x 12x       12x   12x   12x 7x         12x 12x                                       31x 31x   31x   31x 31x   31x 31x     31x 31x 19x 2x       31x 31x   30x 27x 4x   30x 30x 30x   30x   30x 30x 30x       31x   30x                     42x 23x 23x     19x   19x 19x     19x             19x 19x 15x   22x 22x     20x       20x     20x 20x 13x     20x   20x   20x 13x     7x     20x                   4x   8x 8x 8x 8x 8x 8x   8x 4x   2x   2x       4x       7x       7x     7x 7x 1x     7x   7x   7x 1x     6x     7x                       27x 3x 3x     24x       24x 20x   4x 4x 2x 2x   2x     22x 22x 22x   65x   58x 33x     33x       33x 7x 7x   33x         49x 49x 49x 49x 49x 32x 32x 32x             32x 32x 32x 32x                 49x                                                                                                     904x 904x                                 49x   49x 49x     49x 25x                     49x                 27x 7x   27x 27x             27x 27x       49x                                                                   87x 87x 87x 41x 63x 63x 63x 63x   63x 63x 6x     63x               63x 63x                   87x       37x 37x 37x   37x 37x   25x       37x 37x       30x 26x 26x     4x         4x                 50x 50x         50x       50x 2x 2x   50x                               2x 2x       51x                                                                 1x        
import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges } from '@angular/core';
import { TwinpadApiService } from '../../services/twinpad-api.service';
import { NumberSignalData, SignalSample, SignalsData, StringSignalData } from '../../models/signals';
 
import { FormsModule } from '@angular/forms';
 
import type { DataZoomComponentOption, EChartsOption, LineSeriesOption } from 'echarts';
 
import { NgxEchartsDirective, provideEchartsCore } from 'ngx-echarts';
import * as echarts from 'echarts/core';
import { Subscription } from 'rxjs';
import { saveAs } from 'file-saver';
import { DatePipe, NgIf } from '@angular/common';
import { DurationPipe } from '../../pipes/duration.pipe';
 
import { LineChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import { GridComponent, TitleComponent, ToolboxComponent, DataZoomComponent, LegendComponent } from 'echarts/components';
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorComponent } from '../error/error.component';
echarts.use([LineChart, GridComponent, CanvasRenderer, TitleComponent, ToolboxComponent, DataZoomComponent, LegendComponent]);
 
@Component({
    selector: 'app-signals-graph',
    imports: [FormsModule, NgxEchartsDirective, DatePipe, DurationPipe, ErrorComponent, NgIf],
    providers: [provideEchartsCore({ echarts })],
    templateUrl: './signals-graph.component.html',
    styleUrl: './signals-graph.component.scss'
})
export class SignalsGraphComponent implements OnInit, OnChanges, OnDestroy{
 
  isLoading: boolean;
  error: HttpErrorResponse | null = null;
  @Input() signalIdsToPlot: string[];
  @Input() isLive: boolean=true;
  @Input() refreshTime: number=5;
  @Input() requestedWindowMinTs: number;
  @Input() requestedWindowMaxTs: number;
  @Input() liveWindow: number = 60;
  @Input() showLegend: boolean=true;
  @Input() refreshMode: string;
 
  signalsData: SignalsData;
  options: EChartsOption;
  updateOptions: EChartsOption;
  dataSubscription: Subscription;
  firstSampleSubscription: Subscription;
  private chart!: echarts.ECharts;
 
  windowMinTs: number;
  windowMaxTs: number;
  windowStartValue: number;
  windowEndValue: number;
  dataMinTs: number;
  dataMaxTs: number;
  liveMinTs: number;
  lastGraphRefreshTs: number;
 
  isYAxisScaling: boolean = true;
  updateYAxisScaling: boolean = false;
 
  labels: string[] = [];
  firstSamples: SignalSample[] | undefined;
 
  signalsForcibilities: Map<string, boolean>;
 
  @Output() dataDateMin: EventEmitter<Date> = new EventEmitter();
  @Output() dataDateMax: EventEmitter<Date> = new EventEmitter();
  @Output() windowMiddleDate: EventEmitter<Date> = new EventEmitter();
  @Output() isResponseSlowerThanRefresh: EventEmitter<boolean> = new EventEmitter();
 
  constructor(private twinpadApiService: TwinpadApiService) {}
 
  ngOnInit() {
    this.isLoading = true;
    this.signalsForcibilities = new Map();
 
    // First, fetch signals data type to configure Str Y Axis
 
    this.options = this.generateOptions();
 
    this.updateData();
 
    if (this.signalIdsToPlot.length == 0){
      this.isLoading = false;
    }
  }
 
  onChartInit(ec: echarts.ECharts) {
    this.chart = ec;
    this.chart.on('dataZoom', (_: any) => { // eslint-disable-line
      const option = this.chart.getOption() as EChartsOption;
 
      if(option !== undefined && option.dataZoom !== undefined) {
        const dataZoom = option.dataZoom as DataZoomComponentOption[];
        this.windowStartValue = dataZoom[0]['startValue'] as number;
        this.windowEndValue = dataZoom[0]['endValue'] as number;
      }
 
      // Move this to window update?
      if (this.dataMinTs !== undefined && this.dataMaxTs !== undefined){
        this.windowMinTs = this.windowStartValue;
        this.windowMaxTs = this.windowEndValue;
      }
      this.windowMiddleDate.emit(new Date(500*(this.windowMinTs+this.windowMaxTs)));
 
    });
  }
 
  ngOnChanges(changes: SimpleChanges): void {
    this.dataSubscription?.unsubscribe();
    this.firstSampleSubscription?.unsubscribe();
 
    this.firstSamples = undefined;
 
    Eif (this.requestedWindowMinTs !== undefined){
      this.windowMinTs = this.requestedWindowMinTs;
    }
    Eif (this.requestedWindowMaxTs !== undefined){
      this.windowMaxTs = this.requestedWindowMaxTs;
    }
 
    let shouldUpdateData = true;
    if ("isLive" in changes){
      if (changes["isLive"]["currentValue"] === false){
        shouldUpdateData = false;
      }
    }
 
    const labels = new Set<string>();
    this.twinpadApiService.getSignals(0, 0, null, null, this.signalIdsToPlot).subscribe(
      signalsData => {
        for (const signal of signalsData.items){
          for (const enumOption of signal.stringEnumOptions())
            labels.add(enumOption);
        }
        const newLabels = Array.from(labels);
        Eif (this.labels != newLabels){
          shouldUpdateData = true;
        }
        this.labels = newLabels;
 
        Eif (shouldUpdateData){
          this.isLoading = true;
          this.updateData();
        }
      }
    );
    this.twinpadApiService.getSignalsForcibility(this.signalIdsToPlot).subscribe({
      next: forcibilities => {
        this.signalsForcibilities = forcibilities;
      }
    });
  }
 
    /**
   * fetch signalData drom signals to plot and trigger graph update
   * Make the api subscription
   */
  updateData() {
 
    if (this.signalIdsToPlot === undefined || this.signalIdsToPlot.length === 0 || this.signalsData === undefined) {
      this.signalsData = new SignalsData([], null, null);
      this.updateGraphForce();
    }
    else {
      this.firstSampleSubscription?.unsubscribe();
 
      this.twinpadApiService.getSignalFirstValues(this.signalIdsToPlot).subscribe(value => {
        this.firstSamples = value;
      });
 
      this.subscribeData();
 
 
    }
  }
 
  subscribeData(initialDelay?:number){
    this.dataSubscription?.unsubscribe();
    if (this.refreshMode === "Single-point" && this.isLive) {
      this.dataSubscription = this.twinpadApiService.callPeriodically(
      () => {
        this.updateWindowBounds();
        return this.twinpadApiService.getSignalValues(this.signalIdsToPlot);
      }, 1000 * this.refreshTime, initialDelay).subscribe({
          next: (value) => {
            this.error = null;
 
            // check if data request time is longer than refresh time
            // subscribe happens every 1000*refreshTime, so time spent requesting data = difference_between_two_timings - refresh time
            this.isResponseSlowerThanRefresh.emit(Date.now() - (this.lastGraphRefreshTs + this.refreshTime * 1000) > this.refreshTime * 1000);
 
            // Data return callback
            let shouldForce = false;
            if (this.signalsData === undefined || this.signalsData.signals_data === undefined || this.signalsData.signals_data.length !== value?.length) {
              shouldForce = true;
            }
 
            this.updateSignalsData(value);
 
            this.updateDataTimestampBoundaries();
 
            if (shouldForce) {
              this.updateGraphForce();
            }
            else {
              this.updateGraph();
            }
 
            this.lastGraphRefreshTs = Date.now();
          },
          error: (error) => {
            this.error = error;
            this.subscribeData(2000);
 
          }
      });
    }
    else {
      this.dataSubscription = this.twinpadApiService.callPeriodically(
      () => {
        let tsMin = null;
        let tsMax = null;
        this.updateWindowBounds();
        Eif (this.windowMinTs !== undefined && this.windowMaxTs !== undefined) {
          tsMax = this.windowMaxTs + 5;
          tsMin = this.windowMinTs - 5;
        }
        if (this.isLive) {
          switch (this.refreshMode) {
            case "Latest points":
              return this.twinpadApiService.getSignalsData(this.signalIdsToPlot, 100, this.windowMaxTs - this.refreshTime, this.windowMaxTs, false);
            default:
              return this.twinpadApiService.getSignalsData(this.signalIdsToPlot, 800, this.windowMinTs, this.windowMaxTs, true);
          }
        }
        else {
          return this.twinpadApiService.getSignalsDataWithInterestWindow(this.signalIdsToPlot, 800, 200, this.windowMinTs, this.windowMaxTs, tsMin, tsMax);
        }
      }, 1000 * this.refreshTime, initialDelay).subscribe({
          next: (value) => {
            this.error = null;
 
            // check if data request time is longer than refresh time
            // subscribe happens every 1000*refreshTime, so time spent requesting data = difference_between_two_timings - refresh time
            this.isResponseSlowerThanRefresh.emit(Date.now() - (this.lastGraphRefreshTs + this.refreshTime * 1000) > this.refreshTime * 1000);
 
            // Data return callback
            let shouldForce = false;
            if (this.signalsData === undefined || this.signalsData.signals_data === undefined || this.signalsData?.signals_data.length != value?.signals_data.length) {
              shouldForce = true;
            }
 
            this.updateSignalsData(value);
 
            this.updateDataTimestampBoundaries();
 
            if (shouldForce) {
              this.updateGraphForce();
            }
            else {
              this.updateGraph();
            }
 
            this.lastGraphRefreshTs = Date.now();
          },
          error: (error) => {
            this.error = error;
            this.subscribeData(2000);
 
          }
      });
    }
  }
 
  updateSignalsData(newBatch: SignalsData | SignalSample[]) {
    if (!this.isLive) {
      this.signalsData = newBatch as SignalsData;
      return;
    }
 
    Iif (this.signalsData === undefined) {
      this.signalsData = new SignalsData([], null, null);
    }
 
    if ((<SignalSample[]>newBatch)?.length !== undefined) {
      this.signalsData.push(newBatch as SignalSample[]);
    }
    else Eif (newBatch !== undefined) {
      if (this.refreshMode === "Full window") {
        this.signalsData = newBatch as SignalsData;
        return;
      }
      this.signalsData.concat(newBatch as SignalsData);
    }
 
    const delayMargin = 0.1;
    this.signalsData.pruneDeselectedSignals(this.signalIdsToPlot);
    for (const signalData of this.signalsData.signals_data) {
      // remove outdated points with a delay margin
      signalData.time_vector = signalData.time_vector.filter(ts => ts >= this.windowMinTs - delayMargin);
      // count number of points off to the left of the graph and replace them by one point right on the edge
      const numberInvisiblePoints = signalData.time_vector.filter(ts => ts < this.windowMinTs).length;
      for (let i = 0; i < numberInvisiblePoints; i++) {
        signalData.time_vector.shift();
      }
      Iif (numberInvisiblePoints > 0) {
        signalData.time_vector.unshift(this.windowMinTs);
      }
      // adjust to the new length after having removed values
      while (signalData.values.length > signalData.time_vector.length) {
        signalData.values.shift();
        signalData.forced_values.shift();
      }
      signalData.number_samples = signalData.time_vector.length;
    }
  }
 
  generateOptions(): any{ // eslint-disable-line
    const series: LineSeriesOption[] = [];
    const legend: string[] = [];
    const legendSelection: { [id: string]: boolean } = {};
    Eif(this.signalIdsToPlot !== undefined){
      for (const signalId of this.signalIdsToPlot){
            legend.push(signalId);
            legendSelection[signalId] = true;
            series.push({
              name: signalId,
              type: 'line',
              smooth: false,
              symbol: 'none',
              data: []});
 
            const forcedValueName = signalId + ' forced value';
            legend.push(forcedValueName);
            legendSelection[forcedValueName] = false;
            series.push({
              name: forcedValueName,
              type: 'line',
              smooth: false,
              symbol: 'none',
              data: []});
      }
    }
 
    const options: EChartsOption = {
      animation: false,
      grid: {
        left: 0,
        right: 60,
        top: 40,
        containLabel: true,
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          axis: 'x',
          snap: true,
        },
        valueFormatter: function(value) {
          const tooltipValue = value?.toString() ?? "0";
          // it received a timestamp:
          if (!Number.isNaN(tooltipValue) && Date.now() / 1000 - +(tooltipValue) < 86400) {
            const date = +(tooltipValue) * 1000;
            const datepipe = new DatePipe("en-US");
            return datepipe.transform(date, "HH:mm:ss.SSS") ?? "";
          }
          return tooltipValue;
        }
      },
      toolbox: {
        show: false,
        feature: {
          dataZoom: {
            yAxisIndex: 'none'
          },
          restore: {},
          saveAsImage: {name: 'twinpad_signals'}
        }
      },
      xAxis: {
        type: 'value',
        minorTick: {
          show: true
        },
        splitLine: {
          show: true,
          lineStyle: {type: 'solid', width:0.3}
        },
        minorSplitLine: {
          show: true,
          lineStyle: {type: 'dashed', width:0.3}
        },
        axisLabel: {
          formatter: function(value){
            const datepipe = new DatePipe("en-US");
            return datepipe.transform(value * 1000, "yyyy/MM/dd - HH:mm:ss") ?? `${value}`;
          }
        },
        axisPointer: {
          label: {
            formatter: function(params) {
              const value = +params.value.toString() * 1000;
              const datepipe = new DatePipe("en-US");
              return datepipe.transform(value, "yyyy/MM/dd - HH:mm:ss.SSS") ?? `${params.value}`;
            }
          }
        }
      },
      dataZoom: this.computeDataZoom(),
      series: series
    };
 
    this.updateYAxis(options);
 
    Eif (this.showLegend){
      options.legend = {data: legend, selectedMode: "multiple", type: 'scroll', selected: legendSelection};
    }
 
    if (this.signalIdsToPlot === undefined || this.signalIdsToPlot.length == 0){
      options.title = {
        text: 'No signal selected',
        textAlign: 'center',
        left: '50%',
        top: '40%',
        textStyle: {
          fontSize: 30
        }
      };
    }
 
    return options;
  }
 
  /**
   * Update dataMinTs and dataMaxTs according to signal data
   * also update windowMinTs and xMaxTs from component input (requested)
   */
  updateDataTimestampBoundaries(){
 
    if (this.signalsData.data_start !== null){
      this.dataMinTs = this.signalsData.data_start;
    }
    Eif (this.signalsData.data_end !== null){
      this.dataMaxTs = this.signalsData.data_end;
    }
    else{
      this.dataMaxTs = Date.now() * 0.001;
    }
 
    // Emitting new dates
    this.dataDateMin.emit(new Date(1000*this.dataMinTs));
    this.dataDateMax.emit(new Date(1000*this.dataMaxTs));
  }
 
  computeDataZoom(){
    return [
      {
        type: 'slider',
        start: 0,
        end: 100,
        xAxisIndex: 0,
        zoomOnMouseWheel: false,
        show: false
      },
      {
        type: 'inside',
        start: 0,
        end: 100,
        xAxisIndex: 0,
        zoomOnMouseWheel: false,
      },
      {
        type: 'slider',
        start: 0,
        end: 100,
        yAxisIndex: 0,
        zoomOnMouseWheel: false
      },
      {
        type: 'inside',
        start: 0,
        end: 100,
        yAxisIndex: 0,
        zoomOnMouseWheel: false
      }
    ];
  }
 
  computeSeries(): LineSeriesOption[]{
    const series: LineSeriesOption[] = [];
    const signalsData = this.signalsData.copy(); // Copy to avoid concurrent update
    if (signalsData.signals_data !== undefined && signalsData.signals_data.length > 0){
      for (let isignal = 0; isignal < this.signalIdsToPlot.length; isignal++){
        const signalData: StringSignalData|NumberSignalData = signalsData.signals_data[isignal];
        const [data, forced_data] = signalData.echartsSerieData();
        Eif (this.firstSamples !== undefined){
          data.unshift([1000*this.firstSamples[isignal].timestamp, this.firstSamples[isignal].value]);
        }
        let yAxisIndex: number = 0;
        if (signalData instanceof StringSignalData){
          yAxisIndex = 1;
        }
 
        series.push({name: this.signalIdsToPlot[isignal],
          type: 'line',
          smooth: false,
          symbol: 'none',
          yAxisIndex: yAxisIndex,
          data: data
        });
 
        Eif (this.signalsForcibilities.get(this.signalIdsToPlot[isignal])) {
          series.push({name: this.signalIdsToPlot[isignal]+" forced value",
            type: 'line',
            smooth: false,
            symbol: 'none',
            yAxisIndex: yAxisIndex,
            data: forced_data
          });
        }
      }
    }
    return series;
  }
 
  updateGraphForce(){
    this.isLoading = true;
    const series = this.computeSeries();
    this.options = this.generateOptions();
 
    this.options.series = series;
    if (this.chart){
        // Pass changes through options updates
        this.chart.setOption(this.options, true);
    }
 
    // Force update: a bit ugly but works
    this.updateGraph();
    this.isLoading = false;
  }
 
  updateWindowBounds(){
    if (this.isLive){
      this.windowMaxTs = Date.now()/1000;
      this.windowMinTs = this.windowMaxTs - this.liveWindow;
    }
    else{
      Iif (this.windowMinTs === undefined){
        if (this.requestedWindowMinTs !== undefined){
          this.windowMinTs = this.requestedWindowMinTs;
        }
      }
      Iif (this.windowMaxTs === undefined){
        if (this.requestedWindowMaxTs !== undefined){
          this.windowMaxTs = this.requestedWindowMaxTs;
        }
      }
    }
  }
 
  updateGraph(){
    const series = this.computeSeries();
    const dataZoom = [
      {type: "slider", startValue: this.windowMinTs, endValue: this.windowMaxTs, zoomOnMouseWheel:!this.isLive, zoomLock:this.isLive, disabled:this.isLive},
      {type: "inside", startValue: this.windowMinTs, endValue: this.windowMaxTs, zoomOnMouseWheel:!this.isLive, zoomLock:this.isLive, disabled:this.isLive}
    ];
 
    this.updateOptions = {
      dataZoom: dataZoom,
      series: series,
    };
    if (this.updateYAxisScaling) {
      this.updateYAxis(this.updateOptions);
      this.updateYAxisScaling = false;
    }
    this.isLoading = false;
  }
 
 
 
  downloadSignalsZip(format: string){
    this.twinpadApiService.downloadSignalsDataZip(format, this.signalIdsToPlot, this.windowMinTs, this.windowMaxTs).subscribe(blob  => {
 
    saveAs(blob, 'signals-data_'+format+'.zip');
    }
    , error => {
      console.error('Error downloading the blob', error);
    });
  }
 
  toggleYAxisScaling() {
    this.isYAxisScaling = !this.isYAxisScaling;
    this.updateYAxisScaling = true;
  }
 
  updateYAxis(options: EChartsOption) {
    options.yAxis = [
        {
        type: 'value',
        id: "0",
        show: true,
        splitNumber: 10,
        position: 'right',
        minorTick: {
          show: true
        },
        splitLine: {
          show: true,
          lineStyle: {type: 'solid', width:0.3}
        },
        minorSplitLine: {
          show: false,
          lineStyle: {type: 'dashed', width:0.3}
        },
        scale: this.isYAxisScaling,
        boundaryGap: ['5%', '5%']
      },
      {
        type: 'category',
        show: this.labels.length>0, //begin without
        axisTick: {"alignWithLabel": true},
        id: "1",
        position: 'left',
        data: this.labels,
      }
    ];
  }
 
  ngOnDestroy() {
    this.dataSubscription?.unsubscribe();
  }
 
}