J1939 Sample

From Digi Developer

Jump to: navigation, search

This page contains a sample on how to use the J1939 Python API on a Digi device.

## Import the CAN module
from digicanbus import *
import struct, time, sys
baud = 125000
if len(sys.argv) >= 2:
  baud = int(sys.argv[1])
## The digicanbus module has CANHandle().  A function that returns a handle to 
## the current CAN bus.
## Specify the CAN bus number.
print "Getting handle to CAN bus 0"
handle = CANHandle(0)
## configure(bitrate) 
## Configures the CAN bus to a specific bps and starts it.  This must be called
## at least once.
print "Configuring the bus to %d bps" %baud
## We create a function to be called when a J1939 message that is matched will
## be passed to.
def callback_1(width, identifier, remote_frame, payload, return_arg):
  PDU = J1939_PDU(width, identifier, remote_frame, payload)
  print "====PDU received===="
  for opt in ['DA', 'DP', 'EDP', 'GE', 'PF', 'PGN', 
              'PS', 'SA', 'priority', 'payload']:
    print opt + " = " + str(PDU.__getattribute__(opt))
  print "Converting to a raw can message, sending it over the CAN bus"
  raw_msg = PDU.CANMsgTuple()
  print "%s %s %s %s" %(raw_msg[0], hex(raw_msg[1]), raw_msg[2], raw_msg[3])
  except Exception, e:
    print e
    print "Message succesfully sent"
## We create a filter that will trigger on 29 bit messages
filter_1 = (29, 0x0, 0x0, callback_1, 'filter_1')
print "Filter 1: ", filter_1
## Register the filters on the CAN bus
print "Registering filters..."
counter = 0
print "Hit enter to send J1939_PDU, type 'quit' to exit"
while raw_input().lower() != 'quit':
  counter += 1
  P = J1939_PDU()
  P.DA = 0x76
  P.PGN = 0xF001
  P.payload = 'msg' + str(counter)
  can_msg = P.CANMsgTuple()
## Unregister the filters created using the stored tuples
print "Unregistering filters"
Personal tools
Wiki Editing