All files / sportident-node-usb/src NodeUsbSiDeviceDriver.ts

91.13% Statements 72/79
37.5% Branches 3/8
100% Functions 25/25
90.9% Lines 70/77

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  2x 2x   2x   2x 2x 2x 2x 2x 2x     2x     1x   1x         5x                                       4x   4x     4x           4x       2x           1x     1x         4x 4x 1x   3x       3x 3x 3x                                                                                                           1x           1x 1x     1x 1x 1x                                                                                                                 2x 2x 2x   2x 2x     2x 2x     2x 2x     2x 2x     2x 2x                 2x 2x               2x           1x 1x 1x               1x 1x     1x 1x   1x           3x 3x         3x   2x     2x 2x               1x 1x 1x 1x         2x   2x   4x  
import {webusb} from 'usb';
import * as utils from 'sportident/lib/utils';
import {DeviceClosedError, ISiDevice, ISiDeviceDriverData, SiDeviceState} from 'sportident/lib/SiDevice/ISiDevice';
import {ISiDeviceDriver, ISiDeviceDriverWithDetection, SiDeviceDriverWithAutodetectionEvents} from 'sportident/lib/SiDevice/ISiDeviceDriver';
import {SiDevice} from 'sportident/lib/SiDevice/SiDevice';
 
const siConfiguration = 1;
const siInterface = 0;
const siAlternate = 0;
const siEndpoint = 1;
const siPacketSize = 64;
const siDeviceFilters = [
    {vendorId: 0x10c4, productId: 0x800a},
];
const matchesSiDeviceFilters = (
    vendorId: number,
    productId: number,
) => siDeviceFilters.some(
    (filter) => (
        vendorId === filter.vendorId
        && productId === filter.productId
    ),
);
 
const getIdent = (device: USBDevice) => `${device.serialNumber}`;
 
export interface NodeUsbSiDeviceDriverData extends ISiDeviceDriverData<NodeUsbSiDeviceDriver> {
    driver: NodeUsbSiDeviceDriver;
    device: USBDevice;
}
 
// interface NodeUsbAutodetectionCallbacks {
//     onAttach: utils.EventCallback<utils.IEvent<'attach'>>;
//     onDetach: utils.EventCallback<utils.IEvent<'detach'>>;
// }
 
export type INodeUsbSiDevice = ISiDevice<NodeUsbSiDeviceDriverData>;
export type NodeUsbSiDevice = SiDevice<NodeUsbSiDeviceDriverData>;
 
class NodeUsbSiDeviceDriver implements
        ISiDeviceDriver<NodeUsbSiDeviceDriverData>,
        ISiDeviceDriverWithDetection<NodeUsbSiDeviceDriverData, []> {
    /* ISiDeviceDriverWithAutodetection<NodeUsbSiDeviceDriverData> */
 
    public name = 'NodeUSB';
 
    private siDeviceByIdent:
        {[ident: string]: NodeUsbSiDevice} = {};
 
    private autodetectedSiDevices:
        {[ident: string]: NodeUsbSiDevice} = {};
 
    // private autodetectionCallbacks?: NodeUsbAutodetectionCallbacks;
 
    constructor(
        private nodeUsb: typeof webusb,
    ) {}
 
    detect(): Promise<NodeUsbSiDevice> {
        return Promise.resolve(
            this.nodeUsb.requestDevice({
                filters: siDeviceFilters,
            }),
        )
            .then((nodeUsbDevice) => {
                Iif (!nodeUsbDevice) {
                    throw new Error('no device found');
                }
                return this.autodetectSiDevice(nodeUsbDevice);
            });
    }
 
    getSiDevice(nodeUsbDevice: USBDevice): NodeUsbSiDevice {
        const ident = getIdent(nodeUsbDevice);
        if (this.siDeviceByIdent[ident] !== undefined) {
            return this.siDeviceByIdent[ident];
        }
        const newSiDeviceData: NodeUsbSiDeviceDriverData = {
            driver: this,
            device: nodeUsbDevice,
        };
        const newSiDevice = new SiDevice(ident, newSiDeviceData);
        this.siDeviceByIdent[ident] = newSiDevice;
        return newSiDevice;
    }
    //
    // forgetSiDevice(
    //     siDevice: NodeUsbSiDevice,
    // ) {
    //     const nodeUsbDevice = siDevice.data.device;
    //     const ident = getIdent(nodeUsbDevice);
    //     delete this.siDeviceByIdent[ident];
    //     if (this.autodetectedSiDevices[ident] !== undefined) {
    //         this.dispatchEvent('remove', new SiDeviceRemoveEvent(siDevice));
    //     }
    //     delete this.autodetectedSiDevices[ident];
    // }
    //
    // startAutoDetection(): Promise<INodeUsbSiDevice[]> {
    //     this.registerAutodetectionCallbacks();
    //     return this.getAutodetectedDevices();
    // }
    //
    // getAutodetectedDevices(): Promise<NodeUsbSiDevice[]> {
    //     return this.nodeUsb.getDevices()
    //         .then((nodeUsbDevices: iNodeUsb.NodeUsbDevice[]) => (
    //             this.autodetectSiDevices(nodeUsbDevices)
    //         ));
    // }
    //
    // autodetectSiDevices(
    //     nodeUsbDevices: iNodeUsb.NodeUsbDevice[]
    // ): Promise<NodeUsbSiDevice[]> {
    //     // TODO: Make this easier when Promise.allSettled polyfill is available
    //     return new Promise((resolve) => {
    //         let numSettled = 0;
    //         const devices: NodeUsbSiDevice[] = [];
    //         const onSettled = () => {
    //             numSettled += 1;
    //             if (numSettled === nodeUsbDevices.length) {
    //                 resolve(devices);
    //             }
    //         };
    //         nodeUsbDevices.forEach(
    //             (nodeUsbDevice: iNodeUsb.NodeUsbDevice) => (
    //                 this.autodetectSiDevice(nodeUsbDevice)
    //                     .then((siDevice: NodeUsbSiDevice) => {
    //                         devices.push(siDevice);
    //                         onSettled();
    //                     })
    //                     .catch(() => onSettled())
    //             )
    //         )
    //     });
    // }
 
    autodetectSiDevice(nodeWebUsbDevice: USBDevice): Promise<NodeUsbSiDevice> {
        Iif (!matchesSiDeviceFilters(
            nodeWebUsbDevice.vendorId,
            nodeWebUsbDevice.productId,
        )) {
            return Promise.reject(new Error('Not a SI device'));
        }
        const ident = getIdent(nodeWebUsbDevice);
        Iif (this.autodetectedSiDevices[ident] !== undefined) {
            return Promise.reject(new Error('Duplicate SI device'));
        }
        const siDevice = this.getSiDevice(nodeWebUsbDevice);
        this.autodetectedSiDevices[ident] = siDevice;
        return siDevice.open();
    }
 
    // registerAutodetectionCallbacks(): void {
    //     if (this.autodetectionCallbacks !== undefined) {
    //         return;
    //     }
    //     const onConnectCallback = (event: iNodeUsb.WebUsbConnectEvent) => {
    //         const nodeUsbDevice = event.device;
    //         this.autodetectSiDevice(nodeUsbDevice)
    //             .then((openedDevice: NodeUsbSiDevice) => {
    //                 this.dispatchEvent('add', new SiDeviceAddEvent(openedDevice));
    //             });
    //     };
    //     this.nodeUsb.addEventListener('connect', onConnectCallback);
    //     const onDisconnectCallback = (event: iNodeUsb.WebUsbDisconnectEvent) => {
    //         const nodeUsbDevice = event.device;
    //         const ident = getIdent(nodeUsbDevice);
    //         const siDevice = this.siDeviceByIdent[ident];
    //         if (siDevice === undefined) {
    //             return;
    //         }
    //         this.forgetSiDevice(siDevice);
    //     };
    //     this.nodeUsb.addEventListener('disconnect', onDisconnectCallback);
    //     this.autodetectionCallbacks = {
    //         onConnect: onConnectCallback,
    //         onDisconnect: onDisconnectCallback,
    //     };
    // }
    //
    // stopAutoDetection(): Promise<unknown> {
    //     this.deregisterAutodetectionCallbacks();
    //     return this.closeAutoOpened();
    // }
    //
    // deregisterAutodetectionCallbacks(): void {
    //     if (this.autodetectionCallbacks === undefined) {
    //         return;
    //     }
    //     this.nodeUsb.removeEventListener('connect', this.autodetectionCallbacks.onConnect);
    //     this.nodeUsb.removeEventListener('disconnect', this.autodetectionCallbacks.onDisconnect);
    //     this.autodetectionCallbacks = undefined;
    // }
    //
    // closeAutoOpened(): Promise<unknown> {
    //     return Promise.all(
    //         Object.values(this.autodetectedSiDevices).map(
    //             (autoOpenedDevice) => autoOpenedDevice.close(),
    //         ),
    //     )
    //         .then(() => {
    //             this.autodetectedSiDevices = {};
    //         });
    // }
 
    open(device: INodeUsbSiDevice): Promise<unknown> {
        console.debug('Opening...');
        const nodeDevice = device.data.device;
        return nodeDevice.open()
            .then(() => {
                console.debug('Resetting...');
                return nodeDevice.reset();
            })
            .then(() => {
                console.debug('Selecting Configuration...');
                return nodeDevice.selectConfiguration(siConfiguration);
            })
            .then(() => {
                console.debug('Claiming Interface...');
                return nodeDevice.claimInterface(siInterface);
            })
            .then(() => {
                console.debug('Selection Alternate Interface...');
                return nodeDevice.selectAlternateInterface(siInterface, siAlternate);
            })
            .then(() => {
                console.debug('Enabling Serial...');
                return nodeDevice.controlTransferOut({
                    requestType: 'vendor',
                    recipient: 'interface',
                    request: 0x00,
                    value: 0x01,
                    index: siInterface,
                });
            })
            .then(() => {
                console.debug('Setting Baudrate...');
                return nodeDevice.controlTransferOut({
                    requestType: 'vendor',
                    recipient: 'interface',
                    request: 0x1E,
                    value: 0x00,
                    index: siInterface,
                }, new Uint8Array([0x00, 0x96, 0x00, 0x00]).buffer);
            })
            .then(() => true);
    }
 
    close(
        device: INodeUsbSiDevice,
    ): Promise<unknown> {
        console.debug('Disabling Serial...');
        const nodeDevice = device.data.device;
        return nodeDevice.controlTransferOut({
            requestType: 'vendor',
            recipient: 'interface',
            request: 0x00,
            value: 0x00,
            index: siInterface,
        })
            .then(() => {
                console.debug('Releasing Interface...');
                return nodeDevice.releaseInterface(siInterface);
            })
            .then(() => {
                console.debug('Closing Device...');
                return nodeDevice.close();
            })
            .then(() => true);
    }
 
    receive(
        device: INodeUsbSiDevice,
    ): Promise<number[]> {
        const nodeDevice = device.data.device;
        Iif (nodeDevice.opened !== true) {
            console.warn('Device has been closed. Stopping receive loop.');
            device.setState(SiDeviceState.Closed);
            throw new DeviceClosedError();
        }
        return nodeDevice.transferIn(siEndpoint, siPacketSize)
            .then((response) => {
                Iif (!response.data) {
                    return [];
                }
                const uint8Data = new Uint8Array(response.data.buffer);
                return [...uint8Data];
            });
    }
 
    send(
        device: INodeUsbSiDevice,
        uint8Data: number[],
    ): Promise<unknown> {
        const nodeDevice = device.data.device;
        const buffer = new Uint8Array(uint8Data);
        return nodeDevice.transferOut(siEndpoint, buffer)
            .then(() => true);
    }
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface NodeUsbSiDeviceDriver extends utils.EventTarget<SiDeviceDriverWithAutodetectionEvents<NodeUsbSiDeviceDriverData>> {}
utils.applyMixins(NodeUsbSiDeviceDriver, [utils.EventTarget]);
 
export const getNodeUsbSiDeviceDriver = (
    nodeWebUsb: typeof webusb,
): NodeUsbSiDeviceDriver => new NodeUsbSiDeviceDriver(nodeWebUsb);