-
Notifications
You must be signed in to change notification settings - Fork 0
/
getPixel.ts
56 lines (52 loc) · 1.87 KB
/
getPixel.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
import { Pixel } from "@systemic-games/pixels-core-connect";
import BleSession from "./BleSession";
import { PixelsMap } from "./PixelsMap";
import { ScannedPixelsRegistry } from "./ScannedPixelsRegistry";
/**
* Error thrown when a Pixel device can't be found.
*/
class GetPixelError extends Error {
constructor(message: string) {
super(message);
this.name = "GetPixelError";
}
}
/**
* Returns a Pixel instance for the corresponding scanned Pixel instance of Pixel id.
* The same instance is returned when called multiple times for the same Pixel.
* @param id Identify which Pixel to use.
* It can be either the system id as a string or the Pixel id as a number.
* @returns A {@link Pixel} instance or undefined.
*/
export function getPixel(id: string | number): Pixel | undefined {
if (typeof id === "number" ? id !== 0 : id?.length > 0) {
const sp = ScannedPixelsRegistry.find(id);
// Get system id from the input data
const systemId = typeof id === "string" ? id : sp?.systemId;
if (systemId?.length) {
// Check for an existing Pixel object for the given system id
const exitingPixel = PixelsMap.get(systemId);
// Or create a new Pixel instance
const pixel =
exitingPixel ?? new Pixel(new BleSession(systemId, sp?.name), sp);
if (!exitingPixel) {
// Keep track of this new instance
PixelsMap.set(systemId, pixel);
}
return pixel;
}
}
}
/**
* Calls {@link getPixel} and throws an error if the Pixel instance cannot be found.
* @param id Identify which Pixel to use.
* It can be either the system id as a string or the Pixel id as a number.
* @returns A {@link Pixel} instance.
*/
export function getPixelOrThrow(id: string | number): Pixel {
const pixel = getPixel(id);
if (!pixel) {
throw new GetPixelError(`No scanned Pixels die with ${id}`);
}
return pixel;
}