rxjs-obd
Version:
RxJS Implementation for OBD (On Board Diagnostics) of vehicles via ELM 327 connections.
84 lines • 2.63 kB
JavaScript
import { EMPTY, Subject } from 'rxjs';
import { OBDConnection } from './OBDConnection';
/**
* The wrapper of Bluetooth Serial plugin for Cordova.
*/
export class BluetoothOBDConnection extends OBDConnection {
/**
* Open connection to OBD Reader.
* @returns the observable of opening connection.
*/
open(config) {
const subject = new Subject();
const { device } = config;
try {
bluetoothSerial.connect(device.id, () => {
this.data$ = new Subject();
bluetoothSerial.subscribe('\r>', (data) => {
this.data$.next(data);
}, (error) => {
this.close();
subject.error(error);
});
subject.complete();
}, (error) => subject.error(error));
}
catch (e) {
subject.error(e);
}
return subject.asObservable();
}
/**
* Close and dispose resources of OBD Reader connection.
* @returns the observable of close operation.
* The events emitted are ignored, wait for complete (successful) or error (failure).
*/
close() {
if (this.data$)
this.data$.complete();
bluetoothSerial.unsubscribe();
bluetoothSerial.disconnect();
return EMPTY;
}
/**
* Listener for data received from OBD Reader.
* @returns Observable of data received from OBD Reader.
*/
onData() {
return this.data$.asObservable();
}
/**
* Send a command to OBD Reader.
* @returns the observable of send operation.
* The events emitted are ignored, wait for complete (successful) or error (failure).
*/
send(command) {
const subject = new Subject();
bluetoothSerial.write(command, () => subject.complete(), (error) => subject.error(error));
return subject.asObservable();
}
/**
* Marshall the string data into bytes array.
* @param data the string data.
* @returns the bytes array.
*/
static marshall(data) {
if (!data) {
return new Uint8Array(0);
}
let bytes = new Uint8Array(data.length);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = data.charCodeAt(i);
}
return bytes;
}
/**
* Unmarshall the bytes array into data string.
* @param bytes the bytes array.
* @returns the string data.
*/
static unmarshall(bytes) {
return String.fromCharCode.apply(null, bytes);
}
}
//# sourceMappingURL=BluetoothOBDConnection.js.map