UNPKG

gan-i3-356-bluetooth

Version:

Library for connecting to and interacting with Bluetooth-enabled Rubik's cubes (GAN)

1 lines 2.53 kB
import{GanCube}from"./gancube";import{EventEmitter}from"./utils";export class BTCube extends EventEmitter{constructor(debug=!1){super(),this.cube=null,this.device=null,this.callback=null,this.evtCallback=null,this.DEBUG=debug}onHardwareEvent(info,event){let res=Promise.resolve();return"disconnect"===info&&(res=Promise.resolve(this.stop())),res.then((()=>"function"==typeof this.evtCallback?this.evtCallback(info,event):void 0))}init(macAddress){if(!window.navigator.bluetooth)throw new Error("NO BLUETOOTH ON BROWSER");let chkAvail=Promise.resolve(!0);window.navigator.bluetooth.getAvailability&&(chkAvail=window.navigator.bluetooth.getAvailability());const onDisconnect=this.onHardwareEvent.bind(this,"disconnect");return chkAvail.then((available=>{if(this.DEBUG&&console.log("[bluetooth]","is available",available),!available)throw new Error("GIIKER_NOBLEMSG");return window.navigator.bluetooth.requestDevice({filters:[{namePrefix:"GAN"}],optionalServices:[].concat((new GanCube).opservs),optionalManufacturerData:[].concat((new GanCube).cics)})})).then((device=>{if(this.DEBUG&&console.log("[bluetooth]",device),this.device=device,device.addEventListener("gattserverdisconnected",onDisconnect),device.name?.startsWith("GAN")||device.name?.startsWith("MG")||device.name?.startsWith("AiCube"))return this.cube=new GanCube,this.cube.init(device,macAddress).then((()=>(this.setupEventForwarding(),Promise.resolve())));throw new Error("Cannot detect device type")}))}stop(){return this.device?Promise.resolve(this.cube?.clear()).then((()=>{if(console.log("[BTCube] Clearing event listeners"),this.clearAllListeners(),this.device){const onDisconnect=this.onHardwareEvent.bind(this,"disconnect");this.device.removeEventListener("gattserverdisconnected",onDisconnect),this.device.gatt&&this.device.gatt.disconnect(),this.device=null}})):Promise.resolve()}isConnected(){return null!=this.device}setCallback(func){this.callback=func}setEventCallback(func){this.evtCallback=func}getCube(){return this.cube}setupEventForwarding(){if(!this.cube)return void console.error("[BTCube] No cube instance to forward events from");this.cube.getInstanceId&&this.cube.getInstanceId(),this.getInstanceId&&this.getInstanceId();["cubeStateChanged","gyroData","move","cubeSolved","unSolved"].forEach((eventName=>{this[`_${eventName}Handler`]&&this.cube?.off(eventName,this[`_${eventName}Handler`]);const forwardHandler=data=>{this.emit(eventName,data)};this[`_${eventName}Handler`]=forwardHandler,this.cube&&this.cube.on(eventName,forwardHandler)}))}}