UNPKG

@canboat/canboatjs

Version:

Native javascript version of canboat

66 lines 2.52 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseEncode = exports.encodeCanIdString = exports.canIdString = exports.encodeCanId = exports.buildCanId = exports.parseCanIdStr = exports.parseCanId = void 0; const fp_1 = require("lodash/fp"); // Decode CAN Identifier (canId). ISO 11783 (CAN 2.0 B Extended Frame Format) const parseCanId = (id) => { const PF = (id >> 16) & 0xff; // PDU Format const PS = (id >> 8) & 0xff; // PDU Specific const DP = (id >> 24) & 1; // Data Page let dst, pgn; if (PF < 240) { /* PDU1 format, the PS contains the destination address */ dst = PS; pgn = (DP << 16) + (PF << 8); } else { /* PDU2 format, the destination is implied global and the PGN is extended */ dst = 0xff; pgn = (DP << 16) + (PF << 8) + PS; } return { canId: id, // Include original canId in return object. prio: (id >> 26) & 0x7, // Priority src: id & 0xff, // Source Address (SA), pgn, dst }; }; exports.parseCanId = parseCanId; // canId should be a hex encoded string without spaces or commas. const parseCanIdStr = (canId) => (0, exports.parseCanId)(parseInt(canId, 16)); exports.parseCanIdStr = parseCanIdStr; const buildCanId = (prio, pgn, dst, src) => ({ prio: Number(prio), pgn: Number(pgn), dst: Number(dst), src: Number(src) }); exports.buildCanId = buildCanId; // Encode CAN Identifier (canId) const encodeCanId = (id) => { let canId = id.src & 0xff; //I can't get this to work, but things seem ok?? //let canId = ((src & 0xff) | 0x80000000)) // src bits are the lowest ones of the CAN ID. Also set the highest bit to 1 as n2k uses // only extended frames (EFF bit). const PF = (id.pgn >> 8) & 0xff; if (PF < 240) { // PDU 1 canId = canId | ((id.dst & 0xff) << 8); canId = canId | (id.pgn << 8); } else { // PDU 2 canId = canId | (id.pgn << 8); } canId = canId | (id.prio << 26); return canId; }; exports.encodeCanId = encodeCanId; const canIdString = (canId) => canId.toString(16).padStart(8, '0'); exports.canIdString = canIdString; exports.encodeCanIdString = (0, fp_1.flow)(exports.encodeCanId, exports.canIdString); // Utility function that parses and re-encodes. Compare result to original. const parseEncode = (x) => (0, exports.encodeCanId)((0, exports.parseCanId)(x)); exports.parseEncode = parseEncode; //# sourceMappingURL=canId.js.map