File: createCMacros.py

package info (click to toggle)
python-canmatrix 1.2~github-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,012 kB
  • sloc: xml: 30,201; python: 14,631; makefile: 31; sh: 7
file content (182 lines) | stat: -rwxr-xr-x 6,752 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/usr/bin/env python
# Copyright (c) 2016, Eduard Broecker
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that
# the following conditions are met:
#
#    Redistributions of source code must retain the above copyright notice, this list of conditions and the
#    following disclaimer.
#    Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
#    following disclaimer in the documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.


import sys
sys.path.append('..')
import canmatrix.formats


def createStoreMacro(signal, prefix="", frame="frame"):
    startBit = signal.get_startbit(bit_numbering=1, start_little=1)
    byteOrder = signal.is_little_endian
    length = signal.size
    startByte = int(startBit / 8)
    startBitInByte = startBit % 8
    currentTargetLength = (8 - startBitInByte)
    mask = ((0xffffffffffffffff) >> (64 - length))

    code = "#define storeSignal%s%s(value) do{" % (prefix, signal.name)
    if signal.is_signed:
        code += "value|=((value&0x8000000000000000)>>(64-length));"

    code += "value&=0x%X;" % (mask)

    code += "%s[%d]|=value<<%d;" % (frame, startByte, startBitInByte)

    if byteOrder:
        endByte = int((startBit + length) / 8)
        for count in range(startByte + 1, endByte):
            code += "%s[%d]|=value<<%d;" % (frame, count, currentTargetLength)
            currentTargetLength += 8
    else:  # motorola / big-endian
        endByte = int((startByte * 8 + 8 - startBitInByte - length) / 8)
        for count in range(startByte - 1, endByte - 1, -1):
            code += "%s[%d]|=value<<%d;" % (frame, count, currentTargetLength)
            currentTargetLength += 8
    code += "}while(0);\n"
    return code


def createDecodeMacro(
        signal, prefix="", macrosource="source", source="source"):
    startBit = signal.get_startbit(bit_numbering=1, start_little=1)
    byteOrder = signal.is_little_endian
    length = signal.signalsize

    mask = ((0xffffffffffffffff) >> (64 - length))

    startByte = int(startBit / 8)
    startBitInByte = startBit % 8

    code = "#define get_signal%s%s(%s)  ((((%s[%d])>>%d" % (
        prefix, signal.name, macrosource, source, startByte, startBitInByte)
    currentTargetLength = (8 - startBitInByte)

    if byteOrder:
        endByte = int((startBit + length) / 8)
        if (startBit + length) % 8 == 0:
            endByte -= 1
        for count in range(startByte + 1, endByte + 1):
            code += "|(%s[%d])<<%d" % (source, count, currentTargetLength)
            currentTargetLength += 8

    else:  # motorola / big-endian
        endByte = int((startByte * 8 + 8 - startBitInByte - length) / 8)

        for count in range(startByte - 1, endByte - 1, -1):
            code += "|%s[%d]<<%d" % (source, count, currentTargetLength)
            currentTargetLength += 8

    code += ")&0x%X)" % (mask)

    if signal.is_signed:
        msb_sign_mask = 1 << (length - 1)
        code += "^0x%x)-0x%x " % (msb_sign_mask, msb_sign_mask)
    else:
        code += ")"
    code += "\n"
    return code


def createDecodeMacrosForFrame(
        Frame, prefix="", macrosource="source", source="source"):
    code = ""
    for signal in Frame.signals:
        code += createDecodeMacro(signal, prefix, macrosource, source)
    return code


def createStoreMacrosForFrame(Frame, prefix="", framename="frame"):
    code = ""
    for signal in Frame.signals:
        code += createStoreMacro(signal, prefix, frame=framename)
    return code


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 = canmatrix.formats.loadp(infile)
    db = next(iter(dbs.values()))

    sourceCode = ""
    if cmdlineOptions.exportframe is None and cmdlineOptions.exportecu is None:
        for frame in db.frames:
            sourceCode += createDecodeMacrosForFrame(
                frame, "_" + frame.name + "_")
            sourceCode += createStoreMacrosForFrame(
                frame, "_" + frame.name + "_")

    if cmdlineOptions.exportframe is not None:
        for frameId in cmdlineOptions.exportframe.split(','):
            try:
                frame = db.frame_by_id(canmatrix.ArbitrationId(frameId))
            except ValueError:
                frame = db.frame_by_name(frameId)
            if frame is not None:
                sourceCode += createDecodeMacrosForFrame(
                    frame, "_" + frame.name + "_")
                sourceCode += createStoreMacrosForFrame(
                    frame, "_" + frame.name + "_")

    if cmdlineOptions.exportecu is not None:
        ecuList = cmdlineOptions.exportecu.split(',')
        for frame in db.frames:
            for ecu in ecuList:
                if ecu in frame.transmitters:
                    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()


if __name__ == '__main__':
    sys.exit(main())