Exemplo n.º 1
0
    def setUp(self):
        # mock comm
        self.comm = MagicMock()

        # mock event manager
        self.event_manager = MagicMock()

        self.event_manager_patcher = patch(
            "octoprint.printer.standard.eventManager")
        self.event_manager_getter = self.event_manager_patcher.start()
        self.event_manager_getter.return_value = self.event_manager

        # mock plugin manager
        self.plugin_manager = MagicMock()
        self.plugin_manager.get_hooks.return_value = {}

        self.plugin_manager_patcher = patch(
            "octoprint.printer.standard.plugin_manager")
        self.plugin_manager_getter = self.plugin_manager_patcher.start()
        self.plugin_manager_getter.return_value = self.plugin_manager

        # mock settings
        self.settings = MagicMock()
        self.settings.getInt.return_value = 1
        self.settings.getBoolean.return_value = False

        self.settings_patcher = patch("octoprint.printer.standard.settings")
        self.settings_getter = self.settings_patcher.start()
        self.settings_getter.return_value = self.settings

        self.printer = Printer(MagicMock(), MagicMock(), MagicMock())
        self.printer._comm = self.comm
Exemplo n.º 2
0
    def start_print(self, pos=None, user=None, *args, **kwargs):

        if self.fileType == "gcode":
            Printer.start_print(self, pos, user)

        elif self.fileType == "sla_bin":
            #Printer.startPrint(self, pos, user, external_sd=True)
            #print(dir(self._comm))
            #print("printjob canceled")
            """
			Starts the currently loaded print job.
			Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
			"""
            if self._comm is None or not self._comm.isOperational(
            ) or self._comm.isPrinting():
                return

            with self._selectedFileMutex:
                if self._selectedFile is None:
                    return

            self._fileManager.delete_recovery_data()

            self._lastProgressReport = None
            self._updateProgressData()
            self._setCurrentZ(None)

            self._comm.sendCommand("M6030 '{filename}'".format(
                filename=self._comm._currentFile.getFilename().split(
                    u"/")[-1]))
Exemplo n.º 3
0
    def __init__(self, fileManager, analysisQueue, printerProfileManager):

        self._analysisQueue = analysisQueue
        self._fileManager = fileManager
        self._printerProfileManager = printerProfileManager

        self.fileType = None
        Printer.__init__(self, fileManager, analysisQueue,
                         printerProfileManager)
Exemplo n.º 4
0
    def select_file(self,
                    path,
                    sd,
                    printAfterSelect=False,
                    user=None,
                    pos=None,
                    *args,
                    **kwargs):

        self.fileType = self.get_fileType(path)

        Printer.select_file(self, path, sd, printAfterSelect, user, pos)
Exemplo n.º 5
0
def init_print(absFilename):
	_settings = settings(init=True)
	pluginManager = plugin_manager(init=True)
	pluginManager.reload_plugins(startup=True, initialize_implementations=False)
	printerProfileManager = PrinterProfileManager()
	analysis_queue_factories = dict(gcode=GcodeAnalysisQueue)
	analysis_queue_hooks = pluginManager.get_hooks("octoprint.filemanager.analysis.factory")

	for name, hook in analysis_queue_hooks.items():
		try:
			additional_factories = hook()
			analysis_queue_factories.update(**additional_factories)
		except:
			print("Error while processing analysis queues from {}".format(name))

	analysisQueue = AnalysisQueue(analysis_queue_factories)

	slicingManager = SlicingManager(_settings.getBaseFolder("slicingProfiles"), printerProfileManager)

	storage_managers = dict()
	storage_managers[FileDestinations.LOCAL] = storage.LocalFileStorage(absFilename)

	fileManager = FileManager(analysisQueue, slicingManager, printerProfileManager,
							  initial_storage_managers=storage_managers)

	printer = Printer(fileManager, analysisQueue, printerProfileManager)

	printer_profile = printerProfileManager.get_default()
	connectionOptions = printer.__class__.get_connection_options()

	baselist = []
	baselist = baselist \
			   + glob.glob("/dev/ttyUSB*") \
			   + glob.glob("/dev/ttyACM*") \
			   + glob.glob("/dev/tty.usb*") \
			   + glob.glob("/dev/cu.*") \
			   + glob.glob("/dev/cuaU*") \
			   + glob.glob("/dev/rfcomm*")

	if len(baselist) == 1:
		port = baselist[0]

	print('Connecting to: %s' % port)

	baudrate = 115200

	printer.connect(port=port, baudrate=baudrate,
					profile=printer_profile["id"] if "id" in printer_profile else "_default")

	return printer
Exemplo n.º 6
0
 def _getStateFlags(self):
     flags = Printer._getStateFlags(self)
     flags.update({
         "locked": self.is_locked(),
         "flashing": self.is_flashing(),
     })
     return flags
Exemplo n.º 7
0
 def __init__(self, fileManager, analysisQueue, printerProfileManager):
     Printer.__init__(self, fileManager, analysisQueue,
                      printerProfileManager)
     self._logger = mrb_logger("octoprint.plugins.mrbeam.printer")
     self._stateMonitor = LaserStateMonitor(
         interval=0.5,
         on_update=self._sendCurrentDataCallbacks,
         on_add_temperature=self._sendAddTemperatureCallbacks,
         on_add_log=self._sendAddLogCallbacks,
         on_add_message=self._sendAddMessageCallbacks,
         on_get_progress=self._updateProgressDataCallback)
     self._stateMonitor.reset(state={
         "text": self.get_state_string(),
         "flags": self._getStateFlags()
     },
                              job_data={
                                  "file": {
                                      "name": None,
                                      "size": None,
                                      "origin": None,
                                      "date": None
                                  },
                                  "estimatedPrintTime": None,
                                  "lastPrintTime": None,
                                  "filament": {
                                      "length": None,
                                      "volume": None
                                  }
                              },
                              progress={
                                  "completion": None,
                                  "filepos": None,
                                  "printTime": None,
                                  "printTimeLeft": None
                              },
                              current_z=None)
Exemplo n.º 8
0
def setup_octoprint(persona):

    # Get the EventManager singleton
    event_manager = events.eventManager()

    #################################################################
    # This is the octoprint section

    # Initialize settings
    p_settings = settings(True)

    # Initialize plugin manager
    plugin.plugin_manager(True)

    # Initialize profile manager
    profile_manager = profile.PrinterProfileManager()
    profile_manager.save(gigabot_profile,
                         allow_overwrite=True,
                         make_default=True)

    # Create an analysis queue
    analysis_queue = analysis.AnalysisQueue({})

    # Set up the storage managers. The file manager will need a
    # storage manager, which is a dictionary.
    storage_managers = dict()

    # Create our local storage manager and add it to the dictionary.
    local_storage_manager = storage.LocalFileStorage(persona.localpath)
    storage_managers[FileDestinations.LOCAL] = local_storage_manager

    # Now we can create the file manager...
    file_manager = FileManager(analysis_queue,
                               None,
                               None,
                               initial_storage_managers=storage_managers)

    # And now we can create the printer.
    printer = Printer(file_manager, analysis_queue, profile_manager)

    # This has to happen to start the event dispatching. Prior to
    # dispatching a STARTUP event, events will be queued but not
    # sent.
    event_manager.fire(events.Events.STARTUP)

    # Caller needs the printer and storage manager objects.
    return (printer, local_storage_manager)
Exemplo n.º 9
0
    def add_sd_file(self,
                    filename,
                    path,
                    on_success=None,
                    on_failure=None,
                    *args,
                    **kwargs):

        self.fileType = self.get_fileType(path)

        if self.fileType == "gcode":
            ret = Printer.add_sd_file(self, filename, path, on_success,
                                      on_failure, *args, **kwargs)

        elif self.fileType == "sla_bin":

            on_success()
            print("printjob canceled")
Exemplo n.º 10
0
	def run(self):
		if not self._allowRoot:
			self._check_for_root()

		global app
		global babel

		global printer
		global printerProfileManager
		global fileManager
		global slicingManager
		global analysisQueue
		global userManager
		global eventManager
		global loginManager
		global pluginManager
		global appSessionManager
		global pluginLifecycleManager
		global preemptiveCache
		global debug

		from tornado.ioloop import IOLoop
		from tornado.web import Application, RequestHandler

		import sys

		debug = self._debug

		# first initialize the settings singleton and make sure it uses given configfile and basedir if available
		s = settings(init=True, basedir=self._basedir, configfile=self._configfile)

		# then monkey patch a bunch of stuff
		util.tornado.fix_ioloop_scheduling()
		util.flask.enable_additional_translations(additional_folders=[s.getBaseFolder("translations")])

		# setup app
		self._setup_app(app)

		# setup i18n
		self._setup_i18n(app)

		# then initialize logging
		self._setup_logging(self._debug, self._logConf)
		self._logger = logging.getLogger(__name__)
		def exception_logger(exc_type, exc_value, exc_tb):
			self._logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
		sys.excepthook = exception_logger
		self._logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)

		# start the intermediary server
		self._start_intermediary_server(s)

		# then initialize the plugin manager
		pluginManager = octoprint.plugin.plugin_manager(init=True)

		printerProfileManager = PrinterProfileManager()
		eventManager = events.eventManager()
		analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
		slicingManager = octoprint.slicing.SlicingManager(s.getBaseFolder("slicingProfiles"), printerProfileManager)
		storage_managers = dict()
		storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(s.getBaseFolder("uploads"))
		fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers)
		printer = Printer(fileManager, analysisQueue, printerProfileManager)
		appSessionManager = util.flask.AppSessionManager()
		pluginLifecycleManager = LifecycleManager(pluginManager)
		preemptiveCache = PreemptiveCache(os.path.join(s.getBaseFolder("data"), "preemptive_cache_config.yaml"))

		# ... and initialize all plugins

		def octoprint_plugin_inject_factory(name, implementation):
			"""Factory for injections for all OctoPrintPlugins"""

			if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
				# we only care about OctoPrintPlugins
				return None

			return dict(
				plugin_manager=pluginManager,
				printer_profile_manager=printerProfileManager,
				event_bus=eventManager,
				analysis_queue=analysisQueue,
				slicing_manager=slicingManager,
				file_manager=fileManager,
				printer=printer,
				app_session_manager=appSessionManager,
				plugin_lifecycle_manager=pluginLifecycleManager,
				data_folder=os.path.join(settings().getBaseFolder("data"), name),
				preemptive_cache=preemptiveCache
			)

		def settings_plugin_inject_factory(name, implementation):
			"""Factory for additional injections depending on plugin type"""

			if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
				# we only care about SettingsPlugins
				return None

			# SettingsPlugin instnances get a PluginSettings instance injected
			default_settings = implementation.get_settings_defaults()
			get_preprocessors, set_preprocessors = implementation.get_settings_preprocessors()
			plugin_settings = octoprint.plugin.plugin_settings(name,
			                                                   defaults=default_settings,
			                                                   get_preprocessors=get_preprocessors,
			                                                   set_preprocessors=set_preprocessors)
			return dict(settings=plugin_settings)

		def settings_plugin_config_migration_and_cleanup(name, implementation):
			"""Take care of migrating and cleaning up any old settings"""

			if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
				return

			settings_version = implementation.get_settings_version()
			settings_migrator = implementation.on_settings_migrate

			if settings_version is not None and settings_migrator is not None:
				stored_version = implementation._settings.get_int([octoprint.plugin.SettingsPlugin.config_version_key])
				if stored_version is None or stored_version < settings_version:
					settings_migrator(settings_version, stored_version)
					implementation._settings.set_int([octoprint.plugin.SettingsPlugin.config_version_key], settings_version)

			implementation.on_settings_cleanup()
			implementation._settings.save()

			implementation.on_settings_initialized()

		pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory, settings_plugin_inject_factory]
		pluginManager.initialize_implementations()

		settingsPlugins = pluginManager.get_implementations(octoprint.plugin.SettingsPlugin)
		for implementation in settingsPlugins:
			try:
				settings_plugin_config_migration_and_cleanup(implementation._identifier, implementation)
			except:
				self._logger.exception("Error while trying to migrate settings for plugin {}, ignoring it".format(implementation._identifier))

		pluginManager.implementation_post_inits=[settings_plugin_config_migration_and_cleanup]

		pluginManager.log_all_plugins()

		# initialize file manager and register it for changes in the registered plugins
		fileManager.initialize()
		pluginLifecycleManager.add_callback(["enabled", "disabled"], lambda name, plugin: fileManager.reload_plugins())

		# initialize slicing manager and register it for changes in the registered plugins
		slicingManager.initialize()
		pluginLifecycleManager.add_callback(["enabled", "disabled"], lambda name, plugin: slicingManager.reload_slicers())

		# setup jinja2
		self._setup_jinja2()

		# make sure plugin lifecycle events relevant for jinja2 are taken care of
		def template_enabled(name, plugin):
			if plugin.implementation is None or not isinstance(plugin.implementation, octoprint.plugin.TemplatePlugin):
				return
			self._register_additional_template_plugin(plugin.implementation)
		def template_disabled(name, plugin):
			if plugin.implementation is None or not isinstance(plugin.implementation, octoprint.plugin.TemplatePlugin):
				return
			self._unregister_additional_template_plugin(plugin.implementation)
		pluginLifecycleManager.add_callback("enabled", template_enabled)
		pluginLifecycleManager.add_callback("disabled", template_disabled)

		# setup assets
		self._setup_assets()

		# configure timelapse
		octoprint.timelapse.configure_timelapse()

		# setup command triggers
		events.CommandTrigger(printer)
		if self._debug:
			events.DebugEventListener()

		# setup access control
		userManagerName = s.get(["accessControl", "userManager"])
		try:
			clazz = octoprint.util.get_class(userManagerName)
			userManager = clazz()
		except AttributeError as e:
			self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
			userManager = octoprint.users.FilebasedUserManager()
		finally:
			userManager.enabled = s.getBoolean(["accessControl", "enabled"])

		loginManager = LoginManager()
		loginManager.session_protection = "strong"
		loginManager.user_callback = load_user
		if not userManager.enabled:
			loginManager.anonymous_user = users.DummyUser
			principals.identity_loaders.appendleft(users.dummy_identity_loader)
		loginManager.init_app(app)

		# register API blueprint
		self._setup_blueprints()

		## Tornado initialization starts here

		if self._host is None:
			self._host = s.get(["server", "host"])
		if self._port is None:
			self._port = s.getInt(["server", "port"])

		ioloop = IOLoop()
		ioloop.install()

		self._router = SockJSRouter(self._create_socket_connection, "/sockjs")

		upload_suffixes = dict(name=s.get(["server", "uploads", "nameSuffix"]), path=s.get(["server", "uploads", "pathSuffix"]))

		def mime_type_guesser(path):
			from octoprint.filemanager import get_mime_type
			return get_mime_type(path)

		download_handler_kwargs = dict(
			as_attachment=True,
			allow_client_caching=False
		)
		additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
		admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))
		no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path), status_code=404))

		def joined_dict(*dicts):
			if not len(dicts):
				return dict()

			joined = dict()
			for d in dicts:
				joined.update(d)
			return joined

		server_routes = self._router.urls + [
			# various downloads
			(r"/downloads/timelapse/([^/]*\.mp[g4])", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("timelapse")), download_handler_kwargs, no_hidden_files_validator)),
			(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("uploads")), download_handler_kwargs, no_hidden_files_validator, additional_mime_types)),
			(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("logs")), download_handler_kwargs, admin_validator)),
			# camera snapshot
			(r"/downloads/camera/current", util.tornado.UrlProxyHandler, dict(url=s.get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
			# generated webassets
			(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(s.getBaseFolder("generated"), "webassets"))),
			# online indicators - text file with "online" as content and a transparent gif
			(r"/online.txt", util.tornado.StaticDataHandler, dict(data="online\n")),
			(r"/online.gif", util.tornado.StaticDataHandler, dict(data=bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")), content_type="image/gif"))
		]

		# fetch additional routes from plugins
		for name, hook in pluginManager.get_hooks("octoprint.server.http.routes").items():
			try:
				result = hook(list(server_routes))
			except:
				self._logger.exception("There was an error while retrieving additional server routes from plugin hook {name}".format(**locals()))
			else:
				if isinstance(result, (list, tuple)):
					for entry in result:
						if not isinstance(entry, tuple) or not len(entry) == 3:
							continue
						if not isinstance(entry[0], basestring):
							continue
						if not isinstance(entry[2], dict):
							continue

						route, handler, kwargs = entry
						route = r"/plugin/{name}/{route}".format(name=name, route=route if not route.startswith("/") else route[1:])

						self._logger.debug("Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}".format(**locals()))
						server_routes.append((route, handler, kwargs))

		server_routes.append((r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app), file_prefix="octoprint-file-upload-", file_suffix=".tmp", suffixes=upload_suffixes)))

		self._tornado_app = Application(server_routes)
		max_body_sizes = [
			("POST", r"/api/files/([^/]*)", s.getInt(["server", "uploads", "maxSize"])),
			("POST", r"/api/languages", 5 * 1024 * 1024)
		]

		# allow plugins to extend allowed maximum body sizes
		for name, hook in pluginManager.get_hooks("octoprint.server.http.bodysize").items():
			try:
				result = hook(list(max_body_sizes))
			except:
				self._logger.exception("There was an error while retrieving additional upload sizes from plugin hook {name}".format(**locals()))
			else:
				if isinstance(result, (list, tuple)):
					for entry in result:
						if not isinstance(entry, tuple) or not len(entry) == 3:
							continue
						if not entry[0] in util.tornado.UploadStorageFallbackHandler.BODY_METHODS:
							continue
						if not isinstance(entry[2], int):
							continue

						method, route, size = entry
						route = r"/plugin/{name}/{route}".format(name=name, route=route if not route.startswith("/") else route[1:])

						self._logger.debug("Adding maximum body size of {size}B for {method} requests to {route})".format(**locals()))
						max_body_sizes.append((method, route, size))

		self._stop_intermediary_server()

		# initialize and bind the server
		self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=s.getInt(["server", "maxSize"]))
		self._server.listen(self._port, address=self._host)

		eventManager.fire(events.Events.STARTUP)

		# auto connect
		if s.getBoolean(["serial", "autoconnect"]):
			(port, baudrate) = s.get(["serial", "port"]), s.getInt(["serial", "baudrate"])
			printer_profile = printerProfileManager.get_default()
			connectionOptions = get_connection_options()
			if port in connectionOptions["ports"]:
				printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")

		# start up watchdogs
		if s.getBoolean(["feature", "pollWatched"]):
			# use less performant polling observer if explicitely configured
			observer = PollingObserver()
		else:
			# use os default
			observer = Observer()
		observer.schedule(util.watchdog.GcodeWatchdogHandler(fileManager, printer), s.getBaseFolder("watched"))
		observer.start()

		# run our startup plugins
		octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
		                             "on_startup",
		                             args=(self._host, self._port))

		def call_on_startup(name, plugin):
			implementation = plugin.get_implementation(octoprint.plugin.StartupPlugin)
			if implementation is None:
				return
			implementation.on_startup(self._host, self._port)
		pluginLifecycleManager.add_callback("enabled", call_on_startup)

		# prepare our after startup function
		def on_after_startup():
			self._logger.info("Listening on http://%s:%d" % (self._host, self._port))

			# now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for
			# which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons
			# or service xmls or the like). While they are working though the ioloop would block. Therefore we'll
			# create a single use thread in which to perform our after-startup-tasks, start that and hand back
			# control to the ioloop
			def work():
				octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
				                             "on_after_startup")

				def call_on_after_startup(name, plugin):
					implementation = plugin.get_implementation(octoprint.plugin.StartupPlugin)
					if implementation is None:
						return
					implementation.on_after_startup()
				pluginLifecycleManager.add_callback("enabled", call_on_after_startup)

				# when we are through with that we also run our preemptive cache
				if settings().getBoolean(["devel", "cache", "preemptive"]):
					self._execute_preemptive_flask_caching(preemptiveCache)

			import threading
			threading.Thread(target=work).start()
		ioloop.add_callback(on_after_startup)

		# prepare our shutdown function
		def on_shutdown():
			# will be called on clean system exit and shutdown the watchdog observer and call the on_shutdown methods
			# on all registered ShutdownPlugins
			self._logger.info("Shutting down...")
			observer.stop()
			observer.join()
			octoprint.plugin.call_plugin(octoprint.plugin.ShutdownPlugin,
			                             "on_shutdown")

			if self._octoprint_daemon is not None:
				self._logger.info("Cleaning up daemon pidfile")
				self._octoprint_daemon.terminated()

			self._logger.info("Goodbye!")
		atexit.register(on_shutdown)

		def sigterm_handler(*args, **kwargs):
			# will stop tornado on SIGTERM, making the program exit cleanly
			def shutdown_tornado():
				ioloop.stop()
			ioloop.add_callback_from_signal(shutdown_tornado)
		signal.signal(signal.SIGTERM, sigterm_handler)

		try:
			# this is the main loop - as long as tornado is running, OctoPrint is running
			ioloop.start()
		except (KeyboardInterrupt, SystemExit):
			pass
		except:
			self._logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!")
			self._logger.exception("Stacktrace follows:")
Exemplo n.º 11
0
	def run(self):
		if not self._allowRoot:
			self._check_for_root()

		global app
		global babel

		global printer
		global printerProfileManager
		global fileManager
		global slicingManager
		global analysisQueue
		global userManager
		global eventManager
		global loginManager
		global pluginManager
		global appSessionManager
		global pluginLifecycleManager
		global debug

		from tornado.ioloop import IOLoop
		from tornado.web import Application, RequestHandler

		import sys

		debug = self._debug

		# first initialize the settings singleton and make sure it uses given configfile and basedir if available
		s = settings(init=True, basedir=self._basedir, configfile=self._configfile)

		# then monkey patch a bunch of stuff
		util.tornado.fix_ioloop_scheduling()
		util.flask.enable_additional_translations(additional_folders=[s.getBaseFolder("translations")])

		# setup app
		self._setup_app()

		# setup i18n
		self._setup_i18n(app)

		# then initialize logging
		self._setup_logging(self._debug, self._logConf)
		self._logger = logging.getLogger(__name__)
		def exception_logger(exc_type, exc_value, exc_tb):
			self._logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
		sys.excepthook = exception_logger
		self._logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)

		# then initialize the plugin manager
		pluginManager = octoprint.plugin.plugin_manager(init=True)

		printerProfileManager = PrinterProfileManager()
		eventManager = events.eventManager()
		analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
		slicingManager = octoprint.slicing.SlicingManager(s.getBaseFolder("slicingProfiles"), printerProfileManager)
		storage_managers = dict()
		storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(s.getBaseFolder("uploads"))
		fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers)
		printer = Printer(fileManager, analysisQueue, printerProfileManager)
		appSessionManager = util.flask.AppSessionManager()
		pluginLifecycleManager = LifecycleManager(pluginManager)

		def octoprint_plugin_inject_factory(name, implementation):
			if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
				return None
			return dict(
				plugin_manager=pluginManager,
				printer_profile_manager=printerProfileManager,
				event_bus=eventManager,
				analysis_queue=analysisQueue,
				slicing_manager=slicingManager,
				file_manager=fileManager,
				printer=printer,
				app_session_manager=appSessionManager,
				plugin_lifecycle_manager=pluginLifecycleManager,
				data_folder=os.path.join(settings().getBaseFolder("data"), name)
			)

		def settings_plugin_inject_factory(name, implementation):
			if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
				return None
			default_settings = implementation.get_settings_defaults()
			get_preprocessors, set_preprocessors = implementation.get_settings_preprocessors()
			plugin_settings = octoprint.plugin.plugin_settings(name,
			                                                   defaults=default_settings,
			                                                   get_preprocessors=get_preprocessors,
			                                                   set_preprocessors=set_preprocessors)
			return dict(settings=plugin_settings)

		def settings_plugin_config_migration(name, implementation):
			if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
				return

			settings_version = implementation.get_settings_version()
			settings_migrator = implementation.on_settings_migrate

			if settings_version is not None and settings_migrator is not None:
				stored_version = implementation._settings.get_int(["_config_version"])
				if stored_version is None or stored_version < settings_version:
					settings_migrator(settings_version, stored_version)
					implementation._settings.set_int(["_config_version"], settings_version)
					implementation._settings.save()

			implementation.on_settings_initialized()

		pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory, settings_plugin_inject_factory]
		pluginManager.initialize_implementations()

		settingsPlugins = pluginManager.get_implementations(octoprint.plugin.SettingsPlugin)
		for implementation in settingsPlugins:
			try:
				settings_plugin_config_migration(implementation._identifier, implementation)
			except:
				self._logger.exception("Error while trying to migrate settings for plugin {}, ignoring it".format(implementation._identifier))

		pluginManager.implementation_post_inits=[settings_plugin_config_migration]

		pluginManager.log_all_plugins()

		# initialize file manager and register it for changes in the registered plugins
		fileManager.initialize()
		pluginLifecycleManager.add_callback(["enabled", "disabled"], lambda name, plugin: fileManager.reload_plugins())

		# initialize slicing manager and register it for changes in the registered plugins
		slicingManager.initialize()
		pluginLifecycleManager.add_callback(["enabled", "disabled"], lambda name, plugin: slicingManager.reload_slicers())

		# setup jinja2
		self._setup_jinja2()
		def template_enabled(name, plugin):
			if plugin.implementation is None or not isinstance(plugin.implementation, octoprint.plugin.TemplatePlugin):
				return
			self._register_additional_template_plugin(plugin.implementation)
		def template_disabled(name, plugin):
			if plugin.implementation is None or not isinstance(plugin.implementation, octoprint.plugin.TemplatePlugin):
				return
			self._unregister_additional_template_plugin(plugin.implementation)
		pluginLifecycleManager.add_callback("enabled", template_enabled)
		pluginLifecycleManager.add_callback("disabled", template_disabled)

		# setup assets
		self._setup_assets()

		# configure timelapse
		octoprint.timelapse.configureTimelapse()

		# setup command triggers
		events.CommandTrigger(printer)
		if self._debug:
			events.DebugEventListener()

		# setup access control
		if s.getBoolean(["accessControl", "enabled"]):
			userManagerName = s.get(["accessControl", "userManager"])
			try:
				clazz = octoprint.util.get_class(userManagerName)
				userManager = clazz()
			except AttributeError, e:
				self._logger.exception("Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName)
Exemplo n.º 12
0
class ScriptsTestCase(unittest.TestCase):
    def setUp(self):
        # mock comm
        self.comm = MagicMock()

        # mock event manager
        self.event_manager = MagicMock()

        self.event_manager_patcher = patch(
            "octoprint.printer.standard.eventManager")
        self.event_manager_getter = self.event_manager_patcher.start()
        self.event_manager_getter.return_value = self.event_manager

        # mock plugin manager
        self.plugin_manager = MagicMock()
        self.plugin_manager.get_hooks.return_value = {}

        self.plugin_manager_patcher = patch(
            "octoprint.printer.standard.plugin_manager")
        self.plugin_manager_getter = self.plugin_manager_patcher.start()
        self.plugin_manager_getter.return_value = self.plugin_manager

        # mock settings
        self.settings = MagicMock()
        self.settings.getInt.return_value = 1
        self.settings.getBoolean.return_value = False

        self.settings_patcher = patch("octoprint.printer.standard.settings")
        self.settings_getter = self.settings_patcher.start()
        self.settings_getter.return_value = self.settings

        self.printer = Printer(MagicMock(), MagicMock(), MagicMock())
        self.printer._comm = self.comm

    def tearDown(self):
        self.settings_patcher.stop()
        self.plugin_manager_patcher.stop()
        self.event_manager_patcher.stop()

    def test_event_name(self):
        self.printer.script("testEvent")

        self.event_manager.fire.assert_any_call("GcodeScriptTestEventRunning",
                                                ANY)

    def test_event_order(self):
        self.printer.script("EventOrder")

        expected_order = [
            call("GcodeScriptEventOrderRunning", ANY),
            call("GcodeScriptEventOrderFinished", ANY),
        ]

        self.event_manager.fire.assert_has_calls(expected_order)

    def test_payload_handling(self):
        expected_paylod = {"payloadKey": "payloadValue"}
        context = {"event": expected_paylod}

        self.printer.script("GetPayload", context)

        self.event_manager.fire.assert_called_with(ANY, expected_paylod)

        self.printer.script("WrongPayload", [])

        self.event_manager.fire.assert_called_with(ANY, None)

        self.printer.script("WrongContext", {"noEvent": {}})

        self.event_manager.fire.assert_called_with(ANY, None)
Exemplo n.º 13
0
 def is_operational(self):
     return Printer.is_operational(self) or self.is_locked()
Exemplo n.º 14
0
 def create_printer(self, components, *args, **kwargs):
     self.printer = Printer()
     return self.printer
Exemplo n.º 15
0
    def run(self):
        if not self._allowRoot:
            self._checkForRoot()

        global printer
        global printerProfileManager
        global fileManager
        global slicingManager
        global analysisQueue
        global userManager
        global eventManager
        global loginManager
        global pluginManager
        global appSessionManager
        global debug

        from tornado.ioloop import IOLoop
        from tornado.web import Application

        import sys

        debug = self._debug

        # first initialize the settings singleton and make sure it uses given configfile and basedir if available
        settings(init=True, basedir=self._basedir, configfile=self._configfile)

        # then initialize logging
        self._initLogging(self._debug, self._logConf)
        logger = logging.getLogger(__name__)

        def exception_logger(exc_type, exc_value, exc_tb):
            logger.error("Uncaught exception",
                         exc_info=(exc_type, exc_value, exc_tb))

        sys.excepthook = exception_logger
        logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)

        # then initialize the plugin manager
        pluginManager = octoprint.plugin.plugin_manager(init=True)

        printerProfileManager = PrinterProfileManager()
        eventManager = events.eventManager()
        analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
        slicingManager = octoprint.slicing.SlicingManager(
            settings().getBaseFolder("slicingProfiles"), printerProfileManager)
        storage_managers = dict()
        storage_managers[
            octoprint.filemanager.FileDestinations.
            LOCAL] = octoprint.filemanager.storage.LocalFileStorage(
                settings().getBaseFolder("uploads"))
        fileManager = octoprint.filemanager.FileManager(
            analysisQueue,
            slicingManager,
            printerProfileManager,
            initial_storage_managers=storage_managers)
        printer = Printer(fileManager, analysisQueue, printerProfileManager)
        appSessionManager = util.flask.AppSessionManager()

        def octoprint_plugin_inject_factory(name, implementation):
            if not isinstance(implementation,
                              octoprint.plugin.OctoPrintPlugin):
                return None
            return dict(plugin_manager=pluginManager,
                        printer_profile_manager=printerProfileManager,
                        event_bus=eventManager,
                        analysis_queue=analysisQueue,
                        slicing_manager=slicingManager,
                        file_manager=fileManager,
                        printer=printer,
                        app_session_manager=appSessionManager)

        def settings_plugin_inject_factory(name, implementation):
            if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
                return None
            default_settings = implementation.get_settings_defaults()
            get_preprocessors, set_preprocessors = implementation.get_settings_preprocessors(
            )
            plugin_settings = octoprint.plugin.plugin_settings(
                name,
                defaults=default_settings,
                get_preprocessors=get_preprocessors,
                set_preprocessors=set_preprocessors)
            return dict(settings=plugin_settings)

        pluginManager.initialize_implementations(additional_inject_factories=[
            octoprint_plugin_inject_factory, settings_plugin_inject_factory
        ])
        pluginManager.log_all_plugins()
        slicingManager.initialize()

        # configure additional template folders for jinja2
        template_plugins = pluginManager.get_implementations(
            octoprint.plugin.TemplatePlugin)
        additional_template_folders = []
        for plugin in template_plugins:
            folder = plugin.get_template_folder()
            if folder is not None:
                additional_template_folders.append(
                    plugin.get_template_folder())

        import jinja2
        jinja_loader = jinja2.ChoiceLoader([
            app.jinja_loader,
            jinja2.FileSystemLoader(additional_template_folders)
        ])
        app.jinja_loader = jinja_loader
        del jinja2
        app.jinja_env.add_extension("jinja2.ext.do")

        # configure timelapse
        octoprint.timelapse.configureTimelapse()

        # setup command triggers
        events.CommandTrigger(printer)
        if self._debug:
            events.DebugEventListener()

        if settings().getBoolean(["accessControl", "enabled"]):
            userManagerName = settings().get(["accessControl", "userManager"])
            try:
                clazz = octoprint.util.get_class(userManagerName)
                userManager = clazz()
            except AttributeError, e:
                logger.exception(
                    "Could not instantiate user manager %s, will run with accessControl disabled!"
                    % userManagerName)