Forem

Peter G.
Peter G.

Posted on

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

Enter fullscreen mode Exit fullscreen mode

(-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()


Enter fullscreen mode Exit fullscreen mode

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay