UNPKG

@awarns/ble

Version:

AwarNS Framework package that allows to scan for nearby BLE devices

51 lines 2.14 kB
import { ProviderInterrupter } from '@awarns/core/providers'; import { BleScan, BleScanType } from './scan'; import { getBleScanProvider as getNativeProvider, } from 'nativescript-context-apis/ble'; import { firstValueFrom, map, Subject, takeUntil, timer, toArray } from 'rxjs'; export class BleScanProvider { constructor(scanTime, scanMode, iBeaconUuids, nativeProvider = getNativeProvider) { this.scanTime = scanTime; this.scanMode = scanMode; this.iBeaconUuids = iBeaconUuids; this.nativeProvider = nativeProvider; } get provides() { return BleScanType; } async checkIfIsReady() { const isReady = await this.nativeProvider().isReady(); if (!isReady) { throw bleScanProviderNotReadyErr; } } async prepare() { return this.nativeProvider().prepare(); } next() { const interrupter = new ProviderInterrupter(); const scanResult = this.obtainBleScan(interrupter); return [scanResult, () => interrupter.interrupt()]; } obtainBleScan(interrupter) { const interrupted$ = new Subject(); interrupter.interruption = () => { interrupted$.next(); interrupted$.complete(); }; return firstValueFrom(this.nativeProvider() .bleScanStream({ reportInterval: 100 /* Lower report intervals don't seem to report anything in background*/, scanMode: this.scanMode, iBeaconUuids: this.iBeaconUuids, }) .pipe(takeUntil(timer(this.scanTime)), toArray(), map((results) => scanFromResults(results)))); } } function scanFromResults(results) { if (results.length === 0) { throw new Error('No BLE devices were found nearby!'); } return new BleScan(results.reduce((prev, curr) => [...prev, ...curr.seen], []), results[results.length - 1].timestamp); } const bleScanProviderNotReadyErr = new Error("BLE scan provider is not ready. Perhaps permissions haven't been granted, location services have been disabled or Bluetooth is turn off"); //# sourceMappingURL=provider.js.map