All files / sportident/src/SiDevice SiDevice.ts

100% Statements 64/64
100% Branches 11/11
100% Functions 18/18
100% Lines 64/64

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 1375x 5x     5x             41x 41x 41x 41x       60x       51x 46x 46x               6x 1x   5x 1x   4x 1x   3x 3x 3x   1x 1x 1x 1x     1x 1x     1x         6x 1x   5x 1x   4x 1x   3x 3x 3x   1x 1x     1x 1x     1x         18x 18x   3x 3x           4x 1x 1x   3x 3x   6x 1x   11x 11x 11x 3x 3x   8x 7x         15x             18x       22x 22x         5x  
import {DeviceClosedError, ISiDevice, ISiDeviceDriverData, SiDeviceEvents, SiDeviceReceiveEvent, SiDeviceState, SiDeviceStateChangeEvent} from './ISiDevice';
import * as utils from '../utils';
import { ISiDeviceDriver } from './ISiDeviceDriver';
 
export class SiDevice<T extends ISiDeviceDriverData<ISiDeviceDriver<T>>> implements ISiDevice<T> {
    name: string;
    ident: string;
    data: T;
    private internalState: SiDeviceState;
 
    constructor(typeSpecificIdent: string, data: T) {
        this.data = data;
        this.name = `${data.driver.name}(${typeSpecificIdent})`;
        this.ident = `${data.driver.name}-${typeSpecificIdent}`;
        this.internalState = SiDeviceState.Closed;
    }
 
    get state(): SiDeviceState {
        return this.internalState;
    }
 
    setState(newState: SiDeviceState): void {
        if (newState !== this.internalState) {
            this.internalState = newState;
            this.dispatchEvent(
                'stateChange',
                new SiDeviceStateChangeEvent(this, newState),
            );
        }
    }
 
    open(): Promise<SiDevice<T>> {
        if (this.state === SiDeviceState.Closing) {
            return Promise.reject(new Error(`Cannot open closing ${this.constructor.name}`));
        }
        if (this.state === SiDeviceState.Opening) {
            return Promise.reject(new Error(`Cannot open opening ${this.constructor.name}`));
        }
        if (this.state === SiDeviceState.Opened) {
            return Promise.resolve(this);
        }
        this.setState(SiDeviceState.Opening);
        try {
            return this.data.driver.open(this)
                .then(() => {
                    console.debug('Starting Receive Loop...');
                    this.receiveLoop();
                    this.setState(SiDeviceState.Opened);
                    return this;
                })
                .catch((err: Error) => {
                    this.setState(SiDeviceState.Closed);
                    throw err;
                });
        } catch (err) {
            return Promise.reject(err);
        }
    }
 
    close(): Promise<SiDevice<T>> {
        if (this.state === SiDeviceState.Closing) {
            return Promise.reject(new Error(`Cannot close closing ${this.constructor.name}`));
        }
        if (this.state === SiDeviceState.Opening) {
            return Promise.reject(new Error(`Cannot close opening ${this.constructor.name}`));
        }
        if (this.state === SiDeviceState.Closed) {
            return Promise.resolve(this);
        }
        this.setState(SiDeviceState.Closing);
        try {
            return this.data.driver.close(this)
                .then(() => {
                    this.setState(SiDeviceState.Closed);
                    return this;
                })
                .catch((err: Error) => {
                    this.setState(SiDeviceState.Closed);
                    throw err;
                });
        } catch (err) {
            return Promise.reject(err);
        }
    }
 
    receiveLoop(): void {
        try {
            this.receive()
                .then((uint8Data) => {
                    console.debug(`<= (${this.name})\n${utils.prettyHex(uint8Data, 16)}`);
                    this.dispatchEvent(
                        'receive',
                        new SiDeviceReceiveEvent(this, uint8Data),
                    );
                })
                .catch((err: Error) => {
                    if (this.shouldStopReceivingBecauseOfError(err)) {
                        console.warn('Receive loop stopped while receiving');
                        throw err;
                    }
                    console.warn(`${this.name}: Error receiving: ${err.message}`);
                    return utils.waitFor(100);
                })
                .then(() => this.receiveLoop())
                .catch(() => undefined);
        } catch (exc: unknown) {
            const err = utils.getErrorOrThrow(exc);
            console.warn(`${this.name}: Error starting receiving: ${err.message}`);
            if (this.shouldStopReceivingBecauseOfError(err)) {
                console.warn('Receive loop stopped while starting receiving');
                return;
            }
            utils.waitFor(100)
                .then(() => this.receiveLoop());
        }
    }
 
    shouldStopReceivingBecauseOfError(error: unknown): boolean {
        return (
            error instanceof DeviceClosedError
            || error instanceof utils.NotImplementedError
        );
    }
 
    receive(): Promise<number[]> {
        return this.data.driver.receive(this);
    }
 
    send(buffer: number[]): Promise<unknown> {
        console.debug(`=> (${this.name})\n${utils.prettyHex(buffer, 16)}`);
        return this.data.driver.send(this, buffer);
    }
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars
export interface SiDevice<T extends ISiDeviceDriverData<ISiDeviceDriver<T>>> extends utils.EventTarget<SiDeviceEvents> {}
utils.applyMixins(SiDevice, [utils.EventTarget]);