Last active
August 30, 2019 15:21
-
-
Save srounce/10298508fa6dc01a3274c72f6c8f41e6 to your computer and use it in GitHub Desktop.
Read speed from ELM327 over TCP/IP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { createConnection } = require("net") | |
const { format } = require("util") | |
const socket = createConnection({ port: 35000 }) | |
const CURRENT_DATA_MODE = "01" | |
const CURRENT_DATA_MODE_RESPONSE = "41" | |
const VEHICLE_SPEED_PID = "0D" | |
const debounceWait = (time: number) => { | |
let readTimeoutHandle = -1 | |
return (fn: Function) => { | |
clearTimeout(readTimeoutHandle) | |
readTimeoutHandle = setTimeout(fn, time) | |
} | |
} | |
const writeDelay = debounceWait(100) | |
const requestSpeed = () => { | |
const message = `${CURRENT_DATA_MODE} ${VEHICLE_SPEED_PID}\r` | |
console.log(format("<< %s", message)) | |
socket.write(message) | |
} | |
socket.on("data", (data: Buffer) => { | |
if (data.includes('>')) { | |
writeDelay(requestSpeed) | |
} | |
const messages: Array<string> = data | |
.toString("utf8") | |
.split(/[\r\n]+/g) | |
.filter(v => v.length) | |
const responses = messages | |
.map(message => message.split(" ")) | |
.filter(segments => segments[0] === CURRENT_DATA_MODE_RESPONSE) | |
const speedResponses = responses | |
.filter(res => res[1] === VEHICLE_SPEED_PID) | |
speedResponses | |
.forEach(segments => { | |
const speedHex = segments.slice(-1).join(" ") | |
const speed = parseInt(speedHex, 16) | |
console.log(format(">> Speed: %s", speed)) | |
}) | |
}) | |
socket.write(`AT Z\r`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment