import Adapter , { Params , Listener , FindCondition } from "@sblendid/adapter-node" ; import Peripheral , { Options } from "./peripheral" ; export type PeripheralListener = ( peripheral : Peripheral ) => Promish < void > ; export type FindFunction = ( peripheral : Peripheral ) => Promish < boolean > ; export type Condition = FindFunction | string ; export default class Sblendid { public adapter : Adapter = new Adapter ( ) ; private scanListener : Listener < "discover" > = ( ) => { } ; public static async powerOn ( ) { const sblendid = new Sblendid ( ) ; await sblendid . powerOn ( ) ; return sblendid ; } public static async powerOff ( ) { await Adapter . powerOff ( ) ; } public static async connect ( condition ) { const sblendid = await Sblendid . powerOn ( ) ; const peripheral = await sblendid . find ( condition ) ; await peripheral . connect ( ) ; return peripheral ; } public async powerOn ( ) { await Adapter . powerOn ( ) ; } public async powerOff ( ) { await Adapter . powerOff ( ) ; } public async find ( condition ) { const adapterCondition = this . getAdapterCondition ( condition ) ; const discoverParams = await this . adapter . find ( adapterCondition ) ; const [ uuid , options ] = this . parseDiscoverParams ( discoverParams ) ; return new Peripheral ( uuid , this . adapter , options ) ; } public startScanning ( listener ? ) { this . adapter . off ( "discover" , this . scanListener ) ; this . scanListener = this . getDiscoverListener ( listener ) ; this . adapter . on ( "discover" , this . scanListener ) ; this . adapter . startScanning ( ) ; } public stopScanning ( ) { this . adapter . off ( "discover" , this . scanListener ) ; this . scanListener = ( ) => { } ; this . adapter . stopScanning ( ) ; } private getAdapterCondition ( condition ) { return typeof condition === "string" ? this . getConditionFromString ( condition ) : this . getConditionFromFunction ( condition ) ; } private getConditionFromString ( str ) { return ( ... peripheralData ) => { const [ uuid , address , , , advertisement ] = peripheralData ; const { localName } = advertisement ; return [ uuid , address , localName ] . includes ( str ) ; } ; } private getConditionFromFunction ( fn ) { return ( ... discoverParams ) => { const [ uuid , options ] = this . parseDiscoverParams ( discoverParams ) ; const peripheral = new Peripheral ( uuid , this . adapter , options ) ; return fn ( peripheral ) ; } ; } private getDiscoverListener ( listener = ( ) => { } ) { return ( ... discoverParams ) => { const [ uuid , options ] = this . parseDiscoverParams ( discoverParams ) ; const peripheral = new Peripheral ( uuid , this . adapter , options ) ; listener ( peripheral ) ; } ; } private parseDiscoverParams ( data ) { const [ uuid , address , addressType , connectable , advertisement ] = data ; const options = { address , addressType , connectable , advertisement } ; return [ uuid , options ] ; } }