From 4ec6fd431b65178e08fc922f064de47d95203678 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eduard=20Br=C3=B6cker?= Date: Fri, 22 Feb 2019 21:59:23 +0100 Subject: [PATCH] [WIP] - Refactoring Snail case (#292) #236 * refactor api to snail_case * rename BoardUnits to ecus * fix some utils --- examples/BusmasterRestbus.py | 2 +- examples/createCMacros.py | 8 +- examples/createJ1939Dbc.py | 16 +- src/canmatrix/arxml.py | 106 ++--- src/canmatrix/cancluster.py | 8 +- src/canmatrix/canmatrix.py | 484 ++++++++++----------- src/canmatrix/cmcsv.py | 4 +- src/canmatrix/cmjson.py | 38 +- src/canmatrix/compare.py | 32 +- src/canmatrix/convert.py | 40 +- src/canmatrix/copy.py | 48 +- src/canmatrix/dbc.py | 208 +++++---- src/canmatrix/dbf.py | 108 ++--- src/canmatrix/fibex.py | 6 +- src/canmatrix/join.py | 16 +- src/canmatrix/kcd.py | 46 +- src/canmatrix/sym.py | 72 +-- src/canmatrix/tests/test_canmatrix.py | 218 +++++----- src/canmatrix/tests/test_cmjson.py | 24 +- src/canmatrix/tests/test_copy.py | 32 +- src/canmatrix/tests/test_dbc.py | 32 +- src/canmatrix/tests/test_frame_decoding.py | 12 +- src/canmatrix/tests/test_frame_encoding.py | 12 +- src/canmatrix/tests/test_sym.py | 8 +- src/canmatrix/xls.py | 46 +- src/canmatrix/xls_common.py | 20 +- src/canmatrix/xlsx.py | 46 +- src/canmatrix/yaml.py | 6 +- test/createTestFdMatrix.py | 22 +- test/createTestMatrix.py | 36 +- 30 files changed, 877 insertions(+), 879 deletions(-) diff --git a/examples/BusmasterRestbus.py b/examples/BusmasterRestbus.py index f018ebeb..aca801b2 100755 --- a/examples/BusmasterRestbus.py +++ b/examples/BusmasterRestbus.py @@ -163,7 +163,7 @@ def tickerBoardUnits(db, dbcname): MyBuList = [] - for bu in db.boardUnits: + for bu in db.ecus: if bu.name not in MyBuList: MyBuList.append(bu.name) # no duplicate Nodes else: diff --git a/examples/createCMacros.py b/examples/createCMacros.py index eb2c20ac..ee44843c 100755 --- a/examples/createCMacros.py +++ b/examples/createCMacros.py @@ -26,7 +26,7 @@ def createStoreMacro(signal, prefix="", frame="frame"): - startBit = signal.getStartbit(bitNumbering=1, startLittle=1) + startBit = signal.get_startbit(bit_numbering=1, start_little=1) byteOrder = signal.is_little_endian length = signal.signalsize startByte = int(startBit / 8) @@ -58,7 +58,7 @@ def createStoreMacro(signal, prefix="", frame="frame"): def createDecodeMacro( signal, prefix="", macrosource="source", source="source"): - startBit = signal.getStartbit(bitNumbering=1, startLittle=1) + startBit = signal.get_startbit(bit_numbering=1, start_little=1) byteOrder = signal.is_little_endian length = signal.signalsize @@ -152,9 +152,9 @@ def main(): if cmdlineOptions.exportframe is not None: for frameId in cmdlineOptions.exportframe.split(','): try: - frame = db.frameById(int(frameId)) + frame = db.frame_by_id(int(frameId)) except ValueError: - frame = db.frameByName(frameId) + frame = db.frame_by_name(frameId) if frame is not None: sourceCode += createDecodeMacrosForFrame( frame, "_" + frame.name + "_") diff --git a/examples/createJ1939Dbc.py b/examples/createJ1939Dbc.py index 5e074631..85913363 100644 --- a/examples/createJ1939Dbc.py +++ b/examples/createJ1939Dbc.py @@ -10,8 +10,8 @@ comment = "J1939 packet containing >8 byte payload") for i in range(1,9): sig = canmatrix.Signal("ch%d" % i, size = 32, is_float = True, is_little_endian = False, startBit = (i-1)*32) - frame1.addSignal(sig) -cm.addFrame(frame1) + frame1.add_signal(sig) +cm.add_frame(frame1) # # create frame Node605 @@ -22,9 +22,9 @@ sig = canmatrix.Signal("ch1", size=32, is_float=True, is_little_endian=False, startBit=0) sig2 = canmatrix.Signal("ch2", size=32, is_float=True, is_little_endian=False, startBit=32) -frame2.addSignal(sig) -frame2.addSignal(sig2) -cm.addFrame(frame2) +frame2.add_signal(sig) +frame2.add_signal(sig2) +cm.add_frame(frame2) # @@ -34,11 +34,11 @@ j1939_source = 0x80, comment="J1939 packet containing <8 byte payload") sig = canmatrix.Signal("ch1", size=32, is_float=True, is_little_endian=False, startBit=0) -frame3.addSignal(sig) -cm.addFrame(frame3) +frame3.add_signal(sig) +cm.add_frame(frame3) -cm.recalcDLC("force") +cm.recalc_dlc("force") # save dbc canmatrix.formats.dumpp({"":cm}, "example_j1939.dbc") diff --git a/src/canmatrix/arxml.py b/src/canmatrix/arxml.py index a466abbb..76d330f3 100644 --- a/src/canmatrix/arxml.py +++ b/src/canmatrix/arxml.py @@ -429,7 +429,7 @@ def dump(dbs, f, **options): signalRef.set('DEST', 'I-SIGNAL') createSubElement(signalToPduMapping, 'START-POSITION', - str(signal.getStartbit(bitNumbering=1))) + str(signal.get_startbit(bit_numbering=1))) # missing: TRANSFER-PROPERTY: PENDING/... for group in frame.signalGroups: @@ -663,7 +663,7 @@ def dump(dbs, f, **options): elements = createSubElement(arPackage, 'ELEMENTS') for name in dbs: db = dbs[name] - for ecu in db.boardUnits: + for ecu in db.ecus: ecuInstance = createSubElement(elements, 'ECU-INSTANCE') createSubElement(ecuInstance, 'SHORT-NAME', ecu.name) if ecu.comment: @@ -961,7 +961,7 @@ def getSysSignals(syssignal, syssignalarray, Bo, Id, ns): members = [] for signal in syssignalarray: members.append(arGetName(signal, ns)) - Bo.addSignalGroup(arGetName(syssignal, ns), 1, members) + Bo.add_signal_group(arGetName(syssignal, ns), 1, members) def decodeCompuMethod(compuMethod, arDict, ns, float_factory): @@ -1179,7 +1179,7 @@ def getSignals(signalarray, Bo, xmlRoot, ns, multiplexId, float_factory): if startBit is not None: newSig = Signal(name.text, - startBit=int(startBit.text), + start_bit=int(startBit.text), size=int(length.text), is_little_endian=is_little_endian, is_signed=is_signed, @@ -1198,7 +1198,7 @@ def getSignals(signalarray, Bo, xmlRoot, ns, multiplexId, float_factory): if newSig.is_little_endian == 0: # startbit of motorola coded signals are MSB in arxml - newSig.setStartbit(int(startBit.text), bitNumbering=1) + newSig.set_startbit(int(startBit.text), bitNumbering=1) # save signal, to determin receiver-ECUs for this signal later signalRxs[syssignal] = newSig @@ -1206,22 +1206,22 @@ def getSignals(signalarray, Bo, xmlRoot, ns, multiplexId, float_factory): if baseType is not None: temp = arGetChild(baseType, "SHORT-NAME", xmlRoot, ns) if temp is not None and "boolean" == temp.text: - newSig.addValues(1, "TRUE") - newSig.addValues(0, "FALSE") + newSig.add_values(1, "TRUE") + newSig.add_values(0, "FALSE") if initvalue is not None and initvalue.text is not None: initvalue.text = canmatrix.utils.guess_value(initvalue.text) newSig._initValue = int(initvalue.text) - newSig.addAttribute("GenSigStartValue", str(newSig._initValue)) + newSig.add_attribute("GenSigStartValue", str(newSig._initValue)) else: newSig._initValue = 0 for key, value in list(values.items()): - newSig.addValues(key, value) + newSig.add_values(key, value) if sig_long_name is not None: - newSig.addAttribute("LongName", sig_long_name) - Bo.addSignal(newSig) + newSig.add_attribute("LongName", sig_long_name) + Bo.add_signal(newSig) def getFrame(frameTriggering, xmlRoot, multiplexTranslation, ns, float_factory): @@ -1251,7 +1251,7 @@ def getFrame(frameTriggering, xmlRoot, multiplexTranslation, ns, float_factory): newFrame = Frame(arGetName(frameR, ns), id=idNum, size=int(dlc.text)) comment = getDesc(frameR, xmlRoot, ns) if comment is not None: - newFrame.addComment(comment) + newFrame.add_comment(comment) else: # without frameinfo take short-name of frametriggering and dlc = 8 logger.debug("Frame %s has no FRAME-REF" % (sn)) @@ -1276,11 +1276,11 @@ def getFrame(frameTriggering, xmlRoot, multiplexTranslation, ns, float_factory): if selectorByteOrder.text == 'MOST-SIGNIFICANT-BYTE-LAST': is_little_endian = True is_signed = False # unsigned - multiplexor = Signal("Multiplexor",startBit=int(selectorStart.text),size=int(selectorLen.text), + multiplexor = Signal("Multiplexor",start_bit=int(selectorStart.text),size=int(selectorLen.text), is_little_endian=is_little_endian,multiplex="Multiplexor") multiplexor._initValue = 0 - newFrame.addSignal(multiplexor) + newFrame.add_signal(multiplexor) staticPart = arGetChild(pdu, "STATIC-PART", xmlRoot, ns) ipdu = arGetChild(staticPart, "I-PDU", xmlRoot, ns) if ipdu is not None: @@ -1307,7 +1307,7 @@ def getFrame(frameTriggering, xmlRoot, multiplexTranslation, ns, float_factory): getSignals(pdusigmapping,newFrame,xmlRoot,ns,selectorId.text, float_factory) if newFrame.comment is None: - newFrame.addComment(getDesc(pdu, xmlRoot, ns)) + newFrame.add_comment(getDesc(pdu, xmlRoot, ns)) if extEle is not None: if extEle.text == 'EXTENDED': @@ -1328,39 +1328,39 @@ def getFrame(frameTriggering, xmlRoot, multiplexTranslation, ns, float_factory): timePeriod = arGetChild(cyclicTiming, "TIME-PERIOD", xmlRoot, ns) if cyclicTiming is not None and eventTiming is not None: - newFrame.addAttribute("GenMsgSendType", "cyclicAndSpontanX") # CycleAndSpontan + newFrame.add_attribute("GenMsgSendType", "cyclicAndSpontanX") # CycleAndSpontan if minimumDelay is not None: - newFrame.addAttribute("GenMsgDelayTime", str(int(float_factory(minimumDelay.text) * 1000))) + newFrame.add_attribute("GenMsgDelayTime", str(int(float_factory(minimumDelay.text) * 1000))) if repeats is not None: - newFrame.addAttribute("GenMsgNrOfRepetitions", repeats.text) + newFrame.add_attribute("GenMsgNrOfRepetitions", repeats.text) elif cyclicTiming is not None: - newFrame.addAttribute("GenMsgSendType", "cyclicX") # CycleX + newFrame.add_attribute("GenMsgSendType", "cyclicX") # CycleX if minimumDelay is not None: - newFrame.addAttribute("GenMsgDelayTime", str(int(float_factory(minimumDelay.text) * 1000))) + newFrame.add_attribute("GenMsgDelayTime", str(int(float_factory(minimumDelay.text) * 1000))) if repeats is not None: - newFrame.addAttribute("GenMsgNrOfRepetitions", repeats.text) + newFrame.add_attribute("GenMsgNrOfRepetitions", repeats.text) else: - newFrame.addAttribute("GenMsgSendType", "spontanX") # Spontan + newFrame.add_attribute("GenMsgSendType", "spontanX") # Spontan if minimumDelay is not None: - newFrame.addAttribute("GenMsgDelayTime", str(int(float_factory(minimumDelay.text) * 1000))) + newFrame.add_attribute("GenMsgDelayTime", str(int(float_factory(minimumDelay.text) * 1000))) if repeats is not None: - newFrame.addAttribute("GenMsgNrOfRepetitions", repeats.text) + newFrame.add_attribute("GenMsgNrOfRepetitions", repeats.text) if startingTime is not None: value = arGetChild(startingTime, "VALUE", xmlRoot, ns) - newFrame.addAttribute("GenMsgStartDelayTime",str(int(float_factory(value.text) * 1000))) + newFrame.add_attribute("GenMsgStartDelayTime", str(int(float_factory(value.text) * 1000))) elif cyclicTiming is not None: value = arGetChild(timeOffset, "VALUE", xmlRoot, ns) if value is not None: - newFrame.addAttribute("GenMsgStartDelayTime",str(int(float_factory(value.text) * 1000))) + newFrame.add_attribute("GenMsgStartDelayTime", str(int(float_factory(value.text) * 1000))) value = arGetChild(repeatingTime, "VALUE", xmlRoot, ns) if value is not None: - newFrame.addAttribute("GenMsgCycleTime",str(int(float_factory(value.text) * 1000))) + newFrame.add_attribute("GenMsgCycleTime", str(int(float_factory(value.text) * 1000))) elif cyclicTiming is not None: value = arGetChild(timePeriod, "VALUE", xmlRoot, ns) if value is not None: - newFrame.addAttribute("GenMsgCycleTime",str(int(float_factory(value.text) * 1000))) + newFrame.add_attribute("GenMsgCycleTime", str(int(float_factory(value.text) * 1000))) # pdusigmappings = arGetChild(pdu, "SIGNAL-TO-PDU-MAPPINGS", arDict, ns) @@ -1471,9 +1471,9 @@ def processEcu(ecu, db, arDict, multiplexTranslation, ns): for out in outFrame: if out in multiplexTranslation: out = multiplexTranslation[out] - frame = db.frameByName(out) + frame = db.frame_by_name(out) if frame is not None: - frame.addTransmitter(arGetName(ecu, ns)) + frame.add_transmitter(arGetName(ecu, ns)) else: pass @@ -1488,13 +1488,13 @@ def processEcu(ecu, db, arDict, multiplexTranslation, ns): # signal.receiver.append(recname) # else: # print "in not found: " + inf - bu = BoardUnit(arGetName(ecu, ns)) + bu = ecu(arGetName(ecu, ns)) if nmAddress is not None: - bu.addAttribute("NWM-Stationsadresse", nmAddress.text) - bu.addAttribute("NWM-Knoten", "ja") + bu.add_attribute("NWM-Stationsadresse", nmAddress.text) + bu.add_attribute("NWM-Knoten", "ja") else: - bu.addAttribute("NWM-Stationsadresse", "0") - bu.addAttribute("NWM-Knoten", "nein") + bu.add_attribute("NWM-Stationsadresse", "0") + bu.add_attribute("NWM-Knoten", "nein") return bu def ecuc_extract_signal(signal_node, ns): @@ -1522,7 +1522,7 @@ def ecuc_extract_signal(signal_node, ns): signal_type = (attribute.getparent().find(".//" +ns + "VALUE").text) if attribute.text.endswith("ComTimeout"): timeout = int(attribute.getparent().find(".//" +ns + "VALUE").text) - return canmatrix.Signal(arGetName(signal_node,ns), startBit = start_bit, size=size, is_little_endian = is_little) + return canmatrix.Signal(arGetName(signal_node,ns), start_bit = start_bit, size=size, is_little_endian = is_little) def extract_cm_from_ecuc(com_module, search_point, ns): db = CanMatrix() @@ -1531,7 +1531,7 @@ def extract_cm_from_ecuc(com_module, search_point, ns): if definition.text.endswith("ComIPdu"): container = definition.getparent() frame = canmatrix.Frame(arGetName(container, ns)) - db.addFrame(frame) + db.add_frame(frame) allReferences = arGetChildren(container,"ECUC-REFERENCE-VALUE",search_point,ns) for reference in allReferences: value = arGetChild(reference,"VALUE",search_point,ns) @@ -1539,8 +1539,8 @@ def extract_cm_from_ecuc(com_module, search_point, ns): signal_definition = value.find('./' + ns + "DEFINITION-REF") if signal_definition.text.endswith("ComSignal"): signal = ecuc_extract_signal(value,ns) - frame.addSignal(signal) - db.recalcDLC(strategy = "max") + frame.add_signal(signal) + db.recalc_dlc(strategy = "max") return {"": db} def load(file, **options): @@ -1616,18 +1616,18 @@ def load(file, **options): for cc in ccs: db = CanMatrix() # Defines not jet imported... - db.addBUDefines("NWM-Stationsadresse", 'HEX 0 63') - db.addBUDefines("NWM-Knoten", 'ENUM "nein","ja"') - db.addSignalDefines("LongName", 'STRING') - db.addFrameDefines("GenMsgCycleTime", 'INT 0 65535') - db.addFrameDefines("GenMsgDelayTime", 'INT 0 65535') - db.addFrameDefines("GenMsgNrOfRepetitions", 'INT 0 65535') - db.addFrameDefines("GenMsgStartValue", 'STRING') - db.addFrameDefines("GenMsgStartDelayTime", 'INT 0 65535') - db.addFrameDefines( + db.add_ecu_defines("NWM-Stationsadresse", 'HEX 0 63') + db.add_ecu_defines("NWM-Knoten", 'ENUM "nein","ja"') + db.add_signal_defines("LongName", 'STRING') + db.add_frame_defines("GenMsgCycleTime", 'INT 0 65535') + db.add_frame_defines("GenMsgDelayTime", 'INT 0 65535') + db.add_frame_defines("GenMsgNrOfRepetitions", 'INT 0 65535') + db.add_frame_defines("GenMsgStartValue", 'STRING') + db.add_frame_defines("GenMsgStartDelayTime", 'INT 0 65535') + db.add_frame_defines( "GenMsgSendType", 'ENUM "cyclicX","spontanX","cyclicIfActiveX","spontanWithDelay","cyclicAndSpontanX","cyclicAndSpontanWithDelay","spontanWithRepitition","cyclicIfActiveAndSpontanWD","cyclicIfActiveFast","cyclicWithRepeatOnDemand","none"') - db.addSignalDefines("GenSigStartValue", 'HEX 0 4294967295') + db.add_signal_defines("GenSigStartValue", 'HEX 0 4294967295') if ignoreClusterInfo == True: canframetrig = root.findall('.//' + ns + 'CAN-FRAME-TRIGGERING') @@ -1666,7 +1666,7 @@ def load(file, **options): for frameTrig in canframetrig: frameObject = getFrame(frameTrig,searchPoint,multiplexTranslation,ns, float_factory) if frameObject is not None: - db.addFrame(frameObject) + db.add_frame(frameObject) if ignoreClusterInfo == True: pass @@ -1706,15 +1706,15 @@ def load(file, **options): desc = arGetChild(node, "DESC", searchPoint, ns) l2 = arGetChild(desc, "L-2", searchPoint, ns) if l2 is not None: - bu.addComment(l2.text) + bu.add_comment(l2.text) - db.addEcu(bu) + db.add_ecu(bu) for frame in db.frames: sig_value_hash = dict() for sig in frame.signals: sig_value_hash[sig.name] = sig._initValue frameData = frame.encode(sig_value_hash) - frame.addAttribute("GenMsgStartValue", "".join(["%02x" % x for x in frameData])) + frame.add_attribute("GenMsgStartValue", "".join(["%02x" % x for x in frameData])) result[busname] = db return result diff --git a/src/canmatrix/cancluster.py b/src/canmatrix/cancluster.py index cb7933f8..a1961dcb 100644 --- a/src/canmatrix/cancluster.py +++ b/src/canmatrix/cancluster.py @@ -15,9 +15,9 @@ def updateFrames(self): else: index = frameArrayName.index(frame.name) for transmitter in frame.transmitters: - frameArray[index].addTransmitter(transmitter) + frameArray[index].add_transmitter(transmitter) for receiver in frame.receiver: - frameArray[index].addReceiver(receiver) + frameArray[index].add_receiver(receiver) self._frames = frameArray return frameArray @@ -33,14 +33,14 @@ def updateSignals(self): else: index = signalArrayName.index(signal.name) for receiver in signal.receiver: - signalArray[index].addReceiver(receiver) + signalArray[index].add_receiver(receiver) self._signals = signalArray def updateECUs(self): ECUArray = [] ECUArrayName = [] for matrixName in self: - for ecu in self[matrixName].boardUnits: + for ecu in self[matrixName].ecus: if ecu.name not in ECUArrayName: ECUArrayName.append(ecu.name) ECUArray.append(ecu) diff --git a/src/canmatrix/canmatrix.py b/src/canmatrix/canmatrix.py index 5cfbd65d..8c1c4605 100644 --- a/src/canmatrix/canmatrix.py +++ b/src/canmatrix/canmatrix.py @@ -62,7 +62,7 @@ class DecodingComplexMultiplexed(ExceptionTemplate): pass class DecodingFrameLength(ExceptionTemplate): pass @attr.s -class BoardUnit(object): +class ecu(object): """ Contains one Boardunit/ECU """ @@ -82,12 +82,12 @@ def attribute(self, attributeName, db=None, default=None): if attributeName in self.attributes: return self.attributes[attributeName] elif db is not None: - if attributeName in db.buDefines: - define = db.buDefines[attributeName] + if attributeName in db.ecu_defines: + define = db.ecu_defines[attributeName] return define.defaultValue return default - def addAttribute(self, attribute, value): + def add_attribute(self, attribute, value): """ Add the Attribute to current Boardunit/ECU. If the attribute already exists, update the value. @@ -96,7 +96,7 @@ def addAttribute(self, attribute, value): """ self.attributes[attribute] = value - def addComment(self, comment): + def add_comment(self, comment): """ Set Board unit comment. @@ -105,7 +105,7 @@ def addComment(self, comment): self.comment = comment -def normalizeValueTable(table): +def normalize_value_table(table): return {int(k): v for k, v in table.items()} @@ -117,7 +117,7 @@ class Signal(object): Signal has following attributes: * name - * startBit, size (in Bits) + * start_bit, size (in Bits) * is_little_endian (1: Intel, 0: Motorola) * is_signed (bool) * factor, offset, min, max @@ -129,7 +129,7 @@ class Signal(object): name = attr.ib(default="") # float_factory = attr.ib(default=defaultFloatFactory) float_factory = defaultFloatFactory - startBit = attr.ib(type=int, default=0) + start_bit = attr.ib(type=int, default=0) size = attr.ib(type=int, default=0) is_little_endian = attr.ib(type=bool, default=True) is_signed = attr.ib(type=bool, default=True) @@ -146,10 +146,10 @@ class Signal(object): enumeration = attr.ib(type=str, default=None) comments = attr.ib(type=dict, factory=dict) attributes = attr.ib(type=dict, factory=dict) - values = attr.ib(type=dict, converter=normalizeValueTable, factory=dict) - muxValMax = attr.ib(default=0) - muxValMin = attr.ib(default=0) - muxerForSignal = attr.ib(type=str, default=None) + values = attr.ib(type=dict, converter=normalize_value_table, factory=dict) + mux_val_max = attr.ib(default=0) + mux_val_min = attr.ib(default=0) + muxer_for_signal = attr.ib(type=str, default=None) # offset = attr.ib(converter=float_factory, default=0.0) calc_min_for_none = attr.ib(type=bool, default=True) @@ -163,8 +163,8 @@ class Signal(object): ) ) @min.default - def setDefaultMin(self): - return self.setMin() + def set_default_min(self): + return self.set_min() max = attr.ib( converter=lambda value, float_factory=float_factory: ( @@ -174,11 +174,11 @@ def setDefaultMin(self): ) ) @max.default - def setDefaultMax(self): - return self.setMax() + def set_default_max(self): + return self.set_max() def __attrs_post_init__(self): - self.multiplex = self.multiplexSetter(self.multiplex) + self.multiplex = self.multiplex_setter(self.multiplex) @property @@ -186,7 +186,7 @@ def spn(self): """Get signal J1939 SPN or None if not defined.""" return self.attributes.get("SPN", None) - def multiplexSetter(self, value): + def multiplex_setter(self, value): self.mux_val = None self.is_multiplexer = False ret_multiplex = None @@ -201,7 +201,7 @@ def multiplexSetter(self, value): def attribute(self, attributeName, db=None, default=None): """Get any Signal attribute by its name. - :param str attributeName: attribute name, can be mandatory (ex: startBit, size) or optional (customer) attribute. + :param str attributeName: attribute name, can be mandatory (ex: start_bit, size) or optional (customer) attribute. :param CanMatrix db: Optional database parameter to get global default attribute value. :param default: Default value if attribute doesn't exist. :return: Return the attribute value if found, else `default` or None @@ -211,12 +211,12 @@ def attribute(self, attributeName, db=None, default=None): if attributeName in self.attributes: return self.attributes[attributeName] if db is not None: - if attributeName in db.signalDefines: - define = db.signalDefines[attributeName] + if attributeName in db.signal_defines: + define = db.signal_defines[attributeName] return define.defaultValue return default - def addComment(self, comment): + def add_comment(self, comment): """ Set signal description. @@ -224,7 +224,7 @@ def addComment(self, comment): """ self.comment = comment - def addReceiver(self, receiver): + def add_receiver(self, receiver): """Add signal receiver (ECU). :param str receiver: ECU name. @@ -232,7 +232,7 @@ def addReceiver(self, receiver): if receiver not in self.receiver: self.receiver.append(receiver) - def delReceiver(self, receiver): + def del_receiver(self, receiver): """ Remove receiver (ECU) from signal @@ -241,7 +241,7 @@ def delReceiver(self, receiver): if receiver in self.receiver: self.receiver.remove(receiver) - def addAttribute(self, attribute, value): + def add_attribute(self, attribute, value): """ Add user defined attribute to the Signal. Update the value if the attribute already exists. @@ -250,7 +250,7 @@ def addAttribute(self, attribute, value): """ self.attributes[attribute] = value - def delAttribute(self, attribute): + def del_attribute(self, attribute): """ Remove user defined attribute from Signal. @@ -259,7 +259,7 @@ def delAttribute(self, attribute): if attribute in self.attributes: del self.attributes[attribute] - def addValues(self, value, valueName): + def add_values(self, value, valueName): """ Add named Value Description to the Signal. @@ -268,9 +268,9 @@ def addValues(self, value, valueName): """ self.values[int(value)] = valueName - def setStartbit(self, startBit, bitNumbering=None, startLittle=None): + def set_startbit(self, start_bit, bitNumbering=None, startLittle=None): """ - Set startBit. + Set start_bit. bitNumbering is 1 for LSB0/LSBFirst, 0 for MSB0/MSBFirst. If bit numbering is consistent with byte order (little=LSB0, big=MSB0) @@ -278,35 +278,35 @@ def setStartbit(self, startBit, bitNumbering=None, startLittle=None): Otherwise reverse bit numbering. For DBC, ArXML (OSEK), both little endian and big endian use LSB0. If bitNumbering is None, assume consistent with byte order. - If startLittle is set, given startBit is assumed start from lsb bit + If startLittle is set, given start_bit is assumed start from lsb bit rather than the start of the signal data in the message data. """ # bit numbering not consistent with byte order. reverse if bitNumbering is not None and bitNumbering != self.is_little_endian: - startBit = startBit - (startBit % 8) + 7 - (startBit % 8) - # if given startBit is for the end of signal data (lsbit), + start_bit = start_bit - (start_bit % 8) + 7 - (start_bit % 8) + # if given start_bit is for the end of signal data (lsbit), # convert to start of signal data (msbit) if startLittle is True and self.is_little_endian is False: - startBit = startBit + 1 - self.size - if startBit < 0: - print("wrong startBit found Signal: %s Startbit: %d" % - (self.name, startBit)) + start_bit = start_bit + 1 - self.size + if start_bit < 0: + print("wrong start_bit found Signal: %s Startbit: %d" % + (self.name, start_bit)) raise StarbitLowerZero - self.startBit = startBit + self.start_bit = start_bit - def getStartbit(self, bitNumbering=None, startLittle=None): + def get_startbit(self, bit_numbering=None, start_little=None): """Get signal start bit. Handle byte and bit order.""" - startBitInternal = self.startBit + startBitInternal = self.start_bit # convert from big endian start bit at # start bit(msbit) to end bit(lsbit) - if startLittle is True and self.is_little_endian is False: + if start_little is True and self.is_little_endian is False: startBitInternal = startBitInternal + self.size - 1 # bit numbering not consistent with byte order. reverse - if bitNumbering is not None and bitNumbering != self.is_little_endian: + if bit_numbering is not None and bit_numbering != self.is_little_endian: startBitInternal = startBitInternal - (startBitInternal % 8) + 7 - (startBitInternal % 8) return int(startBitInternal) - def calculateRawRange(self): + def calculate_raw_range(self): """Compute raw signal range based on Signal bit width and whether the Signal is signed or not. :return: Signal range, i.e. (0, 15) for unsigned 4 bit Signal or (-8, 7) for signed one. @@ -323,38 +323,38 @@ def calculateRawRange(self): factory(rawRange - 1), ) - def setMin(self, min=None): + def set_min(self, min=None): """Set minimal physical Signal value. - :param float or None min: minimal physical value. If None, compute using `calcMin` + :param float or None min: minimal physical value. If None, compute using `calc_min` """ self.min = min if self.calc_min_for_none and self.min is None: - self.min = self.calcMin() + self.min = self.calc_min() return self.min - def calcMin(self): - """Compute minimal physical Signal value based on offset and factor and `calculateRawRange`.""" - rawMin = self.calculateRawRange()[0] + def calc_min(self): + """Compute minimal physical Signal value based on offset and factor and `calculate_raw_range`.""" + rawMin = self.calculate_raw_range()[0] return self.offset + (self.float_factory(rawMin) * self.factor) - def setMax(self, max=None): + def set_max(self, max=None): """Set maximal signal value. - :param float or None max: minimal physical value. If None, compute using `calcMax` + :param float or None max: minimal physical value. If None, compute using `calc_max` """ self.max = max if self.calc_max_for_none and self.max is None: - self.max = self.calcMax() + self.max = self.calc_max() return self.max - def calcMax(self): - """Compute maximal physical Signal value based on offset, factor and `calculateRawRange`.""" - rawMax = self.calculateRawRange()[1] + def calc_max(self): + """Compute maximal physical Signal value based on offset, factor and `calculate_raw_range`.""" + rawMax = self.calculate_raw_range()[1] return self.offset + (self.float_factory(rawMax) * self.factor) @@ -414,7 +414,7 @@ def __str__(self): @attr.s(cmp=False) -class SignalGroup(object): +class signal_group(object): """ Represents signal-group, containing multiple Signals. """ @@ -422,7 +422,7 @@ class SignalGroup(object): id = attr.ib(type=int) signals = attr.ib(type=list, factory=list, repr=False) - def addSignal(self, signal): + def add_signal(self, signal): """Add a Signal to SignalGroup. :param Signal signal: signal to add @@ -430,7 +430,7 @@ def addSignal(self, signal): if signal not in self.signals: self.signals.append(signal) - def delSignal(self, signal): + def del_signal(self, signal): """Remove Signal from SignalGroup. :param Signal signal: signal to remove @@ -438,7 +438,7 @@ def delSignal(self, signal): if signal in self.signals: self.signals.remove(signal) - def byName(self, name): + def by_name(self, name): """ Find a Signal in the group by Signal name. @@ -456,14 +456,14 @@ def __iter__(self): return iter(self.signals) def __getitem__(self, name): - signal = self.byName(name) + signal = self.by_name(name) if signal: return signal raise KeyError("Signal '{}' doesn't exist".format(name)) @attr.s -class DecodedSignal(object): +class decoded_signal(object): """ Contains a decoded signal (frame decoding) @@ -605,7 +605,7 @@ def pgn(self): @pgn.setter def pgn(self, value): self.j1939_pgn = value - self.recalcJ1939Id() + self.recalc_J1939_id() @property def priority(self): @@ -616,7 +616,7 @@ def priority(self): def priority(self, value): """Set J1939 priority.""" self.j1939_prio = value - self.recalcJ1939Id() + self.recalc_J1939_id() @property def source(self): @@ -627,9 +627,9 @@ def source(self): def source(self, value): """Set J1939 source.""" self.j1939_source = value - self.recalcJ1939Id() + self.recalc_J1939_id() - def recalcJ1939Id(self): + def recalc_J1939_id(self): """Recompute J1939 ID""" self.id = (self.j1939_source & 0xff) + ((self.j1939_pgn & 0xffff) << 8) + ((self.j1939_prio & 0x7) << 26) self.extended = True @@ -671,8 +671,8 @@ def attribute(self, attributeName, db=None, default=None): return getattr(self, attributeName) if attributeName in self.attributes: return self.attributes[attributeName] - elif db is not None and attributeName in db.frameDefines: - define = db.frameDefines[attributeName] + elif db is not None and attributeName in db.frame_defines: + define = db.frame_defines[attributeName] return define.defaultValue return default @@ -680,36 +680,36 @@ def __iter__(self): """Iterator over all signals.""" return iter(self.signals) - def addSignalGroup(self, Name, Id, signalNames): + def add_signal_group(self, Name, Id, signalNames): """Add new SignalGroup to the Frame. Add given signals to the group. :param str Name: Group name :param int Id: Group id :param list of str signalNames: list of Signal names to add. Non existing names are ignored. """ - newGroup = SignalGroup(Name, Id) + newGroup = signal_group(Name, Id) self.signalGroups.append(newGroup) for signal in signalNames: signal = signal.strip() if signal.__len__() == 0: continue - signalId = self.signalByName(signal) + signalId = self.signal_by_name(signal) if signalId is not None: - newGroup.addSignal(signalId) + newGroup.add_signal(signalId) - def signalGroupByName(self, name): + def signal_group_by_name(self, name): """Get signal group. :param str name: group name :return: SignalGroup by name or None if not found. - :rtype: SignalGroup + :rtype: signal_group """ for signalGroup in self.signalGroups: if signalGroup.name == name: return signalGroup return None - def addSignal(self, signal): + def add_signal(self, signal): """ Add Signal to Frame. @@ -719,7 +719,7 @@ def addSignal(self, signal): self.signals.append(signal) return self.signals[len(self.signals) - 1] - def addTransmitter(self, transmitter): + def add_transmitter(self, transmitter): """Add transmitter ECU Name to Frame. :param str transmitter: transmitter name @@ -727,7 +727,7 @@ def addTransmitter(self, transmitter): if transmitter not in self.transmitters: self.transmitters.append(transmitter) - def delTransmitter(self, transmitter): + def del_transmitter(self, transmitter): """Delete transmitter ECU Name from Frame. :param str transmitter: transmitter name @@ -735,7 +735,7 @@ def delTransmitter(self, transmitter): if transmitter in self.transmitters: self.transmitters.remove(transmitter) - def addReceiver(self, receiver): + def add_receiver(self, receiver): """Add receiver ECU Name to Frame. :param str receiver: receiver name @@ -743,7 +743,7 @@ def addReceiver(self, receiver): if receiver not in self.receivers: self.receivers.append(receiver) - def signalByName(self, name): + def signal_by_name(self, name): """ Get signal by name. @@ -755,7 +755,7 @@ def signalByName(self, name): return signal return None - def globSignals(self, globStr): + def glob_signals(self, globStr): """Find Frame Signals by given glob pattern. :param str globStr: glob pattern for signal name. See `fnmatch.fnmatchcase` @@ -768,7 +768,7 @@ def globSignals(self, globStr): returnArray.append(signal) return returnArray - def addAttribute(self, attribute, value): + def add_attribute(self, attribute, value): """ Add the attribute with value to customer Frame attribute-list. If Attribute already exits, modify its value. :param str attribute: Attribute name @@ -779,7 +779,7 @@ def addAttribute(self, attribute, value): except UnicodeDecodeError: self.attributes[attribute] = value - def delAttribute(self, attribute): + def del_attribute(self, attribute): """ Remove attribute from customer Frame attribute-list. @@ -788,7 +788,7 @@ def delAttribute(self, attribute): if attribute in self.attributes: del self.attributes[attribute] - def addComment(self, comment): + def add_comment(self, comment): """ Set Frame comment. @@ -796,7 +796,7 @@ def addComment(self, comment): """ self.comment = comment - def calcDLC(self): + def calc_dlc(self): """ Compute minimal Frame DLC (length) based on its Signals @@ -804,8 +804,8 @@ def calcDLC(self): """ maxBit = 0 for sig in self.signals: - if sig.getStartbit() + int(sig.size) > maxBit: - maxBit = sig.getStartbit() + int(sig.size) + if sig.get_startbit() + int(sig.size) > maxBit: + maxBit = sig.get_startbit() + int(sig.size) self.size = max(self.size, int(math.ceil(maxBit / 8))) def get_frame_layout(self): @@ -824,13 +824,13 @@ def get_frame_layout(self): big_bits = [[] for _dummy in range((self.size * 8))] for signal in self.signals: if signal.is_little_endian: - least = len(little_bits) - signal.startBit + least = len(little_bits) - signal.start_bit most = least - signal.size for little_bit_signals in little_bits[most:least]: little_bit_signals.append(signal) else: - most = signal.startBit + most = signal.start_bit least = most + signal.size for big_bit_signals in big_bits[most:least]: big_bit_signals.append(signal) @@ -859,19 +859,19 @@ def create_dummy_signals(self): if (index == (len(bitfield)-1) or bit_signals != []) and startBit != -1: if index == (len(bitfield)-1): index = len(bitfield) - self.addSignal(Signal("_Dummy_%s_%d" % (self.name,sigCount),size=index-startBit, startBit=startBit, is_little_endian = False)) + self.add_signal(Signal("_Dummy_%s_%d" % (self.name, sigCount), size=index - startBit, start_bit=startBit, is_little_endian = False)) startBit = -1 sigCount += 1 - def updateReceiver(self): + def update_receiver(self): """ Collect Frame receivers out of receiver given in each signal. Add them to `self.receiver` list. """ for sig in self.signals: for receiver in sig.receiver: - self.addReceiver(receiver) + self.add_receiver(receiver) def signals_to_bytes(self, data): @@ -890,12 +890,12 @@ def signals_to_bytes(self, data): bits = pack_bitstring(signal.size, signal.is_float, value, signal.is_signed) if signal.is_little_endian: - least = self.size * 8 - signal.startBit + least = self.size * 8 - signal.start_bit most = least - signal.size little_bits[most:least] = bits else: - most = signal.startBit + most = signal.start_bit least = most + signal.size big_bits[most:least] = bits @@ -970,12 +970,12 @@ def bitstring_to_signal_list(self, signals, big, little): unpacked = [] for signal in signals: if signal.is_little_endian: - least = self.size * 8 - signal.startBit + least = self.size * 8 - signal.start_bit most = least - signal.size bits = little[most:least] else: - most = signal.startBit + most = signal.start_bit least = most + signal.size bits = big[most:least] @@ -1006,7 +1006,7 @@ def unpack(self, data, report_error=True): returnDict= dict() for s, v in zip(self.signals, unpacked): - returnDict[s.name] = DecodedSignal(v, s) + returnDict[s.name] = decoded_signal(v, s) return returnDict @@ -1059,7 +1059,7 @@ def __init__(self, definition): self.type = None self.defaultValue = None - def safeConvertStrToInt(inStr): + def safe_convert_str_to_int(inStr): """Convert string to int safely. Check that it isn't float. :param str inStr: integer represented as string. @@ -1074,8 +1074,8 @@ def safeConvertStrToInt(inStr): if definition[0:3] == 'INT': self.type = 'INT' min, max = definition[4:].split(' ', 2) - self.min = safeConvertStrToInt(min) - self.max = safeConvertStrToInt(max) + self.min = safe_convert_str_to_int(min) + self.max = safe_convert_str_to_int(max) elif definition[0:6] == 'STRING': self.type = 'STRING' @@ -1093,8 +1093,8 @@ def safeConvertStrToInt(inStr): elif definition[0:3] == 'HEX': # differently rendered in DBC editor, but values are saved like for an INT self.type = 'HEX' min, max = definition[4:].split(' ', 2) - self.min = safeConvertStrToInt(min) - self.max = safeConvertStrToInt(max) + self.min = safe_convert_str_to_int(min) + self.max = safe_convert_str_to_int(max) elif definition[0:5] == 'FLOAT': self.type = 'FLOAT' @@ -1103,7 +1103,7 @@ def safeConvertStrToInt(inStr): self.max = defaultFloatFactory(max) - def setDefault(self, default): + def set_default(self, default): """Set Definition default value. :param default: default value; number, str or quoted str ("value") @@ -1137,15 +1137,15 @@ class CanMatrix(object): """ attributes = attr.ib(type=dict, factory=dict) - boardUnits = attr.ib(type=list, factory=list) + ecus = attr.ib(type=list, factory=list) frames = attr.ib(type=list, factory=list) - signalDefines = attr.ib(type=dict, factory=dict) - frameDefines = attr.ib(type=dict, factory=dict) - globalDefines = attr.ib(type=dict, factory=dict) - buDefines = attr.ib(type=dict, factory=dict) - valueTables = attr.ib(type=dict, factory=dict) - envVars = attr.ib(type=dict, factory=dict) + signal_defines = attr.ib(type=dict, factory=dict) + frame_defines = attr.ib(type=dict, factory=dict) + global_defines = attr.ib(type=dict, factory=dict) + ecu_defines = attr.ib(type=dict, factory=dict) + value_tables = attr.ib(type=dict, factory=dict) + env_vars = attr.ib(type=dict, factory=dict) signals = attr.ib(type=list, factory=list) load_errors = attr.ib(type=list, factory=list) @@ -1154,8 +1154,8 @@ def __iter__(self): """Matrix iterates over Frames (Messages).""" return iter(self.frames) - def addEnvVar(self, name, envVarDict): - self.envVars[name] = envVarDict + def add_env_var(self, name, envVarDict): + self.env_vars[name] = envVarDict @property def contains_fd(self): @@ -1183,19 +1183,19 @@ def attribute(self, attributeName, default=None): if attributeName in self.attributes: return self.attributes[attributeName] else: - if attributeName in self.globalDefines: - define = self.globalDefines[attributeName] + if attributeName in self.global_defines: + define = self.global_defines[attributeName] return define.defaultValue - def addValueTable(self, name, valueTable): + def add_value_table(self, name, valueTable): """Add named value table. :param str name: value table name :param valueTable: value table itself """ - self.valueTables[name] = normalizeValueTable(valueTable) + self.value_tables[name] = normalize_value_table(valueTable) - def addAttribute(self, attribute, value): + def add_attribute(self, attribute, value): """ Add attribute to Matrix attribute-list. @@ -1204,63 +1204,63 @@ def addAttribute(self, attribute, value): """ self.attributes[attribute] = value - def addSignalDefines(self, type, definition): + def add_signal_defines(self, type, definition): """ Add signal-attribute definition to canmatrix. :param str type: signal type :param str definition: signal-attribute string definition, see class Define """ - if type not in self.signalDefines: - self.signalDefines[type] = Define(definition) + if type not in self.signal_defines: + self.signal_defines[type] = Define(definition) - def addFrameDefines(self, type, definition): + def add_frame_defines(self, type, definition): """ Add frame-attribute definition to canmatrix. :param str type: frame type :param str definition: frame definition as string """ - if type not in self.frameDefines: - self.frameDefines[type] = Define(definition) + if type not in self.frame_defines: + self.frame_defines[type] = Define(definition) - def addBUDefines(self, type, definition): + def add_ecu_defines(self, type, definition): """ Add Boardunit-attribute definition to canmatrix. :param str type: Boardunit type :param str definition: BU definition as string """ - if type not in self.buDefines: - self.buDefines[type] = Define(definition) + if type not in self.ecu_defines: + self.ecu_defines[type] = Define(definition) - def addGlobalDefines(self, type, definition): + def add_global_defines(self, type, definition): """ Add global-attribute definition to canmatrix. :param str type: attribute type :param str definition: attribute definition as string """ - if type not in self.globalDefines: - self.globalDefines[type] = Define(definition) + if type not in self.global_defines: + self.global_defines[type] = Define(definition) - def addDefineDefault(self, name, value): - if name in self.signalDefines: - self.signalDefines[name].setDefault(value) - if name in self.frameDefines: - self.frameDefines[name].setDefault(value) - if name in self.buDefines: - self.buDefines[name].setDefault(value) - if name in self.globalDefines: - self.globalDefines[name].setDefault(value) + def add_define_default(self, name, value): + if name in self.signal_defines: + self.signal_defines[name].set_default(value) + if name in self.frame_defines: + self.frame_defines[name].set_default(value) + if name in self.ecu_defines: + self.ecu_defines[name].set_default(value) + if name in self.global_defines: + self.global_defines[name].set_default(value) - def deleteObsoleteDefines(self): + def delete_obsolete_defines(self): """Delete all unused Defines. Delete them from frameDefines, buDefines and signalDefines. """ toBeDeleted = [] - for frameDef in self.frameDefines: + for frameDef in self.frame_defines: found = False for frame in self.frames: if frameDef in frame.attributes: @@ -1269,21 +1269,21 @@ def deleteObsoleteDefines(self): if found is False and found not in toBeDeleted: toBeDeleted.append(frameDef) for element in toBeDeleted: - del self.frameDefines[element] + del self.frame_defines[element] toBeDeleted = [] - for buDef in self.buDefines: + for buDef in self.ecu_defines: found = False - for ecu in self.boardUnits: + for ecu in self.ecus: if buDef in ecu.attributes: found = True break if found is False and found not in toBeDeleted: toBeDeleted.append(buDef) for element in toBeDeleted: - del self.buDefines[element] + del self.ecu_defines[element] toBeDeleted = [] - for signalDef in self.signalDefines: + for signalDef in self.signal_defines: found = False for frame in self.frames: for signal in frame.signals: @@ -1293,9 +1293,9 @@ def deleteObsoleteDefines(self): if found is False and found not in toBeDeleted: toBeDeleted.append(signalDef) for element in toBeDeleted: - del self.signalDefines[element] + del self.signal_defines[element] - def frameById(self, Id, extended=None): + def frame_by_id(self, Id, extended=None): """Get Frame by its arbitration id. :param Id: Frame id as str or int @@ -1323,7 +1323,7 @@ def frameById(self, Id, extended=None): return test return None - def frameByName(self, name): + def frame_by_name(self, name): """Get Frame by name. :param str name: Frame name to search for @@ -1334,7 +1334,7 @@ def frameByName(self, name): return test return None - def globFrames(self, globStr): + def glob_frames(self, globStr): """Find Frames by given glob pattern. :param str globStr: glob pattern to filter Frames. See `fnmatch.fnmatchcase`. @@ -1346,32 +1346,32 @@ def globFrames(self, globStr): returnArray.append(test) return returnArray - def boardUnitByName(self, name): + def ecu_by_name(self, name): """ Returns Boardunit by Name. :param str name: BoardUnit name - :rtype: BoardUnit or None + :rtype: ecu or None """ - for test in self.boardUnits: + for test in self.ecus: if test.name == name: return test return None - def globBoardUnits(self, globStr): + def glob_ecus(self, globStr): """ Find ECUs by given glob pattern. :param globStr: glob pattern to filter BoardUnits. See `fnmatch.fnmatchcase`. - :rtype: list of BoardUnit + :rtype: list of ecu """ returnArray = [] - for test in self.boardUnits: + for test in self.ecus: if fnmatch.fnmatchcase(test.name, globStr): returnArray.append(test) return returnArray - def addFrame(self, frame): + def add_frame(self, frame): """Add the Frame to the Matrix. :param Frame frame: Frame to add @@ -1380,14 +1380,14 @@ def addFrame(self, frame): self.frames.append(frame) return self.frames[len(self.frames) - 1] - def removeFrame(self, frame): + def remove_frame(self, frame): """Remove the Frame from Matrix. :param Frame frame: frame to remove from CAN Matrix """ self.frames.remove(frame) - def addSignal(self, signal): + def add_signal(self, signal): """ Add Signal to Frame. @@ -1397,21 +1397,21 @@ def addSignal(self, signal): self.signals.append(signal) return self.signals[len(self.signals) - 1] - def removeSignal(self, signal): + def remove_signal(self, signal): """Remove the Frame from Matrix. :param Frame frame: frame to remove from CAN Matrix """ self.signals.remove(signal) - def deleteZeroSignals(self): + def delete_zero_signals(self): """Delete all signals with zero bit width from all Frames.""" for frame in self.frames: for signal in frame.signals: if 0 == signal.size: frame.signals.remove(signal) - def delSignalAttributes(self, unwantedAttributes): + def del_signal_attributes(self, unwantedAttributes): """Delete Signal attributes from all Signals of all Frames. :param list of str unwantedAttributes: List of attributes to remove @@ -1419,18 +1419,18 @@ def delSignalAttributes(self, unwantedAttributes): for frame in self.frames: for signal in frame.signals: for attrib in unwantedAttributes: - signal.delAttribute(attrib) + signal.del_attribute(attrib) - def delFrameAttributes(self, unwantedAttributes): + def del_frame_attributes(self, unwantedAttributes): """Delete Frame attributes from all Frames. :param list of str unwantedAttributes: List of attributes to remove """ for frame in self.frames: for attrib in unwantedAttributes: - frame.delAttribute(attrib) + frame.del_attribute(attrib) - def recalcDLC(self, strategy): + def recalc_dlc(self, strategy): """Recompute DLC of all Frames. :param str strategy: selected strategy, "max" or "force". @@ -1438,24 +1438,24 @@ def recalcDLC(self, strategy): for frame in self.frames: originalDlc = frame.size # unused, remove? if "max" == strategy: - frame.calcDLC() + frame.calc_dlc() if "force" == strategy: maxBit = 0 for sig in frame.signals: - if sig.getStartbit() + int(sig.size) > maxBit: - maxBit = sig.getStartbit() + int(sig.size) + if sig.get_startbit() + int(sig.size) > maxBit: + maxBit = sig.get_startbit() + int(sig.size) frame.size = math.ceil(maxBit / 8) - def renameEcu(self, old, newName): + def rename_ecu(self, old, newName): """Rename ECU in the Matrix. Update references in all Frames. - :param str or BoardUnit old: old name or ECU instance + :param str or ecu old: old name or ECU instance :param str newName: new name """ if type(old).__name__ == 'instance': pass else: - old = self.boardUnitByName(old) + old = self.ecu_by_name(old) if old is None: return oldName = old.name @@ -1463,55 +1463,55 @@ def renameEcu(self, old, newName): for frame in self.frames: if oldName in frame.transmitters: frame.transmitters.remove(oldName) - frame.addTransmitter(newName) + frame.add_transmitter(newName) for signal in frame.signals: if oldName in signal.receiver: signal.receiver.remove(oldName) - signal.addReceiver(newName) - frame.updateReceiver() + signal.add_receiver(newName) + frame.update_receiver() - def addEcu(self, ecu): + def add_ecu(self, ecu): """Add new ECU to the Matrix. Do nothing if ecu with the same name already exists. - :param BoardUnit ecu: ECU name to add + :param ecu ecu: ECU name to add """ - for bu in self.boardUnits: + for bu in self.ecus: if bu.name.strip() == ecu.name: return - self.boardUnits.append(ecu) + self.ecus.append(ecu) - def delEcu(self, ecu): + def del_ecu(self, ecu): """Remove ECU from Matrix and all Frames. - :param str or BoardUnit ecu: ECU instance or glob pattern to remove from list + :param str or ecu ecu: ECU instance or glob pattern to remove from list """ if type(ecu).__name__ == 'instance': ecuList = [ecu] else: - ecuList = self.globBoardUnits(ecu) + ecuList = self.glob_ecus(ecu) for ecu in ecuList: - if ecu in self.boardUnits: - self.boardUnits.remove(ecu) + if ecu in self.ecus: + self.ecus.remove(ecu) for frame in self.frames: if ecu.name in frame.transmitters: frame.transmitters.remove(ecu.name) for signal in frame.signals: if ecu.name in signal.receiver: signal.receiver.remove(ecu.name) - frame.updateReceiver() + frame.update_receiver() - def updateEcuList(self): + def update_ecu_list(self): """Check all Frames and add unknown ECUs to the Matrix ECU list.""" for frame in self.frames: - for ecu in frame.transmitters: - self.addEcu(BoardUnit(ecu)) - frame.updateReceiver() + for transmit_ecu in frame.transmitters: + self.add_ecu(canmatrix.ecu(transmit_ecu)) + frame.update_receiver() for signal in frame.signals: - for ecu in signal.receiver: - self.addEcu(BoardUnit(ecu)) + for receive_ecu in signal.receiver: + self.add_ecu(canmatrix.ecu(receive_ecu)) - def renameFrame(self, old, newName): + def rename_frame(self, old, newName): """Rename Frame. :param Frame or str old: Old Frame instance or name or part of the name with '*' at the beginning or the end. @@ -1531,17 +1531,17 @@ def renameFrame(self, old, newName): elif frame.name == old: frame.name = newName - def delFrame(self, frame): + def del_frame(self, frame): """Delete Frame from Matrix. :param Frame or str frame: Frame or name to delete""" if type(frame).__name__ == 'instance' or type(frame).__name__ == 'Frame': pass else: - frame = self.frameByName(frame) + frame = self.frame_by_name(frame) self.frames.remove(frame) - def renameSignal(self, old, newName): + def rename_signal(self, old, newName): """Rename Signal. :param Signal or str old: Old Signal instance or name or part of the name with '*' at the beginning or the end. @@ -1563,11 +1563,11 @@ def renameSignal(self, old, newName): signal.name = signal.name[:-oldSuffixLen] + newName else: - signal = frame.signalByName(old) + signal = frame.signal_by_name(old) if signal is not None: signal.name = newName - def delSignal(self, signal): + def del_signal(self, signal): """Delete Signal from Matrix and all Frames. :param Signal or str signal: Signal instance or glob pattern to be deleted""" @@ -1577,66 +1577,66 @@ def delSignal(self, signal): frame.signals.remove(signal) else: for frame in self.frames: - signalList = frame.globSignals(signal) + signalList = frame.glob_signals(signal) for sig in signalList: frame.signals.remove(sig) - def addSignalReceiver(self, globFrame, globSignal, ecu): + def add_signal_receiver(self, globFrame, globSignal, ecu): """Add Receiver to all Frames and Signals by glob pattern. :param str globFrame: glob pattern for Frame name. :param str globSignal: glob pattern for Signal name. Only signals under globFrame are filtered. :param str ecu: Receiver ECU name """ - frames = self.globFrames(globFrame) + frames = self.glob_frames(globFrame) for frame in frames: - for signal in frame.globSignals(globSignal): - signal.addReceiver(ecu) - frame.updateReceiver() + for signal in frame.glob_signals(globSignal): + signal.add_receiver(ecu) + frame.update_receiver() - def delSignalReceiver(self, globFrame, globSignal, ecu): + def del_signal_receiver(self, globFrame, globSignal, ecu): """Delete Receiver from all Frames by glob pattern. :param str globFrame: glob pattern for Frame name. :param str globSignal: glob pattern for Signal name. Only signals under globFrame are filtered. :param str ecu: Receiver ECU name """ - frames = self.globFrames(globFrame) + frames = self.glob_frames(globFrame) for frame in frames: - for signal in frame.globSignals(globSignal): - signal.delReceiver(ecu) - frame.updateReceiver() + for signal in frame.glob_signals(globSignal): + signal.del_receiver(ecu) + frame.update_receiver() - def addFrameTransmitter(self, globFrame, ecu): + def add_frame_transmitter(self, globFrame, ecu): """Add Transmitter to all Frames by glob pattern. :param str globFrame: glob pattern for Frame name. :param str ecu: Receiver ECU name """ - frames = self.globFrames(globFrame) + frames = self.glob_frames(globFrame) for frame in frames: - frame.addTransmitter(ecu) + frame.add_transmitter(ecu) - def addFrameReceiver(self, globFrame, ecu): + def add_frame_receiver(self, globFrame, ecu): """Add Receiver to all Frames by glob pattern. :param str globFrame: glob pattern for Frame name. :param str ecu: Receiver ECU name """ - frames = self.globFrames(globFrame) + frames = self.glob_frames(globFrame) for frame in frames: for signal in frame.signals: - signal.addReceiver(ecu) + signal.add_receiver(ecu) - def delFrameTransmitter(self, globFrame, ecu): + def del_frame_transmitter(self, globFrame, ecu): """Delete Transmitter from all Frames by glob pattern. :param str globFrame: glob pattern for Frame name. :param str ecu: Receiver ECU name """ - frames = self.globFrames(globFrame) + frames = self.glob_frames(globFrame) for frame in frames: - frame.delTransmitter(ecu) + frame.del_transmitter(ecu) def merge(self, mergeArray): """Merge multiple Matrices to this Matrix. @@ -1651,15 +1651,15 @@ def merge(self, mergeArray): copyResult = canmatrix.copy.copyFrame(frame.id, dbTemp, self) if copyResult == False: logger.error( - "ID Conflict, could not copy/merge frame " + frame.name + " %xh " % frame.id + self.frameById(frame.id).name) - for envVar in dbTemp.envVars: - if envVar not in self.envVars: - self.addEnvVar(envVar, dbTemp.envVars[envVar]) + "ID Conflict, could not copy/merge frame " + frame.name + " %xh " % frame.id + self.frame_by_id(frame.id).name) + for envVar in dbTemp.env_vars: + if envVar not in self.env_vars: + self.add_env_var(envVar, dbTemp.envVars[envVar]) else: logger.error( "Name Conflict, could not copy/merge EnvVar " + envVar) - def setFdType(self): + def set_fd_type(self): """Try to guess and set the CAN type for every frame. If a Frame is longer than 8 bytes, it must be Flexible Data Rate frame (CAN-FD). @@ -1677,7 +1677,7 @@ def encode(self, frame_id, data): :param data: data dictionary :return: A byte string of the packed values. """ - return self.frameById(frame_id).encode(data) + return self.frame_by_id(frame_id).encode(data) def decode(self, frame_id, data): """Return OrderedDictionary with Signal Name: object decodedSignal @@ -1687,49 +1687,49 @@ def decode(self, frame_id, data): i.e. (0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8) :return: OrderedDictionary """ - return self.frameById(frame_id).decode(data) + return self.frame_by_id(frame_id).decode(data) - def EnumAttribs2Values(self): - for define in self.buDefines: - if self.buDefines[define].type == "ENUM": - for bu in self.boardUnits: + def enum_attribs_to_values(self): + for define in self.ecu_defines: + if self.ecu_defines[define].type == "ENUM": + for bu in self.ecus: if define in bu.attributes: - bu.attributes[define] = self.buDefines[define].values[int(bu.attributes[define])] + bu.attributes[define] = self.ecu_defines[define].values[int(bu.attributes[define])] - for define in self.frameDefines: - if self.frameDefines[define].type == "ENUM": + for define in self.frame_defines: + if self.frame_defines[define].type == "ENUM": for frame in self.frames: if define in frame.attributes: - frame.attributes[define] = self.frameDefines[define].values[int(frame.attributes[define])] + frame.attributes[define] = self.frame_defines[define].values[int(frame.attributes[define])] - for define in self.signalDefines: - if self.signalDefines[define].type == "ENUM": + for define in self.signal_defines: + if self.signal_defines[define].type == "ENUM": for frame in self.frames: for signal in frame.signals: if define in signal.attributes: - signal.attributes[define] = self.signalDefines[define].values[int(signal.attributes[define])] + signal.attributes[define] = self.signal_defines[define].values[int(signal.attributes[define])] - def EnumAttribs2Keys(self): - for define in self.buDefines: - if self.buDefines[define].type == "ENUM": - for bu in self.boardUnits: + def enum_attribs_to_keys(self): + for define in self.ecu_defines: + if self.ecu_defines[define].type == "ENUM": + for bu in self.ecus: if define in bu.attributes: if len(bu.attributes[define]) > 0: - bu.attributes[define] = self.buDefines[define].values.index(bu.attributes[define]) + bu.attributes[define] = self.ecu_defines[define].values.index(bu.attributes[define]) bu.attributes[define] = str(bu.attributes[define]) - for define in self.frameDefines: - if self.frameDefines[define].type == "ENUM": + for define in self.frame_defines: + if self.frame_defines[define].type == "ENUM": for frame in self.frames: if define in frame.attributes: if len(frame.attributes[define]) > 0: - frame.attributes[define] = self.frameDefines[define].values.index(frame.attributes[define]) + frame.attributes[define] = self.frame_defines[define].values.index(frame.attributes[define]) frame.attributes[define] = str(frame.attributes[define]) - for define in self.signalDefines: - if self.signalDefines[define].type == "ENUM": + for define in self.signal_defines: + if self.signal_defines[define].type == "ENUM": for frame in self.frames: for signal in frame.signals: if define in signal.attributes: - signal.attributes[define] = self.signalDefines[define].values.index(signal.attributes[define]) + signal.attributes[define] = self.signal_defines[define].values.index(signal.attributes[define]) signal.attributes[define] = str(signal.attributes[define]) diff --git a/src/canmatrix/cmcsv.py b/src/canmatrix/cmcsv.py index d0027103..6ddf1579 100644 --- a/src/canmatrix/cmcsv.py +++ b/src/canmatrix/cmcsv.py @@ -141,7 +141,7 @@ def dump(db, thefile, delimiter=',', **options): # write frameardunits in first row: buList = [] - for bu in db.boardUnits: + for bu in db.ecus: headerrow.write(col, bu.name) buList.append(bu.name) col += 1 @@ -179,7 +179,7 @@ def dump(db, thefile, delimiter=',', **options): # sort signals: sigHash = {} for sig in frame.signals: - sigHash["%02d" % int(sig.getStartbit()) + sig.name] = sig + sigHash["%02d" % int(sig.get_startbit()) + sig.name] = sig additionalFrameInfo = [] for frameInfo in additionalFrameCollums: diff --git a/src/canmatrix/cmjson.py b/src/canmatrix/cmjson.py index 59f32579..626494d1 100644 --- a/src/canmatrix/cmjson.py +++ b/src/canmatrix/cmjson.py @@ -60,9 +60,9 @@ def dump(db, f, **options): signals = {} for signal in frame.signals: signals[ - signal.getStartbit( - bitNumbering=1, - startLittle=True)] = { + signal.get_startbit( + bit_numbering=1, + start_little=True)] = { "name": signal.name, "bit_length": signal.signalsize, "factor": signal.factor, @@ -76,13 +76,13 @@ def dump(db, f, **options): for signal in frame.signals: if not signal.is_little_endian: if motorolaBitFormat == "msb": - startBit = signal.getStartbit(bitNumbering=1) + startBit = signal.get_startbit(bit_numbering=1) elif motorolaBitFormat == "msbreverse": - startBit = signal.getStartbit() + startBit = signal.get_startbit() else: # motorolaBitFormat == "lsb" - startBit = signal.getStartbit(bitNumbering=1, startLittle=True) + startBit = signal.get_startbit(bit_numbering=1, start_little=True) else: - startBit = signal.getStartbit(bitNumbering=1, startLittle=True) + startBit = signal.get_startbit(bit_numbering=1, start_little=True) signals.append({ "name": signal.name, @@ -108,12 +108,12 @@ def dump(db, f, **options): else: # exportAll for frame in db.frames: frameattribs = {} - for attribute in db.frameDefines: + for attribute in db.frame_defines: frameattribs[attribute] = frame.attribute(attribute, db=db) signals = [] for signal in frame.signals: attribs = {} - for attribute in db.signalDefines: + for attribute in db.signal_defines: attribs[attribute] = signal.attribute(attribute, db=db) values = {} @@ -121,13 +121,13 @@ def dump(db, f, **options): values[key] = signal.values[key] if not signal.is_little_endian: if motorolaBitFormat == "msb": - startBit = signal.getStartbit(bitNumbering=1) + startBit = signal.get_startbit(bit_numbering=1) elif motorolaBitFormat == "msbreverse": - startBit = signal.getStartbit() + startBit = signal.get_startbit() else: # motorolaBitFormat == "lsb" - startBit = signal.getStartbit(bitNumbering=1, startLittle=True) + startBit = signal.get_startbit(bit_numbering=1, start_little=True) else: # motorolaBitFormat == "lsb" - startBit = signal.getStartbit(bitNumbering=1, startLittle=True) + startBit = signal.get_startbit(bit_numbering=1, start_little=True) signalDict = { @@ -212,7 +212,7 @@ def load(f, **options): else: is_signed = False newsignal = canmatrix.Signal(signal["name"], - startBit=signal["start_bit"], + start_bit=signal["start_bit"], size=signal["bit_length"], is_little_endian=is_little_endian, is_signed=is_signed, @@ -234,11 +234,11 @@ def load(f, **options): if signal.get("values", False): for key in signal["values"]: - newsignal.addValues(key, signal["values"][key]) + newsignal.add_values(key, signal["values"][key]) if newsignal.is_little_endian == False: - newsignal.setStartbit( - newsignal.startBit, bitNumbering=1, startLittle=True) - newframe.addSignal(newsignal) - db.addFrame(newframe) + newsignal.set_startbit( + newsignal.start_bit, bitNumbering=1, startLittle=True) + newframe.add_signal(newsignal) + db.add_frame(newframe) f.close() return db diff --git a/src/canmatrix/compare.py b/src/canmatrix/compare.py index 621036c9..b18243cd 100644 --- a/src/canmatrix/compare.py +++ b/src/canmatrix/compare.py @@ -61,13 +61,13 @@ def propagateChanges(res): def compareDb(db1, db2, ignore=None): result = compareResult() for f1 in db1.frames: - f2 = db2.frameById(f1.id) + f2 = db2.frame_by_id(f1.id) if f2 is None: result.addChild(compareResult("deleted", "FRAME", f1)) else: result.addChild(compareFrame(f1, f2, ignore)) for f2 in db2.frames: - f1 = db1.frameById(f2.id) + f1 = db1.frame_by_id(f2.id) if f1 is None: result.addChild(compareResult("added", "FRAME", f2)) @@ -77,14 +77,14 @@ def compareDb(db1, db2, ignore=None): else: result.addChild(compareAttributes(db1, db2, ignore)) - for bu1 in db1.boardUnits: - bu2 = db2.boardUnitByName(bu1.name) + for bu1 in db1.ecus: + bu2 = db2.ecu_by_name(bu1.name) if bu2 is None: result.addChild(compareResult("deleted", "ecu", bu1)) else: result.addChild(compareBu(bu1, bu2, ignore)) - for bu2 in db2.boardUnits: - bu1 = db1.boardUnitByName(bu2.name) + for bu2 in db2.ecus: + bu1 = db1.ecu_by_name(bu2.name) if bu1 is None: result.addChild(compareResult("added", "ecu", bu2)) @@ -179,10 +179,10 @@ def compareSignalGroup(sg1, sg2): logger.debug("Strange - sg wo members???") return result for member in sg1.signals: - if sg2.byName(member.name) is None: + if sg2.by_name(member.name) is None: result.addChild(compareResult("deleted", str(member.name), member)) for member in sg2.signals: - if sg1.byName(member.name) is None: + if sg1.by_name(member.name) is None: result.addChild(compareResult("added", str(member.name), member)) return result @@ -272,7 +272,7 @@ def compareFrame(f1, f2, ignore=None): result = compareResult("equal", "FRAME", f1) for s1 in f1: - s2 = f2.signalByName(s1.name) + s2 = f2.signal_by_name(s1.name) if not s2: result.addChild(compareResult("deleted", "SIGNAL", s1)) else: @@ -299,9 +299,9 @@ def compareFrame(f1, f2, ignore=None): f2.extended])) if not "comment" in ignore: if f2.comment is None: - f2.addComment("") + f2.add_comment("") if f1.comment is None: - f1.addComment("") + f1.add_comment("") if f1.comment != f2.comment: result.addChild( compareResult( @@ -309,7 +309,7 @@ def compareFrame(f1, f2, ignore=None): "comment: " + f1.comment, "comment: " + f2.comment])) for s2 in f2.signals: - s1 = f1.signalByName(s2.name) + s1 = f1.signal_by_name(s2.name) if not s1: result.addChild(compareResult("added", "SIGNAL", s2)) @@ -330,14 +330,14 @@ def compareFrame(f1, f2, ignore=None): result.addChild(compareResult("added", "Frame-Transmitter", f2)) for sg1 in f1.signalGroups: - sg2 = f2.signalGroupByName(sg1.name) + sg2 = f2.signal_group_by_name(sg1.name) if sg2 is None: result.addChild(compareResult("removed", "Signalgroup", sg1)) else: result.addChild(compareSignalGroup(sg1, sg2)) for sg2 in f2.signalGroups: - if f1.signalGroupByName(sg2.name) is None: + if f1.signal_group_by_name(sg2.name) is None: result.addChild(compareResult("added", "Signalgroup", sg2)) return result @@ -569,10 +569,10 @@ def main(): onlyInMatrix1 = [] onlyInMatrix2 = [] for frame in db1.frames: - if db2.frameByName(frame.name) is None: + if db2.frame_by_name(frame.name) is None: onlyInMatrix1.append(frame.name) for frame in db2.frames: - if db1.frameByName(frame.name) is None: + if db1.frame_by_name(frame.name) is None: onlyInMatrix2.append(frame.name) print ("Frames only in " + matrix1 + ": " + " ".join(onlyInMatrix1)) print ("Frames only in " + matrix2 + ": " + " ".join(onlyInMatrix2)) diff --git a/src/canmatrix/convert.py b/src/canmatrix/convert.py index a193a0d0..8fdea46a 100644 --- a/src/canmatrix/convert.py +++ b/src/canmatrix/convert.py @@ -94,29 +94,29 @@ def convert(infile, outfileName, **options): renameTuples = options['renameEcu'].split(',') for renameTuple in renameTuples: old, new = renameTuple.split(':') - db.renameEcu(old, new) + db.rename_ecu(old, new) if 'deleteEcu' in options and options['deleteEcu'] is not None: deleteEcuList = options['deleteEcu'].split(',') for ecu in deleteEcuList: - db.delEcu(ecu) + db.del_ecu(ecu) if 'renameFrame' in options and options['renameFrame'] is not None: renameTuples = options['renameFrame'].split(',') for renameTuple in renameTuples: old, new = renameTuple.split(':') - db.renameFrame(old, new) + db.rename_frame(old, new) if 'deleteFrame' in options and options['deleteFrame'] is not None: deleteFrameList = options['deleteFrame'].split(',') for frame in deleteFrameList: - db.delFrame(frame) + db.del_frame(frame) if 'addFrameReceiver' in options and options['addFrameReceiver'] is not None: touples = options['addFrameReceiver'].split(',') for touple in touples: (frameName, ecu) = touple.split(':') - frames = db.globFrames(frameName) + frames = db.glob_frames(frameName) for frame in frames: for signal in frame.signals: - signal.addReceiver(ecu) - frame.updateReceiver() + signal.add_receiver(ecu) + frame.update_receiver() if 'frameIdIncrement' in options and options['frameIdIncrement'] is not None: idIncrement = int(options['frameIdIncrement']) @@ -126,7 +126,7 @@ def convert(infile, outfileName, **options): changeTuples = options['changeFrameId'].split(',') for renameTuple in changeTuples: old, new = renameTuple.split(':') - frame = db.frameById(int(old)) + frame = db.frame_by_id(int(old)) if frame is not None: frame.id = int(new) else: @@ -136,13 +136,13 @@ def convert(infile, outfileName, **options): if 'setFrameFd' in options and options['setFrameFd'] is not None: fdFrameList = options['setFrameFd'].split(',') for frame in fdFrameList: - framePtr = db.frameByName(frame) + framePtr = db.frame_by_name(frame) if framePtr is not None: framePtr.is_fd = True if 'unsetFrameFd' in options and options['unsetFrameFd'] is not None: fdFrameList = options['unsetFrameFd'].split(',') for frame in fdFrameList: - framePtr = db.frameByName(frame) + framePtr = db.frame_by_name(frame) if framePtr is not None: framePtr.is_fd = False @@ -152,49 +152,49 @@ def convert(infile, outfileName, **options): if frame.size > int(options['skipLongDlc']): deleteFrameList.append(frame) for frame in deleteFrameList: - db.delFrame(frame) + db.del_frame(frame) if 'cutLongFrames' in options and options['cutLongFrames'] is not None: for frame in db.frames: if frame.size > int(options['cutLongFrames']): deleteSignalList = [] for sig in frame.signals: - if sig.getStartbit() + int(sig.signalsize) > int(options['cutLongFrames'])*8: + if sig.get_startbit() + int(sig.signalsize) > int(options['cutLongFrames'])*8: deleteSignalList.append(sig) for sig in deleteSignalList: frame.signals.remove(sig) frame.size = 0 - frame.calcDLC() + frame.calc_dlc() if 'renameSignal' in options and options['renameSignal'] is not None: renameTuples = options['renameSignal'].split(',') for renameTuple in renameTuples: old, new = renameTuple.split(':') - db.renameSignal(old, new) + db.rename_signal(old, new) if 'deleteSignal' in options and options['deleteSignal'] is not None: deleteSignalList = options['deleteSignal'].split(',') for signal in deleteSignalList: - db.delSignal(signal) + db.del_signal(signal) if 'deleteZeroSignals' in options and options['deleteZeroSignals']: - db.deleteZeroSignals() + db.delete_zero_signals() if 'deleteSignalAttributes' in options and options[ 'deleteSignalAttributes']: unwantedAttributes = options['deleteSignalAttributes'].split(',') - db.delSignalAttributes(unwantedAttributes) + db.del_signal_attributes(unwantedAttributes) if 'deleteFrameAttributes' in options and options[ 'deleteFrameAttributes']: unwantedAttributes = options['deleteFrameAttributes'].split(',') - db.delFrameAttributes(unwantedAttributes) + db.del_frame_attributes(unwantedAttributes) if 'deleteObsoleteDefines' in options and options[ 'deleteObsoleteDefines']: - db.deleteObsoleteDefines() + db.delete_obsolete_defines() if 'recalcDLC' in options and options['recalcDLC']: - db.recalcDLC(options['recalcDLC']) + db.recalc_dlc(options['recalcDLC']) logger.info(name) logger.info("%d Frames found" % (db.frames.__len__())) diff --git a/src/canmatrix/copy.py b/src/canmatrix/copy.py index ddab0cf4..7b7e7941 100644 --- a/src/canmatrix/copy.py +++ b/src/canmatrix/copy.py @@ -37,20 +37,20 @@ def copyBU(buId, sourceDb, targetDb): if type(buId).__name__ == 'BoardUnit': buList = [buId] else: - buList = sourceDb.globBoardUnits(buId) + buList = sourceDb.glob_ecus(buId) for bu in buList: - targetDb.addEcu(deepcopy(bu)) + targetDb.add_ecu(deepcopy(bu)) # copy all bu-defines for attribute in bu.attributes: - if attribute not in targetDb.buDefines: - targetDb.addBUDefines( - deepcopy(attribute), deepcopy(sourceDb.buDefines[attribute].definition)) - targetDb.addDefineDefault( - deepcopy(attribute), deepcopy(sourceDb.buDefines[attribute].defaultValue)) + if attribute not in targetDb.ecu_defines: + targetDb.add_ecu_defines( + deepcopy(attribute), deepcopy(sourceDb.ecu_defines[attribute].definition)) + targetDb.add_define_default( + deepcopy(attribute), deepcopy(sourceDb.ecu_defines[attribute].defaultValue)) # update enum-datatypes if needed: - if sourceDb.buDefines[attribute].type == 'ENUM': + if sourceDb.ecu_defines[attribute].type == 'ENUM': tempAttr = bu.attribute(attribute, db=sourceDb) if tempAttr not in targetDb.buDefines[attribute].values: targetDb.buDefines[attribute].values.append(deepcopy(tempAttr)) @@ -67,12 +67,12 @@ def copyBUwithFrames(buId, sourceDb, targetDb): if type(buId).__name__ == 'instance': buList = [buId] else: - buList = sourceDb.globBoardUnits(buId) + buList = sourceDb.glob_ecus(buId) for bu in buList: logger.info("Copying ECU " + bu.name) - targetDb.addEcu(deepcopy(bu)) + targetDb.add_ecu(deepcopy(bu)) # copy tx-frames for frame in sourceDb.frames: @@ -89,9 +89,9 @@ def copyBUwithFrames(buId, sourceDb, targetDb): # copy all bu-defines for attribute in bu.attributes: if attribute not in targetDb.buDefines: - targetDb.addBUDefines( + targetDb.add_ecu_defines( deepcopy(attribute), deepcopy(sourceDb.buDefines[attribute].definition)) - targetDb.addDefineDefault( + targetDb.add_define_default( deepcopy(attribute), deepcopy(sourceDb.buDefines[attribute].defaultValue)) # update enum-datatypes if needed: if sourceDb.buDefines[attribute].type == 'ENUM': @@ -116,27 +116,27 @@ def copyFrame(frameId, sourceDb, targetDb): """ # check wether frameId is object, id or symbolic name if 'int' in type(frameId).__name__ or 'long' in type(frameId).__name__: - frameList = [sourceDb.frameById(frameId)] + frameList = [sourceDb.frame_by_id(frameId)] elif type(frameId).__name__ == 'Frame': frameList = [frameId] else: - frameList = sourceDb.globFrames(frameId) + frameList = sourceDb.glob_frames(frameId) for frame in frameList: logger.info("Copying Frame " + frame.name) - if targetDb.frameById(frame.id) is not None: + if targetDb.frame_by_id(frame.id) is not None: # frame already in targetdb... return False # copy Frame-Object: - targetDb.addFrame(deepcopy(frame)) + targetDb.add_frame(deepcopy(frame)) # Boardunits: # each transmitter of Frame could be ECU that is not listed already for transmitter in frame.transmitters: - targetBU = targetDb.boardUnitByName(transmitter) - sourceBU = sourceDb.boardUnitByName(transmitter) + targetBU = targetDb.ecu_by_name(transmitter) + sourceBU = sourceDb.ecu_by_name(transmitter) if sourceBU is not None and targetBU is None: copyBU(sourceBU, sourceDb, targetDb) @@ -144,8 +144,8 @@ def copyFrame(frameId, sourceDb, targetDb): for sig in frame.signals: # each receiver of Signal could be ECU that is not listed already for receiver in sig.receiver: - targetBU = targetDb.boardUnitByName(receiver) - sourceBU = sourceDb.boardUnitByName(receiver) + targetBU = targetDb.ecu_by_name(receiver) + sourceBU = sourceDb.ecu_by_name(receiver) if sourceBU is not None and targetBU is None: copyBU(sourceBU, sourceDb, targetDb) @@ -153,9 +153,9 @@ def copyFrame(frameId, sourceDb, targetDb): attributes = frame.attributes for attribute in attributes: if attribute not in targetDb.frameDefines: - targetDb.addFrameDefines( + targetDb.add_frame_defines( deepcopy(attribute), deepcopy(sourceDb.frameDefines[attribute].definition)) - targetDb.addDefineDefault( + targetDb.add_define_default( deepcopy(attribute), deepcopy(sourceDb.frameDefines[attribute].defaultValue)) # update enum-datatypes if needed: if sourceDb.frameDefines[attribute].type == 'ENUM': @@ -168,9 +168,9 @@ def copyFrame(frameId, sourceDb, targetDb): for sig in frame.signals: # delete all 'unknown' attributes for attribute in sig.attributes: - targetDb.addSignalDefines( + targetDb.add_signal_defines( deepcopy(attribute), deepcopy(sourceDb.signalDefines[attribute].definition)) - targetDb.addDefineDefault( + targetDb.add_define_default( deepcopy(attribute), deepcopy(sourceDb.signalDefines[attribute].defaultValue)) # update enum-datatypes if needed: if sourceDb.signalDefines[attribute].type == 'ENUM': diff --git a/src/canmatrix/dbc.py b/src/canmatrix/dbc.py index fab91ee3..f3848538 100644 --- a/src/canmatrix/dbc.py +++ b/src/canmatrix/dbc.py @@ -32,8 +32,9 @@ from builtins import * -from .canmatrix import * +import canmatrix import re +import math logger = logging.getLogger(__name__) default_float_factory = decimal.Decimal @@ -88,27 +89,27 @@ def dump(mydb, f, **options): if db.contains_fd or db.contains_j1939: if db.contains_fd: - db.addGlobalDefines("BusType", "STRING") - db.addAttribute("BusType", "CAN FD") + db.add_global_defines("BusType", "STRING") + db.add_attribute("BusType", "CAN FD") elif db.contains_j1939: - db.addGlobalDefines("ProtocolType", "STRING") - db.addAttribute("ProtocolType", "J1939") - db.addFrameDefines("VFrameFormat",'ENUM "StandardCAN","ExtendedCAN","StandardCAN_FD","ExtendedCAN_FD","J1939PG"') + db.add_global_defines("ProtocolType", "STRING") + db.add_attribute("ProtocolType", "J1939") + db.add_frame_defines("VFrameFormat", 'ENUM "StandardCAN","ExtendedCAN","StandardCAN_FD","ExtendedCAN_FD","J1939PG"') for frame in db.frames: if frame.is_fd: if frame.extended: - frame.addAttribute("VFrameFormat", "ExtendedCAN_FD") + frame.add_attribute("VFrameFormat", "ExtendedCAN_FD") else: - frame.addAttribute("VFrameFormat", "StandardCAN_FD") + frame.add_attribute("VFrameFormat", "StandardCAN_FD") elif frame.is_j1939: - frame.addAttribute("VFrameFormat","J1939PG") + frame.add_attribute("VFrameFormat", "J1939PG") else: if frame.extended: - frame.addAttribute("VFrameFormat", "ExtendedCAN") + frame.add_attribute("VFrameFormat", "ExtendedCAN") else: - frame.addAttribute("VFrameFormat", "StandardCAN") + frame.add_attribute("VFrameFormat", "StandardCAN") - db.EnumAttribs2Keys() + db.enum_attribs_to_keys() if len(db.signals) > 0: free_signals_dummy_frame = canmatrix.Frame("VECTOR__INDEPENDENT_SIG_MSG", id = 0x40000000, extended=True) @@ -127,20 +128,20 @@ def dump(mydb, f, **options): f.write("BU_: ".encode(dbcExportEncoding)) id = 1 nodeList = {} - for bu in db.boardUnits: + for bu in db.ecus: f.write((bu.name + " ").encode(dbcExportEncoding)) f.write("\n\n".encode(dbcExportEncoding)) if writeValTable: # ValueTables - for table in sorted(db.valueTables): + for table in sorted(db.value_tables): f.write(("VAL_TABLE_ " + table).encode(dbcExportEncoding)) - for row in db.valueTables[table]: + for row in db.value_tables[table]: f.write( (' ' + str(row) + ' "' + - db.valueTables[table][row] + + db.value_tables[table][row] + '"').encode(dbcExportEncoding)) f.write(";\n".encode(dbcExportEncoding)) f.write("\n".encode(dbcExportEncoding)) @@ -151,9 +152,9 @@ def dump(mydb, f, **options): for frame in db.frames: for s in frame.signals: if len(s.name) > 32: - s.addAttribute("SystemSignalLongSymbol", s.name) + s.add_attribute("SystemSignalLongSymbol", s.name) s.name = s.name[0:32] - db.addSignalDefines("SystemSignalLongSymbol", "STRING") + db.add_signal_defines("SystemSignalLongSymbol", "STRING") normalized_names = collections.OrderedDict(( (s, normalizeName(s.name, whitespaceReplacement)) @@ -183,7 +184,7 @@ def dump(mydb, f, **options): for frame in db.frames: multiplex_written = False if frame.transmitters.__len__() == 0: - frame.addTransmitter("Vector__XXX") + frame.add_transmitter("Vector__XXX") if frame.extended == 1: frame.id += 0x80000000 @@ -217,7 +218,7 @@ def dump(mydb, f, **options): - startbit = signal.getStartbit(bitNumbering=1) + startbit = signal.get_startbit(bit_numbering=1) if signal.is_signed: sign = '-' @@ -243,7 +244,7 @@ def dump(mydb, f, **options): f.write(signal.unit.encode(dbcExportEncoding)) f.write('" '.encode(dbcExportEncoding)) if signal.receiver.__len__() == 0: - signal.addReceiver('Vector__XXX') + signal.add_receiver('Vector__XXX') f.write((','.join(signal.receiver) + "\n").encode(dbcExportEncoding)) f.write("\n".encode(dbcExportEncoding)) f.write("\n".encode(dbcExportEncoding)) @@ -290,7 +291,7 @@ def dump(mydb, f, **options): f.write("\n".encode(dbcExportEncoding)) # boarUnit comments - for bu in db.boardUnits: + for bu in db.ecus: if bu.comment is not None and bu.comment.__len__() > 0: f.write( ("CM_ BU_ " + @@ -303,8 +304,7 @@ def dump(mydb, f, **options): f.write("\n".encode(dbcExportEncoding)) defaults = {} - - for (dataType, define) in sorted(list(db.frameDefines.items())): + for (dataType, define) in sorted(list(db.frame_defines.items())): check_define(define) f.write( ('BA_DEF_ BO_ "' + dataType + '" ').encode(dbcExportEncoding) + define.definition.encode(dbcExportEncoding, 'replace') + ';\n'.encode(dbcExportEncoding)) @@ -314,7 +314,7 @@ def dump(mydb, f, **options): else: defaults[dataType] = define.defaultValue - for (dataType, define) in sorted(list(db.signalDefines.items())): + for (dataType, define) in sorted(list(db.signal_defines.items())): check_define(define) f.write( ('BA_DEF_ SG_ "' + dataType + '" ').encode(dbcExportEncoding) + @@ -324,7 +324,7 @@ def dump(mydb, f, **options): defaults[dataType] = '"' + define.defaultValue + '"' else: defaults[dataType] = define.defaultValue - for (dataType, define) in sorted(list(db.buDefines.items())): + for (dataType, define) in sorted(list(db.ecu_defines.items())): check_define(define) f.write( ('BA_DEF_ BU_ "' + dataType + '" ').encode(dbcExportEncoding) + @@ -334,7 +334,7 @@ def dump(mydb, f, **options): defaults[dataType] = '"' + define.defaultValue + '"' else: defaults[dataType] = define.defaultValue - for (dataType, define) in sorted(list(db.globalDefines.items())): + for (dataType, define) in sorted(list(db.global_defines.items())): check_define(define) f.write(('BA_DEF_ "' + dataType + '" ').encode(dbcExportEncoding) + define.definition.encode(dbcExportEncoding, 'replace') + ';\n'.encode(dbcExportEncoding)) if dataType not in defaults and define.defaultValue is not None: @@ -348,9 +348,9 @@ def dump(mydb, f, **options): defaults[define].encode(dbcExportEncoding,'replace') + ';\n'.encode(dbcExportEncoding)) # boardunit-attributes: - for bu in db.boardUnits: + for bu in db.ecus: for attrib, val in sorted(bu.attributes.items()): - if db.buDefines[attrib].type == "STRING": + if db.ecu_defines[attrib].type == "STRING": val = '"' + val + '"' elif not val: val = '""' @@ -359,7 +359,7 @@ def dump(mydb, f, **options): # global-attributes: for attrib, val in sorted(db.attributes.items()): - if db.globalDefines[attrib].type == "STRING": + if db.global_defines[attrib].type == "STRING": val = '"' + val + '"' elif not val: val = '""' @@ -370,7 +370,7 @@ def dump(mydb, f, **options): # messages-attributes: for frame in db.frames: for attrib, val in sorted(frame.attributes.items()): - if db.frameDefines[attrib].type == "STRING": + if db.frame_defines[attrib].type == "STRING": val = '"' + val + '"' elif not val: val = '""' @@ -382,7 +382,7 @@ def dump(mydb, f, **options): for signal in frame.signals: for attrib, val in sorted(signal.attributes.items()): name = output_names[frame][signal] - if db.signalDefines[attrib].type == "STRING": + if db.signal_defines[attrib].type == "STRING": val = '"' + val + '"' elif not val: val = '""' @@ -439,7 +439,7 @@ def dump(mydb, f, **options): if signal.muxerForSignal is not None: f.write(("SG_MUL_VAL_ %d %s %s %d-%d;\n" % (frame.id, signal.name, signal.muxerForSignal, signal.muxValMin, signal.muxValMax)).encode(dbcExportEncoding)) - for envVarName in db.envVars: + for envVarName in db.env_vars: envVar = db.envVars[envVarName] f.write("EV_ {0} : {1} [{2}|{3}] \"{4}\" {5} {6} {7} {8};\n".format(envVarName, envVar["varType"], envVar["min"], envVar["max"], envVar["unit"],envVar["initialValue"], @@ -461,7 +461,7 @@ class FollowUps(object): signal = None frame = None boardUnit = None - db = CanMatrix() + db = canmatrix.CanMatrix() for line in f: i = i + 1 l = line.strip() @@ -477,7 +477,7 @@ class FollowUps(object): if l.endswith(b'";'): followUp = FollowUps.nothing if signal is not None: - signal.addComment(comment[0:-2]) + signal.add_comment(comment[0:-2]) continue elif followUp == FollowUps.frameComment: try: @@ -488,7 +488,7 @@ class FollowUps(object): if l.endswith(b'";'): followUp = FollowUps.nothing if frame is not None: - frame.addComment(comment[0:-2]) + frame.add_comment(comment[0:-2]) continue elif followUp == FollowUps.boardUnitComment: try: @@ -499,14 +499,14 @@ class FollowUps(object): if l.endswith(b'";'): followUp = FollowUps.nothing if boardUnit is not None: - boardUnit.addComment(comment[0:-2]) + boardUnit.add_comment(comment[0:-2]) continue decoded = l.decode(dbcImportEncoding).strip() if decoded.startswith("BO_ "): regexp = re.compile(r"^BO_ ([^\ ]+) ([^\ ]+) *: ([^\ ]+) ([^\ ]+)") temp = regexp.match(decoded) # db.frames.addFrame(Frame(temp.group(1), temp.group(2), temp.group(3), temp.group(4))) - frame = Frame(temp.group(2), id=int(temp.group(1)), size=int(temp.group(3)), transmitters=temp.group(4).split()) + frame = canmatrix.Frame(temp.group(2), id=int(temp.group(1)), size=int(temp.group(3)), transmitters=temp.group(4).split()) db.frames.append(frame) elif decoded.startswith("SG_ "): pattern = r"^SG_ +(\w+) *: *(\d+)\|(\d+)@(\d+)([\+|\-]) +\(([0-9.+\-eE]+),([0-9.+\-eE]+)\) +\[([0-9.+\-eE]+)\|([0-9.+\-eE]+)\] +\"(.*)\" +(.*)" @@ -521,9 +521,9 @@ class FollowUps(object): # if float_factory is not None: # extras['float_factory'] = float_factory - tempSig = Signal( + tempSig = canmatrix.Signal( temp.group(1), - startBit=int(temp.group(2)), + start_bit=int(temp.group(2)), size=int(temp.group(3)), is_little_endian=(int(temp.group(4)) == 1), is_signed=(temp.group(5) == '-'), @@ -537,8 +537,8 @@ class FollowUps(object): ) if not tempSig.is_little_endian: # startbit of motorola coded signals are MSB in dbc - tempSig.setStartbit(int(temp.group(2)), bitNumbering=1) - frame.addSignal(tempSig) + tempSig.set_startbit(int(temp.group(2)), bitNumbering=1) + frame.add_signal(tempSig) # db.frames.addSignalToLastFrame(tempSig) else: pattern = r"^SG_ +(\w+) +(\w+) *: *(\d+)\|(\d+)@(\d+)([\+|\-]) +\(([0-9.+\-eE]+),([0-9.+\-eE]+)\) +\[([0-9.+\-eE]+)\|([0-9.+\-eE]+)\] +\"(.*)\" +(.*)" @@ -567,9 +567,9 @@ class FollowUps(object): # if float_factory is not None: # extras['float_factory'] = float_factory - tempSig = Signal( + tempSig = canmatrix.Signal( temp.group(1), - startBit=int(temp.group(3)), + start_bit=int(temp.group(3)), size=int(temp.group(4)), is_little_endian=(int(temp.group(5)) == 1), is_signed=(temp.group(6) == '-'), @@ -589,8 +589,8 @@ class FollowUps(object): if not tempSig.is_little_endian: # startbit of motorola coded signals are MSB in dbc - tempSig.setStartbit(int(temp.group(3)), bitNumbering=1) - frame.addSignal(tempSig) + tempSig.set_startbit(int(temp.group(3)), bitNumbering=1) + frame.add_signal(tempSig) if is_complex_multiplexed: frame.is_complex_multiplexed = True @@ -599,9 +599,9 @@ class FollowUps(object): elif decoded.startswith("BO_TX_BU_ "): regexp = re.compile(r"^BO_TX_BU_ ([0-9]+) *: *(.+);") temp = regexp.match(decoded) - botschaft = db.frameById(temp.group(1)) + botschaft = db.frame_by_id(temp.group(1)) for bu in temp.group(2).split(','): - botschaft.addTransmitter(bu) + botschaft.add_transmitter(bu) elif decoded.startswith("CM_ SG_ "): pattern = r"^CM_ +SG_ +(\w+) +(\w+) +\"(.*)\";" regexp = re.compile(pattern) @@ -609,11 +609,11 @@ class FollowUps(object): temp = regexp.match(decoded) temp_raw = regexp_raw.match(l) if temp: - botschaft = db.frameById(temp.group(1)) - signal = botschaft.signalByName(temp.group(2)) + botschaft = db.frame_by_id(temp.group(1)) + signal = botschaft.signal_by_name(temp.group(2)) if signal: try: - signal.addComment(temp_raw.group(3).decode( + signal.add_comment(temp_raw.group(3).decode( dbcCommentEncoding).replace('\\"', '"')) except: logger.error( @@ -626,8 +626,8 @@ class FollowUps(object): temp = regexp.match(decoded) temp_raw = regexp_raw.match(l) if temp: - botschaft = db.frameById(temp.group(1)) - signal = botschaft.signalByName(temp.group(2)) + botschaft = db.frame_by_id(temp.group(1)) + signal = botschaft.signal_by_name(temp.group(2)) try: comment = temp_raw.group(3).decode( dbcCommentEncoding).replace('\\"', '"') @@ -644,10 +644,10 @@ class FollowUps(object): temp = regexp.match(decoded) temp_raw = regexp_raw.match(l) if temp: - frame = db.frameById(temp.group(1)) + frame = db.frame_by_id(temp.group(1)) if frame: try: - frame.addComment(temp_raw.group(2).decode( + frame.add_comment(temp_raw.group(2).decode( dbcCommentEncoding).replace('\\"', '"')) except: logger.error( @@ -660,7 +660,7 @@ class FollowUps(object): temp = regexp.match(decoded) temp_raw = regexp_raw.match(l) if temp: - frame = db.frameById(temp.group(1)) + frame = db.frame_by_id(temp.group(1)) try: comment = temp_raw.group(2).decode( dbcCommentEncoding).replace('\\"', '"') @@ -676,10 +676,10 @@ class FollowUps(object): temp = regexp.match(decoded) temp_raw = regexp_raw.match(l) if temp: - boardUnit = db.boardUnitByName(temp.group(1)) + boardUnit = db.ecu_by_name(temp.group(1)) if boardUnit: try: - boardUnit.addComment(temp_raw.group(2).decode( + boardUnit.add_comment(temp_raw.group(2).decode( dbcCommentEncoding).replace('\\"', '"')) except: logger.error( @@ -692,7 +692,7 @@ class FollowUps(object): temp = regexp.match(decoded) temp_raw = regexp_raw.match(l) if temp: - boardUnit = db.boardUnitByName(temp.group(1)) + boardUnit = db.ecu_by_name(temp.group(1)) if boardUnit: try: comment = temp_raw.group(2).decode( @@ -711,7 +711,7 @@ class FollowUps(object): myTempListe = temp.group(1).split(' ') for ele in myTempListe: if len(ele.strip()) > 1: - db.boardUnits.append(BoardUnit(ele)) + db.ecus.append(canmatrix.ecu(ele)) elif decoded.startswith("VAL_ "): regexp = re.compile(r"^VAL_ +(\w+) +(\w+) +(.*);") @@ -722,12 +722,12 @@ class FollowUps(object): tempList = temp.group(3).split('"') if botschaftId.isnumeric(): # value for Frame try: - bo = db.frameById(botschaftId) - sg = bo.signalByName(signal) + bo = db.frame_by_id(botschaftId) + sg = bo.signal_by_name(signal) for i in range(math.floor(len(tempList) / 2)): val = tempList[i * 2 + 1] if sg: - sg.addValues(tempList[i * 2], val) + sg.add_values(tempList[i * 2], val) except: logger.error("Error with Line: " + str(tempList)) else: @@ -746,7 +746,7 @@ class FollowUps(object): valHash[tempList[i * 2].strip()] = val.strip() except: logger.error("Error with Line: " + str(tempList)) - db.addValueTable(tableName, valHash) + db.add_value_table(tableName, valHash) else: logger.debug(l) @@ -757,8 +757,8 @@ class FollowUps(object): temp = regexp.match(decoded) temp_raw = regexp_raw.match(l) if temp: - db.addSignalDefines(temp.group(1), - temp_raw.group(2).decode(dbcImportEncoding)) + db.add_signal_defines(temp.group(1), + temp_raw.group(2).decode(dbcImportEncoding)) elif decoded.startswith("BA_DEF_ BO_ "): pattern = r"^BA_DEF_ +BO_ +\"([A-Za-z0-9\-_]+)\" +(.+);" regexp = re.compile(pattern) @@ -766,8 +766,8 @@ class FollowUps(object): temp = regexp.match(decoded) temp_raw = regexp_raw.match(l) if temp: - db.addFrameDefines(temp.group(1), - temp_raw.group(2).decode(dbcImportEncoding)) + db.add_frame_defines(temp.group(1), + temp_raw.group(2).decode(dbcImportEncoding)) elif decoded.startswith("BA_DEF_ BU_ "): pattern = r"^BA_DEF_ +BU_ +\"([A-Za-z0-9\-_]+)\" +(.+);" regexp = re.compile(pattern) @@ -775,8 +775,8 @@ class FollowUps(object): temp = regexp.match(decoded) temp_raw = regexp_raw.match(l) if temp: - db.addBUDefines(temp.group(1), - temp_raw.group(2).decode(dbcImportEncoding)) + db.add_ecu_defines(temp.group(1), + temp_raw.group(2).decode(dbcImportEncoding)) elif decoded.startswith("BA_DEF_ "): pattern = r"^BA_DEF_ +\"([A-Za-z0-9\-_]+)\" +(.+);" regexp = re.compile(pattern) @@ -784,8 +784,8 @@ class FollowUps(object): temp = regexp.match(decoded) temp_raw = regexp_raw.match(l) if temp: - db.addGlobalDefines(temp.group(1), - temp_raw.group(2).decode(dbcImportEncoding)) + db.add_global_defines(temp.group(1), + temp_raw.group(2).decode(dbcImportEncoding)) elif decoded.startswith("BA_ "): regexp = re.compile(r"^BA_ +\"[A-Za-z0-9[\-_ .]+\" +(.+)") @@ -794,19 +794,19 @@ class FollowUps(object): if tempba.group(1).strip().startswith("BO_ "): regexp = re.compile(r"^BA_ +\"(.*)\" +BO_ +(\w+) +(.+);") temp = regexp.match(decoded) - db.frameById(int(temp.group(2))).addAttribute( + db.frame_by_id(int(temp.group(2))).add_attribute( temp.group(1), temp.group(3)) elif tempba.group(1).strip().startswith("SG_ "): regexp = re.compile(r"^BA_ +\"(.*)\" +SG_ +(\w+) +(\w+) +(.+);") temp = regexp.match(decoded) if temp!=None: - db.frameById(int(temp.group(2))).signalByName( - temp.group(3)).addAttribute(temp.group(1), temp.group(4)) + db.frame_by_id(int(temp.group(2))).signal_by_name( + temp.group(3)).add_attribute(temp.group(1), temp.group(4)) elif tempba.group(1).strip().startswith("BU_ "): regexp = re.compile(r"^BA_ +\"(.*)\" +BU_ +(\w+) +(.+);") temp = regexp.match(decoded) - db.boardUnitByName( - temp.group(2)).addAttribute( + db.ecu_by_name( + temp.group(2)).add_attribute( temp.group(1), temp.group(3)) else: @@ -814,22 +814,22 @@ class FollowUps(object): r"^BA_ +\"([A-Za-z0-9\-_]+)\" +([\"A-Za-z0-9\-_\.]+);") temp = regexp.match(decoded) if temp: - db.addAttribute(temp.group(1), temp.group(2)) + db.add_attribute(temp.group(1), temp.group(2)) elif decoded.startswith("SIG_GROUP_ "): regexp = re.compile(r"^SIG_GROUP_ +(\w+) +(\w+) +(\w+) +\:(.*);") temp = regexp.match(decoded) - frame = db.frameById(temp.group(1)) + frame = db.frame_by_id(temp.group(1)) if frame is not None: signalArray = temp.group(4).split(' ') - frame.addSignalGroup(temp.group(2), temp.group(3), signalArray) + frame.add_signal_group(temp.group(2), temp.group(3), signalArray) elif decoded.startswith("SIG_VALTYPE_ "): regexp = re.compile(r"^SIG_VALTYPE_ +(\w+) +(\w+)\s*\:(.*);") temp = regexp.match(decoded) - frame = db.frameById(temp.group(1)) + frame = db.frame_by_id(temp.group(1)) if frame: - signal = frame.signalByName(temp.group(2)) + signal = frame.signal_by_name(temp.group(2)) signal.is_float = True # SIG_VALTYPE_ 0 float : 1; @@ -840,8 +840,8 @@ class FollowUps(object): temp = regexp.match(decoded) temp_raw = regexp_raw.match(l) if temp: - db.addDefineDefault(temp.group(1), - temp_raw.group(2).decode(dbcImportEncoding)) + db.add_define_default(temp.group(1), + temp_raw.group(2).decode(dbcImportEncoding)) elif decoded.startswith("SG_MUL_VAL_ "): pattern = r"^SG_MUL_VAL_ +([0-9]+) +([A-Za-z0-9\-_]+) +([A-Za-z0-9\-_]+) +([0-9]+)\-([0-9]+) *;" regexp = re.compile(pattern) @@ -854,9 +854,9 @@ class FollowUps(object): muxerForSignal = temp.group(3) muxValMin = int(temp.group(4)) muxValMax = int(temp.group(4)) - frame = db.frameById(frameId) + frame = db.frame_by_id(frameId) if frame is not None: - signal = frame.signalByName(signalName) + signal = frame.signal_by_name(signalName) frame.is_complex_multiplexed = True signal.muxerForSignal = muxerForSignal signal.muxValMin = muxValMin @@ -875,7 +875,7 @@ class FollowUps(object): evId = temp.group(7) accessType = temp.group(8) accessNodes = temp.group(9).split(",") - db.addEnvVar( varName, {"varType": varType, "min" : min, "max" : max, + db.add_env_var(varName, {"varType": varType, "min" : min, "max" : max, "unit" : unit, "initialValue" : initialValue, "evId" : evId, "accessType" : accessType, "accessNodes" : accessNodes}) @@ -883,14 +883,12 @@ class FollowUps(object): except: print ("error with line no: %d" % i) print (line) - # else: -# print("Unrecocniced line: " + l + " (%d) " % i) # Backtracking for frame in db.frames: # receiver is only given in the signals, so do propagate the receiver # to the frame: - frame.updateReceiver() + frame.update_receiver() # extended-flag is implicite in canid, thus repair this: if frame.id > 0x80000000: frame.id -= 0x80000000 @@ -902,34 +900,34 @@ class FollowUps(object): for signal in frame.signals: if signal.attribute("SystemSignalLongSymbol") is not None: signal.name = signal.attribute("SystemSignalLongSymbol")[1:-1] - signal.delAttribute("SystemSignalLongSymbol") - for define in db.globalDefines: - if db.globalDefines[define].type == "STRING": + signal.del_attribute("SystemSignalLongSymbol") + for define in db.global_defines: + if db.global_defines[define].type == "STRING": if define in db.attributes: db.attributes[define] = db.attributes[define][1:-1] - for define in db.buDefines: - if db.buDefines[define].type == "STRING": - for ecu in db.boardUnits: + for define in db.ecu_defines: + if db.ecu_defines[define].type == "STRING": + for ecu in db.ecus: if define in ecu.attributes: ecu.attributes[define] = ecu.attributes[define][1:-1] - for define in db.frameDefines: - if db.frameDefines[define].type == "STRING": + for define in db.frame_defines: + if db.frame_defines[define].type == "STRING": for frame in db.frames: if define in frame.attributes: frame.attributes[define] = frame.attributes[define][1:-1] - for define in db.signalDefines: - if db.signalDefines[define].type == "STRING": + for define in db.signal_defines: + if db.signal_defines[define].type == "STRING": for frame in db.frames: for signal in frame.signals: if define in signal.attributes: signal.attributes[define] = signal.attributes[define][1:-1] - db.EnumAttribs2Values() - db.updateEcuList() - db.delEcu("Vector__XXX") - free_signals_dummy_frame = db.frameByName("VECTOR__INDEPENDENT_SIG_MSG") + db.enum_attribs_to_values() + db.update_ecu_list() + db.del_ecu("Vector__XXX") + free_signals_dummy_frame = db.frame_by_name("VECTOR__INDEPENDENT_SIG_MSG") if free_signals_dummy_frame is not None and free_signals_dummy_frame.id == 0x40000000: db.signals = free_signals_dummy_frame.signals - db.delFrame(free_signals_dummy_frame) + db.del_frame(free_signals_dummy_frame) return db diff --git a/src/canmatrix/dbf.py b/src/canmatrix/dbf.py index a66079e6..d6137cff 100644 --- a/src/canmatrix/dbf.py +++ b/src/canmatrix/dbf.py @@ -79,8 +79,8 @@ def load(f, **options): else: (boId, temS, SignalName, comment) = line.split(' ', 3) comment = comment.replace('"', '').replace(';', '') - db.frameById(int(boId)).signalByName( - SignalName).addComment(comment) + db.frame_by_id(int(boId)).signal_by_name( + SignalName).add_comment(comment) if mode == 'BUDescription': if line.startswith( @@ -89,7 +89,7 @@ def load(f, **options): else: (BUName, comment) = line.split(' ', 1) comment = comment.replace('"', '').replace(';', '') - db.boardUnitByName(BUName).addComment(comment) + db.ecu_by_name(BUName).add_comment(comment) if mode == 'FrameDescription': if line.startswith( @@ -98,17 +98,17 @@ def load(f, **options): else: (boId, temS, comment) = line.split(' ', 2) comment = comment.replace('"', '').replace(';', '') - frame = db.frameById(int(boId)) + frame = db.frame_by_id(int(boId)) if frame: - frame.addComment(comment) + frame.add_comment(comment) elif mode == 'ParamMsgVal': if line.startswith("[END_PARAM_MSG_VAL]"): mode = '' else: (boId, temS, attrib, value) = line.split(',', 3) - db.frameById( - int(boId)).addAttribute( + db.frame_by_id( + int(boId)).add_attribute( attrib.replace( '"', ''), @@ -121,7 +121,7 @@ def load(f, **options): mode = '' else: (bu, attrib, value) = line.split(',', 2) - db.boardUnitByName(bu).addAttribute( + db.ecu_by_name(bu).add_attribute( attrib.replace('"', ''), value[1:-1]) elif mode == 'ParamNetVal': @@ -129,15 +129,15 @@ def load(f, **options): mode = '' else: (attrib, value) = line.split(',', 1) - db.addAttribute(attrib.replace('"', ''), value[1:-1]) + db.add_attribute(attrib.replace('"', ''), value[1:-1]) elif mode == 'ParamSigVal': if line.startswith("[END_PARAM_SIG_VAL]"): mode = '' else: (boId, temS, SignalName, attrib, value) = line.split(',', 4) - db.frameById( - int(boId)).signalByName(SignalName).addAttribute( + db.frame_by_id( + int(boId)).signal_by_name(SignalName).add_attribute( attrib.replace( '"', ''), value[ 1:-1]) @@ -147,32 +147,32 @@ def load(f, **options): mode = '' else: (name, define, default) = decodeDefine(line) - db.addSignalDefines(name, define) - db.addDefineDefault(name, default) + db.add_signal_defines(name, define) + db.add_define_default(name, default) elif mode == 'ParamMsg': if line.startswith("[END_PARAM_MSG]"): mode = '' else: (name, define, default) = decodeDefine(line) - db.addFrameDefines(name, define) - db.addDefineDefault(name, default) + db.add_frame_defines(name, define) + db.add_define_default(name, default) elif mode == 'ParamNode': if line.startswith("[END_PARAM_NODE]"): mode = '' else: (name, define, default) = decodeDefine(line) - db.addBUDefines(name, define) - db.addDefineDefault(name, default) + db.add_ecu_defines(name, define) + db.add_define_default(name, default) elif mode == 'ParamNet': if line.startswith("[END_PARAM_NET]"): mode = '' else: (name, define, default) = decodeDefine(line) - db.addGlobalDefines(name, define) - db.addDefineDefault(name, default) + db.add_global_defines(name, define) + db.add_define_default(name, default) else: if line.startswith("[START_DESC_SIG]"): @@ -217,7 +217,7 @@ def load(f, **options): transmitters = temparray[6].split() else: transmitters = list() - newBo = db.addFrame( + newBo = db.add_frame( Frame(name, id=int(Id), size=int(size), @@ -231,7 +231,7 @@ def load(f, **options): temstr = line.strip()[6:].strip() boList = temstr.split(',') for bo in boList: - db.addEcu(BoardUnit(bo)) + db.add_ecu(ecu(bo)) if line.startswith("[START_SIGNALS]"): temstr = line.strip()[15:].strip() @@ -267,25 +267,25 @@ def load(f, **options): startbit = int(startbit) startbit += (int(startbyte) - 1) * 8 - newSig = newBo.addSignal(Signal(name, - startBit=int(startbit), - size=int(size), - is_little_endian=( + newSig = newBo.add_signal(Signal(name, + start_bit=int(startbit), + size=int(size), + is_little_endian=( int(byteorder) == 1), - is_signed=is_signed, - factor=factor, - offset=offset, - min=Min * factor, - max=Max * factor, - unit=unit, - receiver=receiver, - is_float=is_float, - multiplex=multiplex)) + is_signed=is_signed, + factor=factor, + offset=offset, + min=Min * factor, + max=Max * factor, + unit=unit, + receiver=receiver, + is_float=is_float, + multiplex=multiplex)) if int(byteorder) == 0: # this is dummy here, because internal lsb is default - for # now - newSig.setStartbit( + newSig.set_startbit( startbit, bitNumbering=1, startLittle=True) if line.startswith("[VALUE_DESCRIPTION]"): @@ -296,14 +296,14 @@ def load(f, **options): if temp: name = temp.group(1) value = temp.group(2) - newSig.addValues(value, name) + newSig.add_values(value, name) for frame in db.frames: # receiver is only given in the signals, so do propagate the # receiver to the frame: - frame.updateReceiver() - db.EnumAttribs2Values() - free_signals_dummy_frame = db.frameByName("VECTOR__INDEPENDENT_SIG_MSG") + frame.update_receiver() + db.enum_attribs_to_values() + free_signals_dummy_frame = db.frame_by_name("VECTOR__INDEPENDENT_SIG_MSG") if free_signals_dummy_frame is not None and free_signals_dummy_frame.id == 0x40000000: db.signals = free_signals_dummy_frame.signals db.delFrame(free_signals_dummy_frame) @@ -314,7 +314,7 @@ def dump(mydb, f, **options): # create copy because export changes database db = deepcopy(mydb) dbfExportEncoding = options.get("dbfExportEncoding", 'iso-8859-1') - db.EnumAttribs2Keys() + db.enum_attribs_to_keys() if len(db.signals) > 0: free_signals_dummy_frame = canmatrix.Frame("VECTOR__INDEPENDENT_SIG_MSG", id = 0x40000000, extended=True) free_signals_dummy_frame.signals = db.signals @@ -347,7 +347,7 @@ def dump(mydb, f, **options): ",%d,%d,%d,1,%c," % (frame.id, frame.size, len(frame.signals), extended) if frame.transmitters.__len__() == 0: - frame.addTransmitter("Vector__XXX") + frame.add_transmitter("Vector__XXX") # DBF does not support multiple Transmitters outstr += frame.transmitters[0] + "\n" @@ -357,9 +357,9 @@ def dump(mydb, f, **options): # m_ucDataFormat whichbyte = int( math.floor( - signal.getStartbit( - bitNumbering=1, - startLittle=True) / + signal.get_startbit( + bit_numbering=1, + start_little=True) / 8) + 1) sign = 'I' @@ -378,8 +378,8 @@ def dump(mydb, f, **options): outstr += "[START_SIGNALS] " + signal.name + ",%d,%d,%d,%c," % (signal.size, whichbyte, - int(signal.getStartbit(bitNumbering=1, - startLittle=True)) % 8, + int(signal.get_startbit(bit_numbering=1, + start_little=True)) % 8, sign) + '{},{}'.format(float(signal.max) / float(signal.factor), float(signal.min) / float(signal.factor)) @@ -405,9 +405,9 @@ def dump(mydb, f, **options): # Boardunits outstr += "[NODE] " count = 1 - for bu in db.boardUnits: + for bu in db.ecus: outstr += bu.name - if count < len(db.boardUnits): + if count < len(db.ecus): outstr += "," count += 1 outstr += "\n" @@ -425,7 +425,7 @@ def dump(mydb, f, **options): # Frame descriptions outstr += "[START_DESC_NODE]\n" - for bu in db.boardUnits: + for bu in db.ecus: if bu.comment is not None: comment = bu.comment.replace("\n", " ") outstr += bu.name + ' "' + comment + '";\n' @@ -450,7 +450,7 @@ def dump(mydb, f, **options): # db-parameter outstr += "[START_PARAM_NET]\n" - for (type, define) in sorted(list(db.globalDefines.items())): + for (type, define) in sorted(list(db.global_defines.items())): defaultVal = define.defaultValue if defaultVal is None: defaultVal = "0" @@ -459,7 +459,7 @@ def dump(mydb, f, **options): # bu-parameter outstr += "[START_PARAM_NODE]\n" - for (type, define) in sorted(list(db.buDefines.items())): + for (type, define) in sorted(list(db.ecu_defines.items())): defaultVal = define.defaultValue if defaultVal is None: defaultVal = "0" @@ -468,7 +468,7 @@ def dump(mydb, f, **options): # frame-parameter outstr += "[START_PARAM_MSG]\n" - for (type, define) in sorted(list(db.frameDefines.items())): + for (type, define) in sorted(list(db.frame_defines.items())): defaultVal = define.defaultValue if defaultVal is None: defaultVal = "0" @@ -478,7 +478,7 @@ def dump(mydb, f, **options): # signal-parameter outstr += "[START_PARAM_SIG]\n" - for (type, define) in list(db.signalDefines.items()): + for (type, define) in list(db.signal_defines.items()): defaultVal = define.defaultValue if defaultVal is None: defaultVal = "0" @@ -488,7 +488,7 @@ def dump(mydb, f, **options): outstr += "[START_PARAM_VAL]\n" # boardunit-attributes: outstr += "[START_PARAM_NODE_VAL]\n" - for bu in db.boardUnits: + for bu in db.ecus: for attrib, val in sorted(list(bu.attributes.items())): outstr += bu.name + ',"' + attrib + '","' + val + '"\n' outstr += "[END_PARAM_NODE_VAL]\n" diff --git a/src/canmatrix/fibex.py b/src/canmatrix/fibex.py index 4c1a6242..b84c2d77 100644 --- a/src/canmatrix/fibex.py +++ b/src/canmatrix/fibex.py @@ -126,7 +126,7 @@ def dump(db, f, **options): # ECUS # ecus = createSubElementFx(elements, "ECUS") - for bu in db.boardUnits: + for bu in db.ecus: ecu = createSubElementFx(ecus, "ECU") ecu.set("ID", bu.name) createShortNameDesc(ecu, bu.name, bu.comment) @@ -152,7 +152,7 @@ def dump(db, f, **options): signalInstance.set("ID", "PDUINST_" + signal.name) # startBit: TODO - find out correct BYTEORDER ... createSubElementFx(signalInstance, "BIT-POSITION", - str(signal.startBit)) + str(signal.start_bit)) if signal.is_little_endian: createSubElementFx( signalInstance, @@ -185,7 +185,7 @@ def dump(db, f, **options): # FUNCTIONS # functions = createSubElementFx(elements, "FUNCTIONS") - for bu in db.boardUnits: + for bu in db.ecus: function = createSubElementFx(functions, "FUNCTION") function.set("ID", "FCT_" + bu.name) createShortNameDesc(function, "FCT_" + bu.name, bu.comment) diff --git a/src/canmatrix/join.py b/src/canmatrix/join.py index f9027ffa..03f54a5b 100644 --- a/src/canmatrix/join.py +++ b/src/canmatrix/join.py @@ -33,8 +33,8 @@ def join_frame_by_signal_startbit(files): for idx, idy in same_pgn: # print("{0:#x} {1:#x}".format(idx, idy)) - targetFr = targetDb.frameById(idx) - sourceFr = sourceDb.frameById(idy) + targetFr = targetDb.frame_by_id(idx) + sourceFr = sourceDb.frame_by_id(idy) to_add = [] for sig_t in targetFr.signals: @@ -44,7 +44,7 @@ def join_frame_by_signal_startbit(files): # print("\t{0} {1}".format(sig_t.name, sig_s.name)) to_add.append(sig_s) for s in to_add: - targetFr.addSignal(s) + targetFr.add_signal(s) return targetDb @@ -65,8 +65,8 @@ def renameFrameWithSAEacronyme(sourceDb, targetDb): same_pgn = ids_sharing_same_pgn(id_x, pgn_x, id_y, pgn_y) for idx, idy in same_pgn: - targetFr = targetDb.frameById(idx) - sourceFr = sourceDb.frameById(idy) + targetFr = targetDb.frame_by_id(idx) + sourceFr = sourceDb.frame_by_id(idy) new_name = sourceFr.name + "__" + targetFr.name targetFr.name = new_name @@ -85,8 +85,8 @@ def join_frame_for_manufacturer(db, files): for idx, idy in same_pgn: # print("{0:#x} {1:#x}".format(idx, idy)) - targetFr = db.frameById(idx) - sourceFr = sourceDb.frameById(idy) + targetFr = db.frame_by_id(idx) + sourceFr = sourceDb.frame_by_id(idy) _, pgn, sa = CanId(targetFr.id).tuples() if(sa < 128): @@ -98,4 +98,4 @@ def join_frame_for_manufacturer(db, files): sig_s.name = new_name to_add.append(sig_s) for s in to_add: - targetFr.addSignal(s) + targetFr.add_signal(s) diff --git a/src/canmatrix/kcd.py b/src/canmatrix/kcd.py index 0fa30b09..ebd93ef9 100644 --- a/src/canmatrix/kcd.py +++ b/src/canmatrix/kcd.py @@ -45,7 +45,7 @@ def createSignal(signal, nodeList, typeEnums): 'Signal', name=signal.name, offset=str( - signal.getStartbit())) + signal.get_startbit())) if signal.size > 1: sig.set("length", str(signal.size)) if signal.is_little_endian == 0: @@ -119,7 +119,7 @@ def dump(dbs, f, **options): canClust = canCluster(dbs) for name in canClust: db = canClust[name] - for (typename, define) in list(db.signalDefines.items()): + for (typename, define) in list(db.signal_defines.items()): defines = re.split(r"\s+", define.definition) define_type = defines[0] if define_type != 'ENUM': @@ -173,7 +173,7 @@ def dump(dbs, f, **options): if frame.extended == 1: message.set("format", "extended") - if "GenMsgCycleTime" in db.frameDefines: + if "GenMsgCycleTime" in db.frame_defines: cycleTime = frame.attribute("GenMsgCycleTime", db=db) if cycleTime is not None and int(cycleTime) > 0: message.set("triggered", "true") @@ -203,7 +203,7 @@ def dump(dbs, f, **options): for signal in frame.signals: if signal.multiplex is not None and signal.multiplex == 'Multiplexor': multiplexor = etree.Element('Multiplex', name=signal.name, offset=str( - signal.getStartbit()), length=str(int(signal.size))) + signal.get_startbit()), length=str(int(signal.size))) value = etree.Element('Value') if float(signal.min) != 0: value.set('min', "%g" % signal.min) @@ -298,7 +298,7 @@ def parseSignal(signal, mux, namespace, nodelist, float_factory): receiver.append(nodelist[noderef.get('id')]) newSig = Signal(signal.get('name'), - startBit=int(startbit), + start_bit=int(startbit), size=int(signalsize), is_little_endian=is_little_endian, is_signed=is_signed, @@ -314,14 +314,14 @@ def parseSignal(signal, mux, namespace, nodelist, float_factory): if max is not None: newSig.max = float_factory(max) - newSig.setStartbit(int(startbit)) + newSig.set_startbit(int(startbit)) notes = signal.findall('./' + namespace + 'Notes') comment = "" for note in notes: if note.text is not None: comment += note.text - newSig.addComment(comment) + newSig.add_comment(comment) labelsets = signal.findall('./' + namespace + 'LabelSet') for labelset in labelsets: @@ -329,7 +329,7 @@ def parseSignal(signal, mux, namespace, nodelist, float_factory): for label in labels: name = label.get('name') value = label.get('value') - newSig.addValues(value, name) + newSig.add_values(value, name) return newSig def load(f, **options): @@ -347,9 +347,9 @@ def load(f, **options): counter = 0 for bus in busses: db = CanMatrix() - db.addFrameDefines("GenMsgCycleTime", 'INT 0 65535') + db.add_frame_defines("GenMsgCycleTime", 'INT 0 65535') for node in nodes: - db.BUs.add(BoardUnit(node.get('name'))) + db.BUs.add(ecu(node.get('name'))) nodelist[node.get('id')] = node.get('name') messages = bus.findall('./' + namespace + 'Message') @@ -360,7 +360,7 @@ def load(f, **options): newBo = Frame(message.get('name'), id=int(message.get('id'), 16)) if 'triggered' in message.attrib: - newBo.addAttribute("GenMsgCycleTime", message.get('interval')) + newBo.add_attribute("GenMsgCycleTime", message.get('interval')) if 'length' in message.attrib: dlc = int(message.get('length')) @@ -406,7 +406,7 @@ def load(f, **options): for noderef in noderefs: receiver.append(nodelist[noderef.get('id')]) newSig = Signal(multiplex.get('name'), - startBit=int(startbit), + start_bit=int(startbit), size=int(signalsize), is_little_endian=is_little_endian, is_signed=is_signed, @@ -423,12 +423,12 @@ def load(f, **options): if is_little_endian == False: # motorola/big_endian set/convert startbit - newSig.setStartbit(startbit) + newSig.set_startbit(startbit) notes = multiplex.findall('./' + namespace + 'Notes') comment = "" for note in notes: comment += note.text - newSig.addComment(comment) + newSig.add_comment(comment) labelsets = multiplex.findall('./' + namespace + 'LabelSet') for labelset in labelsets: @@ -436,9 +436,9 @@ def load(f, **options): for label in labels: name = label.get('name') value = label.get('value') - newSig.addValues(value, name) + newSig.add_values(value, name) - newBo.addSignal(newSig) + newBo.add_signal(newSig) muxgroups = multiplex.findall('./' + namespace + 'MuxGroup') for muxgroup in muxgroups: @@ -446,7 +446,7 @@ def load(f, **options): signales = muxgroup.findall('./' + namespace + 'Signal') for signal in signales: newSig = parseSignal(signal, mux, namespace, nodelist, float_factory) - newBo.addSignal(newSig) + newBo.add_signal(newSig) signales = message.findall('./' + namespace + 'Signal') @@ -454,25 +454,25 @@ def load(f, **options): for producer in producers: noderefs = producer.findall('./' + namespace + 'NodeRef') for noderef in noderefs: - newBo.addTransmitter(nodelist[noderef.get('id')]) + newBo.add_transmitter(nodelist[noderef.get('id')]) for signal in signales: newSig = parseSignal(signal, None, namespace, nodelist, float_factory) - newBo.addSignal(newSig) + newBo.add_signal(newSig) notes = message.findall('./' + namespace + 'Notes') comment = "" for note in notes: if note.text is not None: comment += note.text - newBo.addComment(comment) + newBo.add_comment(comment) if dlc is None: - newBo.calcDLC() + newBo.calc_dlc() else: newBo.size = dlc - newBo.updateReceiver() - db.addFrame(newBo) + newBo.update_receiver() + db.add_frame(newBo) name = bus.get('name') if not name: name = "CAN%d" % counter diff --git a/src/canmatrix/sym.py b/src/canmatrix/sym.py index 6e780e63..d30930df 100644 --- a/src/canmatrix/sym.py +++ b/src/canmatrix/sym.py @@ -105,7 +105,7 @@ def createSignal(db, signal): output += "unsigned " else: output += "signed " - startBit = signal.getStartbit() + startBit = signal.get_startbit() if signal.is_little_endian == 0: # Motorola output += "%d,%d -m " % (startBit, signal.size) @@ -148,7 +148,7 @@ def createSignal(db, signal): key, val) in sorted( signal.values.items())) + ")" - if "GenSigStartValue" in db.signalDefines: + if "GenSigStartValue" in db.signal_defines: genSigStartVal = signal.attribute("GenSigStartValue", db=db) if genSigStartVal is not None: factory = ( @@ -254,7 +254,7 @@ def sendreceive(f): muxOut += idType first = 1 muxOut += "DLC=%d\n" % (frame.size) - if "GenMsgCycleTime" in db.frameDefines: + if "GenMsgCycleTime" in db.frame_defines: cycleTime = frame.attribute("GenMsgCycleTime", db=db) if cycleTime is not None: muxOut += "CycleTime=" + str(cycleTime) + "\n" @@ -263,11 +263,11 @@ def sendreceive(f): i, muxSignal.name + "%d" % i) muxOut += "Mux=" + muxName - startBit = muxSignal.getStartbit() + startBit = muxSignal.get_startbit() s = str(i) if len(s) > 1: length = len( - '{:X}'.format(int(muxSignal.calcMax())) + '{:X}'.format(int(muxSignal.calc_max())) ) s = '{:0{}X}h'.format(i, length) if signal.is_little_endian == 0: @@ -298,7 +298,7 @@ def sendreceive(f): output += name output += idType output += "DLC=%d\n" % (frame.size) - if "GenMsgCycleTime" in db.frameDefines: + if "GenMsgCycleTime" in db.frame_defines: cycleTime = frame.attribute("GenMsgCycleTime", db=db) if cycleTime is not None: output += "CycleTime=" + str(cycleTime) + "\n" @@ -329,13 +329,13 @@ class Mode(object): frame = None db = CanMatrix() - db.addFrameDefines("GenMsgCycleTime", 'INT 0 65535') - db.addFrameDefines("Receivable", 'BOOL False True') - db.addFrameDefines("Sendable", 'BOOL False True') - db.addSignalDefines("GenSigStartValue", 'FLOAT -3.4E+038 3.4E+038') - db.addSignalDefines("HexadecimalOutput", 'BOOL False True') - db.addSignalDefines("DisplayDecimalPlaces", 'INT 0 65535') - db.addSignalDefines("LongName", 'STR') + db.add_frame_defines("GenMsgCycleTime", 'INT 0 65535') + db.add_frame_defines("Receivable", 'BOOL False True') + db.add_frame_defines("Sendable", 'BOOL False True') + db.add_signal_defines("GenSigStartValue", 'FLOAT -3.4E+038 3.4E+038') + db.add_signal_defines("HexadecimalOutput", 'BOOL False True') + db.add_signal_defines("DisplayDecimalPlaces", 'INT 0 65535') + db.add_signal_defines("LongName", 'STR') for linecount, line in enumerate(f, 1): try: @@ -379,7 +379,7 @@ class Mode(object): for entry in tempArray: tempValTable[entry.split('=')[0].strip()] = entry.split('=')[ 1].replace('"', '').strip() - db.addValueTable(valtabName, tempValTable) + db.add_value_table(valtabName, tempValTable) elif mode in {Mode.send, Mode.sendReceive, Mode.receive}: if line.startswith('['): @@ -390,17 +390,17 @@ class Mode(object): # TODO: CAMPid 939921818394902983238 if frame is not None: if len(frame.mux_names) > 0: - frame.signalByName( + frame.signal_by_name( frame.name + "_MUX").values = frame.mux_names - db.addFrame(frame) + db.add_frame(frame) frame = Frame(frameName) - frame.addAttribute( + frame.add_attribute( 'Receivable', mode in {Mode.receive, Mode.sendReceive} ) - frame.addAttribute( + frame.add_attribute( 'Sendable', mode in {Mode.send, Mode.sendReceive} ) @@ -511,7 +511,7 @@ class Mode(object): # else: # print switch if tmpMux == "Mux": - signal = frame.signalByName(frameName + "_MUX") + signal = frame.signal_by_name(frameName + "_MUX") if signal is None: extras = {} if calc_min_for_none is not None: @@ -522,7 +522,7 @@ class Mode(object): # extras['float_factory'] = float_factory signal = Signal(frameName + "_MUX", - startBit=int(startBit), + start_bit=int(startBit), size=int(signalLength), is_little_endian=intel, is_signed=is_signed, @@ -537,11 +537,11 @@ class Mode(object): signal.min = float_factory(min) if max is not None: signal.max = float_factory(max) - # signal.addComment(comment) + # signal.add_comment(comment) if intel == 0: # motorola set/convert startbit - signal.setStartbit(startBit) - frame.addSignal(signal) + signal.set_startbit(startBit) + frame.add_signal(signal) signal.comments[multiplexor] = comment else: @@ -555,7 +555,7 @@ class Mode(object): # extras['float_factory'] = float_factory signal = Signal(sigName, - startBit=int(startBit), + start_bit=int(startBit), size=int(signalLength), is_little_endian=intel, is_signed=is_signed, @@ -573,22 +573,22 @@ class Mode(object): # if intel == 0: # motorola set/convert startbit - signal.setStartbit(startBit) + signal.set_startbit(startBit) if valueTableName is not None: - signal.values = db.valueTables[valueTableName] + signal.values = db.value_tables[valueTableName] signal.enumeration = valueTableName - # signal.addComment(comment) + # signal.add_comment(comment) # ... (1 / ...) because this somehow made 59.8/0.1 be 598.0 rather than 597.9999999999999 if startValue is not None: startValue = float_factory(startValue) * (1 / float_factory(factor)) - signal.addAttribute("GenSigStartValue", str(startValue)) - frame.addSignal(signal) + signal.add_attribute("GenSigStartValue", str(startValue)) + frame.add_signal(signal) if longName is not None: - signal.addAttribute("LongName", longName) + signal.add_attribute("LongName", longName) if hexadecimal_output: - signal.addAttribute("HexadecimalOutput", str(True)) + signal.add_attribute("HexadecimalOutput", str(True)) if displayDecimalPlaces is not None: - signal.addAttribute( + signal.add_attribute( "DisplayDecimalPlaces", displayDecimalPlaces) # variable processing elif line.startswith('ID'): @@ -598,7 +598,7 @@ class Mode(object): comment = split[1].strip() line = split[0].strip() frame.id = int(line.split('=')[1].strip()[:-1], 16) - frame.addComment(comment) + frame.add_comment(comment) elif line.startswith('Type'): if line.split('=')[1][:8] == "Extended": frame.extended = 1 @@ -606,7 +606,7 @@ class Mode(object): frame.size = int(line.split('=')[1]) elif line.startswith('CycleTime'): - frame.addAttribute( + frame.add_attribute( "GenMsgCycleTime", line.split('=')[1].strip()) # else: @@ -629,7 +629,7 @@ class Mode(object): # TODO: CAMPid 939921818394902983238 if frame is not None: if len(frame.mux_names) > 0: - frame.signalByName(frame.name + "_MUX").values = frame.mux_names - db.addFrame(frame) + frame.signal_by_name(frame.name + "_MUX").values = frame.mux_names + db.add_frame(frame) return db diff --git a/src/canmatrix/tests/test_canmatrix.py b/src/canmatrix/tests/test_canmatrix.py index 972c103c..27b4eeed 100644 --- a/src/canmatrix/tests/test_canmatrix.py +++ b/src/canmatrix/tests/test_canmatrix.py @@ -52,11 +52,11 @@ def test_encode_signal(): assert s6.phys2raw(s6.min) == 0 s7 = canmatrix.canmatrix.Signal('signal', size=8) - s7.addAttribute('GenSigStartValue', '5') + s7.add_attribute('GenSigStartValue', '5') assert s7.phys2raw() == 5 s8 = canmatrix.canmatrix.Signal('signal', size=8, is_signed=False, offset=5) - s8.addAttribute('GenSigStartValue', '5') + s8.add_attribute('GenSigStartValue', '5') assert s8.phys2raw() == 5 s9 = canmatrix.canmatrix.Signal('signal', size=16, is_signed=False, factor='0.001') @@ -119,36 +119,36 @@ def test_decode_signal(): # BoardUnit def test_ecu_find_attribute(): - ecu = canmatrix.canmatrix.BoardUnit(name="Gateway") - ecu.addAttribute("attr1", 255) + ecu = canmatrix.canmatrix.ecu(name="Gateway") + ecu.add_attribute("attr1", 255) assert ecu.attribute("attr1") == 255 def test_ecu_no_attribute(): - ecu = canmatrix.canmatrix.BoardUnit(name="Gateway") + ecu = canmatrix.canmatrix.ecu(name="Gateway") assert ecu.attribute("wrong") is None assert ecu.attribute("wrong", default=0) == 0 def test_ecu_default_attr_from_db(): - ecu = canmatrix.canmatrix.BoardUnit(name="Gateway") + ecu = canmatrix.canmatrix.ecu(name="Gateway") define = canmatrix.canmatrix.Define("INT 0 255") define.defaultValue = 33 - matrix = canmatrix.canmatrix.CanMatrix(buDefines={"temperature": define}) + matrix = canmatrix.canmatrix.CanMatrix(ecu_defines={"temperature": define}) assert ecu.attribute("temperature", db=matrix, default=2) == 33 assert ecu.attribute("wrong", db=matrix, default=2) == 2 def test_ecu_repr(): - ecu = canmatrix.canmatrix.BoardUnit(name="Gateway") - ecu.addComment("with bug") - assert str(ecu) == "BoardUnit(name='Gateway', comment='with bug')" + ecu = canmatrix.canmatrix.ecu(name="Gateway") + ecu.add_comment("with bug") + assert str(ecu) == "ecu(name='Gateway', comment='with bug')" # Signal (generic functions) def test_signal_has_comment(some_signal): comment = "comment01" - some_signal.addComment(comment) + some_signal.add_comment(comment) assert some_signal.comment == comment @@ -157,7 +157,7 @@ def test_signal_find_mandatory_attribute(some_signal): def test_signal_find_optional_attribute(some_signal): - some_signal.addAttribute("attr1", 255) + some_signal.add_attribute("attr1", 255) assert some_signal.attribute("attr1") == 255 @@ -172,112 +172,112 @@ def test_signal_no_attribute_with_default(some_signal): def test_signal_default_attr_from_db(some_signal): define = canmatrix.canmatrix.Define("INT 0 255") define.defaultValue = 33 - matrix = canmatrix.canmatrix.CanMatrix(signalDefines={"from_db": define}) + matrix = canmatrix.canmatrix.CanMatrix(signal_defines={"from_db": define}) assert some_signal.attribute("from_db", db=matrix, default=2) == 33 assert some_signal.attribute("wrong", db=matrix, default=2) == 2 def test_signal_no_duplicate_receiver(some_signal): - some_signal.addReceiver("GW01") - some_signal.addReceiver("GW01") + some_signal.add_receiver("GW01") + some_signal.add_receiver("GW01") assert some_signal.receiver == ["GW01"] def test_signal_delete_receiver(some_signal): - some_signal.addReceiver("GW01") - some_signal.addReceiver("ESP") - some_signal.delReceiver("GW01") + some_signal.add_receiver("GW01") + some_signal.add_receiver("ESP") + some_signal.del_receiver("GW01") assert some_signal.receiver == ["ESP"] def test_signal_delete_wrong_receiver_doesnt_raise(some_signal): - some_signal.delReceiver("wrong") + some_signal.del_receiver("wrong") def test_signal_has_attributes(some_signal): - some_signal.addAttribute("attr1", "val1") + some_signal.add_attribute("attr1", "val1") assert some_signal.attributes == {"attr1": "val1"} def test_signal_delete_attribute(some_signal): - some_signal.addAttribute("attr1", "val1") - some_signal.delAttribute("attr1") + some_signal.add_attribute("attr1", "val1") + some_signal.del_attribute("attr1") assert some_signal.attributes == {} def test_signal_delete_wrong_attribute_doesnt_raise(some_signal): - some_signal.delAttribute("wrong") + some_signal.del_attribute("wrong") def test_signal_spn(some_signal): assert some_signal.spn is None - some_signal.addAttribute("SPN", 10) + some_signal.add_attribute("SPN", 10) assert some_signal.spn == 10 def test_signal_set_startbit(): signal = canmatrix.canmatrix.Signal(size=16) - signal.setStartbit(2) - assert signal.startBit == 2 + signal.set_startbit(2) + assert signal.start_bit == 2 def test_signal_set_startbit_conversion(): signal = canmatrix.canmatrix.Signal(size=16, is_little_endian=False) - signal.setStartbit(20, startLittle=True) - assert signal.startBit == 5 # lsb on 20, msb is 20-15 = 5 + signal.set_startbit(20, startLittle=True) + assert signal.start_bit == 5 # lsb on 20, msb is 20-15 = 5 # TODO add test for reversed endianning def test_signal_set_startbit_raise(): signal = canmatrix.canmatrix.Signal(size=16, is_little_endian=False) with pytest.raises(Exception): - signal.setStartbit(5, startLittle=True) # lsb would be on -10 + signal.set_startbit(5, startLittle=True) # lsb would be on -10 def test_signal_get_startbit(): - signal_big = canmatrix.canmatrix.Signal(startBit=2, size=16, is_little_endian=True) - assert signal_big.getStartbit() == 2 + signal_big = canmatrix.canmatrix.Signal(start_bit=2, size=16, is_little_endian=True) + assert signal_big.get_startbit() == 2 def test_signal_get_startbit_conversion(): - signal_big = canmatrix.canmatrix.Signal(startBit=2, size=16, is_little_endian=False) - assert signal_big.getStartbit(startLittle=True) == 17 # looking for "end" of the signal: 2 + (16 - 1) + signal_big = canmatrix.canmatrix.Signal(start_bit=2, size=16, is_little_endian=False) + assert signal_big.get_startbit(start_little=True) == 17 # looking for "end" of the signal: 2 + (16 - 1) # TODO add test for reversed endianning def test_signal_range(): unsigned = canmatrix.canmatrix.Signal(size=8, is_signed=False) - assert unsigned.calculateRawRange() == (decimal.Decimal(0), decimal.Decimal(255)) + assert unsigned.calculate_raw_range() == (decimal.Decimal(0), decimal.Decimal(255)) signed = canmatrix.canmatrix.Signal(size=8) - assert signed.calculateRawRange() == (decimal.Decimal(-128), decimal.Decimal(127)) + assert signed.calculate_raw_range() == (decimal.Decimal(-128), decimal.Decimal(127)) def test_signal_set_min_max(): signal = canmatrix.canmatrix.Signal(size=8, offset=100) - signal.setMin(-5) - signal.setMax(30) + signal.set_min(-5) + signal.set_max(30) assert signal.min == -5 assert signal.max == 30 def test_signal_set_default_min_max(): signal = canmatrix.canmatrix.Signal(size=8, offset=100, min=-5, max=10) - signal.setMin(None) - signal.setMax(None) + signal.set_min(None) + signal.set_max(None) assert signal.min == -128 + 100 assert signal.max == 127 + 100 def test_signal_decode_named_value(some_signal): - some_signal.addValues(255, "Init") - some_signal.addValues(254, "Error") + some_signal.add_values(255, "Init") + some_signal.add_values(254, "Error") assert some_signal.raw2phys(254, decodeToStr=True) == "Error" assert some_signal.raw2phys(200, decodeToStr=True) == 200 def test_signal_encode_named_value(some_signal): - some_signal.addValues(255, "Init") - some_signal.addValues(254, "Error") + some_signal.add_values(255, "Init") + some_signal.add_values(254, "Error") assert some_signal.phys2raw("Error") == 254 @@ -328,7 +328,7 @@ def test_signal_max_specified_respects_calc_for_max_none_true(): def test_signal_range_type_int(): signal = canmatrix.Signal(is_float=False) - min, max = signal.calculateRawRange() + min, max = signal.calculate_raw_range() min_is = isinstance(min, int) max_is = isinstance(max, int) @@ -338,7 +338,7 @@ def test_signal_range_type_int(): def test_signal_range_type_float(): signal = canmatrix.Signal(is_float=True) - min, max = signal.calculateRawRange() + min, max = signal.calculate_raw_range() factory_type = type(signal.float_factory()) @@ -351,7 +351,7 @@ def test_signal_range_type_float(): # SignalGroup @pytest.fixture def the_group(): - return canmatrix.canmatrix.SignalGroup(name="TestGroup", id=1) + return canmatrix.canmatrix.signal_group(name="TestGroup", id=1) @pytest.fixture @@ -364,43 +364,43 @@ def test_signalgroup_empty(the_group): def test_signalgroup_can_add(the_group, some_signal): - the_group.addSignal(some_signal) + the_group.add_signal(some_signal) assert len(the_group.signals) == 1 def test_signalgroup_can_remove(the_group, some_signal): - the_group.addSignal(some_signal) - the_group.delSignal(some_signal) + the_group.add_signal(some_signal) + the_group.del_signal(some_signal) assert len(the_group.signals) == 0 def test_signalgroup_no_duplicates(the_group, some_signal): - the_group.addSignal(some_signal) - the_group.addSignal(some_signal) + the_group.add_signal(some_signal) + the_group.add_signal(some_signal) assert len(the_group.signals) == 1 def test_signalgroup_is_iterable(the_group, some_signal): - the_group.addSignal(some_signal) + the_group.add_signal(some_signal) assert [some_signal] == [s for s in the_group] def test_signalgroup_find_something(the_group, some_signal): - the_group.addSignal(some_signal) - assert some_signal == the_group.byName("speed") + the_group.add_signal(some_signal) + assert some_signal == the_group.by_name("speed") assert some_signal == the_group["speed"] def test_signalgroup_find_nothing(the_group, some_signal): - the_group.addSignal(some_signal) - assert the_group.byName("wrong") is None + the_group.add_signal(some_signal) + assert the_group.by_name("wrong") is None with pytest.raises(KeyError): _ = the_group["wrong"] def test_signalgroup_delete_nothing(the_group, some_signal): - the_group.addSignal(some_signal) - the_group.delSignal(canmatrix.canmatrix.Signal()) + the_group.add_signal(some_signal) + the_group.del_signal(canmatrix.canmatrix.Signal()) assert len(the_group.signals) == 1 @@ -409,7 +409,7 @@ def test_encode_decode_frame(): s1 = canmatrix.canmatrix.Signal('signal', size=32, is_float=True) f1 = canmatrix.canmatrix.Frame('frame', id=1, size=4) - f1.addSignal(s1) + f1.add_signal(s1) raw_bytes = f1.encode(input_data) decoded_data = f1.decode(raw_bytes) @@ -424,34 +424,34 @@ def empty_frame(): def test_frame_has_comment(empty_frame): - empty_frame.addComment("comm") + empty_frame.add_comment("comm") assert empty_frame.comment == "comm" def test_frame_compute_dlc(): frame = canmatrix.canmatrix.Frame() - frame.addSignal(canmatrix.canmatrix.Signal(startBit=0, size=2)) - frame.addSignal(canmatrix.canmatrix.Signal(startBit=8, size=1)) - frame.addSignal(canmatrix.canmatrix.Signal(startBit=2, size=2)) - frame.calcDLC() + frame.add_signal(canmatrix.canmatrix.Signal(start_bit=0, size=2)) + frame.add_signal(canmatrix.canmatrix.Signal(start_bit=8, size=1)) + frame.add_signal(canmatrix.canmatrix.Signal(start_bit=2, size=2)) + frame.calc_dlc() assert frame.size == 2 def test_frame_find_unused_bits(): frame = canmatrix.canmatrix.Frame(size=1) - frame.addSignal(canmatrix.canmatrix.Signal(name="sig1",startBit=0, size=3)) - frame.addSignal(canmatrix.canmatrix.Signal(name="sig2",startBit=4, size=2)) + frame.add_signal(canmatrix.canmatrix.Signal(name="sig1", start_bit=0, size=3)) + frame.add_signal(canmatrix.canmatrix.Signal(name="sig2", start_bit=4, size=2)) bit_usage = frame.get_frame_layout() assert bit_usage.count([]) == frame.size*8 - 3 - 2 - sig1 = frame.signalByName("sig1") - sig2 = frame.signalByName("sig2") + sig1 = frame.signal_by_name("sig1") + sig2 = frame.signal_by_name("sig2") assert bit_usage == [[], [], [sig2], [sig2], [], [sig1], [sig1], [sig1]] def test_frame_create_dummy_signals_covers_all_bits(): frame = canmatrix.canmatrix.Frame(size=1) - frame.addSignal(canmatrix.canmatrix.Signal(startBit=0, size=3)) - frame.addSignal(canmatrix.canmatrix.Signal(startBit=4, size=2)) + frame.add_signal(canmatrix.canmatrix.Signal(start_bit=0, size=3)) + frame.add_signal(canmatrix.canmatrix.Signal(start_bit=4, size=2)) frame.create_dummy_signals() assert len(frame.signals) == 2 + 2 assert frame.get_frame_layout().count([]) == 0 @@ -459,9 +459,9 @@ def test_frame_create_dummy_signals_covers_all_bits(): def test_frame_update_receivers(): frame = canmatrix.canmatrix.Frame(size=1) - frame.addSignal(canmatrix.canmatrix.Signal(startBit=0, size=3, receiver=["GW", "Keyboard"])) - frame.addSignal(canmatrix.canmatrix.Signal(startBit=4, size=2, receiver=["GW", "Display"])) - frame.updateReceiver() + frame.add_signal(canmatrix.canmatrix.Signal(start_bit=0, size=3, receiver=["GW", "Keyboard"])) + frame.add_signal(canmatrix.canmatrix.Signal(start_bit=4, size=2, receiver=["GW", "Display"])) + frame.update_receiver() assert frame.receivers == ["GW", "Keyboard", "Display"] @@ -473,15 +473,15 @@ def test_frame_to_str(): def test_frame_is_multiplexed(): frame = canmatrix.canmatrix.Frame(name="multiplexed_frame") signal = canmatrix.canmatrix.Signal(name="mx") - signal.multiplexSetter("Multiplexor") - frame.addSignal(signal) + signal.multiplex_setter("Multiplexor") + frame.add_signal(signal) assert frame.is_multiplexed def test_frame_not_multiplexed(): frame = canmatrix.canmatrix.Frame(name="not_multiplexed_frame") assert not frame.is_multiplexed - frame.addSignal(canmatrix.canmatrix.Signal(name="some")) + frame.add_signal(canmatrix.canmatrix.Signal(name="some")) assert not frame.is_multiplexed @@ -496,70 +496,70 @@ def test_frame_calc_j1939_id(): def test_frame_get_j1939_properties(): frame = canmatrix.canmatrix.Frame(j1939_source=0x11, j1939_pgn=0xFFFF, j1939_prio=1) - frame.recalcJ1939Id() # pgn property is computed from id! + frame.recalc_J1939_id() # pgn property is computed from id! assert frame.pgn == frame.j1939_pgn assert frame.source == frame.j1939_source assert frame.priority == frame.j1939_prio def test_frame_add_transmitter(empty_frame): - empty_frame.addTransmitter("BCM") + empty_frame.add_transmitter("BCM") assert empty_frame.transmitters == ["BCM"] def test_frame_add_transmitter_no_duplicities(empty_frame): - empty_frame.addTransmitter("BCM") - empty_frame.addTransmitter("BCM") + empty_frame.add_transmitter("BCM") + empty_frame.add_transmitter("BCM") assert empty_frame.transmitters == ["BCM"] def test_frame_delete_transmitter(empty_frame): - empty_frame.addTransmitter("MFL") - empty_frame.addTransmitter("BCM") - empty_frame.delTransmitter("MFL") + empty_frame.add_transmitter("MFL") + empty_frame.add_transmitter("BCM") + empty_frame.del_transmitter("MFL") assert empty_frame.transmitters == ["BCM"] def test_frame_delete_wrong_transmitter_doesnt_raise(empty_frame): - empty_frame.delTransmitter("wrong") + empty_frame.del_transmitter("wrong") def test_frame_find_signal(empty_frame): - empty_frame.addSignal(canmatrix.canmatrix.Signal("first")) + empty_frame.add_signal(canmatrix.canmatrix.Signal("first")) second_signal = canmatrix.canmatrix.Signal("second") - empty_frame.addSignal(second_signal) - empty_frame.addSignal(canmatrix.canmatrix.Signal("third")) - assert empty_frame.signalByName("second") == second_signal + empty_frame.add_signal(second_signal) + empty_frame.add_signal(canmatrix.canmatrix.Signal("third")) + assert empty_frame.signal_by_name("second") == second_signal def test_frame_find_missing_signal(empty_frame): - assert empty_frame.signalByName("wrong") is None + assert empty_frame.signal_by_name("wrong") is None def test_frame_glob_signals(empty_frame): audio_signal = canmatrix.canmatrix.Signal(name="front_audio_volume") - empty_frame.addSignal(audio_signal) - empty_frame.addSignal(canmatrix.canmatrix.Signal(name="display_dimming")) - assert empty_frame.globSignals("*audio*") == [audio_signal] + empty_frame.add_signal(audio_signal) + empty_frame.add_signal(canmatrix.canmatrix.Signal(name="display_dimming")) + assert empty_frame.glob_signals("*audio*") == [audio_signal] def test_frame_add_attribute(empty_frame): - empty_frame.addAttribute("attr1", "value1") + empty_frame.add_attribute("attr1", "value1") assert empty_frame.attributes == {"attr1": "value1"} def test_frame_del_attribute(empty_frame): - empty_frame.addAttribute("attr1", "value1") - empty_frame.delAttribute("attr1") + empty_frame.add_attribute("attr1", "value1") + empty_frame.del_attribute("attr1") assert "attr1" not in empty_frame.attributes def test_frame_del_missing_attribute_doesnt_raise(empty_frame): - empty_frame.delAttribute("wrong") + empty_frame.del_attribute("wrong") def test_frame_is_iterable(empty_frame, some_signal): - empty_frame.addSignal(some_signal) + empty_frame.add_signal(some_signal) assert [s for s in empty_frame] == [some_signal] @@ -568,7 +568,7 @@ def test_frame_find_mandatory_attribute(empty_frame): def test_frame_find_optional_attribute(empty_frame): - empty_frame.addAttribute("attr1", "str1") + empty_frame.add_attribute("attr1", "str1") assert empty_frame.attribute("attr1") == "str1" @@ -583,7 +583,7 @@ def test_frame_no_attribute_with_default(empty_frame): def test_frame_default_attr_from_db(empty_frame): define = canmatrix.canmatrix.Define("INT 0 255") define.defaultValue = 33 - matrix = canmatrix.canmatrix.CanMatrix(frameDefines={"from_db": define}) + matrix = canmatrix.canmatrix.CanMatrix(frame_defines={"from_db": define}) assert empty_frame.attribute("from_db", db=matrix, default=2) == 33 assert empty_frame.attribute("wrong", db=matrix, default=2) == 2 @@ -593,33 +593,33 @@ def test_frame_add_signal_group(empty_frame): signal_b = canmatrix.canmatrix.Signal(name="B") signal_c = canmatrix.canmatrix.Signal(name="C") empty_frame.signals = [signal_a, signal_b, signal_c] - empty_frame.addSignalGroup("AB", 0, ["A", "B"]) + empty_frame.add_signal_group("AB", 0, ["A", "B"]) assert empty_frame.signalGroups[0].signals == [signal_a, signal_b] def test_frame_add_signal_group_wrong_signal(empty_frame): signal_a = canmatrix.canmatrix.Signal(name="A") empty_frame.signals = [signal_a] - empty_frame.addSignalGroup("Aw", 0, ["A", "wrong", "\t"]) + empty_frame.add_signal_group("Aw", 0, ["A", "wrong", "\t"]) assert empty_frame.signalGroups[0].signals == [signal_a] def test_frame_find_signal_group(empty_frame): - empty_frame.addSignalGroup("G1", 1, []) - assert empty_frame.signalGroupByName("G1") is not None + empty_frame.add_signal_group("G1", 1, []) + assert empty_frame.signal_group_by_name("G1") is not None def test_frame_find_wrong_signal_group(empty_frame): - empty_frame.addSignalGroup("G1", 1, []) - assert empty_frame.signalGroupByName("wrong") is None + empty_frame.add_signal_group("G1", 1, []) + assert empty_frame.signal_group_by_name("wrong") is None # Define tests def test_define_set_default(): define = canmatrix.canmatrix.Define("") - define.setDefault("string") + define.set_default("string") assert define.defaultValue == "string" - define.setDefault('"quoted_string"') + define.set_default('"quoted_string"') assert define.defaultValue == "quoted_string" @@ -695,11 +695,11 @@ def test_canid_repr(): # DecodedSignal tests def test_decoded_signal_phys_value(some_signal): signal = canmatrix.canmatrix.Signal(factor="0.1", values={10: "Init"}) - decoded = canmatrix.canmatrix.DecodedSignal(100, signal) + decoded = canmatrix.canmatrix.decoded_signal(100, signal) assert decoded.phys_value == decimal.Decimal("10") def test_decoded_signal_named_value(): signal = canmatrix.canmatrix.Signal(factor="0.1", values={10: "Init"}) - decoded = canmatrix.canmatrix.DecodedSignal(100, signal) + decoded = canmatrix.canmatrix.decoded_signal(100, signal) assert decoded.named_value == "Init" diff --git a/src/canmatrix/tests/test_cmjson.py b/src/canmatrix/tests/test_cmjson.py index 4a0b4626..c3860e45 100644 --- a/src/canmatrix/tests/test_cmjson.py +++ b/src/canmatrix/tests/test_cmjson.py @@ -14,18 +14,18 @@ def default_matrix(): matrix = canmatrix.canmatrix.CanMatrix() some_define = canmatrix.Define("INT 0 65535") frame = canmatrix.canmatrix.Frame(name="test_frame", id=10) - frame.addAttribute("my_attribute1", "my_value1") + frame.add_attribute("my_attribute1", "my_value1") signal = canmatrix.canmatrix.Signal(name="test_signal", size=8) - signal.addValues(0xFF, "Init") - signal.addAttribute("my_attribute2", "my_value2") - frame.addSignal(signal) + signal.add_values(0xFF, "Init") + signal.add_attribute("my_attribute2", "my_value2") + frame.add_signal(signal) signal = canmatrix.canmatrix.Signal(name="multi", multiplex=True, size=3, unit="attosecond") - frame.addSignal(signal) + frame.add_signal(signal) - matrix.addFrame(frame) - matrix.frameDefines["my_attribute1"] = some_define - matrix.signalDefines["my_attribute2"] = some_define + matrix.add_frame(frame) + matrix.frame_defines["my_attribute1"] = some_define + matrix.signal_defines["my_attribute2"] = some_define return matrix @@ -50,11 +50,11 @@ def test_export_additional_frame_info(default_matrix): def test_export_long_signal_names(): matrix = canmatrix.canmatrix.CanMatrix() frame = canmatrix.canmatrix.Frame(name="test_frame", id=10) - matrix.addFrame(frame) + matrix.add_frame(frame) long_signal_name = "FAILURE_ZELL_UNTERTEMPERATUR_ENTLADEN_ALARM_IDX_01" assert len(long_signal_name) > 32 signal = canmatrix.canmatrix.Signal(name=long_signal_name, size=8) - frame.addSignal(signal) + frame.add_signal(signal) out_file = io.BytesIO() canmatrix.formats.dump(matrix, out_file, "cmjson", jsonAll=True) @@ -66,8 +66,8 @@ def test_export_min_max(): matrix = canmatrix.canmatrix.CanMatrix() frame = canmatrix.canmatrix.Frame(name="test_frame", size=6, id=10) signal = canmatrix.Signal(name="someSigName", size=40, min=-5, max=42) - frame.addSignal(signal) - matrix.addFrame(frame) + frame.add_signal(signal) + matrix.add_frame(frame) out_file = io.BytesIO() canmatrix.formats.dump(matrix, out_file, "cmjson", jsonAll=True) data = json.loads(out_file.getvalue().decode("utf-8")) diff --git a/src/canmatrix/tests/test_copy.py b/src/canmatrix/tests/test_copy.py index 5f89ba98..7a9ef684 100644 --- a/src/canmatrix/tests/test_copy.py +++ b/src/canmatrix/tests/test_copy.py @@ -5,12 +5,12 @@ def test_merge(): matrix1 = canmatrix.canmatrix.CanMatrix() frame1 = canmatrix.canmatrix.Frame("Frame1", id=1) - frame1.addSignal(canmatrix.canmatrix.Signal("SomeSignal")) - matrix1.addFrame(frame1) + frame1.add_signal(canmatrix.canmatrix.Signal("SomeSignal")) + matrix1.add_frame(frame1) matrix2 = canmatrix.canmatrix.CanMatrix() frame2 = canmatrix.canmatrix.Frame("Frame2", id=2) - matrix2.addFrame(frame2) + matrix2.add_frame(frame2) matrix1.merge([matrix2]) @@ -20,34 +20,34 @@ def test_merge(): def test_copy_ECU_with_frames(): matrix1 = canmatrix.canmatrix.CanMatrix() frame1 = canmatrix.canmatrix.Frame("Frame1", id=1) - frame1.addSignal(canmatrix.canmatrix.Signal("SomeSignal")) - matrix1.addFrame(frame1) + frame1.add_signal(canmatrix.canmatrix.Signal("SomeSignal")) + matrix1.add_frame(frame1) matrix2 = canmatrix.canmatrix.CanMatrix() frame2 = canmatrix.canmatrix.Frame("Frame2", id=2, transmitters= ["ECU"]) - matrix2.addFrame(frame2) - matrix2.updateEcuList() + matrix2.add_frame(frame2) + matrix2.update_ecu_list() canmatrix.copy.copyBUwithFrames("ECU", matrix2, matrix1) assert len(matrix1.frames) == 2 - assert len(matrix1.boardUnits) == 1 + assert len(matrix1.ecus) == 1 def test_copy_ECU_without_frames(): matrix1 = canmatrix.canmatrix.CanMatrix() frame1 = canmatrix.canmatrix.Frame("Frame1", id=1) - frame1.addSignal(canmatrix.canmatrix.Signal("SomeSignal")) - matrix1.addFrame(frame1) + frame1.add_signal(canmatrix.canmatrix.Signal("SomeSignal")) + matrix1.add_frame(frame1) matrix2 = canmatrix.canmatrix.CanMatrix() frame2 = canmatrix.canmatrix.Frame("Frame2", id=2, transmitters= ["ECU"]) - matrix2.addFrame(frame2) - matrix2.updateEcuList() - matrix2.addBUDefines("attrib", "STRING") - matrix2.boardUnitByName("ECU").addAttribute("attrib", "attribValue") + matrix2.add_frame(frame2) + matrix2.update_ecu_list() + matrix2.add_ecu_defines("attrib", "STRING") + matrix2.ecu_by_name("ECU").add_attribute("attrib", "attribValue") canmatrix.copy.copyBU("ECU", matrix2, matrix1) assert len(matrix1.frames) == 1 - assert len(matrix1.boardUnits) == 1 - assert matrix1.boardUnitByName("ECU") is not None \ No newline at end of file + assert len(matrix1.ecus) == 1 + assert matrix1.ecu_by_name("ECU") is not None \ No newline at end of file diff --git a/src/canmatrix/tests/test_dbc.py b/src/canmatrix/tests/test_dbc.py index 9d16d18d..8aaffb23 100644 --- a/src/canmatrix/tests/test_dbc.py +++ b/src/canmatrix/tests/test_dbc.py @@ -45,9 +45,9 @@ def test_enum_with_comma(): ''').encode('utf-8')) matrix = canmatrix.dbc.load(dbc, dbcImportEncoding="utf8") - assert matrix.frameDefines[u'example1'].values == ["Val 1","",""," ","'","(",")","[","]","/","-","|","{","}",";",":","<",">",".","?","!","@","#","$","%","^","&","=","`","~"] - assert matrix.signalDefines[u'example2'].values == ['Val1', ','] - assert matrix.buDefines[u'example4'].values == ['Val1', ','] + assert matrix.frame_defines[u'example1'].values == ["Val 1","",""," ","'","(",")","[","]","/","-","|","{","}",";",":","<",">",".","?","!","@","#","$","%","^","&","=","`","~"] + assert matrix.signal_defines[u'example2'].values == ['Val1', ','] + assert matrix.ecu_defines[u'example4'].values == ['Val1', ','] @pytest.mark.parametrize( 'character', @@ -62,37 +62,37 @@ def test_enum_with_special_character(character): BA_DEF_ BO_ "example1" ENUM "Val 1","{}"; ''').format(character[0]).encode('utf-8')) matrix = canmatrix.dbc.load(dbc, dbcImportEncoding="utf8") - assert matrix.frameDefines[u'example1'].values == ["Val 1",character[0]] + assert matrix.frame_defines[u'example1'].values == ["Val 1",character[0]] def test_export_of_unknown_defines(): db = canmatrix.CanMatrix() - db.addFrameDefines("Receivable", 'BOOL False True') - db.addFrameDefines("Sendable", 'BOOL False True') - for (dataType, define) in db.frameDefines.items(): + db.add_frame_defines("Receivable", 'BOOL False True') + db.add_frame_defines("Sendable", 'BOOL False True') + for (dataType, define) in db.frame_defines.items(): orig_definition = define.definition canmatrix.dbc.check_define(define) assert orig_definition != define.definition - db.addSignalDefines("LongName", 'STR') - for (dataType, define) in db.signalDefines.items(): + db.add_signal_defines("LongName", 'STR') + for (dataType, define) in db.signal_defines.items(): orig_definition = define.definition canmatrix.dbc.check_define(define) assert orig_definition != define.definition frame = canmatrix.Frame("someFrame") signal = canmatrix.Signal("SomeSignal") - signal.addAttribute("LongName", "EnableCalcIDCTrip Calc. IDC trip") - frame.addSignal(signal) - db.addFrame(frame) + signal.add_attribute("LongName", "EnableCalcIDCTrip Calc. IDC trip") + frame.add_signal(signal) + db.add_frame(frame) - db.addBUDefines("someName", 'STRING') - for (dataType, define) in db.buDefines.items(): + db.add_ecu_defines("someName", 'STRING') + for (dataType, define) in db.ecu_defines.items(): orig_definition = define.definition canmatrix.dbc.check_define(define) assert orig_definition == define.definition - db.addGlobalDefines("someGlobaName", 'BOOL') - for (dataType, define) in db.globalDefines.items(): + db.add_global_defines("someGlobaName", 'BOOL') + for (dataType, define) in db.global_defines.items(): orig_definition = define.definition canmatrix.dbc.check_define(define) assert orig_definition != define.definition diff --git a/src/canmatrix/tests/test_frame_decoding.py b/src/canmatrix/tests/test_frame_decoding.py index 8280553f..826d694d 100644 --- a/src/canmatrix/tests/test_frame_decoding.py +++ b/src/canmatrix/tests/test_frame_decoding.py @@ -11,7 +11,7 @@ def test_decode_with_dbc_big_endian(): # 001#8d00100100820100 frameData1 = bytearray([141, 0, 16, 1, 0, 130, 1, 0]) - frame1 = cm.frameById(1) + frame1 = cm.frame_by_id(1) decoded1 = frame1.decode(frameData1) assert decoded1["sig0"].raw_value == 1 assert decoded1["sig1"].raw_value == 35 @@ -29,7 +29,7 @@ def test_decode_with_dbc_little_endian(): cm = loadDbc() # 002#0C00057003001F83 frameData = bytearray([12, 0, 5, 112, 3, 0, 31, 131]) - frame = cm.frameById(2) + frame = cm.frame_by_id(2) decoded = frame.decode(frameData) assert decoded["secSig1"].raw_value == 0 assert decoded["secSig2"].raw_value == 0 @@ -48,7 +48,7 @@ def test_decode_with_too_little_dlc(): cm = loadDbc() # 002#0C00057003001F83 frameData = bytearray([12, 0, 5, 112, 3, 0, 31]) - frame = cm.frameById(2) + frame = cm.frame_by_id(2) try: decoded = frame.decode(frameData) except canmatrix.DecodingFrameLength: @@ -58,7 +58,7 @@ def test_decode_with_too_little_dlc(): def test_decode_with_too_big_dlc(): cm = loadDbc() frameData1 = bytearray([0x38, 0x63, 0x8A, 0x7E, 0x00, 0x20, 0x00, 0x00]) - frame = cm.frameById(4) + frame = cm.frame_by_id(4) try: decoded1 = frame.decode(frameData1) except canmatrix.DecodingFrameLength: @@ -70,7 +70,7 @@ def test_decode_with_dbc_float(): cm = loadDbc() # 003#38638A7E58A8C540 frameData = bytearray([0x38, 0x63, 0x8A, 0x7E, 0x58, 0xA8, 0xC5, 0x40]) - frame = cm.frameById(3) + frame = cm.frame_by_id(3) decoded = frame.decode(frameData) assert decoded["floatSignal1"].raw_value == 5.424999835668132e-05 assert decoded["floatSignal2"].raw_value == 6.176799774169922 @@ -79,7 +79,7 @@ def test_decode_with_dbc_float(): def test_decode_with_dbc_multiplex(): cm = loadDbc() frameData1 = bytearray([0x38, 0x63, 0x8A, 0x7E, 0x00, 0x20, 0x00]) - frame = cm.frameById(4) + frame = cm.frame_by_id(4) decoded1 = frame.decode(frameData1) assert decoded1["myMuxer"].raw_value == 0 assert decoded1["muxSig9"].raw_value == 0x20 diff --git a/src/canmatrix/tests/test_frame_encoding.py b/src/canmatrix/tests/test_frame_encoding.py index cf876548..257e7c8e 100644 --- a/src/canmatrix/tests/test_frame_encoding.py +++ b/src/canmatrix/tests/test_frame_encoding.py @@ -15,7 +15,7 @@ def loadDbc(): def test_encode_with_dbc_big_endian(): cm = loadDbc() # 002#0C00057003CD1F83 - frame = cm.frameById(1) + frame = cm.frame_by_id(1) toEncode = dict() @@ -38,7 +38,7 @@ def test_encode_with_dbc_big_endian(): def test_encode_with_dbc_little_endian(): cm = loadDbc() # 002#0C00057003CD1F83 - frame = cm.frameById(2) + frame = cm.frame_by_id(2) toEncode = dict() toEncode["secSig1"] = 0 @@ -61,7 +61,7 @@ def test_encode_with_dbc_little_endian(): def test_encode_with_dbc_float(): cm = loadDbc() # 003#38638A7E58A8C540 - frame = cm.frameById(3) + frame = cm.frame_by_id(3) toEncode = dict() toEncode["floatSignal1"] = 5.424999835668132e-05 @@ -72,7 +72,7 @@ def test_encode_with_dbc_float(): def test_encode_with_dbc_multiplex(): cm = loadDbc() - frame = cm.frameById(4) + frame = cm.frame_by_id(4) toEncode1 = dict() toEncode1["myMuxer"] = 0 toEncode1["muxSig9"] = 0x20 @@ -137,8 +137,8 @@ def test_sym(): f = io.BytesIO(s.encode('utf-8')) matrix = canmatrix.formats.load(f, importType='sym', flatImport=True) - unsigned_frame = matrix.frameByName('Unsigned') - signed_frame = matrix.frameByName('Signed') + unsigned_frame = matrix.frame_by_name('Unsigned') + signed_frame = matrix.frame_by_name('Signed') @attr.s(frozen=True) class TestFrame(object): diff --git a/src/canmatrix/tests/test_sym.py b/src/canmatrix/tests/test_sym.py index a7f1de20..586f0e0f 100644 --- a/src/canmatrix/tests/test_sym.py +++ b/src/canmatrix/tests/test_sym.py @@ -83,18 +83,18 @@ def test_parse_longname_with_colon(): def test_export_default_decimal_places(is_float, value, expected): matrix = canmatrix.canmatrix.CanMatrix() # the `FLOAT` type here is irrelevant at the moment... at least for this - matrix.addSignalDefines('GenSigStartValue', 'FLOAT -3.4E+038 3.4E+038') + matrix.add_signal_defines('GenSigStartValue', 'FLOAT -3.4E+038 3.4E+038') frame = canmatrix.canmatrix.Frame() - matrix.addFrame(frame) + matrix.add_frame(frame) signal = canmatrix.canmatrix.Signal( size=32, is_float=is_float, is_signed=False, ) - signal.addAttribute('GenSigStartValue', value) - frame.addSignal(signal) + signal.add_attribute('GenSigStartValue', value) + frame.add_signal(signal) s = canmatrix.sym.createSignal(db=matrix, signal=signal) diff --git a/src/canmatrix/xls.py b/src/canmatrix/xls.py index 0764a577..7db57e81 100644 --- a/src/canmatrix/xls.py +++ b/src/canmatrix/xls.py @@ -136,7 +136,7 @@ def dump(db, file, **options): # write frameardunits in first row: buList = [] - for bu in db.boardUnits: + for bu in db.ecus: buList.append(bu.name) rowArray += head_top @@ -191,7 +191,7 @@ def dump(db, file, **options): # sort signals: sigHash = {} for sig in frame.signals: - sigHash["%02d" % int(sig.getStartbit()) + sig.name] = sig + sigHash["%02d" % int(sig.get_startbit()) + sig.name] = sig # set style for first line with border sigstyle = sty_first_frame @@ -338,14 +338,14 @@ def load(file, **options): # Defines not imported... # db.addBUDefines("NWM-Stationsadresse", 'HEX 0 63') # db.addBUDefines("NWM-Knoten", 'ENUM "nein","ja"') - db.addFrameDefines("GenMsgCycleTime", 'INT 0 65535') - db.addFrameDefines("GenMsgDelayTime", 'INT 0 65535') - db.addFrameDefines("GenMsgCycleTimeActive", 'INT 0 65535') - db.addFrameDefines("GenMsgNrOfRepetitions", 'INT 0 65535') + db.add_frame_defines("GenMsgCycleTime", 'INT 0 65535') + db.add_frame_defines("GenMsgDelayTime", 'INT 0 65535') + db.add_frame_defines("GenMsgCycleTimeActive", 'INT 0 65535') + db.add_frame_defines("GenMsgNrOfRepetitions", 'INT 0 65535') # db.addFrameDefines("GenMsgStartValue", 'STRING') launchTypes = [] # db.addSignalDefines("GenSigStartValue", 'HEX 0 4294967295') - db.addSignalDefines("GenSigSNA", 'STRING') + db.add_signal_defines("GenSigSNA", 'STRING') # eval search for correct columns: index = {} @@ -395,7 +395,7 @@ def load(file, **options): # BoardUnits: for x in range(index['BUstart'], index['BUend']): - db.addEcu(BoardUnit(sh.cell(0, x).value)) + db.add_ecu(ecu(sh.cell(0, x).value)) # initialize: frameId = None @@ -426,11 +426,11 @@ def load(file, **options): newBo = Frame(frameName, id=int(frameId[:-2], 16), size=dlc, extended = True) else: newBo = Frame(frameName, id=int(frameId[:-1], 16), size=dlc) - db.addFrame(newBo) + db.add_frame(newBo) # eval launctype if launchType is not None: - newBo.addAttribute("GenMsgSendType", launchType) + newBo.add_attribute("GenMsgSendType", launchType) if launchType not in launchTypes: launchTypes.append(launchType) @@ -439,7 +439,7 @@ def load(file, **options): cycleTime = int(cycleTime) except: cycleTime = 0 - newBo.addAttribute("GenMsgCycleTime", str(int(cycleTime))) + newBo.add_attribute("GenMsgCycleTime", str(int(cycleTime))) for additionalIndex in additionalInputs: if "frame" in additionalInputs[additionalIndex]: @@ -483,12 +483,12 @@ def load(file, **options): if signalName != "-": for x in range(index['BUstart'], index['BUend']): if 's' in sh.cell(rownum, x).value: - newBo.addTransmitter(sh.cell(0, x).value.strip()) + newBo.add_transmitter(sh.cell(0, x).value.strip()) if 'r' in sh.cell(rownum, x).value: receiver.append(sh.cell(0, x).value.strip()) # if signalLength > 8: newSig = Signal(signalName, - startBit=(startbyte - 1) * 8 + startbit, + start_bit=(startbyte - 1) * 8 + startbit, size=int(signalLength), is_little_endian=is_little_endian, is_signed=is_signed, @@ -499,12 +499,12 @@ def load(file, **options): if not is_little_endian: # motorola if motorolaBitFormat == "msb": - newSig.setStartbit( + newSig.set_startbit( (startbyte - 1) * 8 + startbit, bitNumbering=1) elif motorolaBitFormat == "msbreverse": - newSig.setStartbit((startbyte - 1) * 8 + startbit) + newSig.set_startbit((startbyte - 1) * 8 + startbit) else: # motorolaBitFormat == "lsb" - newSig.setStartbit( + newSig.set_startbit( (startbyte - 1) * 8 + startbit, bitNumbering=1, startLittle=True) @@ -517,8 +517,8 @@ def load(file, **options): if(len(str(sh.cell(rownum, additionalIndex).value)) > 0): exec (commandStr) - newBo.addSignal(newSig) - newSig.addComment(signalComment) + newBo.add_signal(newSig) + newSig.add_comment(signalComment) function = sh.cell(rownum, index['function']).value @@ -565,17 +565,17 @@ def load(file, **options): newSig.offset = offset if value_table is not None: for value, name in value_table.items(): - newSig.addValues(value, name) + newSig.add_values(value, name) for frame in db.frames: - frame.updateReceiver() - frame.calcDLC() + frame.update_receiver() + frame.calc_dlc() launchTypeEnum = "ENUM" for launchType in launchTypes: if len(launchType) > 0: launchTypeEnum += ' "' + launchType + '",' - db.addFrameDefines("GenMsgSendType", launchTypeEnum[:-1]) + db.add_frame_defines("GenMsgSendType", launchTypeEnum[:-1]) - db.setFdType() + db.set_fd_type() return db diff --git a/src/canmatrix/xls_common.py b/src/canmatrix/xls_common.py index 3c33502c..930d78dd 100644 --- a/src/canmatrix/xls_common.py +++ b/src/canmatrix/xls_common.py @@ -30,14 +30,14 @@ def getFrameInfo(db, frame): # frame-Name retArray.append(frame.name) - if "GenMsgCycleTime" in db.frameDefines: + if "GenMsgCycleTime" in db.frame_defines: # determin cycle-time retArray.append(frame.attribute("GenMsgCycleTime", db=db)) # determin send-type - if "GenMsgSendType" in db.frameDefines: + if "GenMsgSendType" in db.frame_defines: retArray.append(frame.attribute("GenMsgSendType", db=db)) - if "GenMsgDelayTime" in db.frameDefines: + if "GenMsgDelayTime" in db.frame_defines: retArray.append(frame.attribute("GenMsgDelayTime", db=db)) else: retArray.append("") @@ -51,11 +51,11 @@ def getSignal(db, sig, motorolaBitFormat): frontArray = [] backArray = [] if motorolaBitFormat == "msb": - startBit = sig.getStartbit(bitNumbering=1) + startBit = sig.get_startbit(bit_numbering=1) elif motorolaBitFormat == "msbreverse": - startBit = sig.getStartbit() + startBit = sig.get_startbit() else: # motorolaBitFormat == "lsb" - startBit = sig.getStartbit(bitNumbering=1, startLittle=True) + startBit = sig.get_startbit(bit_numbering=1, start_little=True) # startbyte frontArray.append(int(startBit / 8) + 1) @@ -81,10 +81,10 @@ def getSignal(db, sig, motorolaBitFormat): frontArray.append(sig.size) # startvalue of signal available - if "GenSigStartValue" in db.signalDefines: - if db.signalDefines["GenSigStartValue"].definition == "STRING": + if "GenSigStartValue" in db.signal_defines: + if db.signal_defines["GenSigStartValue"].definition == "STRING": frontArray.append(sig.attribute("GenSigStartValue", db=db)) - elif db.signalDefines["GenSigStartValue"].definition == "INT" or db.signalDefines["GenSigStartValue"].definition == "HEX": + elif db.signal_defines["GenSigStartValue"].definition == "INT" or db.signal_defines["GenSigStartValue"].definition == "HEX": frontArray.append("%Xh" % sig.attribute("GenSigStartValue", db=db)) else: frontArray.append(" ") @@ -92,7 +92,7 @@ def getSignal(db, sig, motorolaBitFormat): frontArray.append(" ") # SNA-value of signal available - if "GenSigSNA" in db.signalDefines: + if "GenSigSNA" in db.signal_defines: sna = sig.attribute("GenSigSNA", db=db) if sna is not None: sna = sna[1:-1] diff --git a/src/canmatrix/xlsx.py b/src/canmatrix/xlsx.py index 96feaace..fd3b9006 100644 --- a/src/canmatrix/xlsx.py +++ b/src/canmatrix/xlsx.py @@ -177,7 +177,7 @@ def dump(db, filename, **options): # write frameardunits in first row: buList = [] - for bu in db.boardUnits: + for bu in db.ecus: buList.append(bu.name) rowArray += buList @@ -224,7 +224,7 @@ def dump(db, filename, **options): # sort signals: sigHash = {} for sig in frame.signals: - sigHash["%02d" % int(sig.getStartbit()) + sig.name] = sig + sigHash["%02d" % int(sig.get_startbit()) + sig.name] = sig # set style for first line with border sigstyle = sty_first_frame @@ -333,7 +333,7 @@ def dump(db, filename, **options): # loop over frames ends here worksheet.autofilter(0, 0, row, len(head_top) + - len(head_tail) + len(db.boardUnits)) + len(head_tail) + len(db.ecus)) worksheet.freeze_panes(1, 0) # save file workbook.close() @@ -443,13 +443,13 @@ def load(filename, **options): letterIndex.append("%s%s" % (a, b)) # Defines not imported... - db.addFrameDefines("GenMsgCycleTime", 'INT 0 65535') - db.addFrameDefines("GenMsgDelayTime", 'INT 0 65535') - db.addFrameDefines("GenMsgCycleTimeActive", 'INT 0 65535') - db.addFrameDefines("GenMsgNrOfRepetitions", 'INT 0 65535') + db.add_frame_defines("GenMsgCycleTime", 'INT 0 65535') + db.add_frame_defines("GenMsgDelayTime", 'INT 0 65535') + db.add_frame_defines("GenMsgCycleTimeActive", 'INT 0 65535') + db.add_frame_defines("GenMsgNrOfRepetitions", 'INT 0 65535') launchTypes = [] - db.addSignalDefines("GenSigSNA", 'STRING') + db.add_signal_defines("GenSigSNA", 'STRING') if 'Byteorder' in list(sheet[0].values()): for key in sheet[0]: @@ -467,7 +467,7 @@ def load(filename, **options): # BoardUnits: for x in range(_BUstart, _BUend): - db.addEcu(BoardUnit(sheet[0][letterIndex[x]])) + db.add_ecu(ecu(sheet[0][letterIndex[x]])) # initialize: frameId = None @@ -497,18 +497,18 @@ def load(filename, **options): else: newBo = Frame(frameName, id=int(frameId[:-1], 16), size=dlc) - db.addFrame(newBo) + db.add_frame(newBo) # eval launchtype if launchType is not None: - newBo.addAttribute("GenMsgSendType", launchType) + newBo.add_attribute("GenMsgSendType", launchType) if launchType not in launchTypes: launchTypes.append(launchType) # #eval cycletime if type(cycleTime).__name__ != "float": cycleTime = 0.0 - newBo.addAttribute("GenMsgCycleTime", str(int(cycleTime))) + newBo.add_attribute("GenMsgCycleTime", str(int(cycleTime))) # new signal detected if 'Signal Name' in row and row['Signal Name'] != signalName: @@ -547,7 +547,7 @@ def load(filename, **options): buSenderReceiver = getIfPossible(row, buName) if buSenderReceiver is not None: if 's' in buSenderReceiver: - newBo.addTransmitter(buName) + newBo.add_transmitter(buName) if 'r' in buSenderReceiver: receiver.append(buName) # if signalLength > 8: @@ -565,18 +565,18 @@ def load(filename, **options): if is_little_endian == False: # motorola if motorolaBitFormat == "msb": - newSig.setStartbit( + newSig.set_startbit( (startbyte - 1) * 8 + startbit, bitNumbering=1) elif motorolaBitFormat == "msbreverse": - newSig.setStartbit((startbyte - 1) * 8 + startbit) + newSig.set_startbit((startbyte - 1) * 8 + startbit) else: # motorolaBitFormat == "lsb" - newSig.setStartbit( + newSig.set_startbit( (startbyte - 1) * 8 + startbit, bitNumbering=1, startLittle=True) - newBo.addSignal(newSig) - newSig.addComment(signalComment) + newBo.add_signal(newSig) + newSig.add_comment(signalComment) function = getIfPossible(row, 'Function / Increment Unit') value = getIfPossible(row, 'Value') valueName = getIfPossible(row, 'Name / Phys. Range') @@ -621,7 +621,7 @@ def load(filename, **options): elif valueName.__len__() > 0: if value is not None and value.strip().__len__() > 0: value = int(float(value)) - newSig.addValues(value, valueName) + newSig.add_values(value, valueName) maxi = pow(2, signalLength) - 1 newSig.max = float(maxi) else: @@ -631,14 +631,14 @@ def load(filename, **options): # dlc-estimation / dlc is not in xls, thus calculate a minimum-dlc: for frame in db.frames: - frame.updateReceiver() - frame.calcDLC() + frame.update_receiver() + frame.calc_dlc() launchTypeEnum = "ENUM" for launchType in launchTypes: if len(launchType) > 0: launchTypeEnum += ' "' + launchType + '",' - db.addFrameDefines("GenMsgSendType", launchTypeEnum[:-1]) + db.add_frame_defines("GenMsgSendType", launchTypeEnum[:-1]) - db.setFdType() + db.set_fd_type() return db diff --git a/src/canmatrix/yaml.py b/src/canmatrix/yaml.py index f805a91d..238a3c30 100644 --- a/src/canmatrix/yaml.py +++ b/src/canmatrix/yaml.py @@ -57,8 +57,8 @@ def dump(db, f, **options): for i, frame in enumerate(newdb.frames): for j, signal in enumerate(frame.signals): if signal.is_little_endian == False: - signal.startbit = signal.getStartbit( - bitNumbering=1, startLittle=True) + signal.startbit = signal.get_startbit( + bit_numbering=1, start_little=True) # newdb.frames[i].signals[j].startbit = signal.startbit # f = open(filename, "w") @@ -112,7 +112,7 @@ def signal_constructor(loader, node): ) if signal.is_little_endian == False: - signal.setStartbit( + signal.set_startbit( loader.construct_mapping(node)['_startbit'], bitNumbering=1, startLittle=False) diff --git a/test/createTestFdMatrix.py b/test/createTestFdMatrix.py index 42bf950b..e7316e0f 100755 --- a/test/createTestFdMatrix.py +++ b/test/createTestFdMatrix.py @@ -11,8 +11,8 @@ db = canmatrix.CanMatrix() -db.boardUnits.add(canmatrix.BoardUnit("testBU")) -db.boardUnits.add(canmatrix.BoardUnit("recBU")) +db.ecus.add(canmatrix.ecu("testBU")) +db.ecus.add(canmatrix.ecu("recBU")) myFrame1 = canmatrix.Frame("canFdStandard1",Id=1, dlc=24, is_fd = True, transmitter=["testBU"]) myFrame2 = canmatrix.Frame("CanFdExtended2",Id=2, dlc=16, extended = True, is_fd = True, transmitter=["testBU"]) @@ -23,19 +23,19 @@ mySignal2 = canmatrix.Signal("signal2", signalSize=64, startBit=64, is_little_endian=True, min=0, max=0, is_signed=True, receiver=["recBU"]) mySignal3 = canmatrix.Signal("signal3", signalSize=64, startBit=128, is_little_endian=True, min=0, max=0, is_signed=True) -myFrame1.addSignal(mySignal3) -myFrame1.addSignal(mySignal2) -myFrame1.addSignal(mySignal1) +myFrame1.add_signal(mySignal3) +myFrame1.add_signal(mySignal2) +myFrame1.add_signal(mySignal1) -myFrame2.addSignal(mySignal2) -myFrame2.addSignal(mySignal1) +myFrame2.add_signal(mySignal2) +myFrame2.add_signal(mySignal1) -db.frames.addFrame(myFrame1) -db.frames.addFrame(myFrame2) -db.frames.addFrame(myFrame3) -db.frames.addFrame(myFrame4) +db.frames.add_frame(myFrame1) +db.frames.add_frame(myFrame2) +db.frames.add_frame(myFrame3) +db.frames.add_frame(myFrame4) # diff --git a/test/createTestMatrix.py b/test/createTestMatrix.py index 61bc80cc..731d6aa7 100755 --- a/test/createTestMatrix.py +++ b/test/createTestMatrix.py @@ -12,8 +12,8 @@ db = CanMatrix() -db.boardUnits.add(BoardUnit("testBU")) -db.boardUnits.add(BoardUnit("recBU")) +db.ecus.add(ecu("testBU")) +db.ecus.add(ecu("recBU")) myFrame = Frame("testFrame1", Id=0x123, dlc=8, transmitter="testBU") @@ -34,7 +34,7 @@ max=500, unit=u"specialCharUnitĀ°$", #.decode("utf-8"), receiver=["recBU"]) -mySignal.setStartbit(9, bitNumbering=1, startLittle=True) +mySignal.set_startbit(9, bitNumbering=1, startLittle=True) mySignal2 = Signal("Signal", startBit=20, signalSize=3, @@ -47,30 +47,30 @@ unit="someUnit", receiver=["recBU"]) -mySignal2.addValues(1, "one") -mySignal2.addValues(2, "two") -mySignal2.addValues(3, "three") +mySignal2.add_values(1, "one") +mySignal2.add_values(2, "two") +mySignal2.add_values(3, "three") -mySignal.addComment(comment ) -myFrame.addComment("Multi \n Line \n Frame comment") +mySignal.add_comment(comment) +myFrame.add_comment("Multi \n Line \n Frame comment") -myFrame.addSignal(mySignal) -myFrame.addSignal(mySignal2) +myFrame.add_signal(mySignal) +myFrame.add_signal(mySignal2) myFrame2 = Frame("extendedFrame", Id=0x12, dlc=8, transmitter="testBU") myFrame2.extended = 1 -db.frames.addFrame(myFrame) -db.frames.addFrame(myFrame2) +db.frames.add_frame(myFrame) +db.frames.add_frame(myFrame2) -db.boardUnitByName("testBU").addComment("sender ECU") -db.boardUnitByName("testBU").addAttribute("NetworkNode", 0x111) -db.boardUnitByName("recBU").addComment("receiver ECU") +db.ecu_by_name("testBU").add_comment("sender ECU") +db.ecu_by_name("testBU").add_attribute("NetworkNode", 0x111) +db.ecu_by_name("recBU").add_comment("receiver ECU") -db.frameByName("testFrame1").addAttribute("GenMsgCycleTime", 100) +db.frame_by_name("testFrame1").add_attribute("GenMsgCycleTime", 100) -db.addFrameDefines("GenMsgCycleTime", 'INT 0 65535') -db.addBUDefines("NetworkNode", 'INT 0 65535') +db.add_frame_defines("GenMsgCycleTime", 'INT 0 65535') +db.add_ecu_defines("NetworkNode", 'INT 0 65535') #