-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprovider.ts
69 lines (60 loc) · 2.12 KB
/
provider.ts
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
import { ProviderInterrupter, ProviderInterruption, PullProvider } from '@awarns/core/providers';
import { WifiScan, WifiScanType } from './scan';
import {
FingerprintGrouping,
getWifiScanProvider as getNativeProvider,
WifiFingerprint,
WifiScanProvider as NativeProvider,
} from 'nativescript-context-apis/wifi';
import { firstValueFrom, map, of, Subject, takeUntil, timeout } from 'rxjs';
export class WifiScanProvider implements PullProvider {
get provides(): string {
return WifiScanType;
}
constructor(
private ensureIsNew: boolean,
private timeout: number,
private nativeProvider: () => NativeProvider = getNativeProvider
) {}
async checkIfIsReady(): Promise<void> {
const isReady = await this.nativeProvider().isReady();
if (!isReady) {
throw wifiScanProviderNotReadyErr;
}
}
async prepare(): Promise<void> {
return this.nativeProvider().prepare();
}
next(): [Promise<WifiScan>, ProviderInterruption] {
const interrupter = new ProviderInterrupter();
const scanResult = this.obtainWifiScan(interrupter);
return [scanResult, () => interrupter.interrupt()];
}
private obtainWifiScan(interrupter: ProviderInterrupter): Promise<WifiScan> {
const interrupted$ = new Subject<void>();
interrupter.interruption = () => {
interrupted$.next();
interrupted$.complete();
};
return firstValueFrom(
this.nativeProvider()
.wifiFingerprintStream({
ensureAlwaysNew: this.ensureIsNew,
grouping: FingerprintGrouping.NONE,
continueOnFailure: false,
})
.pipe(
takeUntil(interrupted$),
timeout({ each: this.timeout, with: () => of(null) }),
map((fingerprint) => scanFromFingerprint(fingerprint))
)
);
}
}
function scanFromFingerprint(fingerprint: WifiFingerprint): WifiScan {
const { seen, isNew, timestamp } = fingerprint;
return new WifiScan(seen, isNew, timestamp);
}
export const wifiScanProviderNotReadyErr = new Error(
"Wifi scan provider is not ready. Perhaps permissions haven't been granted, location services have been disabled or wifi is turn off"
);