elm327
Version:
Node.js/TypeScript library for ELM327 OBD2 adapters over USB, Bluetooth and WiFi
279 lines • 8.98 kB
TypeScript
import { EventEmitter } from 'events';
import { LogFormat, LogLevel } from './logger';
import { ConnectionConfig, DiagnosticRequestConfig, DiagnosticResponse, LoggerConfig, OBD2AdapterInfo, OBD2Command, OBD2Response } from './types';
/**
* High-level OBD2 client for communicating with vehicles.
* Supports serial, Bluetooth, and WiFi connections to ELM327 adapters.
*/
export declare class OBD2Client extends EventEmitter {
private config;
private connection;
private adapterInfo?;
private isInitialized;
private autoReconnect;
private reconnectTimer?;
private _manualDisconnect;
private pollers;
private globalPollInterval?;
private pollIntervalMs;
private heartbeatTimer?;
private lastCommandTime;
private readonly heartbeatIntervalMs;
private _canDataHandler?;
private logger;
constructor(config: ConnectionConfig);
/**
* Enables or disables auto-reconnect on connection loss.
*/
setAutoReconnect(enabled: boolean): void;
enableLogger(config: LoggerConfig): void;
disableLogger(): void;
setLoggerFormat(format: LogFormat): void;
setLoggerLevels(levels: LogLevel[]): void;
/**
* Starts the heartbeat timer to keep the connection alive.
* Sends a lightweight AT command every 20s if no other command is sent.
*/
private startHeartbeat;
/**
* Stops the heartbeat timer.
*/
private stopHeartbeat;
/**
* Connects to the OBD2 adapter and initializes it.
*/
connect(): Promise<void>;
/**
* Sets the default polling interval for all pollers.
*/
setPollInterval(ms: number): void;
/**
* Adds a command to the polling list.
* Similar to bluetooth-obd's addPoller("rpm").
*/
addPoller(commandName: string): void;
/**
* Removes a command from the polling list.
*/
removePoller(commandName: string): void;
/**
* Starts automatic polling at the specified interval.
* Similar to serial-obd's startPolling(1000).
*/
startPolling(intervalMs?: number): void;
/**
* Stops the automatic polling.
*/
stopPolling(): void;
/**
* Disconnects from the OBD2 adapter.
*/
disconnect(): Promise<void>;
/**
* Resets the adapter using ATZ command without disconnecting/reconnecting.
* Useful for recovering from communication errors or resetting adapter state.
* This is an independent reset that doesn't recreate the socket/connection.
*
* @example
* try {
* await client.query('ENGINE_RPM');
* } catch (error) {
* console.log('Error, resetting adapter...');
* await client.reset(); // Reset without full reconnect
* await client.query('ENGINE_RPM'); // Try again
* }
*/
reset(): Promise<void>;
/**
* Queries a command by its name (e.g., 'ENGINE_RPM').
*/
query(commandName: string): Promise<OBD2Response>;
/**
* Queries a command by its PID string (e.g., '010C').
*/
queryPid(pid: string): Promise<OBD2Response>;
/**
* Sends a command to the adapter and decodes the response.
*/
queryCommand(command: OBD2Command): Promise<OBD2Response>;
/**
* Queries multiple commands sequentially.
* Sequential execution is intentional to avoid BUFFER FULL on cheap clones.
* Returns array with either OBD2Response or error info.
*/
queryMultiple(commandNames: string[]): Promise<Array<OBD2Response | {
command: string;
error: string;
}>>;
/**
* Gets vehicle information including VIN and adapter details.
*/
getVehicleInfo(): Promise<Record<string, string | OBD2AdapterInfo | {
error?: string;
}>>;
/**
* Returns whether the client is connected and initialized.
*/
isConnected(): boolean;
/**
* Returns information about the connected adapter.
*/
getAdapterInfo(): OBD2AdapterInfo | undefined;
/**
* Returns all available command names.
*/
getAvailableCommands(): string[];
private delay;
/**
* Extracts base PID from a query string like "0100", "0120", etc.
* Returns the numeric base PID (e.g., 0x00, 0x20, 0x40...).
*/
private getBasePid;
/**
* Parses supported PIDs from a Mode 1 PID 00 response.
* Uses getBasePid for clarity.
*/
private parseSupportedPids;
/**
* Gets the current engine RPM.
*/
getRPM(): Promise<number>;
/**
* Gets the current vehicle speed in km/h.
*/
getSpeed(): Promise<number>;
/**
* Gets the engine coolant temperature in °C.
*/
getCoolantTemperature(): Promise<number>;
/**
* Gets the calculated engine load as a percentage.
*/
getEngineLoad(): Promise<number>;
/**
* Gets the fuel tank level as a percentage.
*/
getFuelLevel(): Promise<number>;
/**
* Gets the absolute throttle position as a percentage.
*/
getThrottlePosition(): Promise<number>;
/**
* Sends a custom diagnostic request using DiagnosticRequestConfig.
* Similar to OpenXC's create_diagnostic_request method.
*/
sendDiagnosticRequest(config: DiagnosticRequestConfig): Promise<DiagnosticResponse>;
/**
* Sends a Mode 1 request (current data) for a specific PID.
* Convenience method for common diagnostic requests.
*/
queryMode1(pid: number): Promise<DiagnosticResponse>;
/**
* Gets the VIN using Mode 9 PID 02.
* Similar to OpenXC's get_vin method.
*/
getVIN(): Promise<string>;
/**
* Gets the calibration ID (Mode 9 PID 04).
*/
getCalibrationID(): Promise<string>;
/**
* Scans all OBD-II PIDs to see which ones respond.
* Similar to OpenXC's openxc-obd2scanner tool.
*
* @param mode - The diagnostic mode (default: 0x01 for current data)
* @param startPid - Starting PID to scan (default: 0x00)
* @param endPid - Ending PID to scan (default: 0x80)
* @param onProgress - Optional callback for progress updates
*
* @emits scanProgress with { pid, response } when each PID is tested
* @emits scanComplete when scanning is finished
*/
scanPids(mode?: number, startPid?: number, endPid?: number, onProgress?: (pid: number, response: DiagnosticResponse | null) => void): Promise<Map<number, DiagnosticResponse>>;
/**
* Gets all DTCs (Diagnostic Trouble Codes) using Mode 3.
*/
getDTCs(): Promise<string[]>;
/**
* Gets freeze frame data for a specific PID (Mode 02).
* Freeze frame captures data at the moment a fault occurred.
*
* @param pid - The PID to get freeze frame data for (e.g., 0x0C for RPM)
* @returns The freeze frame value, or null if not available
*/
getFreezeFrame(pid: number): Promise<OBD2Response | null>;
/**
* Gets all available freeze frame data.
* Scans PIDs 0x00-0x4F in Mode 02.
*
* @returns Array of freeze frame responses
*/
getAllFreezeFrames(): Promise<OBD2Response[]>;
/**
* Dynamically scans all supported PIDs (Mode 01).
* Recursively checks 0x00, 0x20, 0x40, 0x60, etc.
*
* @returns Array of supported PID numbers
*/
getSupportedPids(): Promise<number[]>;
/**
* Clears all DTCs using Mode 4.
*/
clearDTCs(): Promise<void>;
/**
* Parses DTCs from a Mode 3 response.
* Uses proper byte pair matching.
*/
private parseDTCs;
/**
* Decodes two bytes into a DTC code.
*/
private decodeDTC;
/**
* Gets adapter firmware version.
* Similar to OpenXC's version command.
*/
getAdapterVersion(): Promise<string>;
/**
* Gets protocol information.
*/
getProtocolInfo(): Promise<{
protocol: string;
version: string;
device: string;
}>;
/**
* Sends raw AT command (for debugging).
*/
sendRaw(command: string): Promise<string>;
/**
* Starts CAN bus monitoring (AT MA - Monitor All).
* Listens to all CAN traffic without sending requests.
* Data is emitted via the 'canData' event.
* Use stopCANMonitor() to exit monitor mode.
*
* @example
* client.on('canData', (data) => {
* console.log('CAN Frame:', data);
* });
* await client.startCANMonitor();
*/
startCANMonitor(): Promise<void>;
/**
* Starts CAN monitoring with a specific CAN ID filter (AT MP + AT MA).
* Only frames matching the specified CAN ID will be received.
*
* @param canId - CAN ID to filter (e.g., '7E8', '7DF')
*/
startCANMonitorWithFilter(canId: string): Promise<void>;
/**
* Stops CAN monitoring mode.
* Sends escape command to exit AT MA mode.
*/
stopCANMonitor(): Promise<void>;
/**
* Clean response helper.
*/
private cleanResponse;
}
//# sourceMappingURL=obd2-client.d.ts.map