UNPKG

rxjs-obd

Version:

RxJS Implementation for OBD (On Board Diagnostics) of vehicles via ELM 327 connections.

76 lines 2.47 kB
import { EMPTY, Subject } from 'rxjs'; import { OBDConnection } from './OBDConnection'; /** * The wrapper of Socket for Cordova plugin Socket For Cordova. */ export class CordovaOBDConnection extends OBDConnection { /** * Open connection to OBD Reader. * @returns the observable of opening connection. */ open(config) { const { port, host } = config; const subject = new Subject(); this.socket = new Socket(); this.socket.open(host, port, () => { this.data$ = new Subject(); this.socket.onData = (data) => { this.data$.next(CordovaOBDConnection.unmarshall(data)); }; subject.complete(); }, (error) => subject.error(error)); return subject.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(); this.socket.write(CordovaOBDConnection.marshall(command), () => subject.complete(), (error) => subject.error(error)); return subject.asObservable(); } /** * Listener for data received from OBD Reader. * @returns Observable of data received from OBD Reader. */ onData() { return this.data$.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() { this.data$.complete(); this.socket.shutdownWrite(); setTimeout(this.socket.close); return EMPTY; } /** * 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=CordovaOBDConnection.js.map