Example #1
0
    def getKnownPackets(self, project=None):
        """
        Get all known packets of a Project as objects.
        Uses the global project if no project is given.

        :param project: Optional parameter to specify the project to use
        :return: A list of all known packets as KnownPacket objects
        """

        if project is None:
            project = Globals.project
        if Toolbox.Toolbox.checkProjectIsNone(project):
            return

        cursor = self.connection.cursor()
        cursor.execute(
            DatabaseStatements.getSelectAllStatementWhereEquals(
                DatabaseStatements.knownPacketTableName, "ProjectID",
                project.id))
        rows = cursor.fetchall()
        knownPackets = []
        for row in rows:
            assert len(row) == 5
            knownPackets.append(
                KnownPacket(row[0], row[1], row[2], row[3], row[4]))
        return knownPackets
Example #2
0
    def addKnownPacket(self, CANID=None, data=None, description=None):
        """
        Save a known packet to the current project (and database)
        Default: Get values from the GUI elements. But you can also specify the values
        using the optional parameters.

        :param CANID: Optional: CAN ID
        :param data:  Optional: Payload data
        :param description: Optional: Description of the known packet
        :return:
        """

        if Globals.project is None:
            QtGui.QMessageBox.information(
                Globals.ui.tabWidgetMain,
                Strings.noProjectSelectedMessageBoxTitle,
                Strings.noProjectSelectedMessageBoxText, QtGui.QMessageBox.Ok)
            return

        if CANID is None:
            CANID = self.lineEditKnownPacketID.text()

        if data is None:
            data = self.lineEditKnownPacketData.text()

        if description is None:
            description = self.lineEditKnownPacketDescription.text()

        if len(CANID) < 1 or len(data) < 1 or len(description) < 1:
            self.logger.info(Strings.managerTabKnownPacketNotAdded)
            return

        knownPacket = KnownPacket(None, Globals.project.id, CANID, data,
                                  description)
        Globals.db.saveKnownPacket(knownPacket)
        self.populateKnownPackets()
        # Update the dictionary of known values
        self.getKnownPacketsForCurrentProject()

        self.lineEditKnownPacketID.clear()
        self.lineEditKnownPacketData.clear()
        self.lineEditKnownPacketDescription.clear()
        self.logger.info(Strings.managerTabKnownPacketAdded)
Example #3
0
    def editKnownPacket(self):
        """
        Update a known packet with new specified values.
        """

        selectedKnownPacket = self.comboBoxEditKnownPackets.itemData(
            self.comboBoxEditKnownPackets.currentIndex())
        if selectedKnownPacket is None:
            return

        oldCANID = selectedKnownPacket.CANID
        oldData = selectedKnownPacket.data

        newCANID = self.lineEditKnownPacketEditID.text()
        newData = self.lineEditKnownPacketEditData.text()
        newDescription = self.lineEditKnownPacketEditDescription.text()

        if len(newCANID) == 0 or len(newData) == 0 or len(newDescription) == 0:
            self.logger.warn(Strings.managerTabKnownPacketNotEdited)
            return

        updatedKnownPacket = KnownPacket(selectedKnownPacket.id,
                                         Globals.project.id, newCANID, newData,
                                         newDescription)

        Globals.db.updateKnownPacket(updatedKnownPacket)

        # Also update the comboboxes
        self.populateKnownPackets(keepCurrentIndex=True)

        # Also update the global variable that stores all descriptions
        oldStrIdx = Toolbox.Toolbox.getPacketDictIndex(oldCANID, oldData)
        # Delete the old value
        Globals.knownPackets.pop(oldStrIdx, None)
        # Inser the new value
        newStrIdx = Toolbox.Toolbox.getPacketDictIndex(newCANID, newData)
        Globals.knownPackets[newStrIdx] = newDescription

        self.logger.info(Strings.managerTabKnownPacketUpdated)
Example #4
0
    def importProject(self):
        """
        Import a project from a JSON file.
        The ``fromJSON()`` method of every class is called to re-create objects.
        """

        # A tuple is returned --> only use the first element which represents the absolute file path
        filePath = QtGui.QFileDialog.getOpenFileName(self.packetTableView,
                                                     Strings.openDialogTitle,
                                                     QtCore.QDir.homePath())[0]

        importedProject = None
        importedPacketSets = []
        importedPackets = []
        importedKnownPackets = []

        if filePath:

            with open(filePath, "r") as importFile:
                importData = importFile.read()

            if importData == "":
                self.logger.warn(Strings.managerTabNoProjectFound)
                return

            progressDialog = Toolbox.Toolbox.getWorkingDialog(
                Strings.managerTabImportingProject)
            progressDialog.open()
            try:
                sections = importData.split(
                    Strings.projectExportEndSectionMarker)

                if len(sections) == 0 or not any(sections):
                    self.logger.info(Strings.managerTabNoDataToImport)
                    return

                # For every section, ignoring the header
                for sectionIndex in range(1, len(sections)):
                    section = sections[sectionIndex]
                    values = section.split(
                        Strings.projectExportEndElementMarker)

                    firstValue = True
                    className = None
                    for value in values:
                        QtCore.QCoreApplication.processEvents()
                        if len(value) == 0:
                            continue

                        # The first value determines the objet type (~ class)
                        if firstValue:
                            firstValue = False
                            className = value.splitlines()[0]
                            # Remove the first line as it contains the class name
                            value = "".join(value.splitlines()[1:])

                        if len(value) == 0:
                            continue

                        # We've got the class name and the data --> lets create objects
                        if className == Strings.projectExportProjectHeader:
                            importedProject = Project.fromJSON(value)

                        elif className == Strings.projectExportPacketSetHeader:
                            packetSet = PacketSet.fromJSON(value)
                            importedPacketSets.append(packetSet)

                        elif className == Strings.projectExportPacketHeader:
                            packet = Packet.Packet.fromJSON(value)
                            importedPackets.append(packet)

                        elif className == Strings.projectExportKnownPacketHeader:
                            knownPacket = KnownPacket.fromJSON(value)
                            importedKnownPackets.append(knownPacket)

                self.logger.info(Strings.managerTabObjectsImported)

                if importedProject is None:
                    self.logger.warn(Strings.managerTabNoProjectFound)
                    return

                # Objects created, let's save them to the DB with the new project ID

                # We don't know how many attempts the user needs to find a new name for a
                # project name collision
                while True:
                    try:
                        newProjectID = Globals.db.saveProject(importedProject)

                    # Theres already a project with the same name --> get new name
                    except IntegrityError:
                        # Get the name from the tuple returned by the dialog
                        newProjectName = QtGui.QInputDialog.getText(
                            self.packetTableView,
                            Strings.
                            managerTabDBIntegrityNewProjectNameMessageBoxTitle,
                            Strings.
                            managerTabDBIntegrityNewProjectNameMessageBoxText,
                        )[0]

                        if len(newProjectName) == 0:
                            self.logger.error(
                                Strings.managerTabInvalidProjectName)
                            return

                        else:
                            # Try it again with a new name
                            importedProject.name = newProjectName
                            continue
                    break

                # Import the packet sets along with the packets
                for importedPacketSet in importedPacketSets:
                    packetsOfPacketSet = [
                        packet for packet in importedPackets
                        if packet.packetSetID == importedPacketSet.id
                    ]

                    Globals.db.savePacketSetWithData(
                        importedPacketSet.name,
                        packets=packetsOfPacketSet,
                        project=importedProject)

                # Import known packets
                for importedKnownPacket in importedKnownPackets:
                    QtCore.QCoreApplication.processEvents()
                    importedKnownPacket.projectID = newProjectID
                    Globals.db.saveKnownPacket(importedKnownPacket)

                self.logger.info(Strings.managerTabObjectsWritten)

                QtCore.QCoreApplication.processEvents()

                # Populate all GUI elements accordingly
                MainTab.MainTab.populateProjects()
                self.populateProjects()
                self.populatePacketSets()
                self.populateKnownPackets()

            finally:
                progressDialog.close()
        else:
            self.logger.info(Strings.managerTabProjectNoFileGiven)
Example #5
0
    def createDump(self, rawPackets=None):
        """
        Save a new dump to the database. This creates a new PacketSet along with associated Packet objects.
        If only one packet is saved, the user will be asked if he wants to create a known packet entry for the
        just saved packet.

        :param rawPackets: Optional: If this is not None, the values from ``rawPackets`` will be used instead of
               the data that is currently being displayed in the GUI table.
        """

        if rawPackets is None:
            rawPackets = self.rawData

        if len(rawPackets) == 0:
            return

        if Toolbox.Toolbox.checkProjectIsNone():
            return

        # Get the name from the tuple returned by the dialog
        packetSetName = QtGui.QInputDialog.getText(
            self.packetTableView,
            Strings.packetSetSaveMessageBoxTitle,
            Strings.packetSetSaveMessageBoxText,
        )[0]

        if len(packetSetName) == 0:
            self.logger.error(Strings.packetSetInvalidName)
            return

        progressDialog = Toolbox.Toolbox.getWorkingDialog(
            Strings.managerTabSavingPackets)
        progressDialog.open()
        try:
            # We've got data, lets save it
            packetSetID = Globals.db.savePacketSetWithData(
                packetSetName, rawPackets=rawPackets)
            if packetSetID is not None and packetSetID > 0:
                # Reload is being handled by the triggered event anyway
                self.populatePacketSets(IDtoChoose=packetSetID)

                if len(rawPackets) == 1:
                    # The user added a PacketSet with size 1 -- maybe he wants to add it as a known packet too
                    if Toolbox.Toolbox.yesNoBox(
                            Strings.managerTabAddAsKnownPacketMessageBoxTitle,
                            Strings.managerTabAddAsKnownPacketMessageBoxText):

                        rawPacket = rawPackets[0]
                        CANID = rawPacket[0]
                        data = rawPacket[1]

                        # Get the description from the tuple returned by the dialog
                        description = QtGui.QInputDialog.getText(
                            self.packetTableView,
                            Strings.
                            managerTabAskKnownPacketDescriptionMessageBoxTitle,
                            Strings.
                            managerTabAskKnownPacketDescriptionMessageBoxText,
                        )[0]

                        if len(description) == 0:
                            self.logger.error(
                                Strings.knownPacketInvalidDescription)
                            return

                        # Create the object and save it
                        knownPacket = KnownPacket(None, Globals.project.id,
                                                  CANID, data, description)
                        Globals.db.saveKnownPacket(knownPacket)
                        self.populateKnownPackets()
        finally:
            progressDialog.close()