Example #1
0
def gcodeFileCommand(filename, target):
    if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
        return make_response("Unknown target: %s" % target, 404)

    if not _verifyFileExists(target, filename):
        return make_response("File not found on '%s': %s" % (target, filename),
                             404)

    # valid file commands, dict mapping command name to mandatory parameters
    valid_commands = {"select": []}

    command, data, response = util.getJsonCommandFromRequest(
        request, valid_commands)
    if response is not None:
        return response

    if command == "select":
        # selects/loads a file
        printAfterLoading = False
        if "print" in data.keys() and data["print"]:
            if not printer.isOperational():
                return make_response(
                    "Printer is not operational, cannot directly start printing",
                    409)
            printAfterLoading = True

        sd = False
        if target == FileDestinations.SDCARD:
            filenameToSelect = filename
            sd = True
        else:
            filenameToSelect = gcodeManager.getAbsolutePath(filename)
        printer.selectFile(filenameToSelect, sd, printAfterLoading)

    return NO_CONTENT
Example #2
0
def gcodeFileCommand(filename, target):
	if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
		return make_response("Unknown target: %s" % target, 404)

	if not _verifyFileExists(target, filename):
		return make_response("File not found on '%s': %s" % (target, filename), 404)

	# valid file commands, dict mapping command name to mandatory parameters
	valid_commands = {
		"select": []
	}

	command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
	if response is not None:
		return response

	if command == "select":
		# selects/loads a file
		printAfterLoading = False
		if "print" in data.keys() and data["print"]:
			if not printer.isOperational():
				return make_response("Printer is not operational, cannot directly start printing", 409)
			printAfterLoading = True

		sd = False
		if target == FileDestinations.SDCARD:
			filenameToSelect = filename
			sd = True
		else:
			filenameToSelect = gcodeManager.getAbsolutePath(filename)
		printer.selectFile(filenameToSelect, sd, printAfterLoading)

	return NO_CONTENT
Example #3
0
def apiLoad():
    logger = logging.getLogger(__name__)

    if not settings.get("api", "enabled"):
        abort(401)

    if not "apikey" in request.values.keys():
        abort(401)

    if request.values["apikey"] != settings.get("api", "key"):
        abort(403)

    if not "file" in request.files.keys():
        abort(400)

    # Perform an upload
    file = request.files["file"]
    if not gcodefiles.isGcodeFileName(file.filename):
        abort(400)

    destination = FileDestinations.LOCAL
    filename, done = gcodeManager.addFile(file, destination)
    if filename is None:
        logger.warn("Upload via API failed")
        abort(500)

    # Immediately perform a file select and possibly print too
    printAfterSelect = False
    if "print" in request.values.keys() and request.values["print"] in valid_boolean_trues:
        printAfterSelect = True
    filepath = gcodeManager.getAbsolutePath(filename)
    if filepath is not None:
        printer.selectFile(filepath, False, printAfterSelect)
    return jsonify(SUCCESS)
Example #4
0
def apiLoad():
    logger = logging.getLogger(__name__)

    if not settings().get(["api", "enabled"]):
        abort(401)

    if not "apikey" in request.values.keys():
        abort(401)

    if request.values["apikey"] != settings().get(["api", "key"]):
        abort(403)

    if not "file" in request.files.keys():
        abort(400)

    # Perform an upload
    file = request.files["file"]
    if not gcodefiles.isGcodeFileName(file.filename):
        abort(400)

    destination = FileDestinations.LOCAL
    filename, done = gcodeManager.addFile(file, destination)
    if filename is None:
        logger.warn("Upload via API failed")
        abort(500)

    # Immediately perform a file select and possibly print too
    printAfterSelect = False
    if "print" in request.values.keys(
    ) and request.values["print"] in valid_boolean_trues:
        printAfterSelect = True
    filepath = gcodeManager.getAbsolutePath(filename)
    if filepath is not None:
        printer.selectFile(filepath, False, printAfterSelect)
    return jsonify(SUCCESS)
Example #5
0
def gcodeFileCommand(filename, target):
	if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
		return make_response("Invalid target: %s" % target, 400)

	# valid file commands, dict mapping command name to mandatory parameters
	valid_commands = {
		"load": []
	}

	command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
	if response is not None:
		return response

	if command == "load":
		# selects/loads a file
		printAfterLoading = False
		if "print" in data.keys() and data["print"] in valid_boolean_trues:
			printAfterLoading = True

		sd = False
		if target == FileDestinations.SDCARD:
			filenameToSelect = filename
			sd = True
		else:
			filenameToSelect = gcodeManager.getAbsolutePath(filename)
		printer.selectFile(filenameToSelect, sd, printAfterLoading)
		return jsonify(SUCCESS)

	return make_response("Command %s is currently not implemented" % command, 400)
Example #6
0
def gcodeFileCommand(filename=None, target=None, request=None):
    if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
        return make_response("Unknown target: %s" % target, 404)

    # not _verifyFileExists(target, filename):
    #return make_response("File not found on '%s': %s" % (target, filename), 404)

    filepath = gcodeManager._uploadFolder
    verifyResult = _verifyFileExists(target, filename)
    if verifyResult and gcodeManager._uploadFolder == gcodeManager._usbpath:
        filename = gcodeManager.startThreadToCopyFile(filename, timeout=3 *
                                                      60)  #wait for 3 mins
        fileTempPath = gcodeManager._usbpath
        gcodeManager._uploadFolder = gcodeManager._localpath
    elif not verifyResult and gcodeManager._uploadFolder == gcodeManager._usbpath:
        fileTempPath = gcodeManager._usbpath
        gcodeManager._uploadFolder = gcodeManager._localpath

        if not _verifyFileExists(target, filename):
            gcodeManager._uploadFolder = filepath
            return make_response(
                "File not found on '%s': %s" % (target, filename), 404)
    elif not verifyResult:
        return make_response("File not found on '%s': %s" % (target, filename),
                             404)

    # valid file commands, dict mapping command name to mandatory parameters
    valid_commands = {"select": []}

    command, data, response = util.getJsonCommandFromRequest(
        request, valid_commands)
    #print "gcodeFileCommand",filename,target,command, data, response,"gcodeFileCommand"
    #if response is not None:
    #3return response

    if response is not None:
        gcodeManager._uploadFolder = filepath
        return response

    if command == "select":
        # selects/loads a file
        printAfterLoading = False
        if "print" in data.keys() and data["print"]:
            if not printer.isOperational():
                gcodeManager._uploadFolder = filepath
                return make_response(
                    "Printer is not operational, cannot directly start printing",
                    409)
            printAfterLoading = True

        sd = False
        if target == FileDestinations.SDCARD:
            filenameToSelect = filename
            sd = True
        else:
            filenameToSelect = gcodeManager.getAbsolutePath(filename)
        printer.selectFile(filenameToSelect, sd, printAfterLoading)
    gcodeManager._uploadFolder = filepath
    return NO_CONTENT
Example #7
0
def loadGcodeFile():
    if "filename" in request.values.keys():
        printAfterLoading = False
        if "print" in request.values.keys() and request.values["print"] in valid_boolean_trues:
            printAfterLoading = True

        sd = False
        if "target" in request.values.keys() and request.values["target"] == "sd":
            filename = request.values["filename"]
            sd = True
        else:
            filename = gcodeManager.getAbsolutePath(request.values["filename"])
        printer.selectFile(filename, sd, printAfterLoading)
    return jsonify(SUCCESS)
Example #8
0
def loadGcodeFile():
    if "filename" in request.values.keys():
        printAfterLoading = False
        if "print" in request.values.keys(
        ) and request.values["print"] in valid_boolean_trues:
            printAfterLoading = True

        sd = False
        if "target" in request.values.keys(
        ) and request.values["target"] == "sd":
            filename = request.values["filename"]
            sd = True
        else:
            filename = gcodeManager.getAbsolutePath(request.values["filename"])
        printer.selectFile(filename, sd, printAfterLoading)
    return jsonify(SUCCESS)
Example #9
0
    def download_print_file(self, print_file_id, progressCb, successCb,
                            errorCb):
        progressCb(2)

        try:
            r = requests.get('%s/print-files/%s' %
                             (self.apiHost, print_file_id),
                             auth=self.hmacAuth)
            data = r.json()
        except:
            data = None

        destFile = None

        if data and "download_url" in data and "name" in data and "info" in data:
            progressCb(5)

            r = requests.get(data["download_url"], stream=True)

            if r.status_code == 200:
                from octoprint.server import gcodeManager

                content_length = float(r.headers['Content-Length'])
                downloaded_size = 0.0

                destFile = gcodeManager.getAbsolutePath(data['name'],
                                                        mustExist=False)

                with open(destFile, 'wb') as fd:
                    for chunk in r.iter_content(524288):  #0.5 MB
                        downloaded_size += len(chunk)
                        fd.write(chunk)
                        progressCb(5 +
                                   round((downloaded_size / content_length) *
                                         95.0, 1))

                fileInfo = {'id': print_file_id, 'info': data["info"]}

                successCb(destFile, fileInfo)
                return True

            else:
                r.close()

        errorCb(destFile, 'Unable to download file')
        return False
Example #10
0
def gcodeFileCommand(filename, target):
	if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
		return make_response("Unknown target: %s" % target, 404)

	if not _verifyFileExists(target, filename):
		return make_response("File not found on '%s': %s" % (target, filename), 404)

	# valid file commands, dict mapping command name to mandatory parameters
	valid_commands = {
		"select": []
	}

	command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
	if response is not None:
		return response

	if command == "select":
		# selects/loads a file
		printAfterLoading = False
		if "print" in data.keys() and data["print"]:
			if not printer.isOperational():
				#We try at least once
				printer.connect()

				start = time.time()
				connect_timeout = 5 #5 secs

				while not printer.isOperational() and not printer.isClosedOrError() and time.time() - start < connect_timeout:
					time.sleep(1)

				if not printer.isOperational():
					return make_response("The printer is not responding, can't start printing", 409)

			printAfterLoading = True

		sd = False
		if target == FileDestinations.SDCARD:
			filenameToSelect = filename
			sd = True
		else:
			filenameToSelect = gcodeManager.getAbsolutePath(filename)
		printer.selectFile(filenameToSelect, sd, printAfterLoading)

	return NO_CONTENT
Example #11
0
	def download_print_file(self, print_file_id, progressCb, successCb, errorCb):
		progressCb(2)

		try:
			r = requests.get('%s/print-files/%s' % (self.apiHost, print_file_id), auth=self.hmacAuth)
			data = r.json()
		except:
			data = None

		destFile = None

		if data and "download_url" in data and "name" in data and "info" in data:
			progressCb(5)

			r = requests.get(data["download_url"], stream=True)

			if r.status_code == 200:
				from octoprint.server import gcodeManager

				content_length = float(r.headers['Content-Length']);
				downloaded_size = 0.0

				destFile = gcodeManager.getAbsolutePath(data['name'], mustExist=False)

				with open(destFile, 'wb') as fd:
					for chunk in r.iter_content(524288): #0.5 MB
						downloaded_size += len(chunk)
						fd.write(chunk)
						progressCb(5 + round((downloaded_size / content_length) * 95.0, 1))

				fileInfo = {
					'id': print_file_id,
					'info': data["info"]
				}

				successCb(destFile, fileInfo)
				return True;

			else:
				r.close()

		errorCb(destFile, 'Unable to download file')
		return False