All files / src/app/components/signals-values-table signals-values-table.component.ts

85.98% Statements 92/107
50% Branches 14/28
87.5% Functions 28/32
84.37% Lines 81/96

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                                                                      41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x       93x 93x 93x                     112x 4x 4x 4x   4x         4x 4x                   4x               4x   4x     4x 4x 4x   4x                   4x       4x 17x 17x 13x 13x         13x     4x           1x 1x 1x                                     14x 14x   14x 14x 41x 41x 41x   14x 14x 14x 14x 14x           14x 23x     23x   23x 93x 93x 93x     23x           14x   61x 296x 296x 480x 296x 296x                 7328x       4x                 5x 5x 1x                                 41x 41x 41x 41x 41x   14x 14x       70x       70x 108x    
import { Component, OnDestroy, OnInit, ViewChild, AfterViewInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { DatePipe, NgFor, NgIf } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
 
import { Subscription } from 'rxjs';
 
import { TableModule, TableRowReorderEvent } from 'primeng/table';
import { MultiSelectModule } from 'primeng/multiselect';
import { DialogModule } from 'primeng/dialog';
import { ButtonModule } from 'primeng/button';
import { Badge } from 'primeng/badge';
import { SliderModule } from 'primeng/slider';
import { SelectModule } from 'primeng/select';
 
import { SignalCardComponent } from '../signal-card/signal-card.component';
import { MultiSelectSignalsComponent } from '../multi-select-signals/multi-select-signals.component';
import { RefreshRateSelectorComponent } from '../refresh-rate-selector/refresh-rate-selector.component';
import { TwinpadApiService } from '../../services/twinpad-api.service';
import { DurationOption, Signal, SignalSample } from '../../models/signals';
import { getSeverity, getDistinctElements } from '../../utils/utils';
 
 
interface Column {
  label: string;
  field: string;
}
 
class FlatSignalAndSample extends Signal {
  device_name: string;
  timestamp: number;
  value: number | string;
  forced_value: number | string;
 
  constructor(signal: Signal) {
    super();
    this.signal_id = signal.signal_id;
    this.type = signal.type;
    this.unit = signal.unit;
    this.frequency = signal.frequency;
    this.description = signal.description;
    this.status = signal.status;
    this.data_type = signal.data_type;
    this.device = signal.device;
    this.precision_digits = signal.precision_digits;
    this.forcible = signal.forcible;
  }
 
  updateValues(sample: SignalSample) {
    this.timestamp = sample?.timestamp;
    this.value = sample?.value;
    this.forced_value = sample?.forced_value;
  }
}
 
 
@Component({
  selector: 'app-signals-values-table',
  imports: [TableModule, MultiSelectModule, FormsModule, NgFor, NgIf, DialogModule, SignalCardComponent, ButtonModule, MultiSelectSignalsComponent, RefreshRateSelectorComponent, Badge, DatePipe, SliderModule, SelectModule],
  templateUrl: './signals-values-table.component.html',
  styleUrl: './signals-values-table.component.scss'
})
export class SignalsValuesTableComponent implements OnInit, AfterViewInit, OnDestroy {
  private twinpadApiService = inject(TwinpadApiService);
  private router = inject(Router);
  private route = inject(ActivatedRoute);
 
  @ViewChild(MultiSelectSignalsComponent) multiSelectSignals!: MultiSelectSignalsComponent;
  isLoading: boolean;
 
  signalIdsToDisplay: string[];
  extendedSignalsById: Map<string, FlatSignalAndSample>;
  frequencies: number[] = [];
  frequencyThresholds: number[] = [0, 0];
  units: string[];
  types: string[];
  precisionDigits: string[];
  statuses: string[];
 
  columns: Column[];
  selectedColumns: Column[];
  rows: FlatSignalAndSample[];
 
  selectedSignal: Signal | null = null;
  signalDialogVisible: boolean;
 
  valuesSubscription: Subscription;
  signalToDeviceSubscription: Map<Signal, Subscription>;
 
  refreshTime: DurationOption;
  lastGraphRefreshTs: number;
  isResponseSlowerThanRefresh: boolean = false;
 
  signalsSelectionLimit: number = 50;
 
  ngOnInit(): void {
    this.rows = [];
    this.extendedSignalsById = new Map();
    this.signalToDeviceSubscription = new Map();
 
    this.columns = [
      { field: 'value', label: 'Value' },
      { field: 'forced_value', label: 'Forced value' },
      { field: 'unit', label: 'Unit' },
      { field: 'frequency', label: 'Frequency' },
      { field: 'type', label: 'Type' },
      { field: 'precision_digits', label: 'Precision Digits' },
      { field: 'status', label: 'Status' }
    ];
 
    this.selectedColumns = this.columns.slice(0, 3);
  }
 
  ngAfterViewInit(): void {
    this.route.queryParams.subscribe(params => {
      const signalIds = params["signal_id"];
      if (signalIds) {
        Eif (signalIds instanceof Array) {
          this.signalIdsToDisplay = signalIds;
        }
        else {
          this.signalIdsToDisplay = [signalIds];
        }
        this.onSignalsChange();
      }
      else {
        this.signalIdsToDisplay = [];
      }
    });
  }
 
  showSignal(signal: Signal) {
    this.selectedSignal = signal;
    this.signalDialogVisible = true;
    this.router.navigate([], {
      fragment: signal.signal_id,
      queryParamsHandling: 'preserve'
    });
  }
 
  hideSignal() {
    this.selectedSignal = null;
    this.route.fragment.subscribe(fragment => {
      if (fragment) {
        const el = document.getElementById(fragment);
        if (el) {
          el.scrollIntoView({ behavior: 'smooth', block: 'end' });
        }
      }
    });
  }
 
  onSignalsChange() {
    this.isLoading = true;
    this.twinpadApiService.getSignals(this.signalsSelectionLimit, 0, null, null, this.signalIdsToDisplay, null).subscribe({
      next: signals => {
        const rows = [];
        for (const signal of signals.items) {
          const newFlatSignal = new FlatSignalAndSample(signal);
          this.extendedSignalsById.set(signal.signal_id, newFlatSignal);
          rows.push(newFlatSignal);
        }
        this.rows = rows;
        this.updateSliders();
        this.getDeviceNameFromSignals();
        this.updateValuesSubscription();
        this.isLoading = false;
      }
    });
  }
 
  updateValuesSubscription() {
    this.valuesSubscription?.unsubscribe();
    this.valuesSubscription = this.twinpadApiService.callPeriodically(() => { return this.twinpadApiService.getSignalValues(this.signalIdsToDisplay); }, 1000 * this.refreshTime.duration)
      .subscribe({
        next: samples => {
          this.isResponseSlowerThanRefresh = Date.now() - (this.lastGraphRefreshTs + this.refreshTime.duration * 1000) > this.refreshTime.duration * 1000;
 
          for (let i = 0; i < this.signalIdsToDisplay.length; i++) {
            const flatSignal = this.extendedSignalsById.get(this.signalIdsToDisplay[i]);
            Eif (flatSignal !== undefined) {
              flatSignal.updateValues(samples[i]);
            }
          }
          this.lastGraphRefreshTs = Date.now();
        }
      });
  }
 
  getDeviceNameFromSignals() {
    this.twinpadApiService.devicesBehaviorSubject$.subscribe({
      next: devices => {
        for (const signalId of this.signalIdsToDisplay) {
          const flatSignal = this.extendedSignalsById.get(signalId);
          Eif (flatSignal !== undefined) {
            const device = devices.find(device => device.device_id === signalId.split('.')[0]);
            Eif (device !== undefined) {
              flatSignal.device_name = device.name;
            }
          }
        }
      }
    });
  }
 
  getSeverity(status: string) {
    return getSeverity(status);
  }
 
  handleSignalsLoaded() {
    for (const flatSignal of this.extendedSignalsById.values()) {
      if (flatSignal.device_name === undefined) {
        this.getDeviceNameFromSignals();
        return;
      }
    }
  }
 
  handleRefreshRateChange(selected: DurationOption) {
    this.refreshTime = selected;
    if (this.signalIdsToDisplay) {
      this.onSignalsChange();
    }
  }
 
  onRowReorder(event: TableRowReorderEvent) {
    if (event.dragIndex !== undefined && event.dropIndex !== undefined) {
      const elements = this.signalIdsToDisplay.splice(event.dragIndex, 1);
      this.signalIdsToDisplay.splice(event.dropIndex, 0, elements[0]);
    }
    this.onSignalsChange();
  }
 
  ngOnDestroy() {
    this.valuesSubscription?.unsubscribe();
  }
 
  updateSliders() {
    this.frequencies = getDistinctElements(this.rows.map(flatSignal => flatSignal.frequency));
    this.units = getDistinctElements(this.rows.map(flatSignal => flatSignal.unit ?? "")).filter(unit => unit !== "");
    this.types = getDistinctElements(this.rows.map(flatSignal => flatSignal.type));
    this.precisionDigits = getDistinctElements(this.rows.map(flatSignal => flatSignal.precision_digits?.toString() ?? "")).filter(unit => unit !== "");
    this.statuses = getDistinctElements(this.rows.map(flatSignal => flatSignal.status.status));
 
    this.frequencyThresholds[0] = this.getArrayMin(this.frequencies);
    this.frequencyThresholds[1] = this.getArrayMax(this.frequencies);
  }
 
  getArrayMin(array: number[]): number {
    return Math.min.apply(null, array);
  }
 
  getArrayMax(array: number[]): number {
    return Math.max.apply(null, array);
  }
}