[TypeScript] 透過藍芽連線接收資料

  • 540
  • 0

web bluetooth connect device by using TypeScript/JavaScript.

程式碼:

title: string = 'bluetooth';
status: string;
value: string;

execBluetooth() {
	const mobileNavigatorObject: Navigator | any = window.navigator;
	this.status = 'begin';
	this.value = '';

	/** one charactristic */
	if (mobileNavigatorObject && mobileNavigatorObject.bluetooth) {
		(mobileNavigatorObject.bluetooth.requestDevice({
			filters: [{
				namePrefix: 'Calyx Sensing',
			}],
			optionalServices: ['0000fff0-0000-1000-8000-00805f9b34fb'],
		}) as Promise<any>).then((device) => {
			this.status = 'Connecting to GATT Server...';
			console.log(device);
			return device.gatt.connect();
		}).then((server) => {
			this.status = 'Getting Device Information Service...';
			console.log(server);
			return server.getPrimaryService('0000fff0-0000-1000-8000-00805f9b34fb');
		}).then((service) => {
			this.status = 'Getting Device Information Characteristics...';
			console.log(service);
			return service.getCharacteristic('0000ffc0-0000-1000-8000-00805f9b34fb'); // 0x2901
		}).then((characteristic) => {
			this.status = 'Reading Values...';
			console.log(characteristic.readValue());

			/** delay 2 seconds in order to wait the slow bluetooth */
			return new Promise(
				(res) => setTimeout(() =>
					res((characteristic.readValue() as Promise<DataView>)),
					2000,
				)
			);
		}).then((value: DataView) => {
			for (let i = 0; i < value.byteLength; i++) {
				this.value += `${value.getUint8(i)},`;
			}
			this.status = 'Completed!'
		}).catch((error: any) => {
			this.status = `Error! ${error.message}`;
		});
	}
}