Home Backend Development Python Tutorial CANBUS Speed Converter

CANBUS Speed Converter

Oct 06, 2024 am 06:08 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

What is the reason why pipeline files cannot be written when using Scapy crawler? What is the reason why pipeline files cannot be written when using Scapy crawler? Apr 02, 2025 am 06:45 AM

Discussion on the reasons why pipeline files cannot be written when using Scapy crawlers When learning and using Scapy crawlers for persistent data storage, you may encounter pipeline files...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

See all articles