All files / src/shared/services point-cloud.service.ts

3.7% Statements 1/27
100% Branches 0/0
0% Functions 0/15
4.16% Lines 1/24

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                    1x                                                                                                                      
import { Inject, Injectable } from '@angular/core';
import * as signalR from '@microsoft/signalr';
import { BehaviorSubject, from, fromEventPattern, Observable, using } from 'rxjs';
import { concatMap, filter, share, skipWhile } from 'rxjs/operators';
import { LogService } from 'src/app/log/log.service';
import { Point3 } from '@reflex/shared-types';
 
@Injectable({
  providedIn: 'root'
})
export class PointCloudService {
  private readonly connection: signalR.HubConnection;
 
  private readonly isConnected = new BehaviorSubject<boolean>(false);
  private readonly isStarted = new BehaviorSubject<boolean>(false);
 
  private readonly startAfterConnected$: Observable<void>;
  private readonly points$: Observable<Array<Point3>>;
 
  // eslint-disable-next-line new-cap
  public constructor(@Inject('BASE_URL') private readonly baseUrl: string, private readonly logService: LogService) {
    this.connection = new signalR.HubConnectionBuilder()
      .withUrl(`${this.baseUrl}pointcloudhub`)
      .build();
 
    // update connection status the rxjs way
    from(this.connection.start()).subscribe(
      () => this.isConnected.next(true),
      (error) => {
        console.error(error);
        this.logService.sendErrorLog(`${error}`);
      }
    );
 
    this.points$ = fromEventPattern<Array<Point3>>(
      (handler) => this.connection.on('pointCloud', handler),
      (handler) => this.connection.off('pointCloud', handler)
    )
      .pipe(
        share(),
        filter((x) => x !== undefined)
      );
 
    // send 'startState' only after 'isConnected' emits true
    this.startAfterConnected$ = this.isConnected.pipe(
      skipWhile((value) => !value),
      concatMap(async () => this.connection.send('startPointCloud').catch((error) => {
        console.error(error);
        this.logService.sendErrorLog(`${error}`);
      }))
    );
  }
 
  /**
   * @return an Observable of Arrays of Point3 from the currently configured camera
   */
  public getPointCloud(): Observable<Array<Point3>> {
    return using(() => {
      this.startAfterConnected$.subscribe(() => this.isStarted.next(true));
 
      // eslint-disable-next-line @typescript-eslint/no-misused-promises
      return { unsubscribe: async () => this.connection.send('stopPointCloud').catch((error) => {
        console.error(error);
        this.logService.sendErrorLog(`${error}`);
      }) };
    }, () => this.points$);
 
  }
}