DEV Community

Cover image for Listening to a Perkins Generator on J1939: Decoding Engine Data and Fault Codes in Python
Ibrahim Nauman
Ibrahim Nauman

Posted on

Listening to a Perkins Generator on J1939: Decoding Engine Data and Fault Codes in Python

`

Here's a situation we see on Pakistani sites more than you'd expect. A plant has a perfectly good electronic engine on its standby set, the engine is broadcasting its speed, coolant temperature, oil pressure and active faults several times a second, and nobody is recording any of it. The controller screen shows the current value, then the number is gone.

We at Enpower look after a fair number of these. Several models in our Perkins EPG catalogue, which goes up to 1375 kVA, are built on electronic engines, the ones with an "E" in the engine code such as the 1206A-E70TTAG2. If you have a Perkins generator like that and a spare Linux box, you can listen to the engine yourself. This post walks through doing it read-only with Python.

What's actually on the wire

Electronic engines like these talk to the generator controller over SAE J1939, a protocol that runs on CAN. Every frame has a 29-bit identifier and up to 8 bytes of data. Most engine buses run at 250 kbit/s, though some use 500 kbit/s, so check the wiring diagram for your set before you connect anything.

Inside that identifier sits a Parameter Group Number (PGN), which tells you what kind of message it is, and a source address, which tells you who sent it. Each PGN carries one or more Suspect Parameter Numbers (SPNs), and the J1939 standard defines where each SPN sits in the data bytes and how to scale it. That's the whole trick. Once you can pull the PGN out and you know the scaling, the engine becomes readable.

Tapping the bus without upsetting it

A standby Perkins generator has one job, which is to start when the grid drops, so anything you add must not interfere with it. Three rules we'd hold to.

First, check the termination. A J1939 backbone has a 120 ohm resistor at each end. With everything powered off, you should read about 60 ohms between CAN-H and CAN-L. If you do, don't enable the terminator on your own adapter, because a third one weakens the signal.

Second, keep the stub short and connect at a point the wiring diagram shows as part of the engine bus, usually the controller's CAN terminals or a service connector. Don't splice into a harness on a hunch.

Third, listen only. Bring the interface up so it can't transmit at all:

sudo ip link set can0 up type can bitrate 250000 listen-only on

A cheap USB-CAN adapter that shows up as a SocketCAN device on a Raspberry Pi or an old laptop is enough. Install python-can with pip and you're ready.

Turning a 29-bit ID into a PGN

The PGN lives in bits 8 to 25 of the identifier. There's one catch. If the PDU format byte is below 240, the low byte is a destination address rather than part of the PGN, so it gets masked off.

import can, csv

PGN_EEC1, PGN_ET1, PGN_EFLP1, PGN_VEP1 = 61444, 65262, 65263, 65271
PGN_DM1, PGN_TP_CM, PGN_TP_DT = 65226, 60416, 60160

def parse_id(arb_id):
    pgn = (arb_id >> 8) & 0x3FFFF
    if ((pgn >> 8) & 0xFF) < 240:   # PDU1: low byte is a destination
        pgn &= 0x3FF00
    return pgn, arb_id & 0xFF

Decoding the values a Perkins generator broadcasts

Four messages cover most of what a maintenance team cares about. Engine speed (SPN 190) is in EEC1, bytes 4 and 5, at 0.125 rpm per bit. Coolant temperature (SPN 110) is the first byte of ET1, 1°C per bit with a minus 40 offset. Oil pressure (SPN 100) is byte 4 of the engine fluid level and pressure message, 4 kPa per bit. Battery voltage (SPN 168) is bytes 5 and 6 of VEP1, 0.05 V per bit.

J1939 reserves the top of each range for "error" and "not available", so the decoder returns None instead of a nonsense reading.

def u8(d, i):
    return None if d[i] > 0xFA else d[i]

def u16(d, i):
    v = d[i] | (d[i + 1] << 8)          # little-endian
    return None if v > 0xFAFF else v

def scaled(raw, factor, offset=0.0):
    return None if raw is None else raw * factor + offset

DECODERS = {
    PGN_EEC1:  ("engine_rpm", lambda d: scaled(u16(d, 3), 0.125)),
    PGN_ET1:   ("coolant_c",  lambda d: scaled(u8(d, 0), 1, -40)),
    PGN_EFLP1: ("oil_kpa",    lambda d: scaled(u8(d, 3), 4)),
    PGN_VEP1:  ("battery_v",  lambda d: scaled(u16(d, 4), 0.05)),
}

Faults: DM1 and the transport protocol

Active faults arrive in DM1. After two bytes of lamp status, each fault takes four bytes: a 19-bit SPN, a 5-bit Failure Mode Identifier (FMI) and a 7-bit occurrence count. The FMI tells you how the reading failed. FMI 3 and 4, for example, mean the signal voltage is shorted high or low, which points at wiring or a sensor rather than the engine itself.

One active fault fits in a single frame. Two or more don't, so the engine sends a broadcast announce message (BAM) and then the data in numbered 7-byte packets. If you skip this step, you'll only ever see single faults.

FMI_TEXT = {0: "high, most severe", 1: "low, most severe",
            2: "erratic", 3: "shorted high", 4: "shorted low",
            5: "open circuit", 6: "grounded circuit"}

def decode_dm1(data):
    faults = []
    for i in range(2, len(data) - 3, 4):
        b0, b1, b2, b3 = data[i:i + 4]
        spn = b0 | (b1 << 8) | ((b2 & 0xE0) << 11)
        if spn in (0, 0x7FFFF):          # "no fault" or padding
            continue
        faults.append((spn, b2 & 0x1F, b3 & 0x7F))
    return faults

class Bam:
    def __init__(self):
        self.open = {}                   # source address: [pgn, size, count, buf]

    def feed(self, pgn, sa, d):
        if pgn == PGN_TP_CM and d[0] == 0x20:
            self.open[sa] = [d[5] | d[6] << 8 | d[7] << 16,
                             d[1] | d[2] << 8, d[3], bytearray()]
        elif pgn == PGN_TP_DT and sa in self.open:
            packed, size, count, buf = self.open[sa]
            buf.extend(d[1:8])
            if d[0] == count:            # last packet
                del self.open[sa]
                return packed, bytes(buf[:size])
        return None

The logging loop

EEC1 can arrive every few tens of milliseconds, which is far more than anyone needs in a CSV. The loop below keeps one reading per value per second and writes every fault it sees.

bus = can.Bus(interface="socketcan", channel="can0")
bam, last = Bam(), {}

with open("engine_log.csv", "a", newline="") as f:
    out = csv.writer(f)
    for msg in bus:
        if not msg.is_extended_id:
            continue
        pgn, sa = parse_id(msg.arbitration_id)
        data = bytes(msg.data)
        done = bam.feed(pgn, sa, data)
        if done:
            pgn, data = done
        if pgn in DECODERS:
            name, fn = DECODERS[pgn]
            if msg.timestamp - last.get(name, 0) >= 1.0:
                last[name] = msg.timestamp
                out.writerow([msg.timestamp, sa, name, fn(data)])
        elif pgn == PGN_DM1:
            for spn, fmi, oc in decode_dm1(data):
                out.writerow([msg.timestamp, sa, "fault",
                              f"SPN {spn} FMI {fmi} {FMI_TEXT.get(fmi, '')} x{oc}"])
        f.flush()

What the log is good for, and what it isn't

The value shows up over weeks, not minutes. On a Perkins generator at a Multan or Sukkur site in June, coolant temperature that climbs a few degrees higher each afternoon at the same load usually means the radiator is clogging, often with dust from the last andhi. Battery voltage logged during cranking shows a tired battery long before the morning it fails to start the set. Oil pressure at warm running, compared month to month, is an early hint worth passing to your technician.

Repeating faults are the other win. A water-in-fuel warning (SPN 97) that appears after every tanker delivery tells you something about your supplier that no single screen reading would.

Know the limits, too. This listens to what the engine in your Perkins generator broadcasts. It won't give you the stored fault history, calibration or anything that Perkins dealer diagnostic software is built for, and you shouldn't try to clear codes or send requests on a live standby bus from a script. Scaling and byte positions here follow the J1939 standard, but confirm them against the engine's own documentation before you trust a number.

If you'd like help working out which engine sits in your set or how its bus is wired, the service team at Enpower can walk you through it.

`

Top comments (0)