diff --git a/src/j1939_decoder.py b/src/j1939_decoder.py index e67bbbf..c8985fe 100644 --- a/src/j1939_decoder.py +++ b/src/j1939_decoder.py @@ -17,27 +17,28 @@ def decode_j1939_metadata(lf: pl.LazyFrame) -> pl.LazyFrame: Decodes J1939 fields and bundles them into a Struct column. """ id_int = pl.col("ID").str.to_integer(base=16).cast(pl.UInt32) - mask = get_j1939_mask() - priority = (id_int // 67108864) % 8 - pf = (id_int // 65536) % 256 - ps = (id_int // 256) % 256 - sa = id_int % 256 + id_shifted_8 = id_int // 256 + id_shifted_16 = id_int // 65536 + + priority = ((id_int // 67108864) % 8).cast(pl.UInt8) + pf = (id_shifted_16 % 256).cast(pl.UInt8) + ps = (id_shifted_8 % 256).cast(pl.UInt8) + sa = (id_int % 256).cast(pl.UInt8) da = pl.when(pf < 240).then(ps).otherwise(pl.lit(255, dtype=pl.UInt8)) - pgn = pl.when(pf < 240).then((id_int // 256) % 65536).otherwise((id_int // 256) % 262144).cast(pl.UInt32) - j1939_struct = pl.struct([ - priority.cast(pl.UInt8).alias("Priority"), - pf.cast(pl.UInt8).alias("PF"), - ps.cast(pl.UInt8).alias("PS"), - sa.cast(pl.UInt8).alias("SA"), - da.cast(pl.UInt8).alias("DA"), - pgn.alias("PGN") - ]) + pgn = pl.when(pf < 240).then(id_shifted_8 % 65536).otherwise(id_shifted_8 % 262144).cast(pl.UInt32) return lf.with_columns( - pl.when(mask).then(j1939_struct).otherwise(None).alias("j1939_metadata") + pl.struct([ + priority.alias("Priority"), + pf.alias("PF"), + ps.alias("PS"), + sa.alias("SA"), + da.alias("DA"), + pgn.alias("PGN") + ]).alias("j1939_metadata") ) if __name__ == "__main__":