예제 #1
0
def join_frame_by_signal_startbit(files):
    targetDb = next(iter(im.importany(files.pop(0)).values()))

    pgn_x, id_x = list_pgn(db=targetDb)

    for f in files:
        sourceDb = next(iter(im.importany(f).values()))
        pgn_y, id_y = list_pgn(db=sourceDb)

        same_pgn = ids_sharing_same_pgn(id_x, pgn_x, id_y, pgn_y)

        for idx, idy in same_pgn:
            # print("{0:#x} {1:#x}".format(idx, idy))
            targetFr = targetDb.frameById(idx)
            sourceFr = sourceDb.frameById(idy)

            to_add = []
            for sig_t in targetFr._signals:
                for sig_s in sourceFr._signals:
                    # print(sig._name)
                    if sig_t._startbit == sig_s._startbit:
                        # print("\t{0} {1}".format(sig_t._name, sig_s._name))
                        to_add.append(sig_s)
            for s in to_add:
                targetFr.addSignal(s)

    return targetDb
예제 #2
0
def join_frame_by_signal_startbit(files):
    targetDb = next(iter(im.importany(files.pop(0)).values()))

    pgn_x, id_x = list_pgn(db=targetDb)

    for f in files:
        sourceDb = next(iter(im.importany(f).values()))
        pgn_y, id_y = list_pgn(db=sourceDb)

        same_pgn = ids_sharing_same_pgn(id_x, pgn_x, id_y, pgn_y)

        for idx, idy in same_pgn:
            # print("{0:#x} {1:#x}".format(idx, idy))
            targetFr = targetDb.frameById(idx)
            sourceFr = sourceDb.frameById(idy)

            to_add = []
            for sig_t in targetFr._signals:
                for sig_s in sourceFr._signals:
                    # print(sig._name)
                    if sig_t._startbit == sig_s._startbit:
                        # print("\t{0} {1}".format(sig_t._name, sig_s._name))
                        to_add.append(sig_s)
            for s in to_add:
                targetFr.addSignal(s)

    return targetDb
예제 #3
0
def main():
    if len(sys.argv) < 3:
        sys.stderr.write('Usage: sys.argv[0] matrix1 matrix2\n')
        sys.stderr.write('matrixX can be any of *.dbc|*.dbf|*.kcd|*.arxml\n')
        sys.exit(1)

    matrix1 = sys.argv[1]
    matrix2 = sys.argv[2]

    print("Importing " + matrix1 + " ... ")
    db1 = im.importany(matrix1)
    print("%d Frames found" % (db1._fl._list.__len__()))

    print("Importing " + matrix2 + " ... ")
    db2 = im.importany(matrix2)
    print("%d Frames found" % (db2._fl._list.__len__()))


    print("\n\n")


    ignore = {}
    #ignore["ATTRIBUTE"] = "*"
    #ignore["DEFINE"] = "*"
    obj = compareDb(db1, db2, ignore)
    dumpResult(obj)
예제 #4
0
def main():

    from optparse import OptionParser

    usage = """
    %prog [options] cancompare matrix1 matrix2
    
    matrixX can be any of *.dbc|*.dbf|*.kcd|*.arxml
    """

    parser = OptionParser(usage=usage)
    parser.add_option(
        "-s",
        dest="silent",
        action="store_true",
        help="don't print status messages to stdout. (only errors)",
        default=False)
    parser.add_option("-v",
                      dest="verbosity",
                      action="count",
                      help="Output verbosity",
                      default=0)
    (cmdlineOptions, args) = parser.parse_args()

    if len(args) < 2:
        parser.print_help()
        sys.exit(1)

    matrix1 = args[0]
    matrix2 = args[1]

    verbosity = cmdlineOptions.verbosity
    if cmdlineOptions.silent:
        # Only print ERROR messages (ignore import warnings)
        verbosity = -1
    set_log_level(logger, verbosity)

    # import only after setting log level, to also disable warning messages in silent mode.
    import canmatrix.importany as im

    logger.info("Importing " + matrix1 + " ... ")
    db1 = im.importany(matrix1)
    logger.info("%d Frames found" % (db1._fl._list.__len__()))

    logger.info("Importing " + matrix2 + " ... ")
    db2 = im.importany(matrix2)
    logger.info("%d Frames found" % (db2._fl._list.__len__()))

    ignore = {}
    #ignore["ATTRIBUTE"] = "*"
    #ignore["DEFINE"] = "*"
    obj = compareDb(db1, db2, ignore)
    dumpResult(obj)
예제 #5
0
def join_frame_for_manufacturer(db, files):
    #targetDb = next(iter(im.importany(files.pop(0)).values()))

    pgn_x, id_x = list_pgn(db=db)

    for f in files:
        sourceDb = next(iter(im.importany(f).values()))
        pgn_y, id_y = list_pgn(db=sourceDb)

        same_pgn = ids_sharing_same_pgn(id_x, pgn_x, id_y, pgn_y)

        for idx, idy in same_pgn:
            # print("{0:#x} {1:#x}".format(idx, idy))
            targetFr = db.frameById(idx)
            sourceFr = sourceDb.frameById(idy)

            _, pgn, sa = CanId(targetFr._Id).tuples()
            if (sa < 128):
                print('less', targetFr._name)
                to_add = []
                for sig_s in sourceFr._signals:
                    new_name = "{name}_{pgn:#04x}_{sa:03}".format(
                        name=sig_s._name, pgn=pgn, sa=sa)
                    sig_s._name = new_name
                    to_add.append(sig_s)
                for s in to_add:
                    targetFr.addSignal(s)
예제 #6
0
def join_frame_for_manufacturer(db, files):
    #targetDb = next(iter(im.importany(files.pop(0)).values()))

    pgn_x, id_x = list_pgn(db=db)

    for f in files:
        sourceDb = next(iter(im.importany(f).values()))
        pgn_y, id_y = list_pgn(db=sourceDb)

        same_pgn = ids_sharing_same_pgn(id_x, pgn_x, id_y, pgn_y)

        for idx, idy in same_pgn:
            # print("{0:#x} {1:#x}".format(idx, idy))
            targetFr = db.frameById(idx)
            sourceFr = sourceDb.frameById(idy)

            _, pgn, sa = CanId(targetFr._Id).tuples()
            if(sa<128):
                print('less',targetFr._name)
                to_add = []
                for sig_s in sourceFr._signals:
                    new_name = "{name}_{pgn:#04x}_{sa:03}".format(name=sig_s._name, pgn=pgn, sa=sa)
                    sig_s._name=new_name
                    to_add.append(sig_s)
                for s in to_add:
                    targetFr.addSignal(s)
예제 #7
0
def main():
    from optparse import OptionParser

    usage = """
    %prog [options] canDatabaseFile targetFile.c

    import-file: *.dbc|*.dbf|*.kcd|*.arxml|*.xls(x)|*.sym

    """

    parser = OptionParser(usage=usage)
    parser.add_option("", "--frame",
                                      dest="exportframe", default=None,
                                      help="create macros for Frame(s); Comma seperated list of Names ")
    parser.add_option("", "--ecu",
                                      dest="exportecu", default=None,
                                      help="create macros for Ecu(s) Comma seperated ")
 
    (cmdlineOptions, args) = parser.parse_args()
    if len(args) < 2:
        parser.print_help()
        sys.exit(1)

    infile = args[0]
    outfile = args[1]
 
    dbs = im.importany(infile)
    db = next(iter(dbs.values()))

    sourceCode = ""
    if cmdlineOptions.exportframe == None and cmdlineOptions.exportecu == None:
        for frame in db._fl._list:
            sourceCode += createDecodeMacrosForFrame(frame, "_" + frame._name + "_")
            sourceCode += createStoreMacrosForFrame(frame, "_" + frame._name + "_")

    if cmdlineOptions.exportframe != None:
        for frameId in cmdlineOptions.exportframe.split(','):
            try: 
                frame = db.frameById(int(frameId))
            except ValueError:
                frame = db.frameByName(frameId)
            if frame != None:            
                sourceCode += createDecodeMacrosForFrame(frame, "_" + frame._name + "_")
                sourceCode += createStoreMacrosForFrame(frame, "_" + frame._name + "_")
        
    if cmdlineOptions.exportecu != None:
        ecuList = cmdlineOptions.exportecu.split(',')
        for frame in db._fl._list:
            for ecu in ecuList:
                if ecu in frame._Transmitter:
                    sourceCode += createStoreMacrosForFrame(frame, "_" + frame._name + "_")
                for signal in frame._signals:
                    if ecu in signal._receiver:
                        sourceCode += createDecodeMacro(signal, "_" + frame._name + "_")
                 
    cfile = open(outfile, "w")    
    cfile.write(sourceCode)
    cfile.close()    
예제 #8
0
def main():
    
    from optparse import OptionParser

    usage = """
    %prog [options] cancompare matrix1 matrix2
    
    matrixX can be any of *.dbc|*.dbf|*.kcd|*.arxml
    """

    parser = OptionParser(usage=usage)
    parser.add_option("-s", dest="silent", action="store_true", help="don't print status messages to stdout. (only errors)", default=False)
    parser.add_option("-v", dest="verbosity", action="count", help="Output verbosity", default=0)
    (cmdlineOptions, args) = parser.parse_args()

    if len(args) < 2:
        parser.print_help()
        sys.exit(1)

    matrix1 = args[0]
    matrix2 = args[1]

    verbosity = cmdlineOptions.verbosity
    if cmdlineOptions.silent:
        # Only print ERROR messages (ignore import warnings)
        verbosity = -1
    set_log_level(logger, verbosity)
   
    # import only after setting log level, to also disable warning messages in silent mode.
    import canmatrix.importany as im
    
    logger.info("Importing " + matrix1 + " ... ")
    db1 = im.importany(matrix1)
    logger.info("%d Frames found" % (db1._fl._list.__len__()))

    logger.info("Importing " + matrix2 + " ... ")
    db2 = im.importany(matrix2)
    logger.info("%d Frames found" % (db2._fl._list.__len__()))

    ignore = {}
    #ignore["ATTRIBUTE"] = "*"
    #ignore["DEFINE"] = "*"
    obj = compareDb(db1, db2, ignore)
    dumpResult(obj)
예제 #9
0
def main():
    from optparse import OptionParser

    usage = """
    %prog [options] canDatabaseFile targetFile.c

    import-file: *.dbc|*.dbf|*.kcd|*.arxml|*.xls(x)|*.sym

    """

    parser = OptionParser(usage=usage)
    parser.add_option("", "--frame",
                                      dest="exportframe", default=None,
                                      help="create macros for Frame(s); Comma seperated list of Names ")
    parser.add_option("", "--ecu",
                                      dest="exportecu", default=None,
                                      help="create macros for Ecu(s) Comma seperated ")
 
    (cmdlineOptions, args) = parser.parse_args()
    if len(args) < 2:
        parser.print_help()
        sys.exit(1)

    infile = args[0]
    outfile = args[1]
 
    dbs = im.importany(infile)
    db = next(iter(dbs.values()))

    sourceCode = ""
    if cmdlineOptions.exportframe == None and cmdlineOptions.exportecu == None:
        for frame in db._fl._list:
            sourceCode += createDecodeMacrosForFrame(frame, "_" + frame._name + "_")

    if cmdlineOptions.exportframe != None:
        for frameId in cmdlineOptions.exportframe.split(','):
            try: 
                frame = db.frameById(int(frameId))
            except ValueError:
                frame = db.frameByName(frameId)
            if frame != None:            
                sourceCode += createDecodeMacrosForFrame(frame, "_" + frame._name + "_")
         
    if cmdlineOptions.exportecu != None:
        ecuList = cmdlineOptions.exportecu.split(',')
        for frame in db._fl._list:
            for ecu in ecuList:
                if ecu in frame._Transmitter:
                    sourceCode += createDecodeMacrosForFrame(frame, "_" + frame._name + "_")
                for signal in frame._signals:
                    if ecu in signal._receiver:
                        sourceCode += createDecodeMacro(signal, "_" + frame._name + "_")
 
    cfile = open(outfile, "w")    
    cfile.write(sourceCode)
    cfile.close()    
예제 #10
0
def main():
    if len(sys.argv) < 3:
        sys.stderr.write('Usage: sys.argv[0] import-file export-file\n')
        sys.stderr.write('import-file: *.dbc|*.dbf|*.kcd\n')
        sys.stderr.write('export-file: somefile.zip\n')
        sys.exit(1)

    infile = sys.argv[1]
    outfile = os.path.splitext(sys.argv[2])[0]

    db = im.importany(infile)
    tickerBoardUnits(db, outfile)
예제 #11
0
def main():
    if len(sys.argv) < 3:
        sys.stderr.write('Usage: sys.argv[0] import-file export-file\n')
        sys.stderr.write('import-file: *.dbc|*.dbf|*.kcd\n')
        sys.stderr.write('export-file: somefile.zip\n')
        sys.exit(1)

    infile = sys.argv[1]
    outfile = os.path.splitext(sys.argv[2])[0]

    db = im.importany(infile)
    tickerBoardUnits(db, outfile)
예제 #12
0
#!/usr/bin/env python3

# importany laed alle verfuegbaren importfilter
from canmatrix.copy import *
import canmatrix.importany as im
import canmatrix.exportall as ex
#fuer Fileio:
import sys

#
# read source Can-Matrixes
#

# import of one CAN-Matrix (*.dbc, *.dbf, *.kcd, *.arxml)
db1 = im.importany("first.dbc")
# import of a second CAN-Matrix (*.dbc, *.dbf, *.kcd, *.arxml)
db2 = im.importany("second.dbc")

#
# create target Matrix
#

db3 = CanMatrix()

#
# Here a new Can-Matrix can be  'programmed':
# -----------------------------------------------------
#

#Copy Can-ID 1234 from second CAN-Matrix to target-Matrix
copyFrame(1234, db2, db3)
예제 #13
0
def convert(infile, outfileName, **options):
    import canmatrix.exportall as ex
    import canmatrix.importany as im
    import canmatrix.canmatrix as cm
    import canmatrix.copy as cmcp
    dbs = {}

    logger.info("Importing " + infile + " ... ")
    dbs = im.importany(infile, **options)
    logger.info("done\n")

    logger.info("Exporting " + outfileName + " ... ")

    for name in dbs:
        db = None        

        if 'ecus' in options and options['ecus'] != None:
            ecuList = options['ecus'].split(',')
            db = cm.CanMatrix()
            for ecu in ecuList:
                logger.info("Copying ECU " + ecu)
                cmcp.copyBUwithFrames(ecu, dbs[name], db) 
        if 'frames' in options and options['frames'] != None:
            frameList = options['frames'].split(',')
            db = cm.CanMatrix()
            for frame in frameList:
                logger.info("Copying Frame " + frame)
                cmcp.copyFrame(frame, dbs[name], db) 
        if db == None:
            db = dbs[name]

        if 'merge' in options and options['merge'] != None:
            mergeFiles = options['merge'].split(',')
            for database in mergeFiles:
                mergeString = database.split(':')
                dbTempList = im.importany(mergeString[0])
                for dbTemp in dbTempList:
                    if mergeString.__len__() == 1:
                        print ("merge complete: " + mergeString[0])                    
                        for frame in dbTempList[dbTemp]._fl._list:
                            cmcp.copyFrame (frame._Id, dbTempList[dbTemp], db)
                    for mergeOpt in mergeString[1:]:
                        if mergeOpt.split('=')[0] == "ecu":
                            cmcp.copyBUwithFrames(mergeOpt.split('=')[1], dbTempList[dbTemp], db) 
                        if mergeOpt.split('=')[0] == "frame":
                            cmcp.copyFrame(mergeOpt.split('=')[1], dbTempList[dbTemp], db) 


        if 'deleteZeroSignals' in options and options['deleteZeroSignals']:
            db.deleteZeroSignals()
        
        if 'recalcDLC' in options and options['recalcDLC']:
            db.recalcDLC(options['recalcDLC'])

        logger.info(name)
        logger.info("%d Frames found" % (db._fl._list.__len__()))

        if len(name) > 0:
            path = os.path.split(outfileName)
            outfile = os.path.join(path[0], name + "_" + path[1])
        else:
            outfile = outfileName
           
        # Get output file extension   
        fileext = '' 
        if 'force_output' in options and options['force_output']:
            # Provided by the command line
            fileext = options['force_output']
        else:
            # Get extension from output filename
            fileext = os.path.splitext(outfile)[1]
       
        # Strip leading '.' from extension, of exists
        fileext = fileext[1:] if fileext.startswith('.') else fileext
         
                        
        if fileext == 'dbc':
            ex.exportDbc(db, outfile, **options)
        elif fileext == 'dbf':
            ex.exportDbf(db, outfile, **options)
        elif fileext == 'sym':
            ex.exportSym(db, outfile, **options)
        elif fileext == 'kcd':
            ex.exportKcd(db, outfile)
        elif fileext == 'xlsx':
            ex.exportXlsx(db, outfile, **options)
        elif fileext == 'xls':
            ex.exportXls(db, outfile, **options)
        elif fileext == 'json':
            ex.exportJson(db, outfile, **options)
        elif fileext == 'arxml':
            ex.exportArxml(db, outfile)
        elif fileext == 'yaml':
            ex.exportYaml(db, outfile)
        elif fileext == 'csv':
            ex.exportCsv(db, outfile)
        else:
            logger.error('File not recognized: ' + outfileName + "\n")
    logger.info("done")
예제 #14
0
import sys
sys.path.append('..')

# importany loads all import filter
from canmatrix.copy import *
import canmatrix.importany as im
import canmatrix.exportall as ex
#fuer Fileio:
import sys

#
# read source Can-Matrixes
#

# import of one CAN-Matrix (*.dbc, *.dbf, *.kcd, *.arxml)
db1 = next(iter(im.importany("first.dbc").values()))
# import of a second CAN-Matrix (*.dbc, *.dbf, *.kcd, *.arxml)
db2 = next(iter(im.importany("second.dbc").values()))

#
# create target Matrix
#

db3 = CanMatrix()

#
# Here a new Can-Matrix can be  'programmed':
# -----------------------------------------------------
#

#Copy Can-ID 1234 from second CAN-Matrix to target-Matrix
예제 #15
0
    def __init__(self):
        print(
            """
            RaceControl  Copyright (C) 2016  Florian Eich
            This program comes with ABSOLUTELY NO WARRANTY.
            This is free software, and you are welcome to
            redistribute it under certain conditions; see
            GPLv3 for details.
            """
        )

        # configpath = os.path.expanduser('~/.config/racecontrol')
        configpath = '/home/flrn/.config/racecontrol'
        if not os.path.exists(configpath):
            print('Creating ~/.config/racecontrol and copying default config.')
            os.makedirs(configpath)
            shutil.copy('etc/racecontrol.cfg', configpath)
            print('Success!')

        dbcpath = configpath + '/dbc'
        if not os.path.exists(dbcpath):
            print('Creating ~/.config/racecontrol/dbc.')
            os.makedirs(dbcpath)

        try:
            blacklistdbc = im.importany(dbcpath + '/blacklist.dbc')['']
            prioritydbc = im.importany(dbcpath + '/priority.dbc')['']
            guiupperdbc = im.importany(dbcpath + '/guiupper.dbc')['']
            guilowerdbc = im.importany(dbcpath + '/guilower.dbc')['']
            guitextdbc = im.importany(dbcpath + '/guitext.dbc')['']
        except FileNotFoundError:
            pass

        blacklist = [frame._Id for frame in blacklistdbc._fl._list]
        priority = [frame._Id for frame in prioritydbc._fl._list]

        msgfilter = {}

        upperid = guiupperdbc._fl._list[0]._Id
        lowerid = guilowerdbc._fl._list[0]._Id
        textid = guitextdbc._fl._list[0]._Id

        msgfilter[upperid] = {}
        msgfilter[lowerid] = {}
        msgfilter[textid] = {}

        offset = 0

        uppersignals = guiupperdbc._fl._list[0]._signals
        for sig in uppersignals:
            msgfilter[upperid][offset] = {}
            msgfilter[upperid][offset]['start'] = int(sig._startbit / 8)
            msgfilter[upperid][offset]['size'] = int(sig._signalsize / 8)
            msgfilter[upperid][offset]['name'] = sig._name
            offset += 1

        lowersignals = guilowerdbc._fl._list[0]._signals
        for sig in lowersignals:
            msgfilter[lowerid][offset] = {}
            msgfilter[lowerid][offset]['start'] = int(sig._startbit / 8)
            msgfilter[lowerid][offset]['size'] = int(sig._signalsize / 8)
            msgfilter[lowerid][offset]['name'] = sig._name
            offset += 1

        textsignals = guitextdbc._fl._list[0]._signals
        for sig in textsignals:
            msgfilter[textid][offset] = {}
            msgfilter[textid][offset]['start'] = int(sig._startbit / 8)
            msgfilter[textid][offset]['size'] = int(sig._signalsize / 8)
            msgfilter[textid][offset]['name'] = sig._name
            offset += 1

        self.cancomd = cancom.CANCom(blacklist)
        self.netcomd = netcom.NetCom(priority)
        self.logcomd = logcom.LogCom()
        self.webcomd = webcom.WebCom()
        self.guicomd = webcom.GUICom(self.webcomd.msgqueue, msgfilter)

        self.cancomd.add_listener(self.netcomd.dispatcher.buffer)
        self.cancomd.add_listener(self.guicomd.buffer)
        self.netcomd.add_listener(self.cancomd.buffer)

        for listener in self.logcomd.loggers():
            self.cancomd.add_listener(listener)
            self.netcomd.add_listener(listener)
예제 #16
0
def convert(infile, outfileName, **options):
    import canmatrix.exportall as ex
    import canmatrix.importany as im
    import canmatrix.canmatrix as cm
    import canmatrix.copy as cmcp
    dbs = {}

    logger.info("Importing " + infile + " ... ")
    dbs = im.importany(infile, **options)
    logger.info("done\n")

    logger.info("Exporting " + outfileName + " ... ")

    for name in dbs:
        db = None

        if 'ecus' in options and options['ecus'] != None:
            ecuList = options['ecus'].split(',')
            db = cm.CanMatrix()
            for ecu in ecuList:
                logger.info("Copying ECU " + ecu)
                cmcp.copyBUwithFrames(ecu, dbs[name], db)
        if 'frames' in options and options['frames'] != None:
            frameList = options['frames'].split(',')
            db = cm.CanMatrix()
            for frame in frameList:
                logger.info("Copying Frame " + frame)
                cmcp.copyFrame(frame, dbs[name], db)
        if db == None:
            db = dbs[name]

        if 'merge' in options and options['merge'] != None:
            mergeFiles = options['merge'].split(',')
            for database in mergeFiles:
                mergeString = database.split(':')
                dbTempList = im.importany(mergeString[0])
                for dbTemp in dbTempList:
                    if mergeString.__len__() == 1:
                        print("merge complete: " + mergeString[0])
                        for frame in dbTempList[dbTemp]._fl._list:
                            cmcp.copyFrame(frame._Id, dbTempList[dbTemp], db)
                    for mergeOpt in mergeString[1:]:
                        if mergeOpt.split('=')[0] == "ecu":
                            cmcp.copyBUwithFrames(
                                mergeOpt.split('=')[1], dbTempList[dbTemp], db)
                        if mergeOpt.split('=')[0] == "frame":
                            cmcp.copyFrame(
                                mergeOpt.split('=')[1], dbTempList[dbTemp], db)

        if 'deleteZeroSignals' in options and options['deleteZeroSignals']:
            db.deleteZeroSignals()

        if 'recalcDLC' in options and options['recalcDLC']:
            db.recalcDLC(options['recalcDLC'])

        logger.info(name)
        logger.info("%d Frames found" % (db._fl._list.__len__()))

        if len(name) > 0:
            path = os.path.split(outfileName)
            outfile = os.path.join(path[0], name + "_" + path[1])
        else:
            outfile = outfileName

        # Get output file extension
        fileext = ''
        if 'force_output' in options and options['force_output']:
            # Provided by the command line
            fileext = options['force_output']
        else:
            # Get extension from output filename
            fileext = os.path.splitext(outfile)[1]

        # Strip leading '.' from extension, of exists
        fileext = fileext[1:] if fileext.startswith('.') else fileext

        if fileext == 'dbc':
            ex.exportDbc(db, outfile, **options)
        elif fileext == 'dbf':
            ex.exportDbf(db, outfile, **options)
        elif fileext == 'sym':
            ex.exportSym(db, outfile, **options)
        elif fileext == 'kcd':
            ex.exportKcd(db, outfile)
        elif fileext == 'xlsx':
            ex.exportXlsx(db, outfile, **options)
        elif fileext == 'xls':
            ex.exportXls(db, outfile, **options)
        elif fileext == 'json':
            ex.exportJson(db, outfile, **options)
        elif fileext == 'arxml':
            ex.exportArxml(db, outfile)
        elif fileext == 'yaml':
            ex.exportYaml(db, outfile)
        elif fileext == 'csv':
            ex.exportCsv(db, outfile)
        else:
            logger.error('File not recognized: ' + outfileName + "\n")
    logger.info("done")
예제 #17
0
import sys
sys.path.append('..')

# importany loads all import filter
from canmatrix.copy import *
import canmatrix.importany as im
import canmatrix.exportall as ex
#fuer Fileio:
import sys

#
# read source Can-Matrixes
#

# import of one CAN-Matrix (*.dbc, *.dbf, *.kcd, *.arxml)
db1 = next(iter(im.importany("first.dbc").values()))
# import of a second CAN-Matrix (*.dbc, *.dbf, *.kcd, *.arxml)
db2 = next(iter(im.importany("second.dbc").values()))

#
# create target Matrix
#

db3 = CanMatrix()

#
# Here a new Can-Matrix can be  'programmed':
# -----------------------------------------------------
#

#Copy Can-ID 1234 from second CAN-Matrix to target-Matrix
예제 #18
0
def convert(infile, outfileName, **options):
    import canmatrix.exportany as ex
    import canmatrix.importany as im
    import canmatrix.canmatrix as cm
    import canmatrix.copy as cmcp
    dbs = {}

    logger.info("Importing " + infile + " ... ")
    dbs = im.importany(infile, **options)
    logger.info("done\n")

    logger.info("Exporting " + outfileName + " ... ")

    for name in dbs:
        db = None

        if 'ecus' in options and options['ecus'] != None:
            ecuList = options['ecus'].split(',')
            db = cm.CanMatrix()
            for ecu in ecuList:
                logger.info("Copying ECU " + ecu)
                cmcp.copyBUwithFrames(ecu, dbs[name], db)
        if 'frames' in options and options['frames'] != None:
            frameList = options['frames'].split(',')
            db = cm.CanMatrix()
            for frame in frameList:
                logger.info("Copying Frame " + frame)
                cmcp.copyFrame(frame, dbs[name], db)
        if db == None:
            db = dbs[name]

        if 'merge' in options and options['merge'] != None:
            mergeFiles = options['merge'].split(',')
            for database in mergeFiles:
                mergeString = database.split(':')
                dbTempList = im.importany(mergeString[0])
                for dbTemp in dbTempList:
                    if mergeString.__len__() == 1:
                        print("merge complete: " + mergeString[0])
                        for frame in dbTempList[dbTemp]._fl._list:
                            cmcp.copyFrame(frame._Id, dbTempList[dbTemp], db)
                    for mergeOpt in mergeString[1:]:
                        if mergeOpt.split('=')[0] == "ecu":
                            cmcp.copyBUwithFrames(
                                mergeOpt.split('=')[1], dbTempList[dbTemp], db)
                        if mergeOpt.split('=')[0] == "frame":
                            cmcp.copyFrame(
                                mergeOpt.split('=')[1], dbTempList[dbTemp], db)

        if 'deleteZeroSignals' in options and options['deleteZeroSignals']:
            db.deleteZeroSignals()

        if 'deleteSignalAttributes' in options and options[
                'deleteSignalAttributes']:
            unwantedAttributes = options['deleteSignalAttributes'].split(',')
            db.delSignalAttributes(unwantedAttributes)

        if 'deleteFrameAttributes' in options and options[
                'deleteFrameAttributes']:
            unwantedAttributes = options['deleteFrameAttributes'].split(',')
            db.delFrameAttributes(unwantedAttributes)

        if 'recalcDLC' in options and options['recalcDLC']:
            db.recalcDLC(options['recalcDLC'])

        logger.info(name)
        logger.info("%d Frames found" % (db._fl._list.__len__()))

        if len(name) > 0:
            path = os.path.split(outfileName)
            outfile = os.path.join(path[0], name + "_" + path[1])
        else:
            outfile = outfileName

        ex.exportany(db, outfile, **options)
    logger.info("done")
예제 #19
0
def main():
    if len(sys.argv) <= 2:
        print "not yet working script for generating a communication layer for dedicated ECU out of can database"
        print "! missing support for sending cyclic messages"
        print "! missing any TEST ! "
        print " this code is just proofe of concept \n"
        print "Usage: createccl.py CanDatabaseFile ECU_Name "
        exit()

    ccl_h = "#ifndef __CCL_H__\n#define __CCL_H__\n\n"
    ccl_h += "typedef unsigned char uint8;\ntypedef unsigned int uint32;\n\n"

    ccl_c = "#include <string.h>\n#include <stdint.h>\n#include \"ccl.h\"\n\n"
    infile = sys.argv[1]
    ecu = sys.argv[2]

    dbs = im.importany(infile)
    db = next(iter(dbs.values()))

    receiveArray = []
    receiveDict = {}
    receiveIndex = 0
    sendIndex = 0
    txDict = {}
    for frame in db._fl._list:
        if ecu in frame._receiver:
            receiveArray.append(frame._Id)
            receiveDict[frame] = receiveIndex
            receiveIndex += 1

        if ecu in frame._Transmitter:
            txDict[frame] = sendIndex
            sendIndex += 1
#            print frame._name
#            if "GenMsgCycleTime" in frame._attributes and int(frame._attributes["GenMsgCycleTime"]) != 0:
#                print frame._name,
#                print frame._attributes["GenMsgCycleTime"]
#            ccl_h += createStoreMacrosForFrame(frame, "_" + frame._name + "_")

    tempStr = ""
    for canid in receiveArray:
        tempStr += hex(canid) + ", "

    ccl_c += rxMailboxStruct + "\n"
    ccl_c += txMailboxStruct + "\n"
    ccl_c += receiveIdArray % (tempStr) + "\n"
    ccl_c += getRxCanMailBox + "\n"
    ccl_c += processFrame + "\n"

    ccl_h += "#define COUNTRXMAILBOXES %d" % (receiveArray.__len__()) + "\n"
    ccl_h += "#define COUNTTXMAILBOXES %d" % (txDict.__len__()) + "\n"
    ccl_h += typedef + "\n"
    ccl_h += "extern " + rxMailboxStruct + "\n"
    ccl_h += "extern " + txMailboxStruct + "\n"
    for frame in receiveDict:
        for signal in frame._signals:
            if ecu in signal._receiver:
                ccl_h += createDecodeMacro(
                    signal, "_" + frame._name + "__", "",
                    "RxCanMailboxes[%d].data" % (receiveDict[frame]))


# for complete frame:
#        ccl_h += createDecodeMacrosForFrame(frame, "_" + frame._name + "__", "", "RxCanMailboxes[%d].data" % (receiveDict[frame]))
    for frame in txDict:
        ccl_h += createStoreMacrosForFrame(
            frame,
            "_" + frame._name + "_",
            framename="TxCanMailboxes[%d].data" % txDict[frame])

    ccl_h += "\n\n#endif /*  __CCL_H___ */"

    cfile = open("ccl.c", "w")
    cfile.write(ccl_c)
    cfile.close()

    hfile = open("ccl.h", "w")
    hfile.write(ccl_h)
    hfile.close()
예제 #20
0
def main():
    if len(sys.argv) <= 2:
        print "not yet working script for generating a communication layer for dedicated ECU out of can database"
        print "! missing support for sending cyclic messages"
        print "! missing any TEST ! "
        print " this code is just proofe of concept \n"        
        print "Usage: createccl.py CanDatabaseFile ECU_Name "
        exit()

    ccl_h = "#ifndef __CCL_H__\n#define __CCL_H__\n\n"
    ccl_h += "typedef unsigned char uint8;\ntypedef unsigned int uint32;\n\n"

    ccl_c = "#include <string.h>\n#include <stdint.h>\n#include \"ccl.h\"\n\n"
    infile = sys.argv[1]
    ecu = sys.argv[2] 
    
    dbs = im.importany(infile)
    db = next(iter(dbs.values()))

    receiveArray = []
    receiveDict = {}
    receiveIndex = 0
    sendIndex = 0
    txDict = {}
    for frame in db._fl._list:
        if ecu in frame._receiver:
            receiveArray.append(frame._Id)
            receiveDict[frame] = receiveIndex
            receiveIndex += 1

        if ecu in frame._Transmitter:
            txDict[frame] = sendIndex
            sendIndex += 1
#            print frame._name
#            if "GenMsgCycleTime" in frame._attributes and int(frame._attributes["GenMsgCycleTime"]) != 0:
#                print frame._name,
#                print frame._attributes["GenMsgCycleTime"]
#            ccl_h += createStoreMacrosForFrame(frame, "_" + frame._name + "_")
    
    tempStr = ""
    for canid in receiveArray:
        tempStr += hex(canid) + ", "

    ccl_c += rxMailboxStruct + "\n"
    ccl_c += txMailboxStruct + "\n"
    ccl_c += receiveIdArray % ( tempStr) + "\n"
    ccl_c += getRxCanMailBox + "\n"
    ccl_c += processFrame + "\n"

    ccl_h += "#define COUNTRXMAILBOXES %d" % (receiveArray.__len__()) + "\n"
    ccl_h += "#define COUNTTXMAILBOXES %d" % (txDict.__len__()) + "\n"
    ccl_h += typedef + "\n"
    ccl_h += "extern " + rxMailboxStruct + "\n"
    ccl_h += "extern " + txMailboxStruct + "\n"
    for frame in receiveDict:
        for signal in frame._signals:
           if ecu in signal._receiver:
              ccl_h += createDecodeMacro(signal, "_" + frame._name + "__", "", "RxCanMailboxes[%d].data" % (receiveDict[frame]))
# for complete frame:
#        ccl_h += createDecodeMacrosForFrame(frame, "_" + frame._name + "__", "", "RxCanMailboxes[%d].data" % (receiveDict[frame]))
    for frame in txDict:
        ccl_h += createStoreMacrosForFrame(frame, "_" + frame._name + "_", framename = "TxCanMailboxes[%d].data" % txDict[frame])

    ccl_h += "\n\n#endif /*  __CCL_H___ */"
 
    cfile = open("ccl.c", "w")    
    cfile.write(ccl_c)
    cfile.close()    
 
    hfile = open("ccl.h", "w")    
    hfile.write(ccl_h)
    hfile.close()