Code Monkey home page Code Monkey logo

pyvit's Introduction

pyvit: Python Vehicle Interface Toolkit

image

image

pyvit is a toolkit for interfacing with cars from Python. It aims to implement common hardware interfaces and protocols used in the automotive systems.

Getting Started

pyvit can be installed with pip: pip install pyvit.

See the Getting Started document for detailed instructions.

Contributing

For information on contributing, please see the contribution guidelines.

pyvit's People

Contributors

aclex avatar ericevenchick avatar freebendy avatar guillaumefegefullelec avatar jjardon avatar khaled-karray avatar levwi avatar liviuk2 avatar markste-in avatar naveenal avatar reuted avatar stywin avatar ulabs-sgiroux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyvit's Issues

pyvit doesn't show any CAN frame

I am having a problem running an easy script which only print the data CAN bus.
I have a CANtact V1.0 device and I installed pyserial 3.2.1, future 0.16.0 and pyvit 0.2.0. When I running the script, it doesn't return any data.
This is the script:
2

And this is the image when I runned the script.
3

By other hand, I was debugging the script and when it running the line print(dev.recv()), this returns none in self.target_time in serialutil.py.
screenshot from 2017-05-29 17-18-36

Could someone help me, please?
Kind regards.

Clean Up Old Examples

I am having a problem running the UDS.py example. It appears it's looking for some functions that no longer exist:

pi@raspberrypi:~ $ python3 uds.py 
Traceback (most recent call last):
  File "uds.py", line 3, in <module>
    from pyvit.proto.uds import UdsInterface
  File "/usr/local/lib/python3.4/dist-packages/pyvit/proto/uds.py", line 1, in <module>
    from pyvit.proto.isotp import IsoTpProtocol, IsoTpMessage
ImportError: cannot import name 'IsoTpProtocol'

Project living?

I am interested in using this project for CAN bus tools and reverse engineering native to Mac. The one problem I see is that it does not seem to be very alive, and the version in PIP is missing some useful things like setting the baud rate for the device.

I can potential contribute to this project as long as I know others are also ready. Otherwise it might be more worth my effort to work on my own setup.

Win error

I heve problem

When i write tis all is ok:

from canard import can
from canard.hw import cantact
from canard.proto.uds import UdsInterface
dev = cantact.CantactDev("COM7")
dev.set_bitrate(125000)

dev.start()

but after adding ''p = UdsInterface(dev)" after dev.start()

i got error:
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 66, in open
raise SerialException("could not open port %r: %r" % (self.portstr, ctyp
es.WinError()))
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinEr
ror()))
serial.serialutilserial.serialutil..SerialExceptionSerialException: : ccould not
open port 'COM7': WindowsError(5, 'Access is denied.')ould not open port 'COM7'
: WindowsError(5, 'Access is denied.'

implement-uds - CAN11 CAN29

In order to be compatible with 11bits CAN ids and 29bits CAN ids, UDS an ISOTP Network do not use CAN ids (0x7E0, 0x7DF , ..). for address field.
ISOTP Network and UDS use SA (source address) and TA (target adress) as follow :

  • 0x00 : ECU#0
  • ...
  • 0x07 : ECU#7
  • 0x33 : Functional (only for target address)
  • 0xF7 : Test equipement

And isotp make the correspondance with CAN id as follow,
For CAN11 :

  • 0x7E0 : SA=0xF7 - TA=0x00
  • ...
  • 0x7E7 : SA = 0xF7 - TA = 0x07
  • 0x7E8 : SA = 0x00 - TA = 0x7F
  • ...
  • 0x7EF : SA = 0x07 - TA = 0x7F
  • 0x7DF : SA = 0x7F - TA = 0x33

For CAN29 :

  • 0x18DA00F1 : SA=0xF7 - TA=0x00
  • ...
  • 0x18DA07F1 : SA=0xF7 - TA=0x07
  • 0x18DAF100 : SA = 0x00 - TA = 0x7F
  • ...
  • 0x18DAF107 : SA = 0x07 - TA = 0x7F
  • 0x18DB33F1 : SA = 0x7F - TA = 0x33

Is it possible to add this address abstraction into this API ? Then the user could use TA and SA regardless the CAN 11 / CAN 29 implementation ?

log_frame() only can handle frames with 8 data bytes

in log.py::log_frame()[l.35] is assumed that the frame contains 8 data bytes. IMHO CAN messages might be lower than 8 data bytes esp. 0 data bytes. So I would expect lines something like:
line = ("(%f) %s %03X#" % (ts, self.if_name, frame.arb_id))
line += "".join(["%02X" % x for x in frame.data])
line += "\n"

Infinite recursion when sending frame

My simple test script fails to transmit and infinitely recurses:

from canard import can
from canard.hw import socketcan
dev = socketcan.SocketCanDev("can0")
dev.start()
req = can.Frame(0x705)
req.dlc = 2
req.data = [0x10, 0x11]
dev.send(req)

When run, this script returns:

  File "/usr/lib/python3.5/site-packages/canard/can.py", line 71, in data
    data_len = min(self.dlc, len(self._data))
  RecursionError: maximum recursion depth exceeded while calling a Python object

The issue appears to be in can.py:

    @property
    def data(self):
        # return bytes up to dlc length, pad with zeros
        data_len = min(self.dlc, len(self._data))
        result = self.data[:data_len]
        result.extended([0] * (8 - data_len))
        return result

I tried changing the result to result = self._data[:data_len] which fixed the recursion, but then errored out on setting the extended property on the next line. After commenting out the extended property line, everything appears to work.

getting started example fails

on ubuntu x64 16.04, both 'pip install pyvit' and 'python setup.py install' results in error on set_bitrate, see below.

>>> from pyvit import can
>>> from pyvit.hw.cantact import CantactDev
>>> dev = CantactDev("/dev/ttyACM0")
>>> dev.set_bitrate(500000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pyvit-0.1.2-py2.7.egg/pyvit/hw/cantact.py", line 33, in set_bitrate
    self._dev_write('S6\r')
  File "/usr/local/lib/python2.7/dist-packages/pyvit-0.1.2-py2.7.egg/pyvit/hw/cantact.py", line 11, in _dev_write
    self.ser.write(bytes(string, encoding='ascii'))
TypeError: str() takes at most 1 argument (2 given)

Support additional CAN hardware

Hey I just saw your pycon talk - great stuff. Good luck getting the Tesla for testing purposes!

I've been maintaining a low level library that might interest you: python-can. It supports a whole bunch of physical can interfaces on windows and linux - and supports extended frame formats.

https://github.com/hardbyte/python-can

Cheers and I hope you don't mind the random suggestion out of the blue,
Brian

cannot import name 'can'

$ pip3.5 install pyvit --user
Collecting pyvit
Collecting pyserial>=3.2.1 (from pyvit)
  Using cached https://files.pythonhosted.org/packages/0d/e4/2a744dd9e3be04a0c0907414e2a01a7c88bb3915cbe3c8cc06e209f59c30/pyserial-3.4-py2.py3-none-any.whl
Installing collected packages: pyserial, pyvit
Successfully installed pyserial-3.4 pyvit-0.2.1
$ python3.5 pyvit.py
Traceback (most recent call last):
  File "pyvit.py", line 1, in <module>
    from pyvit import can
  File "/home/brandon/md1775-simulator/pyvit.py", line 1, in <module>
    from pyvit import can
ImportError: cannot import name 'can'

Using ISO-TP Dispatcher functionality

Hi,

I was hoping someone here might be able to help with an example of how to use the dispatcher in a loop and if a condition is met, send a relevant response.

Currently I've just been interacting with Pyvit in a simple while loop with dev.recv. However I'm not sure how to interact with the dispatcher given things are threaded.

Basically, I have a simple program using Pyvit acting as an ECU to send things such as RPM and Speed when requested by a connected device.

As an example:

#!/usr/bin/env python3

from pyvit import can
from pyvit.hw import socketcan

import os,sys,termios,tty,time

SupportedPIDsRequest = "0201000000000000"

RPMRequest = "02010C0000000000"
VINReq = "0209020000000000"

RPMResp = 'cansend vcan0 7E8#04410C1094000000'
VINResp = 'cansend vcan0 7E8#1014490201355445 && sleep 0.1 && ' \
          'cansend vcan0 7E8#214D5535324E3636 &&' \
          'cansend vcan0 7E8#225A323236373433'

def resp_function():
    resp = can.Frame(0x7E8)
    resp.data = frameData
    dev.send(resp)
    print(resp)
    return resp

dev = socketcan.SocketCanDev("vcan0")
dev.start()

while True:
    CanFrameRecv = dev.recv()

    if CanFrameRecv.arb_id == int(0x7DF):
        if (bytes(CanFrameRecv.data)) == bytes.fromhex(SupportedPIDsRequest):
            print('\nSupported PIDs Request  : ' + SupportedPIDsRequest)

            frameData = [0x06, 0x41, 0x00, 0x00, 0x18, 0x30, 0x01]
            response = resp_function()
            print('Supported PIDs Response : ' + str(resp_function().data))

        elif (bytes(CanFrameRecv.data)) == bytes.fromhex(RPMRequest):
            print('\nRPM Request Received    : ' + RPMRequest)
            print('RPM Response            : ' + RPMResp)
            os.system(RPMResp)    
        elif (bytes(CanFrameRecv.data)) == bytes.fromhex(VINReq):
            print('VIN Req          : ' + VINReq)
            print(VINResp)
            os.system(VINResp)

As you can see, I'm "cheating" with the VIN, and just sending the frames out without actually checking if a frame control message is received. I want to improve this, and actually use the ISO-TP functionality.

My issue is I've struggled to get ISO-TP messages working nicely.

Using the isotp_test I was able to get an idea on how to send an ISO-TP frame, provided you send a frame control message.

#!/usr/bin/env python3

import threading
from multiprocessing import Queue

from pyvit.hw import socketcan
from pyvit.dispatch import Dispatcher
from pyvit.proto.isotp import IsotpInterface

dev = socketcan.SocketCanDev("vcan0")
disp = Dispatcher(dev)
recv_queue = Queue()
disp.add_receiver(recv_queue)

# set up an isotp interface Sender/Receiver arb id
sender = IsotpInterface(disp, 0x7DF, 0x7E8)
receiver = IsotpInterface(disp, 0x7E8, 0x7DF)
disp.start()

""" ISOTP transmission and reception of a multi-frame message"""
print("payload creation")
payload = [0x49, 0x02, 0x01, 0x31, 0x41, 0x31, 0x4A, 0x43, 0x35, 0x34, 0x34, 0x34, 0x52, 0x37, 0x32, 0x35, 0x32, 0x33, 0x36, 0x37]

# we need to run this in a thread so that the flow control frame is
# sent and received, as IsotpInterfaces block
print("starting tx_thread")
tx_thread = threading.Thread(target=sender.send, args=(payload,))
tx_thread.start()

# we'll receive data in this thread
resp = receiver.recv()

# wait for the transmitting thread to finish, then verify the result
tx_thread.join()

## I'm really not too sure what the above " .join"actually does....

print("finished")

Example:

pi@rpi-hos:~/repos/pyvit $ python3 print_all_frames.py
payload creation
starting tx_thread
[16, 20, 73, 2, 1, 49, 65, 49] <SEND CONTROL FRAME>
[33, 74, 67, 53, 52, 52, 52, 82]
[34, 55, 50, 53, 50, 51, 54, 55]
finished

I'm just not sure how to interact with the Dispatcher send and receive methods/threads within a while loop.

I'm starting to get the impression my main loop should also be a thread but again not sure how to do this.

Sorry if this is an annoying question - I'm still pretty new to python.

Thanks,

Matt

Relicensing part of the code as MIT.

Hello Eric,

I have taken parts of pyvit to create a single line parser targetted at compatibility with Comma AI's Open Pilot and later Autoware.

Since the code I am developing will be MIT I would like to kindly ask if I can use the code here: autti/veloz@cce91b3 under that license.

I would just import pyvit but then would have to change my codebase from MIT to GPL v3 and that may make contributions to Udacity's self driving car projects in the future more difficult (they are using MIT too).

attribute '__version__'

so far pyvit has no attribute attribute 'version'

I suggest to implement it since .version is a standard call for most python modules

ISOTP protocol frame control message

You should change the flow control message if statement to below:

            if (((rx_frame.arb_id == self.rx_arb_id) or (rx_frame.arb_id == self.tx_arb_id-8)) and
                    rx_frame.data[0] == 0x30):

Frame control frames generally go out to the address of the specific device and not 7DF (rx request arbid).

If you had an ECU with 7E8, the flow control message would go to 7E0.

Decoder support for big(?) endian values

I'm not sure of the byte ordering for candump files (e.g. (time) interface msg_id#msg_Data) but I have a signal which spans bytes 6 and 7 (reading left to right) with 6 being the most significant byte.

My database.json's signal starts at bit 40, and has a bit_length of 16 but I believe the parser is treating bit 40 as the LSB (instead of MSB in my case)

Reference:

{
    "messages": [
        {
	    "name": "test msg",
            "id": "0x080",
	    "signals":
	    {
		"40":
		{
		    "name": "MSB Data",
		    "bit_length": 16,
		    "factor": 1,
		    "offset": 0
		}
	    }
        }
    ]
}

ID=0x080, DLC=8, Data=[90, 00, 7D, 00, 00, 80, 0E, F7]

Test fialures

When I run python can_test.py in canard/test with python 2 and 3, I always have failures because of something like this [1, 2, 3, 4, 5, 6, 0, 0] != [1, 2, 3, 4, 5, 6, None, None].

It looks like when you create a 8-byte frame with only 6 given integers, the rest would be 0 instead of None, if I am right, I will create a pull request to correct this.

Additional COMs except CAN

Hello, i like the tool and the project.

Does it support different Communications except CAN?

Thank you in Advance.

Baud rate settings wrong

Bitrate constants in set_bitrate are outdated - something like the following should work instead:

def set_bitrate(self, bitrate):
        _bitrates = {10000:0,
                 20000:1,
                 50000:2,
                100000:3,
                125000:4,
                250000:5,
                500000:6,
                750000:7,
               1000000:8}

        brnum = _bitrates[bitrate]
        self.ser.write('S%d\r'%brnum)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.