Home > Backend Development > Python Tutorial > CANBUS Speed Converter

CANBUS Speed Converter

Mary-Kate Olsen
Release: 2024-10-06 06:08:31
Original
411 people have browsed it

CANBUS Speed Converter

This python script uses a text file made up of exported values from Tshark. This exported column is strictly made up of each CANBUS payload which is a 5 byte Hex value. (10 characters) This program converts CANBUS hex values into KPH or MPH.

Here is the command I used to extract this information from CanID589.pcap which itself was an exported dissection from Wireshark of specifically CANBUS ID 589 which refers to speed. There 32 other different types of CANBUS IDs but we need not be concerned with those values at the moment.


┌──(kali㉿Z3r0)-[/media/sf_Shared_Kali/NCL Doc/scanningrecon]
└─$ tshark -r CanID589.pcap -T fields -e data.data > Data_speed.txt



Copy after login

(-r) reads the existing pcap file while (-T fields) instructs Tshark to output specific fields (rather than full packet details, summaries, or raw data). It's a way to customize the output, extracting only the desired information instead of dumping all packet data. The -e option is used to specify which field(s) from the packet to extract. In this case, data.data represents the data bytes of each packet. "data.data" refers to the actual content (payload) of the CANBUS frames in hexadecimal form. I had to experiment with different values until the correct data was exported to the text file.

Here is a list of the different fields related to the CAN protocol.

  • can.id: The CAN identifier field (CAN ID)
  • can.dlc: Data Length Code (how many data bytes are present)
  • can.data: The payload data
  • can.errorframe: CAN error frame
  • data.data: The raw byte data (this is what this script is using)

This can also been done individually for each packet but I had 352 different Can.ID = "589" (speed) packets to iterate through


def format_hex_value(hex_value):
    # Tshark exported specific packets to column data.data unformatted.
    return ' '.join(hex_value[i:i+2] for i in range(0, len(hex_value), 2))

def calculate_speed_from_hex_value(hex_value):
    # 5 byte check 
    if len(hex_value) < 10:
        raise ValueError("Hex value must have at least 10 characters for 5 bytes")

    # Extract the relevant bytes from payload (the last two bytes)
    high_byte = int(hex_value[-4:-2], 16)  
    low_byte = int(hex_value[-2:], 16)

    speed = (high_byte << 8) + low_byte  
    # Example: 00 00 00 04 e1 - (04 << 8) + e1 = 1024 + 225 = 1249

    # Convert speed from centi-KPH to KPH then to MPH
    speed_kph = speed / 100.0  # Assuming the value is in centi-KPH
    speed_mph = speed_kph * 0.621371  # Convert KPH to MPH

    return speed_mph

def main():
    speeds = []

    with open('data_speed.txt', 'r') as file:
        for line in file:
            hex_value = line.strip() 

            if hex_value:  

                formatted_hex_value = format_hex_value(hex_value)
                print(f"Formatted Hex Value: {formatted_hex_value}")  

                try:
                    # Calculate speed and store it in the speeds list
                    speed_mph = calculate_speed_from_hex_value(hex_value)
                    speeds.append(speed_mph)
                    print(f"Calculated Speed: {speed_mph:.2f} MPH")
                except ValueError as e:
                    print(f"Error processing value '{hex_value}': {e}")


    speeds.sort() 
    #Sort lowest to highest

    print("\nFinal Sorted Speeds (MPH):")
    for speed in speeds:
        print(f"{speed:.2f} MPH")

if __name__ == "__main__":
    main()




Copy after login

If anyone has any questions, comments, additions, or constructive criticism please feel free to contact me. Thank you

The above is the detailed content of CANBUS Speed Converter. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template