コード例 #1
0
    def data(self, column, role):
        if column != 2:
            return super(FieldItem, self).data(column, role)

        alert = Messaging.getAlert(self.msg, self.fieldInfo)
        if role == Qt.FontRole:
            font = QFont()
            if alert == 1:
                font.setBold(1)
            return font
        if role == Qt.ForegroundRole:
            brush = QBrush()
            if alert == 1:
                brush.setColor(Qt.red)
            return brush

        if role == Qt.DisplayRole:
            value  = Messaging.get(self.msg, self.fieldInfo)
            
            try:
                self.overrideWidget
                valueAsString = Messaging.get(self.msg, self.fieldInfo)
                
                if valueAsString in self.comboBoxIndexOfEnum:
                    #self.overrideWidget.setCurrentText(valueAsString)
                    self.overrideWidget.setCurrentIndex(self.comboBoxIndexOfEnum[valueAsString])
                else:
                    #self.overrideWidget.setEditText(valueAsString)
                    self.overrideWidget.setCurrentIndex(-1)
            except AttributeError:
                pass
                
            return str(value)
            
        return super(FieldItem, self).data(column, role)
コード例 #2
0
    def store_message(self, msg):
        try:
            timeVal = msg.hdr.GetTime()
            timeInfo = Messaging.findFieldInfo(msg.hdr.fields, "Time")
            # if it's not big enough to be an absolute timestamp, give up on using it and just use current time
            if float(timeInfo.maxVal) <= 2**32:
                raise AttributeError
            if timeInfo.units == "ms":
                timeVal = timeVal / 1000.0
            timeVal = datetime.datetime.fromtimestamp(timeVal,
                                                      datetime.timezone.utc)
        except AttributeError:
            timeVal = datetime.datetime.now()

        dbJson = {
            "time": str(timeVal),
            "measurement": msg.MsgName(),
            'fields': {},
            'tags': {}
        }

        for fieldInfo in msg.hdr.fields:
            if len(fieldInfo.bitfieldInfo) == 0:
                if fieldInfo.idbits == 0 and fieldInfo.name != "Time" and fieldInfo.name != "DataLength":
                    dbJson['tags'][fieldInfo.name] = Messaging.get(
                        msg.hdr, fieldInfo)
            else:
                for bitInfo in fieldInfo.bitfieldInfo:
                    if bitInfo.idbits == 0 and bitInfo.name != "Time" and bitInfo.name != "DataLength":
                        dbJson['tags'][bitInfo.name] = Messaging.get(
                            msg.hdr, bitInfo)

        msgClass = type(msg)
        for fieldInfo in msgClass.fields:
            if fieldInfo.count == 1:
                if len(fieldInfo.bitfieldInfo) == 0:
                    dbJson['fields'][
                        fieldInfo.name] = InfluxDBConnection.GetDBValue(
                            msg, fieldInfo)
                else:
                    for bitInfo in fieldInfo.bitfieldInfo:
                        dbJson['fields'][
                            bitInfo.name] = InfluxDBConnection.GetDBValue(
                                msg, bitInfo)
            # leave out arrays until we figure out how to handle them
            #else:
            #    arrayList = []
            #    for i in range(0,fieldInfo.count):
            #        arrayList.append(InfluxDBConnection.GetDBValue(msg, fieldInfo, i))
            #    dbJson['fields'][fieldInfo.name] = arrayList

        #print("Create a retention policy")
        #retention_policy = 'awesome_policy'
        #client.create_retention_policy(retention_policy, '3d', 3, default=True)
        self.db.write_points([dbJson])  #, retention_policy=retention_policy)
コード例 #3
0
ファイル: lumberjack.py プロジェクト: jkominek/MsgTools
    def ProcessMessage(self, msg):
        self.messageCount += 1

        # if we write CSV to multiple files, we'd probably look up a hash table for this message id,
        # and open it and write a header
        if (id in self.outputFiles):
            outputFile = self.outputFiles[id]
        else:
            # create a new file
            outputFile = open(
                self.outputName + "/" + msg.MsgName().replace("/", "_") +
                ".csv", 'w')

            # store a pointer to it, so we can find it next time (instead of creating it again)
            self.outputFiles[id] = outputFile

            # add table header, one column for each message field
            tableHeader = "Time (ms), "
            for fieldInfo in type(msg).fields:
                tableHeader += fieldInfo.name + ", "
                for bitInfo in fieldInfo.bitfieldInfo:
                    tableHeader += bitInfo.name + ", "
            tableHeader += '\n'
            outputFile.write(tableHeader)

        try:
            # \todo Detect time rolling.  this only matters when we're processing a log file
            # with insufficient timestamp size, such that time rolls over from a large number
            # to a small one, during the log.
            thisTimestamp = msg.hdr.GetTime()
            if thisTimestamp < self._lastTimestamp:
                self._timestampOffset += 1

            self._lastTimestamp = thisTimestamp

            # instead of left shifting by 16, we should use the actual size in bits of the timestamp field!
            text = str((self._timestampOffset << 16) + thisTimestamp) + ", "
        except AttributeError:
            text = "unknown, "

        for fieldInfo in type(msg).fields:
            if (fieldInfo.count == 1):
                columnText = str(Messaging.get(msg, fieldInfo)) + ", "
                for bitInfo in fieldInfo.bitfieldInfo:
                    columnText += str(Messaging.get(msg, bitInfo)) + ", "
            else:
                columnText = ""
                for i in range(0, fieldInfo.count):
                    columnText += str(Messaging.get(msg, fieldInfo, i)) + ", "
            text += columnText
        text += '\n'
        outputFile.write(text)
コード例 #4
0
 def PrintAccessors(self, msgClass):
     msg = msgClass()
     for fieldInfo in msgClass.fields:
         txt = "body.%s.%s: " % (msgClass.__name__, fieldInfo.name)
         if (fieldInfo.count == 1):
             txt += str(Messaging.get(msg, fieldInfo))
         else:
             for i in range(0, fieldInfo.count):
                 #print("body.",msgClass.__name__, ".", method.__name__, "[",i,"] = ", method(msg,i), " #", method.__doc__, "in", method.units)
                 txt += str(Messaging.get(msg, fieldInfo, i))
                 if (i < fieldInfo.count - 1):
                     txt += ", "
         txt += " # " + fieldInfo.description + " in " + fieldInfo.units
         print(txt)
コード例 #5
0
ファイル: Test.py プロジェクト: MilesEngineering/MsgTools
 def PrintAccessors(self, msgClass):
     msg = msgClass()
     for fieldInfo in msgClass.fields:
         txt = "body.%s.%s: " % (msgClass.__name__, fieldInfo.name)
         if(fieldInfo.count == 1):
             txt += str(Messaging.get(msg, fieldInfo))
         else:
             for i in range(0,fieldInfo.count):
                 #print("body.",msgClass.__name__, ".", method.__name__, "[",i,"] = ", method(msg,i), " #", method.__doc__, "in", method.units)
                 txt += str(Messaging.get(msg, fieldInfo, i))
                 if(i < fieldInfo.count - 1):
                     txt += ", "
         txt += " # "+fieldInfo.description+" in " + fieldInfo.units
         print(txt)
コード例 #6
0
ファイル: influxdb.py プロジェクト: MilesEngineering/MsgTools
    def store_message(self, msg):
        try:
            timeVal = msg.hdr.GetTime()
            timeInfo = Messaging.findFieldInfo(msg.hdr.fields, "Time")
            # if it's not big enough to be an absolute timestamp, give up on using it and just use current time
            if float(timeInfo.maxVal) <= 2**32:
                raise AttributeError
            if timeInfo.units == "ms":
                timeVal = timeVal / 1000.0
            timeVal = datetime.datetime.fromtimestamp(timeVal, datetime.timezone.utc)
        except AttributeError:
            timeVal = datetime.datetime.now()

        dbJson = {
                "time": str(timeVal),
                "measurement": msg.MsgName(),
                'fields':  {},
                'tags': {}
            }

        for fieldInfo in msg.hdr.fields:
            if len(fieldInfo.bitfieldInfo) == 0:
                if fieldInfo.idbits == 0 and fieldInfo.name != "Time" and fieldInfo.name != "DataLength":
                    dbJson['tags'][fieldInfo.name] = Messaging.get(msg.hdr, fieldInfo)
            else:
                for bitInfo in fieldInfo.bitfieldInfo:
                    if bitInfo.idbits == 0 and bitInfo.name != "Time" and bitInfo.name != "DataLength":
                        dbJson['tags'][bitInfo.name] = Messaging.get(msg.hdr, bitInfo)
        
        msgClass = type(msg)
        for fieldInfo in msgClass.fields:
            if fieldInfo.count == 1:
                if len(fieldInfo.bitfieldInfo) == 0:
                    dbJson['fields'][fieldInfo.name] = InfluxDBConnection.GetDBValue(msg, fieldInfo)
                else:
                    for bitInfo in fieldInfo.bitfieldInfo:
                        dbJson['fields'][bitInfo.name] = InfluxDBConnection.GetDBValue(msg, bitInfo)
            # leave out arrays until we figure out how to handle them
            #else:
            #    arrayList = []
            #    for i in range(0,fieldInfo.count):
            #        arrayList.append(InfluxDBConnection.GetDBValue(msg, fieldInfo, i))
            #    dbJson['fields'][fieldInfo.name] = arrayList

        #print("Create a retention policy")
        #retention_policy = 'awesome_policy'
        #client.create_retention_policy(retention_policy, '3d', 3, default=True)
        self.db.write_points([dbJson]) #, retention_policy=retention_policy)
コード例 #7
0
 def GetDBValue(msg, fieldInfo, index=0):
     # what to do for arrays?
     val = Messaging.get(msg, fieldInfo, index)
     if fieldInfo.type == 'int':
         val = int(val)
     elif fieldInfo.type == 'float':
         val = float(val)
     #elif fieldInfo.type == 'Enum'
     #    what?  int value, string?
     return val
コード例 #8
0
ファイル: influxdb.py プロジェクト: MilesEngineering/MsgTools
 def GetDBValue(msg, fieldInfo, index=0):
     # what to do for arrays?
     val = Messaging.get(msg, fieldInfo, index)
     if fieldInfo.type == 'int':
         val = int(val)
     elif fieldInfo.type == 'float':
         val = float(val)
     #elif fieldInfo.type == 'Enum'
     #    what?  int value, string?
     return val
コード例 #9
0
ファイル: Test.py プロジェクト: MilesEngineering/MsgTools
    def test_accessors(self):
        msgclass = Messaging.MsgClassFromName["Network.Connect"]
        sameMsgClass = Messaging.Messages.Network.Connect
        self.assertEqual(msgclass, sameMsgClass)

        expected = "Testing"
        testMsg = msgclass()
        Messaging.set(testMsg, msgclass.fields[0], expected)
        observed = testMsg.GetName()
        self.assertMultiLineEqual(expected, observed)
        
        expected="MoreTesting"
        testMsg.SetName(expected)
        observed=Messaging.get(testMsg, msgclass.fields[0])
        self.assertMultiLineEqual(expected, observed)
コード例 #10
0
    def test_accessors(self):
        msgclass = Messaging.MsgClassFromName["Network.Connect"]
        sameMsgClass = Messaging.Messages.Network.Connect
        self.assertEqual(msgclass, sameMsgClass)

        expected = "Testing"
        testMsg = msgclass()
        Messaging.set(testMsg, msgclass.fields[0], expected)
        observed = testMsg.GetName()
        self.assertMultiLineEqual(expected, observed)

        expected = "MoreTesting"
        testMsg.SetName(expected)
        observed = Messaging.get(testMsg, msgclass.fields[0])
        self.assertMultiLineEqual(expected, observed)
コード例 #11
0
    def addData(self, msg):
        # TODO what to do for things that can't be numerically expressed?  just ascii strings, i guess?
        for line in self.lines:
            try:
                newDataPoint = Messaging.getFloat(msg, line.fieldInfo,
                                                  line.fieldSubindex)
            except ValueError:
                print("ERROR! Plot of %s.%s cannot accept value %s" %
                      (self.msgClass.MsgName(), line.fieldInfo.name,
                       Messaging.get(msg, line.fieldInfo, line.fieldSubindex)))
                continue
            try:
                timestamp = msg.hdr.GetTime()
                if Messaging.findFieldInfo(msg.hdr.fields,
                                           "Time").units == "ms":
                    timestamp = timestamp / 1000.0
                newTime = float(elapsedSeconds(timestamp))
                if newTime != 0:
                    self.useHeaderTime = 1
                if not self.useHeaderTime:
                    newTime = elapsedSeconds(datetime.now().timestamp())
            except AttributeError:
                # if header has no time, fallback to PC time.
                newTime = elapsedSeconds(datetime.now().timestamp())

            # add data in the array until MAX_LENGTH is reached, then drop data off start of array
            # such that plot appears to scroll.  The array size is limited to MAX_LENGTH.
            if len(line.dataArray) >= MsgPlot.MAX_LENGTH:
                line.dataArray[:-1] = line.dataArray[
                    1:]  # shift data in the array one sample left
                line.dataArray[-1] = newDataPoint
                line.timeArray[:-1] = line.timeArray[
                    1:]  # shift data in the array one sample left
                line.timeArray[-1] = newTime
            else:
                line.dataArray.append(newDataPoint)
                line.timeArray.append(newTime)

            if not self.pause:
                timeArray = line.timeArray
                dataArray = line.dataArray
                count = self.timeSlider.value()
                if len(line.dataArray) > count:
                    timeArray = timeArray[-count:]
                    dataArray = dataArray[-count:]
                line.curve.setData(timeArray, dataArray)
                line.curve.setPos(line.ptr1, 0)
コード例 #12
0
ファイル: Test.py プロジェクト: MilesEngineering/MsgTools
    def test_csv_and_json(self):
        testData = [
         ('TestCase4 ;',                             {"TestCase4": {}, "hdr" : {"DataLength": ";"}}),
         ('TestCase4 ',                              {"TestCase4": {"A":0, "B": [0,0,0], "C": [0,0,0], "D": ""}}),
         ('TestCase4 1, 2,3,4, 5,6,7,ei;ght',        {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "ei;ght"}}),
         ("TestCase4 1, 2;",                         {"TestCase4": {"A":1, "B": [2]}, "hdr" : {"DataLength": ";"}}),
         ("TestCase4 1, 0x0203 ;",                   {"TestCase4": {"A":1, "B": [2,3]}, "hdr" : {"DataLength": ";"}}),
         ("TestCase4 1, 0x020304, 0x00050006 ;",     {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6]}, "hdr" : {"DataLength": ";"}}),
         ("TestCase4 1, 2",                          {"TestCase4": {"A":1, "B": [2, 0,0],"C": [0,0,0], "D": ""}}), # note without semicolon, unspecified fields have default values
         ("TestCase4 1, 0x020304, 5,6,0x07",         {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": ""}}),
         ("TestCase4 1, 2,3,4, 5,6,7, 0x8",          {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "0x8"}}),
         ("TestCase4 1, 2,3,4, 5,6,7, eight",        {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "eight"}}),
         ('TestCase4 1, 2,3,4, 5,6,7, "eight"',      {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "eight"}}),
         ('TestCase4 1, 2,3,4, 5,6,7, "eig,ht"',     {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "eig,ht"}}),
         ("TestCase4 1, 2,3,4, 5,6,7, ei ght",       {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "ei ght"}}),
         ("TestCase4 1, 2,3,4, 5,6,7, 0x8;",         {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "0x8"}, "hdr" : {"DataLength": ";"}}),
         ("TestCase4 1, 2,3,4, 5,6,7, eight;",       {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "eight"}, "hdr" : {"DataLength": ";"}}),
         ('TestCase4 1, 2,3,4, 5,6,7, "eight;"',     {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "eight;"}}),
         ('TestCase4 1, 2,3,4, 5,6,7, "eig,ht";',    {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "eig,ht"}, "hdr" : {"DataLength": ";"}}),
         ("TestCase4 1, 2,3,4, 5,6,7, ei ght;",      {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "ei ght"}, "hdr" : {"DataLength": ";"}})]
        commaTestData = []
        for tc in testData:
            newTestCase = (tc[0].replace("TestCase4 ", "TestCase4,"), tc[1])
            commaTestData.append(newTestCase)
        testData.extend(commaTestData)

        tcNum = 0
        for tc in testData:
            try:
                msg = msgcsv.csvToMsg(tc[0])
                json = msgjson.toJson(msg)
                msg2 = msgjson.jsonToMsg(tc[1])
                #print("csv is " + tc[0])
                self.assertEqual(msg.hdr.GetDataLength(), msg2.hdr.GetDataLength(), self.info(tc, tcNum, "hdr.DataLength"))
                #print("json of csv is " + json)
                for fieldInfo in type(msg).fields:
                    if(fieldInfo.count == 1):
                        if len(fieldInfo.bitfieldInfo) == 0:
                            self.assertEqual(Messaging.get(msg, fieldInfo), Messaging.get(msg2, fieldInfo), self.info(tc, tcNum, fieldInfo.name))
                        else:
                            for bitInfo in fieldInfo.bitfieldInfo:
                                self.assertEqual(Messaging.get(msg, bitInfo), Messaging.get(msg2, bitInfo), self.info(tc, tcNum, fieldInfo.name+"."+bitInfo.name))
                    else:
                        for i in range(0,fieldInfo.count):
                            self.assertEqual(Messaging.get(msg, fieldInfo, i), Messaging.get(msg2, fieldInfo, i), self.info(tc, tcNum, fieldInfo.name+"["+str(i)+"]"))
            except AssertionError:
                print("test_csv_and_json test case %d" % (tcNum))
                raise
            except:
                print("Exception on test case %d, [%s] != [%s]" % (tcNum, tc[0], tc[1]))
                print(traceback.format_exc())
                self.assertEqual(True, False)
            tcNum += 1
コード例 #13
0
    def setData(self, column, role, value):
        if self.index == None:
            return

        if column != 2:
            return

        if self.fieldInfo.name == "ID":
            return

        if self.fieldInfo.type == "int" and value.startswith("0x"):
            value = str(int(value, 0))

        # set the value in the message/header buffer
        Messaging.set(self.msg, self.fieldInfo, value, int(self.index))

        # get the value back from the message/header buffer and pass on to super-class' setData
        super(EditableFieldArrayItem, self).setData(column, role, Messaging.get(self.msg, self.fieldInfo, int(self.index)))
コード例 #14
0
    def setData(self, column, role, value):
        if not column == 2:
            return

        if self.fieldInfo.name == "ID":
            return
        
        if self.fieldInfo.type == "int" and value.startswith("0x"):
            value = str(int(value, 0))

        # if user deletes the value, for anything besides a string,
        # return without setting the new value
        if self.fieldInfo.type != "string" and value == "":
            return

        # set the value in the message/header buffer
        Messaging.set(self.msg, self.fieldInfo, value)

        # get the value back from the message/header buffer and pass on to super-class' setData
        super(FieldItem, self).setData(column, role, Messaging.get(self.msg, self.fieldInfo))
コード例 #15
0
ファイル: msgplot.py プロジェクト: MilesEngineering/MsgTools
    def addData(self, msg):
        # TODO what to do for things that can't be numerically expressed?  just ascii strings, i guess?
        for line in self.lines:
            try:
                newDataPoint = Messaging.getFloat(msg, line.fieldInfo, line.fieldSubindex)
            except ValueError:
                print("ERROR! Plot of %s.%s cannot accept value %s" % (
                    self.msgClass.MsgName(),
                    line.fieldInfo.name,
                    Messaging.get(msg, line.fieldInfo, line.fieldSubindex)))
                continue
            try:
                timestamp = msg.hdr.GetTime()
                if Messaging.findFieldInfo(msg.hdr.fields, "Time").units == "ms":
                    timestamp = timestamp / 1000.0
                newTime = float(elapsedSeconds(timestamp))
                if newTime != 0:
                    self.useHeaderTime = 1
                if not self.useHeaderTime:
                    newTime = elapsedSeconds(datetime.now().timestamp())
            except AttributeError:
                # if header has no time, fallback to PC time.
                newTime = elapsedSeconds(datetime.now().timestamp())
            
            # add data in the array until MAX_LENGTH is reached, then drop data off start of array
            # such that plot appears to scroll.  The array size is limited to MAX_LENGTH.
            if len(line.dataArray) >= MsgPlot.MAX_LENGTH:
                line.dataArray[:-1] = line.dataArray[1:]  # shift data in the array one sample left
                line.dataArray[-1] = newDataPoint
                line.timeArray[:-1] = line.timeArray[1:]  # shift data in the array one sample left
                line.timeArray[-1] = newTime
            else:
                line.dataArray.append(newDataPoint)
                line.timeArray.append(newTime)

            if not self.pause:
                self.refreshLine(line)
コード例 #16
0
    def data(self, column, role):
        if column != 2:
            return super(FieldArrayItem, self).data(column, role)

        if self.index == None:
            return ""

        alert = Messaging.getAlert(self.msg, self.fieldInfo, self.index)
        if role == Qt.FontRole:
            font = QFont()
            if alert == 1:
                font.setBold(1)
            return font
        if role == Qt.ForegroundRole:
            brush = QBrush()
            if alert == 1:
                brush.setColor(Qt.red)
            return brush

        if role == Qt.DisplayRole:
            value  = Messaging.get(self.msg, self.fieldInfo, self.index)
            return str(value)

        return super(FieldArrayItem, self).data(column, role)
コード例 #17
0
    def test_csv_and_json(self):
        testData = [
         ('TestCase4 ;',                             {"TestCase4": {}, "hdr" : {"DataLength": ";"}}),
         ('TestCase4 ',                              {"TestCase4": {"A":0, "B": [0,0,0], "C": [0,0,0], "D": ""}}),
         ('TestCase4 1, 2,3,4, 5,6,7,ei;ght',        {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "ei;ght"}}),
         ("TestCase4 1, 2;",                         {"TestCase4": {"A":1, "B": [2]}, "hdr" : {"DataLength": ";"}}),
         ("TestCase4 1, 0x0203 ;",                   {"TestCase4": {"A":1, "B": [2,3]}, "hdr" : {"DataLength": ";"}}),
         ("TestCase4 1, 0x020304, 0x00050006 ;",     {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6]}, "hdr" : {"DataLength": ";"}}),
         ("TestCase4 1, 2",                          {"TestCase4": {"A":1, "B": [2, 0,0],"C": [0,0,0], "D": ""}}), # note without semicolon, unspecified fields have default values
         ("TestCase4 1, 0x020304, 5,6,0x07",         {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": ""}}),
         ("TestCase4 1, 2,3,4, 5,6,7, 0x8",          {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "0x8"}}),
         ("TestCase4 1, 2,3,4, 5,6,7, eight",        {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "eight"}}),
         ('TestCase4 1, 2,3,4, 5,6,7, "eight"',      {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "eight"}}),
         ('TestCase4 1, 2,3,4, 5,6,7, "eig,ht"',     {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "eig,ht"}}),
         ("TestCase4 1, 2,3,4, 5,6,7, ei ght",       {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "ei ght"}}),
         ("TestCase4 1, 2,3,4, 5,6,7, 0x8;",         {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "0x8"}, "hdr" : {"DataLength": ";"}}),
         ("TestCase4 1, 2,3,4, 5,6,7, eight;",       {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "eight"}, "hdr" : {"DataLength": ";"}}),
         ('TestCase4 1, 2,3,4, 5,6,7, "eight;"',     {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "eight;"}}),
         ('TestCase4 1, 2,3,4, 5,6,7, "eig,ht";',    {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "eig,ht"}, "hdr" : {"DataLength": ";"}}),
         ("TestCase4 1, 2,3,4, 5,6,7, ei ght;",      {"TestCase4": {"A":1, "B": [2,3,4], "C": [5,6,7], "D": "ei ght"}, "hdr" : {"DataLength": ";"}})]

        tcNum = 0
        for tc in testData:
            msg = msgcsv.csvToMsg(tc[0])
            json = msgjson.toJson(msg)
            msg2 = msgjson.jsonToMsg(tc[1])
            #print("csv is " + tc[0])
            self.assertEqual(msg.hdr.GetDataLength(), msg2.hdr.GetDataLength(), self.info(tc, tcNum, "hdr.DataLength"))
            #print("json of csv is " + json)
            for fieldInfo in type(msg).fields:
                if(fieldInfo.count == 1):
                    if len(fieldInfo.bitfieldInfo) == 0:
                        self.assertEqual(Messaging.get(msg, fieldInfo), Messaging.get(msg2, fieldInfo), self.info(tc, tcNum, fieldInfo.name))
                    else:
                        for bitInfo in fieldInfo.bitfieldInfo:
                            self.assertEqual(Messaging.get(msg, bitInfo), Messaging.get(msg2, bitInfo), self.info(tc, tcNum, fieldInfo.name+"."+bitInfo.name))
                else:
                    for i in range(0,fieldInfo.count):
                        self.assertEqual(Messaging.get(msg, fieldInfo, i), Messaging.get(msg2, fieldInfo, i), self.info(tc, tcNum, fieldInfo.name+"["+str(i)+"]"))
            tcNum += 1
コード例 #18
0
    def test_csv_and_json(self):
        testData = [
            ('TestCase4 ;', {
                "TestCase4": {},
                "hdr": {
                    "DataLength": ";"
                }
            }),
            ('TestCase4 ', {
                "TestCase4": {
                    "A": 0,
                    "B": [0, 0, 0],
                    "C": [0, 0, 0],
                    "D": ""
                }
            }),
            ('TestCase4 1, 2,3,4, 5,6,7,ei;ght', {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3, 4],
                    "C": [5, 6, 7],
                    "D": "ei;ght"
                }
            }),
            ("TestCase4 1, 2;", {
                "TestCase4": {
                    "A": 1,
                    "B": [2]
                },
                "hdr": {
                    "DataLength": ";"
                }
            }),
            ("TestCase4 1, 0x0203 ;", {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3]
                },
                "hdr": {
                    "DataLength": ";"
                }
            }),
            ("TestCase4 1, 0x020304, 0x00050006 ;", {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3, 4],
                    "C": [5, 6]
                },
                "hdr": {
                    "DataLength": ";"
                }
            }),
            (
                "TestCase4 1, 2", {
                    "TestCase4": {
                        "A": 1,
                        "B": [2, 0, 0],
                        "C": [0, 0, 0],
                        "D": ""
                    }
                }
            ),  # note without semicolon, unspecified fields have default values
            ("TestCase4 1, 0x020304, 5,6,0x07", {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3, 4],
                    "C": [5, 6, 7],
                    "D": ""
                }
            }),
            ("TestCase4 1, 2,3,4, 5,6,7, 0x8", {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3, 4],
                    "C": [5, 6, 7],
                    "D": "0x8"
                }
            }),
            ("TestCase4 1, 2,3,4, 5,6,7, eight", {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3, 4],
                    "C": [5, 6, 7],
                    "D": "eight"
                }
            }),
            ('TestCase4 1, 2,3,4, 5,6,7, "eight"', {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3, 4],
                    "C": [5, 6, 7],
                    "D": "eight"
                }
            }),
            ('TestCase4 1, 2,3,4, 5,6,7, "eig,ht"', {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3, 4],
                    "C": [5, 6, 7],
                    "D": "eig,ht"
                }
            }),
            ("TestCase4 1, 2,3,4, 5,6,7, ei ght", {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3, 4],
                    "C": [5, 6, 7],
                    "D": "ei ght"
                }
            }),
            ("TestCase4 1, 2,3,4, 5,6,7, 0x8;", {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3, 4],
                    "C": [5, 6, 7],
                    "D": "0x8"
                },
                "hdr": {
                    "DataLength": ";"
                }
            }),
            ("TestCase4 1, 2,3,4, 5,6,7, eight;", {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3, 4],
                    "C": [5, 6, 7],
                    "D": "eight"
                },
                "hdr": {
                    "DataLength": ";"
                }
            }),
            ('TestCase4 1, 2,3,4, 5,6,7, "eight;"', {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3, 4],
                    "C": [5, 6, 7],
                    "D": "eight;"
                }
            }),
            ('TestCase4 1, 2,3,4, 5,6,7, "eig,ht";', {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3, 4],
                    "C": [5, 6, 7],
                    "D": "eig,ht"
                },
                "hdr": {
                    "DataLength": ";"
                }
            }),
            ("TestCase4 1, 2,3,4, 5,6,7, ei ght;", {
                "TestCase4": {
                    "A": 1,
                    "B": [2, 3, 4],
                    "C": [5, 6, 7],
                    "D": "ei ght"
                },
                "hdr": {
                    "DataLength": ";"
                }
            })
        ]
        commaTestData = []
        for tc in testData:
            newTestCase = (tc[0].replace("TestCase4 ", "TestCase4,"), tc[1])
            commaTestData.append(newTestCase)
        testData.extend(commaTestData)

        tcNum = 0
        for tc in testData:
            try:
                msg = msgcsv.csvToMsg(tc[0])
                json = msgjson.toJson(msg)
                msg2 = msgjson.jsonToMsg(tc[1])
                #print("csv is " + tc[0])
                self.assertEqual(msg.hdr.GetDataLength(),
                                 msg2.hdr.GetDataLength(),
                                 self.info(tc, tcNum, "hdr.DataLength"))
                #print("json of csv is " + json)
                for fieldInfo in type(msg).fields:
                    if (fieldInfo.count == 1):
                        if len(fieldInfo.bitfieldInfo) == 0:
                            self.assertEqual(
                                Messaging.get(msg, fieldInfo),
                                Messaging.get(msg2, fieldInfo),
                                self.info(tc, tcNum, fieldInfo.name))
                        else:
                            for bitInfo in fieldInfo.bitfieldInfo:
                                self.assertEqual(
                                    Messaging.get(msg, bitInfo),
                                    Messaging.get(msg2, bitInfo),
                                    self.info(
                                        tc, tcNum,
                                        fieldInfo.name + "." + bitInfo.name))
                    else:
                        for i in range(0, fieldInfo.count):
                            self.assertEqual(
                                Messaging.get(msg, fieldInfo, i),
                                Messaging.get(msg2, fieldInfo, i),
                                self.info(tc, tcNum,
                                          fieldInfo.name + "[" + str(i) + "]"))
            except AssertionError:
                print("test_csv_and_json test case %d" % (tcNum))
                raise
            except:
                print("Exception on test case %d, [%s] != [%s]" %
                      (tcNum, tc[0], tc[1]))
                print(traceback.format_exc())
                self.assertEqual(True, False)
            tcNum += 1