Example #1
0
	def on_settings_load(self):
		data = dict(octoprint.plugin.SettingsPlugin.on_settings_load(self))
		data["hasCustom"] = os.path.isfile(self._customCssPath)
		data["requireNewCSS"] = self._requireNewCSS
		data["refreshCSS"] = self._refreshCSS
		data["whatsNew"] = False

		if admin_permission.can():
			if os.path.isfile(self._whatsNewPath):
				with open(self._whatsNewPath, 'r') as contentFile:
					data["whatsNew"] = contentFile.read()
				os.unlink(self._whatsNewPath)

			if self._requireNewCSS is True:
				self._requireNewCSS = False

			if self._settings.get(["useCustomization"]):
				if os.path.isfile(self._customHashPath) is not True:
					data["requireNewCSS"] = True

			if self._refreshCSS:
				if self._refreshTime < time.time():
					data["refreshCSS"] = False
					self._refreshCSS = False
					self._refreshTime = 0

		return data
Example #2
0
	def on_api_command(self, command, data):
		if not admin_permission.can():
			return make_response("Insufficient rights", 403)

		if command == "install":
			url = data["url"]
			plugin_name = data["plugin"] if "plugin" in data else None
			return self.command_install(url=url,
			                            force="force" in data and data["force"] in valid_boolean_trues,
			                            dependency_links="dependency_links" in data and data["dependency_links"] in valid_boolean_trues,
			                            reinstall=plugin_name)

		elif command == "uninstall":
			plugin_name = data["plugin"]
			if not plugin_name in self._plugin_manager.plugins:
				return make_response("Unknown plugin: %s" % plugin_name, 404)

			plugin = self._plugin_manager.plugins[plugin_name]
			return self.command_uninstall(plugin)

		elif command == "enable" or command == "disable":
			plugin_name = data["plugin"]
			if not plugin_name in self._plugin_manager.plugins:
				return make_response("Unknown plugin: %s" % plugin_name, 404)

			plugin = self._plugin_manager.plugins[plugin_name]
			return self.command_toggle(plugin, command)

		elif command == "refresh_repository":
			self._repository_available = self._refresh_repository()
			return jsonify(repository=dict(available=self._repository_available, plugins=self._repository_plugins))
Example #3
0
def wizardFinish():
	if not s().getBoolean(["server", "firstRun"]) and not admin_permission.can():
		abort(403)

	data = dict()
	try:
		data = request.json
	except:
		abort(400)

	if not "handled" in data:
		abort(400)
	handled = data["handled"]

	if s().getBoolean(["server", "firstRun"]):
		s().setBoolean(["server", "firstRun"], False)

	seen_wizards = dict(s().get(["server", "seenWizards"]))

	wizard_plugins = octoprint.server.pluginManager.get_implementations(octoprint.plugin.WizardPlugin)
	for implementation in wizard_plugins:
		name = implementation._identifier
		try:
			implementation.on_wizard_finish(name in handled)
			if name in handled:
				seen_wizards[name] = implementation.get_wizard_version()
		except:
			logging.getLogger(__name__).exception("There was an error finishing the wizard for {}, ignoring".format(name))

	s().set(["server", "seenWizards"], seen_wizards)
	s().save()

	return NO_CONTENT
Example #4
0
	def on_api_get(self, request):
		if not admin_permission.can():
			return make_response("Insufficient rights", 403)

		plugins = self._plugin_manager.plugins

		result = []
		for name, plugin in plugins.items():
			result.append(self._to_external_representation(plugin))

		if "refresh_repository" in request.values and request.values["refresh_repository"] in valid_boolean_trues:
			self._repository_available = self._refresh_repository()

		return jsonify(plugins=result,
		               repository=dict(
		                   available=self._repository_available,
		                   plugins=self._repository_plugins
		               ),
		               os=self._get_os(),
		               octoprint=self._get_octoprint_version(),
		               pip=dict(
		                   available=self._pip_caller.available,
		                   command=self._pip_caller.command,
		                   version=self._pip_caller.version_string,
		                   use_sudo=self._pip_caller.use_sudo,
		                   additional_args=self._settings.get(["pip_args"])
		               ))
Example #5
0
	def on_api_command(self, command, data):
		user_id = current_user.get_name()
		if not user_id:
			return flask.abort(403)

		if command == "revoke":
			api_key = data.get("key")
			if not api_key:
				return flask.abort(400)

			if not admin_permission.can():
				user_for_key = self._user_for_api_key(api_key)
				if user_for_key is None or user_for_key.user_id != user_id:
					return flask.abort(403)

			self._delete_api_key(api_key)

		elif command == "generate":
			# manual generateKey
			app_name = data.get("app")
			if not app_name:
				return flask.abort(400)

			self._add_api_key(user_id, app_name.strip())

		return NO_CONTENT
Example #6
0
def setTimelapseConfig():
	if "type" in request.values:
		config = {
			"type": request.values["type"],
			"postRoll": 0,
			"options": {}
		}


		if "postRoll" in request.values:
			try:
				config["postRoll"] = int(request.values["postRoll"])
			except ValueError:
				pass

		if "interval" in request.values:
			interval = 10
			try:
				interval = int(request.values["interval"])
			except ValueError:
				pass

			config["options"] = {
				"interval": interval
			}

		if admin_permission.can() and "save" in request.values and request.values["save"] in valid_boolean_trues:
			octoprint.timelapse.configureTimelapse(config, True)
		else:
			octoprint.timelapse.configureTimelapse(config)

	return getTimelapseData()
	def on_api_command(self, command, data):
		if command == "refresh_wifi":
			return jsonify(self._get_wifi_list(force=True))

		# any commands processed after this check require admin permissions
		if not admin_permission.can():
			return make_response("Insufficient rights", 403)

		if command == "configure_wifi":
			if data["psk"]:
				self._logger.info("Configuring wifi {ssid} and psk...".format(**data))
			else:
				self._logger.info("Configuring wifi {ssid}...".format(**data))

			self._configure_and_select_wifi(data["ssid"], data["psk"], force=data["force"] if "force" in data else False)

		elif command == "forget_wifi":
			self._forget_wifi()

		elif command == "reset":
			self._reset()

		elif command == "start_ap":
			self._start_ap()

		elif command == "stop_ap":
			self._stop_ap()
Example #8
0
	def on_api_command(self, command, data):
		if not admin_permission.can():
			return make_response("Insufficient rights", 403)

		if self._printer.is_printing() or self._printer.is_paused():
			# do not update while a print job is running
			return make_response("Printer is currently printing or paused", 409)

		if command == "install":
			url = data["url"]
			plugin_name = data["plugin"] if "plugin" in data else None
			return self.command_install(url=url,
			                            force="force" in data and data["force"] in valid_boolean_trues,
			                            dependency_links="dependency_links" in data and data["dependency_links"] in valid_boolean_trues,
			                            reinstall=plugin_name)

		elif command == "uninstall":
			plugin_name = data["plugin"]
			if not plugin_name in self._plugin_manager.plugins:
				return make_response("Unknown plugin: %s" % plugin_name, 404)

			plugin = self._plugin_manager.plugins[plugin_name]
			return self.command_uninstall(plugin)

		elif command == "enable" or command == "disable":
			plugin_name = data["plugin"]
			if not plugin_name in self._plugin_manager.plugins:
				return make_response("Unknown plugin: %s" % plugin_name, 404)

			plugin = self._plugin_manager.plugins[plugin_name]
			return self.command_toggle(plugin, command)
Example #9
0
	def on_api_get(self, request):
		user_id = current_user.get_name()
		if not user_id:
			return flask.abort(403)

		if request.values.get("all") in valid_boolean_trues and admin_permission.can():
			keys = self._all_api_keys()
		else:
			keys = self._api_keys_for_user(user_id)

		return flask.jsonify(keys=map(lambda x: x.external(), keys),
		                     pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id)))
Example #10
0
	def on_api_get(self, request):
		if not admin_permission.can():
			return make_response("Insufficient rights", 403)

		from octoprint.server import safe_mode

		refresh_repository = request.values.get("refresh_repository", "false") in valid_boolean_trues
		if refresh_repository:
			self._repository_available = self._refresh_repository()

		refresh_notices = request.values.get("refresh_notices", "false") in valid_boolean_trues
		if refresh_notices:
			self._notices_available = self._refresh_notices()

		def view():
			return jsonify(plugins=self._get_plugins(),
			               repository=dict(
			                   available=self._repository_available,
			                   plugins=self._repository_plugins
			               ),
			               os=get_os(),
			               octoprint=get_octoprint_version_string(),
			               pip=dict(
			                   available=self._pip_caller.available,
			                   version=self._pip_caller.version_string,
			                   install_dir=self._pip_caller.install_dir,
			                   use_user=self._pip_caller.use_user,
			                   virtual_env=self._pip_caller.virtual_env,
			                   additional_args=self._settings.get(["pip_args"]),
			                   python=sys.executable
		                    ),
			               safe_mode=safe_mode,
			               online=self._connectivity_checker.online)

		def etag():
			import hashlib
			hash = hashlib.sha1()
			hash.update(repr(self._get_plugins()))
			hash.update(str(self._repository_available))
			hash.update(repr(self._repository_plugins))
			hash.update(str(self._notices_available))
			hash.update(repr(self._notices))
			hash.update(repr(safe_mode))
			hash.update(repr(self._connectivity_checker.online))
			hash.update(repr(_DATA_FORMAT_VERSION))
			return hash.hexdigest()

		def condition():
			return check_etag(etag())

		return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(),
		                                  condition=lambda *args, **kwargs: condition(),
		                                  unless=lambda: refresh_repository or refresh_notices)(view)()
Example #11
0
def setTimelapseConfig():
	if "type" in request.values:
		config = {
			"type": request.values["type"],
			"postRoll": 0,
			"fps": 25,
			"options": {}
		}

		if "postRoll" in request.values:
			try:
				postRoll = int(request.values["postRoll"])
			except ValueError:
				return make_response("Invalid value for postRoll: %r" % request.values["postRoll"], 400)
			else:
				if postRoll >= 0:
					config["postRoll"] = postRoll
				else:
					return make_response("Invalid value for postRoll: %d" % postRoll, 400)

		if "fps" in request.values:
			try:
				fps = int(request.values["fps"])
			except ValueError:
				return make_response("Invalid value for fps: %r" % request.values["fps"], 400)
			else:
				if fps > 0:
					config["fps"] = fps
				else:
					return make_response("Invalid value for fps: %d" % fps, 400)

		if "interval" in request.values:
			config["options"] = {
				"interval": 10
			}

			try:
				interval = int(request.values["interval"])
			except ValueError:
				return make_response("Invalid value for interval: %r" % request.values["interval"])
			else:
				if interval > 0:
					config["options"]["interval"] = interval
				else:
					return make_response("Invalid value for interval: %d" % interval)

		if admin_permission.can() and "save" in request.values and request.values["save"] in valid_boolean_trues:
			octoprint.timelapse.configure_timelapse(config, True)
		else:
			octoprint.timelapse.configure_timelapse(config)

	return getTimelapseData()
Example #12
0
	def on_api_command(self, command, data):
		from flask import abort, jsonify
		from octoprint.server import admin_permission

		if not admin_permission.can():
			abort(403)

		if command == "power_on":
			self._poweron()

		elif command == "power_off":
			self._poweroff()

		return jsonify(**self._status())
Example #13
0
	def on_api_get(self, request):
		if not admin_permission.can():
			return make_response("Insufficient rights", 403)

		plugins = self._plugin_manager.plugins

		result = []
		for name, plugin in plugins.items():
			result.append(self._to_external_representation(plugin))

		if "refresh_repository" in request.values and request.values["refresh_repository"] in valid_boolean_trues:
			self._repository_available = self._refresh_repository()

		return jsonify(plugins=result, repository=dict(available=self._repository_available, plugins=self._repository_plugins), os=self._get_os(), octoprint=self._get_octoprint_version())
    def configure_wifi(self):
        if not admin_permission.can():
            return make_response(jsonify({ "message": "Insufficient rights"}), 403)

        data = request.json
        if "psk" in data:
            self._logger.info("Configuring wifi {ssid} and psk...".format(**data))
        else:
            self._logger.info("Configuring wifi {ssid}...".format(**data))
            data['psk'] = None

        result = self.nmcli.add_wifi_connection(ssid=data["ssid"], psk=data["psk"])

        if result:
            return make_response(jsonify(connection_uuid=result), 200)
        else:
            return make_response(jsonify(), 400)
Example #15
0
def wizardState():
	if not s().getBoolean(["server", "firstRun"]) and not admin_permission.can():
		abort(403)

	seen_wizards = s().get(["server", "seenWizards"])

	result = dict()
	wizard_plugins = octoprint.server.pluginManager.get_implementations(octoprint.plugin.WizardPlugin)
	for implementation in wizard_plugins:
		name = implementation._identifier
		try:
			required = implementation.is_wizard_required()
			details = implementation.get_wizard_details()
			version = implementation.get_wizard_version()
			ignored = octoprint.plugin.WizardPlugin.is_wizard_ignored(seen_wizards, implementation)
		except:
			logging.getLogger(__name__).exception("There was an error fetching wizard details for {}, ignoring".format(name))
		else:
			result[name] = dict(required=required, details=details, version=version, ignored=ignored)

	return jsonify(result)
	def on_api_command(self, command, data):
		self._logger.info("Command {command} with {data} ".format(command=command, data=data))
		if command == "scan_wifi":
			wifis = self._get_wifi_list(force=True)
			self._logger.info("Wifi scan initiated")
			return jsonify(dict(wifis=wifis))

		# any commands processed after this check require admin permissions
		if not admin_permission.can():
			return make_response("Insufficient rights", 403)

		if command == "configure_wifi":
			if data["psk"]:
				self._logger.info("Configuring wifi {ssid} and psk...".format(**data))
			else:
				self._logger.info("Configuring wifi {ssid}...".format(**data))

			return self._configure_and_select_wifi(ssid=data["ssid"], psk=data["psk"])

		elif command == "disconnect_wifi":
			return self._disconnect_wifi()

		elif command == "reset":
			self._reset()
 def reset_wifi(self):
     if not admin_permission.can():
         return make_response(jsonify({"message": "Insufficient rights"}),
                              403)
     self._reset_wifi()
     return make_response(jsonify(), 200)
 def reset_wifi(self):
     if not admin_permission.can():
         return make_response(jsonify({ "message": "Insufficient rights"}), 403)
     self._reset_wifi()
     return make_response(jsonify(), 200)
Example #19
0
def getSettings():
	s = settings()

	connectionOptions = getConnectionOptions()

	data = {
		"api": {
			"enabled": s.getBoolean(["api", "enabled"]),
			"key": s.get(["api", "key"]) if admin_permission.can() else "n/a",
			"allowCrossOrigin": s.get(["api", "allowCrossOrigin"])
		},
		"appearance": {
			"name": s.get(["appearance", "name"]),
			"color": s.get(["appearance", "color"])
		},
		"printer": {
			"defaultExtrusionLength": s.getInt(["printerParameters", "defaultExtrusionLength"])
		},
		"webcam": {
			"streamUrl": s.get(["webcam", "stream"]),
			"snapshotUrl": s.get(["webcam", "snapshot"]),
			"ffmpegPath": s.get(["webcam", "ffmpeg"]),
			"bitrate": s.get(["webcam", "bitrate"]),
			"watermark": s.getBoolean(["webcam", "watermark"]),
			"flipH": s.getBoolean(["webcam", "flipH"]),
			"flipV": s.getBoolean(["webcam", "flipV"])
		},
		"feature": {
			"gcodeViewer": s.getBoolean(["gcodeViewer", "enabled"]),
			"temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]),
			"waitForStart": s.getBoolean(["feature", "waitForStartOnConnect"]),
			"alwaysSendChecksum": s.getBoolean(["feature", "alwaysSendChecksum"]),
			"sdSupport": s.getBoolean(["feature", "sdSupport"]),
			"sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]),
			"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]),
			"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"])
		},
		"serial": {
			"port": connectionOptions["portPreference"],
			"baudrate": connectionOptions["baudratePreference"],
			"portOptions": connectionOptions["ports"],
			"baudrateOptions": connectionOptions["baudrates"],
			"autoconnect": s.getBoolean(["serial", "autoconnect"]),
			"timeoutConnection": s.getFloat(["serial", "timeout", "connection"]),
			"timeoutDetection": s.getFloat(["serial", "timeout", "detection"]),
			"timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]),
			"timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]),
			"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
			"log": s.getBoolean(["serial", "log"])
		},
		"folder": {
			"uploads": s.getBaseFolder("uploads"),
			"timelapse": s.getBaseFolder("timelapse"),
			"timelapseTmp": s.getBaseFolder("timelapse_tmp"),
			"logs": s.getBaseFolder("logs"),
			"watched": s.getBaseFolder("watched")
		},
		"temperature": {
			"profiles": s.get(["temperature", "profiles"])
		},
		"system": {
			"actions": s.get(["system", "actions"]),
			"events": s.get(["system", "events"])
		},
		"terminalFilters": s.get(["terminalFilters"]),
	        "fastbotArgs": {
	                    "firmwareVersion": s.get(["fastbotArgs", "firmwareVersion"]),
	                    "staticIPAddress": s.get(["fastbotArgs", "staticIPAddress"]),
	                    "staticIPNetmask": s.get(["fastbotArgs", "staticIPNetmask"]),
	                    "staticIPGateWay": s.get(["fastbotArgs", "staticIPGateWay"])
	         },
		"cura": {
			"enabled": s.getBoolean(["cura", "enabled"]),
			"path": s.get(["cura", "path"]),
			"config": s.get(["cura", "config"])
		}
	}

	def process_plugin_result(name, plugin, result):
		if result:
			if not "plugins" in data:
				data["plugins"] = dict()
			if "__enabled" in result:
				del result["__enabled"]
			data["plugins"][name] = result

	octoprint.plugin.call_plugin(octoprint.plugin.SettingsPlugin,
	                             "on_settings_load",
	                             callback=process_plugin_result)

	return jsonify(data)
Example #20
0
def setTimelapseConfig():
	data = request.values
	if hasattr(request, "json") and request.json:
		data = request.json

	if "type" in data:
		config = {
			"type": data["type"],
			"postRoll": 0,
			"fps": 25,
			"options": {}
		}

		if "postRoll" in data:
			try:
				postRoll = int(data["postRoll"])
			except ValueError:
				return make_response("Invalid value for postRoll: %r" % data["postRoll"], 400)
			else:
				if postRoll >= 0:
					config["postRoll"] = postRoll
				else:
					return make_response("Invalid value for postRoll: %d" % postRoll, 400)

		if "fps" in data:
			try:
				fps = int(data["fps"])
			except ValueError:
				return make_response("Invalid value for fps: %r" % data["fps"], 400)
			else:
				if fps > 0:
					config["fps"] = fps
				else:
					return make_response("Invalid value for fps: %d" % fps, 400)

		if "interval" in data:
			try:
				interval = int(data["interval"])
			except ValueError:
				return make_response("Invalid value for interval: %r" % data["interval"], 400)
			else:
				if interval > 0:
					config["options"]["interval"] = interval
				else:
					return make_response("Invalid value for interval: %d" % interval, 400)

		if "capturePostRoll" in data:
			try:
				capturePostRoll = bool(data["capturePostRoll"])
			except ValueError:
				return make_response("Invalid value for capturePostRoll: %r" % data["capturePostRoll"], 400)
			else:
				config["options"]["capturePostRoll"] = capturePostRoll

		if "retractionZHop" in data:
			try:
				retractionZHop = float(data["retractionZHop"])
			except ValueError:
				return make_response("Invalid value for retraction Z-Hop: %r" % data["retractionZHop"], 400)
			else:
				if retractionZHop >= 0:
					config["options"]["retractionZHop"] = retractionZHop
				else:
					return make_response("Invalid value for retraction Z-Hop: %f" % retractionZHop, 400)

		if "minDelay" in data:
			try:
				minDelay = float(data["minDelay"])
			except ValueError:
				return make_response("Invalid value for minimum delay: %r" % data["minDelay"], 400)
			else:
				if minDelay > 0:
					config["options"]["minDelay"] = minDelay
				else:
					return make_response("Invalid value for minimum delay: %f" % minDelay, 400)

		if admin_permission.can() and "save" in data and data["save"] in valid_boolean_trues:
			octoprint.timelapse.configure_timelapse(config, True)
		else:
			octoprint.timelapse.configure_timelapse(config)

	return getTimelapseData()
Example #21
0
def getSettings():
    s = settings()

    connectionOptions = printer.__class__.get_connection_options()

    # NOTE: Remember to adjust the docs of the data model on the Settings API if anything
    # is changed, added or removed here

    data = {
        "api": {
            "enabled": s.getBoolean(["api", "enabled"]),
            "key": s.get(["api", "key"]) if admin_permission.can() else "n/a",
            "allowCrossOrigin": s.get(["api", "allowCrossOrigin"])
        },
        "appearance": {
            "name":
            s.get(["appearance", "name"]),
            "color":
            s.get(["appearance", "color"]),
            "colorTransparent":
            s.getBoolean(["appearance", "colorTransparent"]),
            "defaultLanguage":
            s.get(["appearance", "defaultLanguage"]),
            "showFahrenheitAlso":
            s.getBoolean(["appearance", "showFahrenheitAlso"])
        },
        "printer": {
            "defaultExtrusionLength":
            s.getInt(["printerParameters", "defaultExtrusionLength"])
        },
        "webcam": {
            "streamUrl": s.get(["webcam", "stream"]),
            "snapshotUrl": s.get(["webcam", "snapshot"]),
            "ffmpegPath": s.get(["webcam", "ffmpeg"]),
            "bitrate": s.get(["webcam", "bitrate"]),
            "ffmpegThreads": s.get(["webcam", "ffmpegThreads"]),
            "watermark": s.getBoolean(["webcam", "watermark"]),
            "flipH": s.getBoolean(["webcam", "flipH"]),
            "flipV": s.getBoolean(["webcam", "flipV"]),
            "rotate90": s.getBoolean(["webcam", "rotate90"])
        },
        "feature": {
            "gcodeViewer":
            s.getBoolean(["gcodeViewer", "enabled"]),
            "sizeThreshold":
            s.getInt(["gcodeViewer", "sizeThreshold"]),
            "mobileSizeThreshold":
            s.getInt(["gcodeViewer", "mobileSizeThreshold"]),
            "temperatureGraph":
            s.getBoolean(["feature", "temperatureGraph"]),
            "waitForStart":
            s.getBoolean(["feature", "waitForStartOnConnect"]),
            "alwaysSendChecksum":
            s.getBoolean(["feature", "alwaysSendChecksum"]),
            "neverSendChecksum":
            s.getBoolean(["feature", "neverSendChecksum"]),
            "sdSupport":
            s.getBoolean(["feature", "sdSupport"]),
            "sdRelativePath":
            s.getBoolean(["feature", "sdRelativePath"]),
            "sdAlwaysAvailable":
            s.getBoolean(["feature", "sdAlwaysAvailable"]),
            "swallowOkAfterResend":
            s.getBoolean(["feature", "swallowOkAfterResend"]),
            "repetierTargetTemp":
            s.getBoolean(["feature", "repetierTargetTemp"]),
            "externalHeatupDetection":
            s.getBoolean(["feature", "externalHeatupDetection"]),
            "keyboardControl":
            s.getBoolean(["feature", "keyboardControl"]),
            "pollWatched":
            s.getBoolean(["feature", "pollWatched"]),
            "ignoreIdenticalResends":
            s.getBoolean(["feature", "ignoreIdenticalResends"]),
            "modelSizeDetection":
            s.getBoolean(["feature", "modelSizeDetection"]),
            "firmwareDetection":
            s.getBoolean(["feature", "firmwareDetection"]),
            "printCancelConfirmation":
            s.getBoolean(["feature", "printCancelConfirmation"])
        },
        "serial": {
            "port":
            connectionOptions["portPreference"],
            "baudrate":
            connectionOptions["baudratePreference"],
            "portOptions":
            connectionOptions["ports"],
            "baudrateOptions":
            connectionOptions["baudrates"],
            "autoconnect":
            s.getBoolean(["serial", "autoconnect"]),
            "timeoutConnection":
            s.getFloat(["serial", "timeout", "connection"]),
            "timeoutDetection":
            s.getFloat(["serial", "timeout", "detection"]),
            "timeoutCommunication":
            s.getFloat(["serial", "timeout", "communication"]),
            "timeoutTemperature":
            s.getFloat(["serial", "timeout", "temperature"]),
            "timeoutTemperatureTargetSet":
            s.getFloat(["serial", "timeout", "temperatureTargetSet"]),
            "timeoutSdStatus":
            s.getFloat(["serial", "timeout", "sdStatus"]),
            "log":
            s.getBoolean(["serial", "log"]),
            "additionalPorts":
            s.get(["serial", "additionalPorts"]),
            "additionalBaudrates":
            s.get(["serial", "additionalBaudrates"]),
            "longRunningCommands":
            s.get(["serial", "longRunningCommands"]),
            "checksumRequiringCommands":
            s.get(["serial", "checksumRequiringCommands"]),
            "helloCommand":
            s.get(["serial", "helloCommand"]),
            "ignoreErrorsFromFirmware":
            s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
            "disconnectOnErrors":
            s.getBoolean(["serial", "disconnectOnErrors"]),
            "triggerOkForM29":
            s.getBoolean(["serial", "triggerOkForM29"]),
            "supportResendsWithoutOk":
            s.getBoolean(["serial", "supportResendsWithoutOk"]),
            "maxTimeoutsIdle":
            s.getInt(["serial", "maxCommunicationTimeouts", "idle"]),
            "maxTimeoutsPrinting":
            s.getInt(["serial", "maxCommunicationTimeouts", "printing"]),
            "maxTimeoutsLong":
            s.getInt(["serial", "maxCommunicationTimeouts", "long"])
        },
        "folder": {
            "uploads": s.getBaseFolder("uploads"),
            "timelapse": s.getBaseFolder("timelapse"),
            "timelapseTmp": s.getBaseFolder("timelapse_tmp"),
            "logs": s.getBaseFolder("logs"),
            "watched": s.getBaseFolder("watched")
        },
        "temperature": {
            "profiles": s.get(["temperature", "profiles"]),
            "cutoff": s.getInt(["temperature", "cutoff"])
        },
        "system": {
            "actions": s.get(["system", "actions"]),
            "events": s.get(["system", "events"])
        },
        "terminalFilters": s.get(["terminalFilters"]),
        "scripts": {
            "gcode": {
                "afterPrinterConnected": None,
                "beforePrinterDisconnected": None,
                "beforePrintStarted": None,
                "afterPrintCancelled": None,
                "afterPrintDone": None,
                "beforePrintPaused": None,
                "afterPrintResumed": None,
                "snippets": dict()
            }
        },
        "server": {
            "commands": {
                "systemShutdownCommand":
                s.get(["server", "commands", "systemShutdownCommand"]),
                "systemRestartCommand":
                s.get(["server", "commands", "systemRestartCommand"]),
                "serverRestartCommand":
                s.get(["server", "commands", "serverRestartCommand"])
            },
            "diskspace": {
                "warning": s.getInt(["server", "diskspace", "warning"]),
                "critical": s.getInt(["server", "diskspace", "critical"])
            }
        }
    }

    gcode_scripts = s.listScripts("gcode")
    if gcode_scripts:
        data["scripts"] = dict(gcode=dict())
        for name in gcode_scripts:
            data["scripts"]["gcode"][name] = s.loadScript("gcode",
                                                          name,
                                                          source=True)

    plugin_settings = _get_plugin_settings()
    if len(plugin_settings):
        data["plugins"] = plugin_settings

    return jsonify(data)
Example #22
0
def setTimelapseConfig():
    data = request.values
    if hasattr(request, "json") and request.json:
        data = request.json

    if "type" in data:
        config = {
            "type": data["type"],
            "postRoll": 0,
            "fps": 25,
            "options": {}
        }

        if "postRoll" in data:
            try:
                postRoll = int(data["postRoll"])
            except ValueError:
                return make_response(
                    "Invalid value for postRoll: %r" % data["postRoll"], 400)
            else:
                if postRoll >= 0:
                    config["postRoll"] = postRoll
                else:
                    return make_response(
                        "Invalid value for postRoll: %d" % postRoll, 400)

        if "fps" in data:
            try:
                fps = int(data["fps"])
            except ValueError:
                return make_response("Invalid value for fps: %r" % data["fps"],
                                     400)
            else:
                if fps > 0:
                    config["fps"] = fps
                else:
                    return make_response("Invalid value for fps: %d" % fps,
                                         400)

        if "interval" in data:
            config["options"] = {"interval": 10}

            try:
                interval = int(data["interval"])
            except ValueError:
                return make_response("Invalid value for interval: %r" %
                                     data["interval"])
            else:
                if interval > 0:
                    config["options"]["interval"] = interval
                else:
                    return make_response("Invalid value for interval: %d" %
                                         interval)

        if "capturePostRoll" in data:
            config["options"]["capturePostRoll"] = True
            try:
                capturePostRoll = bool(data["capturePostRoll"])
            except ValueError:
                return make_response("Invalid value for capturePostRoll: %r" %
                                     data["capturePostRoll"])
            else:
                config["options"]["capturePostRoll"] = capturePostRoll

        if "retractionZHop" in data:
            config["options"] = {"retractionZHop": 0}

            try:
                retractionZHop = float(data["retractionZHop"])
            except ValueError:
                return make_response("Invalid value for retraction Z-Hop: %r" %
                                     data["retractionZHop"])
            else:
                if retractionZHop > 0:
                    config["options"]["retractionZHop"] = retractionZHop
                else:
                    return make_response(
                        "Invalid value for retraction Z-Hop: %d" %
                        retractionZHop)

        if admin_permission.can(
        ) and "save" in data and data["save"] in valid_boolean_trues:
            octoprint.timelapse.configure_timelapse(config, True)
        else:
            octoprint.timelapse.configure_timelapse(config)

    return getTimelapseData()
Example #23
0
def setTimelapseConfig():
    data = request.get_json(silent=True)
    if data is None:
        data = request.values

    if "type" in data:
        config = {
            "type": data["type"],
            "postRoll": 0,
            "fps": 25,
            "options": {}
        }

        if "postRoll" in data:
            try:
                postRoll = int(data["postRoll"])
            except ValueError:
                abort(400, description="postRoll is invalid")
            else:
                if postRoll >= 0:
                    config["postRoll"] = postRoll
                else:
                    abort(400, description="postRoll is invalid")

        if "fps" in data:
            try:
                fps = int(data["fps"])
            except ValueError:
                abort(400, description="fps is invalid")
            else:
                if fps > 0:
                    config["fps"] = fps
                else:
                    abort(400, description="fps is invalid")

        if "interval" in data:
            try:
                interval = int(data["interval"])
            except ValueError:
                abort(400, description="interval is invalid")
            else:
                if interval > 0:
                    config["options"]["interval"] = interval
                else:
                    abort(400, description="interval is invalid")

        if "retractionZHop" in data:
            try:
                retractionZHop = float(data["retractionZHop"])
            except ValueError:
                abort(400, description="retractionZHop is invalid")
            else:
                if retractionZHop >= 0:
                    config["options"]["retractionZHop"] = retractionZHop
                else:
                    abort(400, description="retractionZHop is invalid")

        if "minDelay" in data:
            try:
                minDelay = float(data["minDelay"])
            except ValueError:
                abort(400, description="minDelay is invalid")
            else:
                if minDelay > 0:
                    config["options"]["minDelay"] = minDelay
                else:
                    abort(400, description="minDelay is invalid")

        if (admin_permission.can() and "save" in data
                and data["save"] in valid_boolean_trues):
            octoprint.timelapse.configure_timelapse(config, True)
        else:
            octoprint.timelapse.configure_timelapse(config)

    return getTimelapseData()
Example #24
0
def setTimelapseConfig():
    data = request.get_json(silent=True)
    if data is None:
        data = request.values

    if "type" in data:
        config = {
            "type": data["type"],
            "postRoll": 0,
            "fps": 25,
            "options": {}
        }

        if "postRoll" in data:
            try:
                postRoll = int(data["postRoll"])
            except ValueError:
                return make_response(
                    "Invalid value for postRoll: %r" % data["postRoll"], 400)
            else:
                if postRoll >= 0:
                    config["postRoll"] = postRoll
                else:
                    return make_response(
                        "Invalid value for postRoll: %d" % postRoll, 400)

        if "fps" in data:
            try:
                fps = int(data["fps"])
            except ValueError:
                return make_response("Invalid value for fps: %r" % data["fps"],
                                     400)
            else:
                if fps > 0:
                    config["fps"] = fps
                else:
                    return make_response("Invalid value for fps: %d" % fps,
                                         400)

        if "interval" in data:
            try:
                interval = int(data["interval"])
            except ValueError:
                return make_response(
                    "Invalid value for interval: %r" % data["interval"], 400)
            else:
                if interval > 0:
                    config["options"]["interval"] = interval
                else:
                    return make_response(
                        "Invalid value for interval: %d" % interval, 400)

        if "retractionZHop" in data:
            try:
                retractionZHop = float(data["retractionZHop"])
            except ValueError:
                return make_response(
                    "Invalid value for retraction Z-Hop: %r" %
                    data["retractionZHop"], 400)
            else:
                if retractionZHop >= 0:
                    config["options"]["retractionZHop"] = retractionZHop
                else:
                    return make_response(
                        "Invalid value for retraction Z-Hop: %f" %
                        retractionZHop, 400)

        if "minDelay" in data:
            try:
                minDelay = float(data["minDelay"])
            except ValueError:
                return make_response(
                    "Invalid value for minimum delay: %r" % data["minDelay"],
                    400)
            else:
                if minDelay > 0:
                    config["options"]["minDelay"] = minDelay
                else:
                    return make_response(
                        "Invalid value for minimum delay: %f" % minDelay, 400)

        if (admin_permission.can() and "save" in data
                and data["save"] in valid_boolean_trues):
            octoprint.timelapse.configure_timelapse(config, True)
        else:
            octoprint.timelapse.configure_timelapse(config)

    return getTimelapseData()
Example #25
0
def getSettings():
	s = settings()

	connectionOptions = printer.__class__.get_connection_options()

	# NOTE: Remember to adjust the docs of the data model on the Settings API if anything
	# is changed, added or removed here

	data = {
		"api": {
			"key": s.get(["api", "key"]) if admin_permission.can() else None,
			"allowCrossOrigin": s.get(["api", "allowCrossOrigin"])
		},
		"appearance": {
			"name": s.get(["appearance", "name"]),
			"color": s.get(["appearance", "color"]),
			"colorTransparent": s.getBoolean(["appearance", "colorTransparent"]),
			"colorIcon": s.getBoolean(["appearance", "colorIcon"]),
			"defaultLanguage": s.get(["appearance", "defaultLanguage"]),
			"showFahrenheitAlso": s.getBoolean(["appearance", "showFahrenheitAlso"]),
			"fuzzyTimes": s.getBoolean(["appearance", "fuzzyTimes"])
		},
		"printer": {
			"defaultExtrusionLength": s.getInt(["printerParameters", "defaultExtrusionLength"])
		},
		"webcam": {
			"webcamEnabled": s.getBoolean(["webcam", "webcamEnabled"]),
			"timelapseEnabled": s.getBoolean(["webcam", "timelapseEnabled"]),
			"streamUrl": s.get(["webcam", "stream"]),
			"streamRatio": s.get(["webcam", "streamRatio"]),
			"streamTimeout": s.getInt(["webcam", "streamTimeout"]),
			"snapshotUrl": s.get(["webcam", "snapshot"]),
			"snapshotTimeout": s.getInt(["webcam", "snapshotTimeout"]),
			"snapshotSslValidation": s.getBoolean(["webcam", "snapshotSslValidation"]),
			"ffmpegPath": s.get(["webcam", "ffmpeg"]),
			"bitrate": s.get(["webcam", "bitrate"]),
			"ffmpegThreads": s.get(["webcam", "ffmpegThreads"]),
			"watermark": s.getBoolean(["webcam", "watermark"]),
			"flipH": s.getBoolean(["webcam", "flipH"]),
			"flipV": s.getBoolean(["webcam", "flipV"]),
			"rotate90": s.getBoolean(["webcam", "rotate90"])
		},
		"feature": {
			"gcodeViewer": s.getBoolean(["gcodeViewer", "enabled"]),
			"sizeThreshold": s.getInt(["gcodeViewer", "sizeThreshold"]),
			"mobileSizeThreshold": s.getInt(["gcodeViewer", "mobileSizeThreshold"]),
			"temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]),
			"sdSupport": s.getBoolean(["feature", "sdSupport"]),
			"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
			"pollWatched": s.getBoolean(["feature", "pollWatched"]),
			"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]),
			"printCancelConfirmation": s.getBoolean(["feature", "printCancelConfirmation"]),
			"g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"]),
			"autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"])
		},
		"serial": {
			"port": connectionOptions["portPreference"],
			"baudrate": connectionOptions["baudratePreference"],
			"exclusive": s.getBoolean(["serial", "exclusive"]),
			"portOptions": connectionOptions["ports"],
			"baudrateOptions": connectionOptions["baudrates"],
			"autoconnect": s.getBoolean(["serial", "autoconnect"]),
			"timeoutConnection": s.getFloat(["serial", "timeout", "connection"]),
			"timeoutDetection": s.getFloat(["serial", "timeout", "detection"]),
			"timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]),
			"timeoutCommunicationBusy": s.getFloat(["serial", "timeout", "communicationBusy"]),
			"timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]),
			"timeoutTemperatureTargetSet": s.getFloat(["serial", "timeout", "temperatureTargetSet"]),
			"timeoutTemperatureAutoreport": s.getFloat(["serial", "timeout", "temperatureAutoreport"]),
			"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
			"timeoutSdStatusAutoreport": s.getFloat(["serial", "timeout", "sdStatusAutoreport"]),
			"timeoutBaudrateDetectionPause": s.getFloat(["serial", "timeout", "baudrateDetectionPause"]),
			"timeoutPositionLogWait": s.getFloat(["serial", "timeout", "positionLogWait"]),
			"log": s.getBoolean(["serial", "log"]),
			"additionalPorts": s.get(["serial", "additionalPorts"]),
			"additionalBaudrates": s.get(["serial", "additionalBaudrates"]),
			"longRunningCommands": s.get(["serial", "longRunningCommands"]),
			"checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]),
			"blockedCommands": s.get(["serial", "blockedCommands"]),
			"pausingCommands": s.get(["serial", "pausingCommands"]),
			"helloCommand": s.get(["serial", "helloCommand"]),
			"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
			"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
			"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]),
			"logPositionOnPause": s.getBoolean(["serial", "logPositionOnPause"]),
			"logPositionOnCancel": s.getBoolean(["serial", "logPositionOnCancel"]),
			"abortHeatupOnCancel": s.getBoolean(["serial", "abortHeatupOnCancel"]),
			"supportResendsWithoutOk": s.get(["serial", "supportResendsWithoutOk"]),
			"waitForStart": s.getBoolean(["serial", "waitForStartOnConnect"]),
			"alwaysSendChecksum": s.getBoolean(["serial", "alwaysSendChecksum"]),
			"neverSendChecksum": s.getBoolean(["serial", "neverSendChecksum"]),
			"sdRelativePath": s.getBoolean(["serial", "sdRelativePath"]),
			"sdAlwaysAvailable": s.getBoolean(["serial", "sdAlwaysAvailable"]),
			"swallowOkAfterResend": s.getBoolean(["serial", "swallowOkAfterResend"]),
			"repetierTargetTemp": s.getBoolean(["serial", "repetierTargetTemp"]),
			"externalHeatupDetection": s.getBoolean(["serial", "externalHeatupDetection"]),
			"ignoreIdenticalResends": s.getBoolean(["serial", "ignoreIdenticalResends"]),
			"firmwareDetection": s.getBoolean(["serial", "firmwareDetection"]),
			"blockWhileDwelling": s.getBoolean(["serial", "blockWhileDwelling"]),
			"maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]),
			"maxTimeoutsPrinting": s.getInt(["serial", "maxCommunicationTimeouts", "printing"]),
			"maxTimeoutsLong": s.getInt(["serial", "maxCommunicationTimeouts", "long"]),
			"capAutoreportTemp": s.getBoolean(["serial", "capabilities", "autoreport_temp"]),
			"capAutoreportSdStatus": s.getBoolean(["serial", "capabilities", "autoreport_sdstatus"]),
			"capBusyProtocol": s.getBoolean(["serial", "capabilities", "busy_protocol"]),
			"capEmergencyParser": s.getBoolean(["serial", "capabilities", "emergency_parser"])
		},
		"folder": {
			"uploads": s.getBaseFolder("uploads"),
			"timelapse": s.getBaseFolder("timelapse"),
			"timelapseTmp": s.getBaseFolder("timelapse_tmp"),
			"logs": s.getBaseFolder("logs"),
			"watched": s.getBaseFolder("watched")
		},
		"temperature": {
			"profiles": s.get(["temperature", "profiles"]),
			"cutoff": s.getInt(["temperature", "cutoff"]),
			"sendAutomatically": s.getBoolean(["temperature", "sendAutomatically"]),
			"sendAutomaticallyAfter": s.getInt(["temperature", "sendAutomaticallyAfter"], min=0, max=30),
		},
		"system": {
			"actions": s.get(["system", "actions"]),
			"events": s.get(["system", "events"])
		},
		"terminalFilters": s.get(["terminalFilters"]),
		"scripts": {
			"gcode": {
				"afterPrinterConnected": None,
				"beforePrinterDisconnected": None,
				"beforePrintStarted": None,
				"afterPrintCancelled": None,
				"afterPrintDone": None,
				"beforePrintPaused": None,
				"afterPrintResumed": None,
				"beforeToolChange": None,
				"afterToolChange": None,
				"snippets": dict()
			}
		},
		"server": {
			"commands": {
				"systemShutdownCommand": s.get(["server", "commands", "systemShutdownCommand"]),
				"systemRestartCommand": s.get(["server", "commands", "systemRestartCommand"]),
				"serverRestartCommand": s.get(["server", "commands", "serverRestartCommand"])
			},
			"diskspace": {
				"warning": s.getInt(["server", "diskspace", "warning"]),
				"critical": s.getInt(["server", "diskspace", "critical"])
			},
			"onlineCheck": {
				"enabled": s.getBoolean(["server", "onlineCheck", "enabled"]),
				"interval": int(s.getInt(["server", "onlineCheck", "interval"]) / 60),
				"host": s.get(["server", "onlineCheck", "host"]),
				"port": s.getInt(["server", "onlineCheck", "port"])
			},
			"pluginBlacklist": {
				"enabled": s.getBoolean(["server", "pluginBlacklist", "enabled"]),
				"url": s.get(["server", "pluginBlacklist", "url"]),
				"ttl": int(s.getInt(["server", "pluginBlacklist", "ttl"]) / 60)
			}
		}
	}

	gcode_scripts = s.listScripts("gcode")
	if gcode_scripts:
		data["scripts"] = dict(gcode=dict())
		for name in gcode_scripts:
			data["scripts"]["gcode"][name] = s.loadScript("gcode", name, source=True)

	plugin_settings = _get_plugin_settings()
	if len(plugin_settings):
		data["plugins"] = plugin_settings

	return jsonify(data)
Example #26
0
def getSettings():
	s = settings()

	connectionOptions = get_connection_options()

	data = {
		"api": {
			"enabled": s.getBoolean(["api", "enabled"]),
			"key": s.get(["api", "key"]) if admin_permission.can() else "n/a",
			"allowCrossOrigin": s.get(["api", "allowCrossOrigin"])
		},
		"appearance": {
			"name": s.get(["appearance", "name"]),
			"color": s.get(["appearance", "color"]),
			"colorTransparent": s.getBoolean(["appearance", "colorTransparent"]),
			"defaultLanguage": s.get(["appearance", "defaultLanguage"])
		},
		"printer": {
			"defaultExtrusionLength": s.getInt(["printerParameters", "defaultExtrusionLength"])
		},
		"webcam": {
			"streamUrl": s.get(["webcam", "stream"]),
			"snapshotUrl": s.get(["webcam", "snapshot"]),
			"ffmpegPath": s.get(["webcam", "ffmpeg"]),
			"bitrate": s.get(["webcam", "bitrate"]),
			"ffmpegThreads": s.get(["webcam", "ffmpegThreads"]),
			"watermark": s.getBoolean(["webcam", "watermark"]),
			"flipH": s.getBoolean(["webcam", "flipH"]),
			"flipV": s.getBoolean(["webcam", "flipV"]),
			"rotate90": s.getBoolean(["webcam", "rotate90"])
		},
		"feature": {
			"gcodeViewer": s.getBoolean(["gcodeViewer", "enabled"]),
			"temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]),
			"waitForStart": s.getBoolean(["feature", "waitForStartOnConnect"]),
			"alwaysSendChecksum": s.getBoolean(["feature", "alwaysSendChecksum"]),
			"sdSupport": s.getBoolean(["feature", "sdSupport"]),
			"sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]),
			"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]),
			"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]),
			"externalHeatupDetection": s.getBoolean(["feature", "externalHeatupDetection"]),
			"keyboardControl": s.getBoolean(["feature", "keyboardControl"])
		},
		"serial": {
			"port": connectionOptions["portPreference"],
			"baudrate": connectionOptions["baudratePreference"],
			"portOptions": connectionOptions["ports"],
			"baudrateOptions": connectionOptions["baudrates"],
			"autoconnect": s.getBoolean(["serial", "autoconnect"]),
			"timeoutConnection": s.getFloat(["serial", "timeout", "connection"]),
			"timeoutDetection": s.getFloat(["serial", "timeout", "detection"]),
			"timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]),
			"timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]),
			"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
			"log": s.getBoolean(["serial", "log"]),
			"additionalPorts": s.get(["serial", "additionalPorts"]),
			"longRunningCommands": s.get(["serial", "longRunningCommands"])
		},
		"folder": {
			"uploads": s.getBaseFolder("uploads"),
			"timelapse": s.getBaseFolder("timelapse"),
			"timelapseTmp": s.getBaseFolder("timelapse_tmp"),
			"logs": s.getBaseFolder("logs"),
			"watched": s.getBaseFolder("watched")
		},
		"temperature": {
			"profiles": s.get(["temperature", "profiles"]),
			"cutoff": s.getInt(["temperature", "cutoff"])
		},
		"system": {
			"actions": s.get(["system", "actions"]),
			"events": s.get(["system", "events"])
		},
		"terminalFilters": s.get(["terminalFilters"]),
		"scripts": {
			"gcode": {
				"afterPrinterConnected": None,
				"beforePrintStarted": None,
				"afterPrintCancelled": None,
				"afterPrintDone": None,
				"beforePrintPaused": None,
				"afterPrintResumed": None,
				"snippets": dict()
			}
		}
	}

	gcode_scripts = s.listScripts("gcode")
	if gcode_scripts:
		data["scripts"] = dict(gcode=dict())
		for name in gcode_scripts:
			data["scripts"]["gcode"][name] = s.loadScript("gcode", name, source=True)

	def process_plugin_result(name, plugin, result):
		if result:
			if not "plugins" in data:
				data["plugins"] = dict()
			if "__enabled" in result:
				del result["__enabled"]
			data["plugins"][name] = result

	octoprint.plugin.call_plugin(octoprint.plugin.SettingsPlugin,
	                             "on_settings_load",
	                             callback=process_plugin_result)

	return jsonify(data)
    def disconnect_wifi(self):
        if not admin_permission.can():
            return make_response(jsonify({ "message": "Insufficient rights"}), 403)

        return self._disconnect_wifi()
    def disconnect_wifi(self):
        if not admin_permission.can():
            return make_response(jsonify({"message": "Insufficient rights"}),
                                 403)

        return self._disconnect_wifi()
Example #29
0
def getSettings():
	logger = logging.getLogger(__name__)

	s = settings()

	connectionOptions = get_connection_options()

	data = {
		"api": {
			"enabled": s.getBoolean(["api", "enabled"]),
			"key": s.get(["api", "key"]) if admin_permission.can() else "n/a",
			"allowCrossOrigin": s.get(["api", "allowCrossOrigin"])
		},
		"appearance": {
			"name": s.get(["appearance", "name"]),
			"color": s.get(["appearance", "color"]),
			"colorTransparent": s.getBoolean(["appearance", "colorTransparent"]),
			"defaultLanguage": s.get(["appearance", "defaultLanguage"])
		},
		"printer": {
			"defaultExtrusionLength": s.getInt(["printerParameters", "defaultExtrusionLength"])
		},
		"webcam": {
			"streamUrl": s.get(["webcam", "stream"]),
			"snapshotUrl": s.get(["webcam", "snapshot"]),
			"ffmpegPath": s.get(["webcam", "ffmpeg"]),
			"bitrate": s.get(["webcam", "bitrate"]),
			"ffmpegThreads": s.get(["webcam", "ffmpegThreads"]),
			"watermark": s.getBoolean(["webcam", "watermark"]),
			"flipH": s.getBoolean(["webcam", "flipH"]),
			"flipV": s.getBoolean(["webcam", "flipV"]),
			"rotate90": s.getBoolean(["webcam", "rotate90"])
		},
		"feature": {
			"gcodeViewer": s.getBoolean(["gcodeViewer", "enabled"]),
			"temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]),
			"waitForStart": s.getBoolean(["feature", "waitForStartOnConnect"]),
			"alwaysSendChecksum": s.getBoolean(["feature", "alwaysSendChecksum"]),
			"sdSupport": s.getBoolean(["feature", "sdSupport"]),
			"sdRelativePath": s.getBoolean(["feature", "sdRelativePath"]),
			"sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]),
			"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]),
			"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]),
			"externalHeatupDetection": s.getBoolean(["feature", "externalHeatupDetection"]),
			"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
			"pollWatched": s.getBoolean(["feature", "pollWatched"]),
			"ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"])
		},
		"serial": {
			"port": connectionOptions["portPreference"],
			"baudrate": connectionOptions["baudratePreference"],
			"portOptions": connectionOptions["ports"],
			"baudrateOptions": connectionOptions["baudrates"],
			"autoconnect": s.getBoolean(["serial", "autoconnect"]),
			"timeoutConnection": s.getFloat(["serial", "timeout", "connection"]),
			"timeoutDetection": s.getFloat(["serial", "timeout", "detection"]),
			"timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]),
			"timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]),
			"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
			"log": s.getBoolean(["serial", "log"]),
			"additionalPorts": s.get(["serial", "additionalPorts"]),
			"longRunningCommands": s.get(["serial", "longRunningCommands"]),
			"checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]),
			"helloCommand": s.get(["serial", "helloCommand"]),
			"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
			"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
			"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]),
			"supportResendsWithoutOk": s.getBoolean(["serial", "supportResendsWithoutOk"]),
			"maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]),
			"maxTimeoutsPrinting": s.getInt(["serial", "maxCommunicationTimeouts", "printing"]),
			"maxTimeoutsLong": s.getInt(["serial", "maxCommunicationTimeouts", "long"])
		},
		"folder": {
			"uploads": s.getBaseFolder("uploads"),
			"timelapse": s.getBaseFolder("timelapse"),
			"timelapseTmp": s.getBaseFolder("timelapse_tmp"),
			"logs": s.getBaseFolder("logs"),
			"watched": s.getBaseFolder("watched")
		},
		"temperature": {
			"profiles": s.get(["temperature", "profiles"]),
			"cutoff": s.getInt(["temperature", "cutoff"])
		},
		"system": {
			"actions": s.get(["system", "actions"]),
			"events": s.get(["system", "events"])
		},
		"terminalFilters": s.get(["terminalFilters"]),
		"scripts": {
			"gcode": {
				"afterPrinterConnected": None,
				"beforePrintStarted": None,
				"afterPrintCancelled": None,
				"afterPrintDone": None,
				"beforePrintPaused": None,
				"afterPrintResumed": None,
				"snippets": dict()
			}
		},
		"server": {
			"commands": {
				"systemShutdownCommand": s.get(["server", "commands", "systemShutdownCommand"]),
				"systemRestartCommand": s.get(["server", "commands", "systemRestartCommand"]),
				"serverRestartCommand": s.get(["server", "commands", "serverRestartCommand"])
			},
			"diskspace": {
				"warning": s.getInt(["server", "diskspace", "warning"]),
				"critical": s.getInt(["server", "diskspace", "critical"])
			}
		}
	}

	gcode_scripts = s.listScripts("gcode")
	if gcode_scripts:
		data["scripts"] = dict(gcode=dict())
		for name in gcode_scripts:
			data["scripts"]["gcode"][name] = s.loadScript("gcode", name, source=True)

	def process_plugin_result(name, result):
		if result:
			try:
				jsonify(test=result)
			except:
				logger.exception("Error while jsonifying settings from plugin {}, please contact the plugin author about this".format(name))

			if not "plugins" in data:
				data["plugins"] = dict()
			if "__enabled" in result:
				del result["__enabled"]
			data["plugins"][name] = result

	for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
		try:
			result = plugin.on_settings_load()
			process_plugin_result(plugin._identifier, result)
		except TypeError:
			logger.warn("Could not load settings for plugin {name} ({version}) since it called super(...)".format(name=plugin._plugin_name, version=plugin._plugin_version))
			logger.warn("in a way which has issues due to OctoPrint's dynamic reloading after plugin operations.")
			logger.warn("Please contact the plugin's author and ask to update the plugin to use a direct call like")
			logger.warn("octoprint.plugin.SettingsPlugin.on_settings_load(self) instead.")
		except:
			logger.exception("Could not load settings for plugin {name} ({version})".format(version=plugin._plugin_version, name=plugin._plugin_name))

	return jsonify(data)
Example #30
0
def getSettings():
    logger = logging.getLogger(__name__)

    s = settings()

    connectionOptions = get_connection_options()

    data = {
        "api": {
            "enabled": s.getBoolean(["api", "enabled"]),
            "key": s.get(["api", "key"]) if admin_permission.can() else "n/a",
            "allowCrossOrigin": s.get(["api", "allowCrossOrigin"])
        },
        "appearance": {
            "name": s.get(["appearance", "name"]),
            "color": s.get(["appearance", "color"]),
            "colorTransparent":
            s.getBoolean(["appearance", "colorTransparent"]),
            "defaultLanguage": s.get(["appearance", "defaultLanguage"])
        },
        "printer": {
            "defaultExtrusionLength":
            s.getInt(["printerParameters", "defaultExtrusionLength"])
        },
        "webcam": {
            "streamUrl": s.get(["webcam", "stream"]),
            "snapshotUrl": s.get(["webcam", "snapshot"]),
            "ffmpegPath": s.get(["webcam", "ffmpeg"]),
            "bitrate": s.get(["webcam", "bitrate"]),
            "ffmpegThreads": s.get(["webcam", "ffmpegThreads"]),
            "watermark": s.getBoolean(["webcam", "watermark"]),
            "flipH": s.getBoolean(["webcam", "flipH"]),
            "flipV": s.getBoolean(["webcam", "flipV"]),
            "rotate90": s.getBoolean(["webcam", "rotate90"])
        },
        "feature": {
            "gcodeViewer":
            s.getBoolean(["gcodeViewer", "enabled"]),
            "temperatureGraph":
            s.getBoolean(["feature", "temperatureGraph"]),
            "waitForStart":
            s.getBoolean(["feature", "waitForStartOnConnect"]),
            "alwaysSendChecksum":
            s.getBoolean(["feature", "alwaysSendChecksum"]),
            "sdSupport":
            s.getBoolean(["feature", "sdSupport"]),
            "sdAlwaysAvailable":
            s.getBoolean(["feature", "sdAlwaysAvailable"]),
            "swallowOkAfterResend":
            s.getBoolean(["feature", "swallowOkAfterResend"]),
            "repetierTargetTemp":
            s.getBoolean(["feature", "repetierTargetTemp"]),
            "externalHeatupDetection":
            s.getBoolean(["feature", "externalHeatupDetection"]),
            "keyboardControl":
            s.getBoolean(["feature", "keyboardControl"]),
            "pollWatched":
            s.getBoolean(["feature", "pollWatched"]),
            "ignoreIdenticalResends":
            s.getBoolean(["feature", "ignoreIdenticalResends"])
        },
        "serial": {
            "port":
            connectionOptions["portPreference"],
            "baudrate":
            connectionOptions["baudratePreference"],
            "portOptions":
            connectionOptions["ports"],
            "baudrateOptions":
            connectionOptions["baudrates"],
            "autoconnect":
            s.getBoolean(["serial", "autoconnect"]),
            "timeoutConnection":
            s.getFloat(["serial", "timeout", "connection"]),
            "timeoutDetection":
            s.getFloat(["serial", "timeout", "detection"]),
            "timeoutCommunication":
            s.getFloat(["serial", "timeout", "communication"]),
            "timeoutTemperature":
            s.getFloat(["serial", "timeout", "temperature"]),
            "timeoutSdStatus":
            s.getFloat(["serial", "timeout", "sdStatus"]),
            "log":
            s.getBoolean(["serial", "log"]),
            "additionalPorts":
            s.get(["serial", "additionalPorts"]),
            "longRunningCommands":
            s.get(["serial", "longRunningCommands"]),
            "ignoreErrorsFromFirmware":
            s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
            "disconnectOnErrors":
            s.getBoolean(["serial", "disconnectOnErrors"]),
        },
        "folder": {
            "uploads": s.getBaseFolder("uploads"),
            "timelapse": s.getBaseFolder("timelapse"),
            "timelapseTmp": s.getBaseFolder("timelapse_tmp"),
            "logs": s.getBaseFolder("logs"),
            "watched": s.getBaseFolder("watched")
        },
        "temperature": {
            "profiles": s.get(["temperature", "profiles"]),
            "cutoff": s.getInt(["temperature", "cutoff"])
        },
        "system": {
            "actions": s.get(["system", "actions"]),
            "events": s.get(["system", "events"])
        },
        "terminalFilters": s.get(["terminalFilters"]),
        "scripts": {
            "gcode": {
                "afterPrinterConnected": None,
                "beforePrintStarted": None,
                "afterPrintCancelled": None,
                "afterPrintDone": None,
                "beforePrintPaused": None,
                "afterPrintResumed": None,
                "snippets": dict()
            }
        },
        "server": {
            "commands": {
                "systemShutdownCommand":
                s.get(["server", "commands", "systemShutdownCommand"]),
                "systemRestartCommand":
                s.get(["server", "commands", "systemRestartCommand"]),
                "serverRestartCommand":
                s.get(["server", "commands", "serverRestartCommand"])
            },
            "diskspace": {
                "warning": s.getInt(["server", "diskspace", "warning"]),
                "critical": s.getInt(["server", "diskspace", "critical"])
            }
        }
    }

    gcode_scripts = s.listScripts("gcode")
    if gcode_scripts:
        data["scripts"] = dict(gcode=dict())
        for name in gcode_scripts:
            data["scripts"]["gcode"][name] = s.loadScript("gcode",
                                                          name,
                                                          source=True)

    def process_plugin_result(name, result):
        if result:
            try:
                jsonify(test=result)
            except:
                logger.exception(
                    "Error while jsonifying settings from plugin {}, please contact the plugin author about this"
                    .format(name))

            if not "plugins" in data:
                data["plugins"] = dict()
            if "__enabled" in result:
                del result["__enabled"]
            data["plugins"][name] = result

    for plugin in octoprint.plugin.plugin_manager().get_implementations(
            octoprint.plugin.SettingsPlugin):
        try:
            result = plugin.on_settings_load()
            process_plugin_result(plugin._identifier, result)
        except TypeError:
            logger.warn(
                "Could not load settings for plugin {name} ({version}) since it called super(...)"
                .format(name=plugin._plugin_name,
                        version=plugin._plugin_version))
            logger.warn(
                "in a way which has issues due to OctoPrint's dynamic reloading after plugin operations."
            )
            logger.warn(
                "Please contact the plugin's author and ask to update the plugin to use a direct call like"
            )
            logger.warn(
                "octoprint.plugin.SettingsPlugin.on_settings_load(self) instead."
            )
        except:
            logger.exception(
                "Could not load settings for plugin {name} ({version})".format(
                    version=plugin._plugin_version, name=plugin._plugin_name))

    return jsonify(data)