All files / src/app/services twinpad-api.service.ts

87.76% Statements 287/327
59.33% Branches 89/150
86.82% Functions 112/129
87.69% Lines 285/325

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 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865                                                      220x               110x 110x   110x   110x 110x 110x 110x   109x 109x 109x                                           1681x 197x     1681x   1681x   34x       27x   7x   1613x                             80x 80x 80x   135x                   132x         80x 30x                         176x 174x   233x                   231x           176x         85x         93x     92x 92x 92x 92x 87x   92x                         11x         140x       9x       4x       1x       1x       3x   3x       59x 59x       111x   111x   111x 9x   111x 48x   111x 20x   111x 8x     111x 77x   111x   108x 108x 760x 760x 760x 760x   108x 108x 108x           116x       31x   29x 29x 48x   29x           2x 2x 2x       50x     50x                 16x   15x           4x 4x 4x   4x 4x     4x 4x             6x 6x 6x   6x 6x   6x 6x   6x 6x   6x 6x   6x 6x     6x 6x         3x 3x 3x     3x 3x         5x 5x 5x   5x 5x   5x 5x     5x 5x         4x 4x 4x   4x 4x   4x 4x     4x 4x         2x   2x       1x   1x       29x     28x                           77x 77x     76x 76x 218x   76x         36x 36x     36x 36x 57x   36x         1x       3x       6x       3x       18x       4x 4x 4x 4x     4x 1x   4x 1x   4x       4x       1x     1x 1x 1x 1x         59x 59x       59x 59x       6x 6x   6x       1x     1x 1x         2x 2x     2x       2x       1x 1x     1x       1x       21x       13x       3x       3x       1x 1x       2x       25x       5x       4x       4x       1x       1x       1x       4x       1x       4x   4x 4x     4x       4x   4x 4x     4x     4x       4x               3x       2x       1x         1x       1x       1x       1x       46x               1x       1x       1x       1x       1x       2x       2x       57x 57x       57x       8x 8x 23x 23x     8x       8x       41x 41x       1x       2023x       12x 12x 1x   11x       12x 12x 1x   11x                 37x 37x 14x   37x       22x 22x 22x 22x       22x         1x 1x       275x 2x   273x       2x                 2x       2x       10x         396x 396x 280x 280x 280x     116x 116x       109x   129x 89x   89x       40x 40x                   87x 87x     87x 140x               89x 89x 93x              
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable, Subscription, interval, of, map, startWith, exhaustMap, timer, BehaviorSubject } from 'rxjs';
 
import { Signal, SignalData, SignalsData, SignalSample, SampleStats, SignalStats, SignalsPreset, ForcedSignal } from '../models/signals';
import { TwinPadStatus, ServicesStatus, Slash } from '../models/status';
import { ListResponse, CommandResponse } from '../models/response';
import { Device, DeviceSetup, Mode, DeviceState } from '../models/devices';
import { EventRule, Event, TwinPadActivity } from '../models/events';
import { Campaign, Phase } from '../models/campaign';
import { Command } from '../models/commands';
import { GraphTheme, LineStyle } from '../models/colorSetting';
 
import { catchError, switchMap } from 'rxjs/operators';
import { Video } from '../models/videos';
import { CustomView } from '../models/customView';
import { User } from '../models/users';
import { jwtDecode } from 'jwt-decode';
import { FormGroup } from '@angular/forms';
import { AccessToken, AccessTokenPayload } from '../models/token';
import { InitService } from './init.service';
import { Router } from '@angular/router';
 
 
@Injectable({
  providedIn: 'root'
})
export class TwinpadApiService {
  // TODO: if api url search fails, display a global error and retry
  loggedInUserBehaviorSubject$: BehaviorSubject<boolean>;
  cloudStatusSubscription: Subscription;
  cloudStatusBehaviorSubject$: BehaviorSubject<TwinPadStatus>;
  devicesSubscription: Subscription;
  devicesBehaviorSubject$: BehaviorSubject<Device[]>;
 
  devicesRefreshTime: number = 3;
  statusRefreshTime: number = 10;
 
  constructor(protected http: HttpClient, private initService: InitService) {
    // TODO: if api url is null, maybe repoll periodicallly and display a message to user that no backend is found
    this.loggedInUserBehaviorSubject$ = new BehaviorSubject(this.isTokenValid());
    this.cloudStatusBehaviorSubject$ = new BehaviorSubject(new TwinPadStatus(new ServicesStatus("up")));
    this.devicesBehaviorSubject$ = new BehaviorSubject<Device[]>([]);
    this.initService.isUrlFound$.subscribe({
      next: isUrlFound => {
        Eif (isUrlFound) {
          this.loggedInUserSubscribe();
          this.cloudStatusBehaviorSubject$.next(new TwinPadStatus(new ServicesStatus("up")));
        }
        else {
          this.cloudStatusBehaviorSubject$.next(new TwinPadStatus(new ServicesStatus("down")));
          timer(1000 * this.statusRefreshTime).subscribe(() => {
            initService.findApiUrl();
          });
        }
      }
    });
  }
 
  protected apiRequest<T>(
    endpoint: string,
    method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE' = "GET",
    options?: {
      body?: any; // eslint-disable-line @typescript-eslint/no-explicit-any
      params?: HttpParams | { [param: string]: string | string[] | number };
      headers?: HttpHeaders | { [header: string]: string | string[] };
      responseType?: 'json';
    }
  ): Observable<T> {
    if (endpoint[0] == '/') {
      endpoint = endpoint.slice(1);
    }
 
    const url = `${this.initService.apiUrl}/${endpoint}`;
 
    switch (method) {
      case 'POST':
        return this.http.post<T>(url, options?.body, options);
      case 'PUT':
        return this.http.put<T>(url, options?.body, options);
      case 'PATCH':
        return this.http.patch<T>(url, options?.body, options);
      case 'DELETE':
        return this.http.delete<T>(url, options);
      case 'GET':
        return this.http.get<T>(url, options);
      default:
        console.error('Unrecognized method', method);
        throw new Error("Unrecognized method");
    }
 
  }
 
 
  // Generic periodic function
  callPeriodically<T>(
    method: () => Observable<T>,
    period: number,
    initialDelay: number = 0
  ): Observable<T> {
    return new Observable(observer => {
      const subscription = timer(initialDelay).pipe(
        switchMap(() => interval(period).pipe(startWith(0))),
        exhaustMap(() =>
          method().pipe(
            catchError(err => {
              return new Observable<T>(subscriber => {
                subscriber.error(err);
                subscriber.complete();
              });
            })
          )
        )
      ).subscribe({
        next: value => observer.next(value),
        error: err => observer.error(err),
        complete: () => observer.complete()
      });
 
      return () => {
        subscription.unsubscribe();
      };
    });
  }
 
  // Generic periodic function
  callPeriodicallyBehaviorSubject<T>(
    method: () => Observable<T>,
    behaviorSubject: BehaviorSubject<T>,
    period: number,
    initialDelay: number = 0,
  ): Subscription {
 
    const subscription = timer(initialDelay).pipe(
      switchMap(() => interval(period).pipe(startWith(0))),
      exhaustMap(() =>
        method().pipe(
          catchError((err) => {
            return new Observable<T>((subscriber) => {
              subscriber.error(err);
              subscriber.complete();
            });
          })
        )
      )
    ).subscribe({
      next: (value) => behaviorSubject.next(value),
      error: (err) => behaviorSubject.error(err),
      complete: () => behaviorSubject.complete()
    });
 
    // Return the BehaviorSubject's subscription
    return subscription;
  }
 
 
  getVersion(): Observable<Slash> {
    return this.apiRequest<Slash>("");
  }
 
 
  private getStatus(): Observable<TwinPadStatus> {
    return this.apiRequest<TwinPadStatus>("status").pipe(
      map((response: TwinPadStatus) => {
        // Deserialize response into TwinPadStatus instance. Move this to models?
        const services = Object.assign(new ServicesStatus('down'), response['services']);
        const status = Object.assign(new TwinPadStatus(services), response);
        status.services = services;
        if ((this.devicesSubscription === undefined || this.devicesSubscription.closed) && status.services.backend === "up") {
          this.deviceSubscribe();
        }
        return status;
      }),
      catchError(error => {
        console.error('Error fetching status:', error);
        // Return a custom object in case of error
        const services = new ServicesStatus("down");
        const status = new TwinPadStatus(services);
        return of(status);
      })
    );
  }
 
  getSignalStats(): Observable<SignalStats> {
    return this.apiRequest<SignalStats>("signals/stats");
  }
 
 
  private getDevices(): Observable<Device[]> {
    return this.apiRequest<Device[]>("devices");
  }
 
  getDevice(device_id: string): Observable<Device> {
    return this.apiRequest<Device>(`devices/${device_id}`);
  }
 
  getDeviceSetups(): Observable<DeviceSetup[]> {
    return this.apiRequest<DeviceSetup[]>("device-setups");
  }
 
  getDeviceSetup(device_setup_id: string): Observable<DeviceSetup> {
    return this.apiRequest<DeviceSetup>(`device-setups/${device_setup_id}`);
  }
 
  deleteDeviceSetup(device_setup_id: string): Observable<DeviceSetup> {
    return this.apiRequest<DeviceSetup>(`device-setups/${device_setup_id}`, "DELETE");
  }
 
  getDeviceStates(device_id: string, limit: number, offset: number = 0, sort_by: string, modified_properties: string[]): Observable<ListResponse<DeviceState>> {
    const params: HttpParams = new HttpParams({ fromObject: { limit: limit, offset: offset, sort_by: sort_by, modified_properties: `in:${modified_properties}` } });
 
    return this.apiRequest<ListResponse<DeviceState>>(`devices/${device_id}/states`, "GET", { params: params });
  }
 
  getNumberSamples(min_timestamp: number, max_timestamp: number, recomputeAmount: boolean = false): Observable<TwinPadActivity[]> {
    const params = new HttpParams({ fromObject: { min_timestamp: min_timestamp, max_timestamp: max_timestamp, recompute_amount: recomputeAmount } });
    return this.apiRequest<TwinPadActivity[]>("number-samples", "GET", { params: params });
  }
 
  getSignals(limit: number, offset: number = 0, filter: string | null = null, device_id: string | null = null, signalIds: string[] | null = null, sortBy: string | null = null): Observable<ListResponse<Signal>> {
    let params: HttpParams = new HttpParams({ fromObject: { limit: limit, offset: offset, post_processing: false } });
 
    const signalIdFilter = [];
 
    if (device_id !== null) {
      signalIdFilter.push(`startswith:${device_id}`);
    }
    if (signalIds !== null) {
      signalIdFilter.push(`in:[${signalIds.join(',')}]`);
    }
    if (filter !== null) {
      signalIdFilter.push(`contains:${filter}`);
    }
    if (sortBy !== null) {
      params = params.set("sort_by", sortBy);
    }
 
    if (signalIdFilter.length) {
      params = params.set("signal_id", signalIdFilter.join("|"));
    }
    return this.apiRequest<ListResponse<Signal>>("signals", "GET", { params: params }).pipe(
      map((response: ListResponse<Signal>) => {
        const signals = [];
        for (const item of response['items']) {
          const device = Object.assign(new Device(), item['device']);
          const signal = Object.assign(new Signal(), item);
          signal.device = device;
          signals.push(signal);
        }
        response = Object.assign(new ListResponse(), response);
        response.items = signals;
        return response;
      })
    );
  }
 
  getSignalsIds(): Observable<string[]> {
    return this.apiRequest<string[]>("signals/ids");
  }
 
  getSignalsForcibility(signalIds: string[]): Observable<Map<string, boolean>> {
    return this.apiRequest<{ [key: string]: boolean }>("/signals/forcibility", "GET", { params: { signal_ids: signalIds } }).pipe(
      map((response) => {
        const newMap: Map<string, boolean> = new Map();
        for (const [key, value] of Object.entries(response)) {
          newMap.set(key, value);
        }
        return newMap;
      })
    );
  }
 
  getForcedSignals(limit: number, offset: number = 0, sortBy: string[]): Observable<ListResponse<ForcedSignal>> {
    let params: HttpParams = new HttpParams({ fromObject: { limit: limit, offset: offset } });
    params = params.set("sort_by", sortBy.join(','));
    return this.apiRequest<ListResponse<ForcedSignal>>("signals/forced", "GET", { params: params });
  }
 
  getSignal(signal_id: string): Observable<Signal> {
    return this.apiRequest<Signal>(`signals/${signal_id}`).pipe(
      map((response: Signal) => {
        // Deserialize
        return Object.assign(new Signal(), response);
      }));
  }
 
  getSignalData(signal_id: string, number_samples_max: number = 5000): Observable<SignalData> {
    return this.apiRequest<SignalData>(`signals/${signal_id}/data`, "GET", { params: { number_samples_max: number_samples_max } });
  }
 
  getSignalNumberSamples(signal_id: string): Observable<SampleStats> {
    return this.apiRequest<SampleStats>(`signals/${signal_id}/number-samples`).pipe(
      map((response: SampleStats) => {
        return response;
      })
    );
  }
 
  getSignalsData(signal_ids: string[], number_samples_max: number = 5000, min_timestamp: number | null = null, max_timestamp: number | null = null, interpolateBounds: boolean): Observable<SignalsData> {
    let params: HttpParams = new HttpParams({ fromObject: { signal_ids: signal_ids, number_samples_max: number_samples_max, interpolate_bounds: interpolateBounds } });
    Eif (min_timestamp !== null) {
      params = params.set("min_timestamp", min_timestamp);
    }
    Eif (max_timestamp !== null) {
      params = params.set("max_timestamp", max_timestamp);
    }
 
    return this.apiRequest<SignalsData>(`signals-data`, "GET", { params: params }).pipe(
      map((response: SignalsData) => { return SignalsData.deserialize(response); })
    );
  }
 
  getSignalsDataWithInterestWindow(signal_ids: string[], windowMaxNumberSamples: number | null = null, outsideMaxNumberSamples: number | null = null,
    windowMinTs: number | null = null, windowMaxTs: number | null = null,
    minTimestamp: number | null = null, maxTimestamp: number | null = null): Observable<SignalsData> {
    let params: HttpParams = new HttpParams({ fromObject: { signal_ids: signal_ids } });
    Eif (windowMaxNumberSamples !== null) {
      params = params.set("window_max_number_samples", windowMaxNumberSamples);
    }
    Eif (outsideMaxNumberSamples !== null) {
      params = params.set("outside_max_number_samples", outsideMaxNumberSamples);
    }
    Eif (windowMinTs !== null) {
      params = params.set("window_min_timestamp", windowMinTs);
    }
    Eif (windowMaxTs !== null) {
      params = params.set("window_max_timestamp", windowMaxTs);
    }
    Eif (minTimestamp !== null) {
      params = params.set("min_timestamp", minTimestamp);
    }
    Eif (maxTimestamp !== null) {
      params = params.set("max_timestamp", maxTimestamp);
    }
 
    return this.apiRequest<SignalsData>("signals-data/interest-window", "GET", { params: params }).pipe(
      map((response: SignalsData) => { return SignalsData.deserialize(response); })
    );
  }
 
  getPostProcessingSignalsData(phaseIds: string[], phaseSyncTimes: number[], signal_ids: string[], windowMinTs: number[], windowMaxTs: number[], maxNumberSamples: number | null = null): Observable<SignalsData> {
    let params: HttpParams = new HttpParams({ fromObject: { phase_ids: phaseIds, phase_sync_times: phaseSyncTimes, signal_ids: signal_ids, window_min_timestamps: windowMinTs, window_max_timestamps: windowMaxTs } });
    Eif (maxNumberSamples !== null) {
      params = params.set("number_samples_max", maxNumberSamples);
    }
 
    return this.apiRequest<SignalsData>("post-processing/signals-data", "GET", { params: params }).pipe(
      map((response: SignalsData) => { return SignalsData.deserialize(response); })
    );
  }
 
  getPostProcessingSingleFunction(phaseId: string, phaseSyncTime: number, signal_id: string, functionName: string, windowMinTs: number | null = null, windowMaxTs: number | null = null, maxNumberSamples: number | null = null): Observable<SignalsData> {
    let params: HttpParams = new HttpParams({ fromObject: { phase_id: phaseId, phase_sync_time: phaseSyncTime, function: functionName, base_signal_id: signal_id } });
    Eif (maxNumberSamples !== null) {
      params = params.set("number_samples_max", maxNumberSamples);
    }
    Eif (windowMinTs !== null) {
      params = params.set("window_min_timestamp", windowMinTs);
    }
    Eif (windowMaxTs !== null) {
      params = params.set("window_max_timestamp", windowMaxTs);
    }
 
    return this.apiRequest<SignalsData>("post-processing/functions/single", "GET", { params: params }).pipe(
      map((response: SignalsData) => { return SignalsData.deserialize(response); })
    );
  }
 
  getPostProcessingMultipleFunction(phaseIds: string[], phaseSyncTimes: number[], signalIds: string[], functionName: string, windowMinTs: number | null = null, windowMaxTs: number | null = null, maxNumberSamples: number | null = null): Observable<SignalsData> {
    let params: HttpParams = new HttpParams({ fromObject: { phase_ids: phaseIds, phase_sync_times: phaseSyncTimes, signal_ids: signalIds, function: functionName } });
    Eif (maxNumberSamples !== null) {
      params = params.set("number_samples_max", maxNumberSamples);
    }
    Eif (windowMinTs !== null) {
      params = params.set("window_min_timestamp", windowMinTs);
    }
    Eif (windowMaxTs !== null) {
      params = params.set("window_max_timestamp", windowMaxTs);
    }
 
    return this.apiRequest<SignalsData>("post-processing/functions/multiple", "GET", { params: params }).pipe(
      map((response: SignalsData) => { return SignalsData.deserialize(response); })
    );
  }
 
  downloadPostProcessingSignalsDataZip(fileFormat: string, phaseIds: string[], phaseSyncTimes: number[], signal_ids: string[], windowMinTs: number[], windowMaxTs: number[]): Observable<Blob> {
    const params: HttpParams = new HttpParams({ fromObject: { file_format: fileFormat, phase_ids: phaseIds, phase_sync_times: phaseSyncTimes, signal_ids: signal_ids, window_min_timestamps: windowMinTs, window_max_timestamps: windowMaxTs } });
 
    return this.apiRequest<Blob>("post-processing/export_zip", "GET", { params: params, responseType: 'blob' as 'json' });
  }
 
  downloadPostProcessingSignalsDataHDF5(phaseIds: string[], phaseSyncTimes: number[], signal_ids: string[], windowMinTs: number[], windowMaxTs: number[]): Observable<Blob> {
    const params: HttpParams = new HttpParams({ fromObject: { phase_ids: phaseIds, phase_sync_times: phaseSyncTimes, signal_ids: signal_ids, window_min_timestamps: windowMinTs, window_max_timestamps: windowMaxTs } });
 
    return this.apiRequest<Blob>("post-processing/export_hdf5", "GET", { params: params, responseType: 'blob' as 'json' });
  }
 
  getSignalValue(signal_id: string) {
    return this.apiRequest<SignalSample>(`signals/${signal_id}/last-value`).pipe(
      map((response: SignalSample) => {
        // Deserialize
        return Object.assign(new SignalSample(), response);
      }));
 
  }
 
  getSignalFirstValue(signal_id: string) {
    return this.apiRequest<SignalSample>(`signals/${signal_id}/first-value`).pipe(
      map((response: SignalSample) => {
        // Deserialize
        return Object.assign(new SignalSample(), response);
      }));
  }
 
  getSignalValues(signal_ids: string[]) {
    const params: HttpParams = new HttpParams({ fromObject: { signal_ids: signal_ids } });
    return this.apiRequest<SignalSample[]>(`signals/last-value`, "GET", { params: params }).pipe(
      map((response: SignalSample[]) => {
        // Deserialize
        const samples = [];
        for (const response_sample of response) {
          samples.push(Object.assign(new SignalSample(), response_sample));
        }
        return samples;
      }));
  }
 
  getSignalFirstValues(signal_ids: string[]) {
    const params: HttpParams = new HttpParams({ fromObject: { signal_ids: signal_ids } });
    return this.apiRequest<SignalSample[]>("signals/first-value", "GET", { params: params }).pipe(
      map((response: SignalSample[]) => {
        // Deserialize
        const samples = [];
        for (const response_sample of response) {
          samples.push(Object.assign(new SignalSample(), response_sample));
        }
        return samples;
      }));
  }
 
  changeDeviceMode(device: Device, newMode: Mode) {
    return this.apiRequest<CommandResponse>(`devices/${device.device_id}`, "PATCH", { body: { mode_id: newMode.mode_id } });
  }
 
  sendSignalCommand(signal: Signal, value: number | string | boolean, forced_value: number | string | boolean | null) {
    return this.apiRequest<CommandResponse>(`signals/${signal.signal_id}`, "PATCH", { body: { value: value, forced_value: forced_value } });
  }
 
  sendSignalForcedValue(signal: Signal, forced_value: number | string | boolean) {
    return this.apiRequest<CommandResponse>(`signals/${signal.signal_id}`, "PATCH", { body: { forced_value: forced_value } });
  }
 
  sendSignalUnforce(signalId: string) {
    return this.apiRequest<CommandResponse>(`signals/${signalId}`, "PATCH", { body: { forced_value: null } });
  }
 
  checkIfCanControlSignal(signal: Signal) {
    return this.apiRequest<boolean>(`signals/${signal.signal_id}/can-force`);
  }
 
  getEvents(limit: number, offset: number = 0, sortBy: string[], timestamp_min: number | null = null, timestamp_max: number | null = null, eventRuleId: string | null = null): Observable<ListResponse<Event>> {
    let params = new HttpParams({ fromObject: { limit: limit, offset: offset } });
    params = params.set("sort_by", sortBy.join(','));
    const timestamp_req: string[] = [];
    Iif (timestamp_min !== null) {
      timestamp_req.push('gte:' + timestamp_min.toString());
    }
    if (timestamp_max !== null) {
      timestamp_req.push('lte:' + timestamp_max.toString());
    }
    if (timestamp_req.length > 0) {
      params = params.set("timestamp", timestamp_req.join('|'));
    }
    Iif (eventRuleId !== null) {
      params = params.set("event_rule_id", eventRuleId);
    }
 
    return this.apiRequest<ListResponse<Event>>("events", "GET", { params: params });
  }
 
  getEvent(eventId: string): Observable<Event> {
    return this.apiRequest<Event>(`events/${eventId}`).pipe(
      map((response: Event) => {
        // Deserialize
        const eventRule = Object.assign(new EventRule(), response['event_rule']);
        const event = Object.assign(new Event(), response);
        event.event_rule = eventRule;
        return event;
      }));
  }
 
  getNumberEvents(min_timestamp: number, max_timestamp: number, recomputeAmount: boolean = false): Observable<TwinPadActivity[]> {
    const params = new HttpParams({ fromObject: { min_timestamp: min_timestamp, max_timestamp: max_timestamp, recompute_amount: recomputeAmount } });
    return this.apiRequest<TwinPadActivity[]>("number-events", "GET", { params: params });
  }
 
  getNumberCommands(min_timestamp: number, max_timestamp: number, recomputeAmount: boolean = false): Observable<TwinPadActivity[]> {
    const params = new HttpParams({ fromObject: { min_timestamp: min_timestamp, max_timestamp: max_timestamp, recompute_amount: recomputeAmount } });
    return this.apiRequest<TwinPadActivity[]>("number-commands", "GET", { params: params });
  }
 
  getEventRules(limit: number, offset: number = 0, sortBy: string[]): Observable<ListResponse<EventRule>> {
    let params = new HttpParams({ fromObject: { limit: limit, offset: offset } });
    params = params.set("sort_by", sortBy.join(','));
 
    return this.apiRequest<ListResponse<EventRule>>("event-rules", "GET", { params: params });
  }
 
  getEventRule(eventRuleId: string): Observable<EventRule> {
    return this.apiRequest<EventRule>(`event-rules/${eventRuleId}`).pipe(
      map((response: EventRule) => {
        // Deserialize
        const event_rule = Object.assign(new EventRule(), response);
        return event_rule;
      }));
  }
 
  downloadSignalsDataZip(file_format: string, signal_ids: string[], min_timestamp: number | null = null, max_timestamp: number | null = null): Observable<Blob> {
    let params: HttpParams = new HttpParams({ fromObject: { file_format: file_format, signal_ids: signal_ids } });
    Iif (min_timestamp !== null) {
      params = params.set("min_timestamp", min_timestamp);
    }
    Iif (max_timestamp !== null) {
      params = params.set("max_timestamp", max_timestamp);
    }
 
    return this.apiRequest<Blob>("signals-data/export_zip", "GET", { params: params, responseType: 'blob' as 'json' },);
  }
 
  downloadSignalsDataHDF5(signal_ids: string[], min_timestamp: number | null = null, max_timestamp: number | null = null): Observable<Blob> {
    let params: HttpParams = new HttpParams({ fromObject: { signal_ids: signal_ids } });
    Iif (min_timestamp !== null) {
      params = params.set("min_timestamp", min_timestamp);
    }
    Iif (max_timestamp !== null) {
      params = params.set("max_timestamp", max_timestamp);
    }
 
    return this.apiRequest<Blob>("signals-data/export_hdf5", "GET", { params: params, responseType: 'blob' as 'json' },);
  }
 
  getCampaigns(): Observable<Campaign[]> {
    return this.apiRequest<Campaign[]>("campaigns");
  }
 
  getCampaignById(campaignId: string): Observable<Campaign> {
    return this.apiRequest<Campaign>(`campaigns/${campaignId}`);
  }
 
  addCampaign(campaignName: string, campaignDescription?: string): Observable<object> {
    const options = {
      headers: new HttpHeaders().set('Content-type', 'application/json'),
      body: { "name": campaignName, "description": campaignDescription }
    };
    return this.apiRequest("campaigns", "POST", options);
  }
 
  editCampaign(campaignId: string, campaignName: string, campaignDescription?: string): Observable<object> {
    const options = { headers: new HttpHeaders().set('Content-type', 'application/json'), body: { "name": campaignName, "description": campaignDescription } };
    return this.apiRequest(`campaigns/${campaignId}`, "PATCH", options);
  }
 
  deleteCampaign(campaignId: string): Observable<object> {
    return this.apiRequest(`campaigns/${campaignId}`, "DELETE");
  }
 
  getPhases(campaignId: string): Observable<Phase[]> {
    return this.apiRequest<Phase[]>(`campaigns/${campaignId}/phases`);
  }
 
  getPhase(phaseId: string): Observable<Phase> {
    return this.apiRequest<Phase>(`phases/${phaseId}`);
  }
 
  addPhase(campaignId: string, phaseName: string, phaseDateStart: number, phaseDateEnd: number, phaseDescription?: string): Observable<Phase> {
    const options = {
      headers: new HttpHeaders().set('Content-type', 'application/json'),
      body: { "name": phaseName, "description": phaseDescription, "start_at": phaseDateStart, "end_at": phaseDateEnd, "campaign_id": campaignId }
    };
    return this.apiRequest("phases", "POST", options);
  }
 
  editPhase(phaseName: string, phaseDateStart: number, phaseDateEnd: number, campaignId: string, phaseId?: string, phaseDescription?: string,) {
    const options = {
      headers: new HttpHeaders().set('Content-type', 'application/json'),
      body: { "name": phaseName, "description": phaseDescription, "start_at": phaseDateStart, "end_at": phaseDateEnd, "campaign_id": campaignId }
    };
    return this.apiRequest(`phases/${phaseId}`, "PATCH", options);
  }
 
  deletePhase(phaseId?: string) {
    return this.apiRequest(`phases/${phaseId}`, "DELETE");
  }
 
  getVideos(): Observable<Video[]> {
    return this.apiRequest<Video[]>("videos");
  }
 
  getStream(video_id: string): Observable<string> {
    return this.apiRequest<string>(`videos/${video_id}`);
  }
 
  getCommands(limit: number, offset: number = 0, filter: string | null = null, sortBy: string[], minTimestamp: number, maxTimestamp: number): Observable<ListResponse<Command>> {
    let params: HttpParams = new HttpParams({ fromObject: { limit: limit, offset: offset } });
 
    const descriptionFilter = [];
    Iif (filter !== null) {
      descriptionFilter.push(`contains:${filter}`);
    }
    Iif (descriptionFilter.length) {
      params = params.set("description", descriptionFilter.join("|"));
    }
 
    params = params.set("sort_by", sortBy.join(','));
 
    const timestamp_req: string[] = [];
    Iif (minTimestamp !== undefined) {
      timestamp_req.push('gte:' + minTimestamp.toString());
    }
    Iif (maxTimestamp !== undefined) {
      timestamp_req.push('lte:' + maxTimestamp.toString());
    }
    Iif (timestamp_req.length > 0) {
      params = params.set("sent_at", timestamp_req.join('|'));
    }
 
    return this.apiRequest<ListResponse<Command>>("commands", "GET", { params: params });
  }
 
  getCustomViews(): Observable<CustomView[]> {
    return this.apiRequest<CustomView[]>("custom-views", "GET");
  }
 
  getCustomViewsFromUserId(userId: string): Observable<CustomView[]> {
    return this.apiRequest<CustomView[]>(`users/${userId}/custom-views`, "GET");
  }
 
  getCustomViewById(customViewId: string): Observable<CustomView> {
    return this.apiRequest<CustomView>(`custom-views/${customViewId}`, "GET");
  }
 
  createCustomView(customView: CustomView): Observable<CustomView> {
    const options = {
      headers: new HttpHeaders().set('Content-type', 'application/json'),
      body: { "name": customView.name, "user_id": customView.user_id, "configuration": customView.configuration }
    };
 
    return this.apiRequest<CustomView>("custom-views", "POST", options);
  }
 
  updateCustomView(customView: CustomView): Observable<CustomView> {
    const options = {
      headers: new HttpHeaders().set('Content-type', 'application/json'),
      body: { "name": customView.name, "user_id": customView.user_id, "configuration": customView.configuration }
    };
    return this.apiRequest<CustomView>(`custom-views/${customView.id}`, "PATCH", options);
  }
 
  deleteCustomView(customViewId: string): Observable<boolean> {
    return this.apiRequest<boolean>(`custom-views/${customViewId}`, "DELETE");
  }
 
  getUserSignalsPresets(): Observable<SignalsPreset[]> {
    return this.apiRequest<SignalsPreset[]>(`signals-presets`, "GET");
  }
 
  getSignalsPresetById(signalsPresetId: string): Observable<SignalsPreset> {
    return this.apiRequest<SignalsPreset>(`signals-presets/${signalsPresetId}`, "GET");
  }
 
  createSignalsPreset(name: string, signalIds: string[]): Observable<string> {
    const options = {
      headers: new HttpHeaders().set('Content-type', 'application/json'),
      body: { "name": name, "signal_ids": signalIds }
    };
    return this.apiRequest<string>("signals-presets", "POST", options);
  }
 
  updateSignalsPreset(signalsPreset: SignalsPreset): Observable<SignalsPreset> {
    const options = {
      headers: new HttpHeaders().set('Content-type', 'application/json'),
      body: { "name": signalsPreset.name, "signal_ids": signalsPreset.signal_ids }
    };
    return this.apiRequest<SignalsPreset>(`signals-presets/${signalsPreset.id}`, "PATCH", options);
  }
 
  deleteSignalsPreset(signalsPresetId: string): Observable<boolean> {
    return this.apiRequest<boolean>(`signals-presets/${signalsPresetId}`, "DELETE");
  }
 
  createGraphTheme(newTheme: GraphTheme) {
    const options = {
      headers: new HttpHeaders().set('Content-type', 'application/json'),
      body: newTheme
    };
    return this.apiRequest<GraphTheme>("/graph-themes", "POST", options);
  }
 
  getGraphThemes() {
    const params: HttpParams = new HttpParams({ fromObject: { sort_by: "created_by_user:-1" } });
    return this.apiRequest<ListResponse<GraphTheme>>("/graph-themes", "GET", { params: params });
  }
 
  getFavoriteGraphThemes() {
    return this.apiRequest<ListResponse<GraphTheme>>("/graph-themes/own");
  }
 
  updateGraphTheme(themeId: string, themeUpdate: GraphTheme) {
    const updateDict: { [key: string]: string | boolean | LineStyle } = {};
    for (const [key, value] of Object.entries(themeUpdate)) {
      Eif (value !== undefined) {
        updateDict[key] = value;
      }
    }
    const options = {
      headers: new HttpHeaders().set('Content-type', 'application/json'),
      body: updateDict
    };
    return this.apiRequest<GraphTheme>(`/graph-themes/${themeId}`, "PATCH", options);
  }
 
  getSignalsGraphThemes(signalIds: string[]) {
    const params: HttpParams = new HttpParams({ fromObject: { signal_ids: signalIds } });
    return this.apiRequest<object>("/signals-appearances", "GET", { params: params });
  }
 
  deleteGraphTheme(themeId: string) {
    return this.apiRequest(`/graph-themes/${themeId}`, "DELETE");
  }
 
  getToken() {
    return localStorage.getItem("accessToken");
  }
 
  getTokenPayload(): AccessTokenPayload | null {
    const token = this.getToken();
    if (token === null) {
      return null;
    }
    return jwtDecode<AccessTokenPayload>(token);
  }
 
  isAdminfromToken() {
    const payload = this.getTokenPayload();
    if (payload === null) {
      return false;
    }
    return payload.admin;
  }
 
  logout() {
    localStorage.removeItem('accessToken');
    this.loggedInUserBehaviorSubject$.next(false);
  }
 
  redirectToLogin(router: Router) {
    const params: { [key: string]: string } = {};
    if (window.location.pathname !== "/") {
      params["redirectTo"] = window.location.pathname?.slice(1);
    }
    router.navigate(['/login'], { queryParams: params });
  }
 
  login(loginForm: FormGroup): Observable<AccessToken> {
    const body = new URLSearchParams();
    body.set('username', loginForm.get('email')?.value);
    body.set('password', loginForm.get('password')?.value);
    const options = {
      headers: new HttpHeaders().set('Content-type', 'application/x-www-form-urlencoded'),
      body: body.toString()
    };
    return this.apiRequest<AccessToken>('token', "POST", options);
  }
 
 
  register(form_firstname: string, form_lastname: string, form_email: string, form_password: string) {
    const payload = { "firstname": form_firstname, "lastname": form_lastname, "email": form_email, "password": form_password };
    return this.apiRequest('users', "POST", { body: payload });
  }
 
  getProfile(userId?: string): Observable<User> {
    if (userId) {
      return this.apiRequest<User>('users/' + userId, "GET", {});
    }
    return this.apiRequest<User>('users/me', "GET", {});
  }
 
  editProfile(profileForm: FormGroup, userId: string): Observable<User> {
    const payload = {
      "id": userId,
      "firstname": profileForm.get('firstname')?.value,
      "lastname": profileForm.get('lastname')?.value,
      "email": profileForm.get('email')?.value,
      "password": profileForm.get('password')?.value,
      "is_active": profileForm.get('userBlocked')?.value,
      "is_admin": profileForm.get('userAdministrator')?.value
    };
    const options = {
      headers: new HttpHeaders().set('Content-type', 'application/x-www-form-urlencoded'),
      body: payload
    };
    return this.apiRequest<User>('users/' + userId, "PATCH", options);
  }
 
  getUsers(): Observable<User[]> {
    return this.apiRequest<User[]>("users", "GET");
  }
 
 
  isTokenValid(): boolean {
    const token = localStorage.getItem("accessToken");
    if (token != null) {
      const exp = jwtDecode(token).exp;
      Eif (exp != null && exp > (Date.now() / 1000)) {  // Divide by 1000 to get same timestamp length
        return true;
      }
    }
    localStorage.removeItem('accessToken');
    return false;
  }
 
  loggedInUserSubscribe() {
    this.loggedInUserBehaviorSubject$.subscribe({
      next: isUserLoggedIn => {
        if (isUserLoggedIn) {
          Eif (this.cloudStatusSubscription === undefined || this.cloudStatusSubscription.closed) {
            // also subscribes to device if backend is up
            this.statusSubscribe();
          }
        }
        else {
          this.cloudStatusSubscription?.unsubscribe();
          this.devicesSubscription?.unsubscribe();
        }
      },
      error: (err) => {
        console.log(err);
      }
    });
  }
 
  deviceSubscribe(initialDelay?: number) {
    this.devicesSubscription?.unsubscribe();
    Iif (this.devicesBehaviorSubject$.closed || !this.devicesBehaviorSubject$.observed) {
      this.devicesBehaviorSubject$ = new BehaviorSubject<Device[]>([]);
    }
    this.devicesSubscription = this.callPeriodicallyBehaviorSubject(
      () => this.getDevices(),
      this.devicesBehaviorSubject$,
      1000 * this.devicesRefreshTime,
      initialDelay,
    );
  }
 
  statusSubscribe(initialDelay?: number) {
    this.cloudStatusSubscription?.unsubscribe();
    this.cloudStatusSubscription = this.callPeriodicallyBehaviorSubject(
      () => this.getStatus(),
      this.cloudStatusBehaviorSubject$,
      1000 * this.statusRefreshTime,
      initialDelay,
    );
  }
}