def _on_clientOpened(self, payload):
		# start-workaround https://github.com/foosel/OctoPrint/issues/3400
		import time
		time.sleep(2)
		selectedSpoolAsDict = None

		# Send plugin storage information
		## Storage
		databaseFileLocation = ""
		if (hasattr(self, "_databaseManager") == True):
			databaseFileLocation = self._databaseManager.getDatabaseFileLocation()

		selectedSpool = self.loadSelectedSpool()
		if (selectedSpool):
			selectedSpoolAsDict = Transformer.transformSpoolModelToDict(selectedSpool)
		else:
			# spool not found
			pass

		self._sendDataToClient(dict(action="initalData",
									databaseFileLocation=databaseFileLocation,
									selectedSpool=selectedSpoolAsDict,
									isFilamentManagerPluginAvailable=self._filamentManagerPluginImplementation != None
									))

		pass
    def select_spool(self):
        self._logger.info("API Store selected spool")
        jsonData = request.json

        databaseId = self._getValueFromJSONOrNone("databaseId", jsonData)
        toolIndex = self._getValueFromJSONOrNone("toolIndex", jsonData)

        if self._printer.is_printing():
            # changing a spool mid-print? we want to know
            commitCurrentSpoolValues = self._getValueFromJSONOrNone(
                "commitCurrentSpoolValues", jsonData)
            if commitCurrentSpoolValues is None:
                self._logger.warning(
                    "selectSpool endpoint called mid-print without commitCurrentState parameter - this shouldn't happen"
                )
                abort(409)

            if commitCurrentSpoolValues:
                self._logger.info("commitCurrentSpoolValues == True")
                self.commitOdometerData()

        spoolModel = self._selectSpool(toolIndex, databaseId)

        spoolModelAsDict = None
        if (spoolModel != None):
            spoolModelAsDict = Transformer.transformSpoolModelToDict(
                spoolModel)

        return flask.jsonify({"selectedSpool": spoolModelAsDict})
    def _upgradeFrom1To2(self):
        self._logger.info(" Starting 1 -> 2")
        # What is changed:
        # - SpoolModel: Add Column colorName
        # - SpoolModel: Add Column remainingWeight (needed fro filtering, sorting)
        connection = sqlite3.connect(self._databaseSettings.fileLocation)
        cursor = connection.cursor()

        sql = """
		PRAGMA foreign_keys=off;
		BEGIN TRANSACTION;

			ALTER TABLE 'spo_spoolmodel' ADD 'colorName' VARCHAR(255);
			ALTER TABLE 'spo_spoolmodel' ADD 'remainingWeight' REAL;

			UPDATE 'spo_pluginmetadatamodel' SET value=2 WHERE key='databaseSchemeVersion';
		COMMIT;
		PRAGMA foreign_keys=on;
		"""
        cursor.executescript(sql)

        connection.close()
        self._logger.info(
            "Database 'altered' successfully. Try to calculate remaining weight."
        )
        #  Calculate the remaining weight for all current spools
        with self._database.atomic() as transaction:  # Opens new transaction.
            try:

                allSpoolModels = self.loadAllSpoolsByQuery(None)
                if (allSpoolModels != None):
                    for spoolModel in allSpoolModels:
                        totalWeight = spoolModel.totalWeight
                        usedWeight = spoolModel.usedWeight
                        remainingWeight = Transformer.calculateRemainingWeight(
                            usedWeight, totalWeight)
                        if (remainingWeight != None):
                            spoolModel.remainingWeight = remainingWeight
                            spoolModel.save()

                # do expicit commit
                transaction.commit()
            except Exception as e:
                # Because this block of code is wrapped with "atomic", a
                # new transaction will begin automatically after the call
                # to rollback().
                transaction.rollback()
                self._logger.exception(
                    "Could not upgrade database scheme from 1 To 2:" + str(e))

                self._passMessageToClient(
                    "error", "DatabaseManager",
                    "Could not upgrade database scheme V1 to V2. See OctoPrint.log for details!"
                )
            pass

        self._logger.info(" Successfully 1 -> 2")
        pass
Beispiel #4
0
    def _upgradeFrom5To6(self):
        self._logger.info(" Starting 5 -> 6")
        # What is changed:
        # - Recalculate remaining weight
        # - offsetTemperature = IntegerField(null=True)  # since V6
        # - offsetBedTemperature = IntegerField(null=True)  # since V6
        # - offsetEnclosureTemperature = IntegerField(null=True)  # since V6

        connection = sqlite3.connect(self._databaseSettings.fileLocation)
        cursor = connection.cursor()

        sql = """
		PRAGMA foreign_keys=off;
		BEGIN TRANSACTION;

			ALTER TABLE 'spo_spoolmodel' ADD 'offsetTemperature' INTEGER;
			ALTER TABLE 'spo_spoolmodel' ADD 'offsetBedTemperature' INTEGER;
			ALTER TABLE 'spo_spoolmodel' ADD 'offsetEnclosureTemperature' INTEGER;

			UPDATE 'spo_pluginmetadatamodel' SET value=6 WHERE key='databaseSchemeVersion';
		COMMIT;
		PRAGMA foreign_keys=on;
		"""
        cursor.executescript(sql)
        connection.close()

        self._logger.info("  try to calculate remaining weight.")
        #  Calculate the remaining weight for all current spools
        with self._database.atomic() as transaction:  # Opens new transaction.
            try:
                allSpoolModels = self.loadAllSpoolsByQuery(None)
                if (allSpoolModels != None):
                    for spoolModel in allSpoolModels:
                        totalWeight = spoolModel.totalWeight
                        usedWeight = spoolModel.usedWeight
                        remainingWeight = Transformer.calculateRemainingWeight(
                            usedWeight, totalWeight)
                        if (remainingWeight != None):
                            spoolModel.remainingWeight = remainingWeight
                            spoolModel.save()
                # do expicit commit
                transaction.commit()
            except Exception as e:
                # Because this block of code is wrapped with "atomic", a
                # new transaction will begin automatically after the call
                # to rollback().
                transaction.rollback()
                self._logger.exception(
                    "Could not calculate remainingWeight during scheme update from 5 To 6:"
                    + str(e))

                return
            pass

        self._logger.info(" Successfully 5 -> 6")
        pass
Beispiel #5
0
    def select_spool(self):
        self._logger.info("API Store selected spool")
        jsonData = request.json

        databaseId = self._getValueFromJSONOrNone("databaseId", jsonData)

        spoolModel = self._selectSpool(databaseId)

        spoolModelAsDict = None
        if (spoolModel != None):
            spoolModelAsDict = Transformer.transformSpoolModelToDict(
                spoolModel)

        return flask.jsonify({"selectedSpool": spoolModelAsDict})
Beispiel #6
0
    def selectSpoolByQRCode(self, databaseId):
        self._logger.info("API select spool by QR code" + str(databaseId))

        spoolModel = self._selectSpool(databaseId)

        spoolModelAsDict = None
        if (spoolModel != None):
            spoolModelAsDict = Transformer.transformSpoolModelToDict(
                spoolModel)
            #Take us back to the SpoolManager plugin tab
            redirectURLWithSpoolSelection = flask.url_for(
                "index", _external=True
            ) + "#tab_plugin_SpoolManager-spoolId" + str(databaseId)
            return flask.redirect(redirectURLWithSpoolSelection, 307)
        else:
            abort(404)
Beispiel #7
0
    def _on_clientOpened(self, payload):
        # start-workaround https://github.com/foosel/OctoPrint/issues/3400
        import time
        time.sleep(3)
        selectedSpoolAsDict = None

        # Check if database is available
        # connected = self._databaseManager.reConnectToDatabase()
        # self._logger.info("ClientOpened. Database connected:"+str(connected))

        connectionErrorResult = self._databaseManager.testDatabaseConnection()

        # Don't show already shown message
        if (self.databaseConnectionProblemConfirmed == False
                and connectionErrorResult != None):
            databaseErrorMessageDict = self._databaseManager.getCurrentErrorMessageDict(
            )
            # The databaseErrorMessages should always be present in that case.
            if (databaseErrorMessageDict != None):
                self._logger.error(databaseErrorMessageDict)
                self._sendDataToClient(
                    dict(action="showConnectionProblem",
                         type=databaseErrorMessageDict["type"],
                         title=databaseErrorMessageDict["title"],
                         message=databaseErrorMessageDict["message"]))

        # Send plugin storage information
        ## Storage
        if (connectionErrorResult == None):
            selectedSpool = self.loadSelectedSpool()
            if (selectedSpool):
                selectedSpoolAsDict = Transformer.transformSpoolModelToDict(
                    selectedSpool)
            else:
                # spool not found
                pass

        pluginNotWorking = connectionErrorResult != None
        self._sendDataToClient(
            dict(action="initalData",
                 selectedSpool=selectedSpoolAsDict,
                 isFilamentManagerPluginAvailable=self.
                 _filamentManagerPluginImplementation != None,
                 pluginNotWorking=pluginNotWorking))

        pass
    def selectSpoolByQRCode(self, databaseId):
        self._logger.info("API select spool by QR code" + str(databaseId))

        if self._printer.is_printing():
            # not doing this mid-print since we can't ask the user what to do
            abort(409)
            return

        spoolModel = self._selectSpool(0, databaseId)

        spoolModelAsDict = None
        if (spoolModel != None):
            spoolModelAsDict = Transformer.transformSpoolModelToDict(
                spoolModel)
            #Take us back to the SpoolManager plugin tab
            redirectURLWithSpoolSelection = flask.url_for(
                "index", _external=True
            ) + "#tab_plugin_SpoolManager-spoolId" + str(databaseId)
            return flask.redirect(redirectURLWithSpoolSelection, 307)
        else:
            abort(404)
	def load_allSpools(self):
		self._logger.debug("API Load all spool")
		# sp1 = SpoolModel()
		# sp1.displayName = "Spool No.1"
		# sp1.vendor = "Janbex"
		# sp1.material = "ABS"
		# sp1.color = "#00dd00"
		# sp1.density = 123.23
		# sp1.diameter = 432.12
		# sp1.temperature = 221
		# sp1.firstUse = datetime.datetime(2019, 5, 17)
		# sp1.lastUse = datetime.datetime(2019, 6, 4)
		# sp1.remainingWeight = 1234
		# sp1.weight = 2000
		# sp1.usedPercentage = str(1234.0 / (2000.0 / 100.0))
		# sp1.usedLength = 32
		# sp1.code = "XS-28787-HKH-234"
		# sp1.purchasedOn = datetime.datetime(2018, 4, 3)
		# sp1.purchasedFrom = "http://www.amazon.de/eorjoeiirjfoiejfoijeroffjeroeoidj"
		# sp1.cost = 3.14
		#
		# sp2 = SpoolModel()
		# sp2.displayName = "Spool No.2"
		# sp2.vendor = "Plastic Joe"
		# sp2.material = "PETG"
		#
		# allSpools = [sp1,sp2]

		tableQuery = flask.request.values

		allSpools = self._databaseManager.loadAllSpoolsByQuery(tableQuery)
		totalItemCount = self._databaseManager.countSpoolsByQuery(tableQuery)

		# allSpoolsAsDict = self._transformAllSpoolModelsToDict(allSpools)
		allSpoolsAsDict = Transformer.transformAllSpoolModelsToDict(allSpools)

		# load all catalogs: vendors, materials, labels, [colors]
		vendors = list(self._databaseManager.loadCatalogVendors(tableQuery))
		materials = list(self._databaseManager.loadCatalogMaterials(tableQuery))
		labels = list(self._databaseManager.loadCatalogLabels(tableQuery))

		tempateSpoolAsDict = None
		allTemplateSpools = self._databaseManager.loadSpoolTemplateSpool()
		for spool in allTemplateSpools:
			tempateSpoolAsDict = Transformer.transformSpoolModelToDict(spool)
			break

		catalogs = {
			"vendors": vendors,
			"materials": materials,
			"labels": labels
		}
		# catalogs = {
		# 	"materials": ["", "ABS", "PLA", "PETG"],
		# 	"colors": ["", "#123", "#456"],
		# 	"labels": ["", "good", "bad"]
		# }
		selectedSpoolAsDict = None
		selectedSpool = self.loadSelectedSpool()
		if (selectedSpool):
			selectedSpoolAsDict = Transformer.transformSpoolModelToDict(selectedSpool)
		else:
			# spool not found
			pass

		return flask.jsonify({
								"templateSpool": tempateSpoolAsDict,
								"catalogs": catalogs,
								"totalItemCount": totalItemCount,
								"allSpools": allSpoolsAsDict,
								"selectedSpool": selectedSpoolAsDict
							})
	def _processCSVUploadAsync(self, path, importCSVMode, databaseManager, backupFolder, sendCSVUploadStatusToClient, logger):
		errorCollection = list()

		# - parsing
		# - backup
		# - append or replace

		def updateParsingStatus(lineNumber):
			# importStatus, currenLineNumber, backupFilePath,  successMessages, errorCollection
			sendCSVUploadStatusToClient("running", lineNumber, "", "", errorCollection)


		resultOfSpools = CSVExportImporter.parseCSV(path, updateParsingStatus, errorCollection, logger)

		if (len(errorCollection) != 0):
			successMessage = "Some error(s) occurs during parsing! No spools imported!"
			# importStatus, currenLineNumber, backupFilePath,  successMessages, errorCollection
			sendCSVUploadStatusToClient("finished", "", "", successMessage, errorCollection)
			return

		importModeText = "append"
		backupDatabaseFilePath = None
		if (len(resultOfSpools) > 0):
			# we could import some jobs

			# - backup
			backupDatabaseFilePath = databaseManager.backupDatabaseFile(backupFolder)

			# - import mode append/replace
			if (SettingsKeys.KEY_IMPORTCSV_MODE_REPLACE == importCSVMode):
				# delete old database and init a clean database
				databaseManager.reCreateDatabase()
				# reset selected spool
				self._selectSpool(None)

				importModeText = "fully replaced"

			# - insert all printjobs in database
			currentSpoolNumber = 0
			for spool in resultOfSpools:
				currentSpoolNumber = currentSpoolNumber + 1
				updateParsingStatus(currentSpoolNumber)

				remainingWeight = Transformer.calculateRemainingWeight(spool.usedWeight, spool.totalWeight)
				if (remainingWeight != None):
					spool.remainingWeight = remainingWeight
					# spool.save()

				databaseManager.saveModel(spool)
			pass
		else:
			errorCollection.append("Nothing to import!")

		successMessage = ""
		if (len(errorCollection) == 0):
			successMessage = "All data is successful " + importModeText + " with '" + str(len(resultOfSpools)) + "' spools."
		else:
			successMessage = "Some error(s) occurs! Maybe you need to manually rollback the database!"
		logger.info(successMessage)
		sendCSVUploadStatusToClient("finished", "", backupDatabaseFilePath,  successMessage, errorCollection)
		pass