コード例 #1
0
ファイル: requesthandler.py プロジェクト: italocjs/AstroBox
	def initial_state(self, data, clientId, done):
		printer = printerManager()
		cm = cameraManager()
		softwareManager = swManager()

		state = {
			'printing': printer.isPrinting() or printer.isPaused(),
			'heatingUp': printer.isHeatingUp(),
			'operational': printer.isOperational(),
			'ready_to_print': printer.isReadyToPrint(),
			'paused': printer.isPaused(),
			'camera': printer.isCameraConnected(),
			'filament' : printerProfileManager().data['filament'],
			'printCapture': cm.timelapseInfo,
			'profile': printerProfileManager().data,
			'remotePrint': True,
			'capabilities': softwareManager.capabilities() + cm.capabilities,
			'tool': printer.getSelectedTool() if printer.isOperational() else None,
			'printSpeed': printer.getPrintingSpeed(),
			'printFlow': printer.getPrintingFlow()
		}

		if state['printing'] or state['paused']:
			#Let's add info about the ongoing print job
			state['job'] = printer._stateMonitor._jobData
			if state['job'] is not None:
				state['job'].update({
					'cloud_job_id': printer.currentPrintJobId
				})

			state['progress'] = printer._stateMonitor._progress

		done(state)
コード例 #2
0
ファイル: requesthandler.py プロジェクト: AstroPrint/AstroBox
	def initial_state(self, data, clientId, done):
		printer = printerManager()
		cm = cameraManager()
		softwareManager = swManager()

		state = {
			'printing': printer.isPrinting(),
			'heatingUp': printer.isHeatingUp(),
			'operational': printer.isOperational(),
			'paused': printer.isPaused(),
			'camera': printer.isCameraConnected(),
			'filament' : printerProfileManager().data['filament'],
			'printCapture': cm.timelapseInfo,
			'profile': printerProfileManager().data,
			'remotePrint': True,
			'capabilities': softwareManager.capabilities() + cm.capabilities,
			'tool': printer.getSelectedTool() if printer.isOperational() else None,
			'printSpeed': printer.getPrintingSpeed(),
			'printFlow': printer.getPrintingFlow()
		}

		if state['printing'] or state['paused']:
			#Let's add info about the ongoing print job
			state['job'] = printer._stateMonitor._jobData
			state['progress'] = printer._stateMonitor._progress

		done(state)
コード例 #3
0
    def processAuthenticate(self, data):
        if data:
            self._silentReconnect = False

            if 'error' in data:
                self._logger.warn(data['message'] if 'message' in
                                  data else 'Unkonwn authentication error')
                self.status = self.STATUS_ERROR
                self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)
                self.close()
                if 'should_retry' in data and data['should_retry']:
                    self._doRetry()

            elif 'success' in data:
                self._logger.info("Connected to astroprint service")
                self.authenticated = True
                self._retries = 0
                self._retryTimer = None
                self.status = self.STATUS_CONNECTED
                self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)

            return None

        else:
            from octoprint.server import VERSION
            from astroprint.printerprofile import printerProfileManager

            nm = networkManager()
            sm = softwareManager()
            ppm = printerProfileManager()

            authData = {
                'silentReconnect':
                self._silentReconnect,
                'boxId':
                self.boxId,
                'variantId':
                sm.variant['id'],
                'boxName':
                nm.getHostname(),
                'swVersion':
                VERSION,
                'platform':
                sm.platform,
                'localIpAddress':
                nm.activeIpAddress,
                'publicKey':
                self._publicKey,
                'privateKey':
                self._privateKey,
                'printerModel':
                ppm.data['printer_model']
                if ppm.data['printer_model']['id'] else None
            }

            pkgId = sm.mfPackageId
            if pkgId:
                authData['mfPackageId'] = pkgId

            return {'type': 'auth', 'data': authData}
コード例 #4
0
ファイル: __init__.py プロジェクト: IceForgTW/AstroBox
	def __init__(self):
		self.broadcastTraffic = 0 #Number of clients that wish to receive serial link traffic
		self.doIdleTempReports = True #Let's the client know if periodic temperature reports should be queries to the printer

		self._comm = None
		self._selectedFile = None
		self._printAfterSelect = False
		self._currentZ = None
		self._progress = None
		self._printTime = None
		self._printTimeLeft = None
		self._currentLayer = None
		self._currentPrintJobId = None

		self._profileManager = printerProfileManager()

		self._fileManager= printFileManagerMap[self._fileManagerClass.name]()
		self._fileManager.registerCallback(self)
		self._state = self.STATE_NONE
		self._logger = logging.getLogger(__name__)

		self._temp = {}
		self._bedTemp = None
		self._temps = deque([], 300)
		self._shutdown = False

		self._messages = deque([], 300)

		# callbacks
		self._callbacks = []
		#self._lastProgressReport = None

		self._stateMonitor = StateMonitor(
			ratelimit= 1.0,
			updateCallback= self._sendCurrentDataCallbacks,
			addTemperatureCallback= self._sendAddTemperatureCallbacks,
			addLogCallback= self._sendAddLogCallbacks,
			addMessageCallback= self._sendAddMessageCallbacks
		)

		self._stateMonitor.reset(
			state={"text": self.getStateString(), "flags": self._getStateFlags()},
			jobData={
				"file": {
					"name": None,
					"size": None,
					"origin": None,
					"date": None
				},
				"estimatedPrintTime": None,
				"filament": {
					"length": None,
					"volume": None
				}
			},
			progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None},
			currentZ=None
		)

		eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished);
コード例 #5
0
ファイル: system.py プロジェクト: italocjs/AstroBox
    def printerProfile(self, data, sendMessage):

        ppm = printerProfileManager()
        pm = printerManager()
        if data:
            if 'driverChoices' in data:
                del data['driverChoices']

            if 'allowTerminal' in data:
                del data['allowTerminal']

            if 'check_clear_bed' in data and data['check_clear_bed'] is False:
                pm.set_bed_clear(True)

            ppm.set(data)
            ppm.save()

            sendMessage({'success': 'no_error'})
        else:

            result = ppm.data.copy()

            result.update({"allowTerminal": pm.allowTerminal})
            result.update({"driverChoices": ppm.driverChoices()})

            sendMessage(result)
コード例 #6
0
ファイル: __init__.py プロジェクト: marianoronchi/AstroBox
	def __init__(self):
		self.broadcastTraffic = 0 #Number of clients that wish to receive serial link traffic
		self.doIdleTempReports = True #Let's the client know if periodic temperature reports should be queries to the printer

		self._comm = None
		self._selectedFile = None
		self._printAfterSelect = False
		self._currentZ = None
		self._progress = None
		self._printTime = None
		self._printTimeLeft = None
		self._currentLayer = None
		self._currentPrintJobId = None

		self._profileManager = printerProfileManager()

		self._fileManager= printFileManagerMap[self._fileManagerClass.name]()
		self._fileManager.registerCallback(self)
		self._state = self.STATE_NONE
		self._logger = logging.getLogger(__name__)

		self._temp = {}
		self._bedTemp = None
		self._temps = deque([], 300)
		self._shutdown = False

		self._messages = deque([], 300)

		# callbacks
		self._callbacks = []
		#self._lastProgressReport = None

		self._stateMonitor = StateMonitor(
			ratelimit= 1.0,
			updateCallback= self._sendCurrentDataCallbacks,
			addTemperatureCallback= self._sendAddTemperatureCallbacks,
			addLogCallback= self._sendAddLogCallbacks,
			addMessageCallback= self._sendAddMessageCallbacks
		)

		self._stateMonitor.reset(
			state={"text": self.getStateString(), "flags": self._getStateFlags()},
			jobData={
				"file": {
					"name": None,
					"size": None,
					"origin": None,
					"date": None
				},
				"estimatedPrintTime": None,
				"filament": {
					"length": None,
					"volume": None
				}
			},
			progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None},
			currentZ=None
		)

		eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished);
コード例 #7
0
ファイル: system.py プロジェクト: pamxy/AstroBox
	def printerConnectionDriver(self, data, sendMessage):

		s = settings()
		pm = printerManager()
		ppm = printerProfileManager()
		connectionOptions = pm.getConnectionOptions()

		if data and data['settings']:
			if "serial" in data.keys():
				if "port" in data["serial"].keys(): s.set(["serial", "port"], data["serial"]["port"])
				if "baudrate" in data["serial"].keys(): s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])

			s.save()

		driverName = ppm.data['driver']
		driverInfo = ppm.driverChoices().get(driverName)
		if driverInfo:
			driverName = driverInfo['name']

		sendMessage({
			"driver": ppm.data['driver'],
			"driverName": driverName,
			"fileFormat": pm.fileManager.fileFormat,
			"serial": {
				"port": connectionOptions["portPreference"],
				"baudrate": connectionOptions["baudratePreference"],
				"portOptions": connectionOptions["ports"],
				"baudrateOptions": connectionOptions["baudrates"]
			}
		})
コード例 #8
0
ファイル: __init__.py プロジェクト: AstroPrint/AstroBox
	def __init__(self):
		self.systemPlugin = False

		self._logger = logging.getLogger('Plugin::%s' % self.__class__.__name__)
		self._definition = None
		self._settings = settings()
		self._pluginEventListeners = {}
		self._profileManager = printerProfileManager()

		#Read it's definition file - plugin.yaml -
		pluginPath = os.path.dirname(sys.modules[self.__module__].__file__)
		definitionFile = os.path.join(pluginPath, 'plugin.yaml')
		if os.path.exists(definitionFile):
			try:
				with open(definitionFile, "r") as f:
					self._definition = yaml.safe_load(f)

			except Exception as e:
				raise e #Raise parse exception here

			if all(key in self._definition for key in REQUIRED_PLUGIN_KEYS):
				min_api_version = int(self._definition['min_api_version'])

				if PLUGIN_API_VERSION >= min_api_version:
					self.initialize()
				else:
					raise Exception("AstroBox API version [%d] is lower than minimum required by %s [%d]" % (PLUGIN_API_VERSION, self._definition['id'], min_api_version))

			else:
				raise Exception("Invalid plugin definition found in %s" % definitionFile)

		else:
			raise Exception("No plugin definition file exists in %s" % pluginPath)
コード例 #9
0
ファイル: system.py プロジェクト: italocjs/AstroBox
    def saveTempPreset(self, data, sendMessage):
        ppm = printerProfileManager()

        if data:
            id = ppm.createTempPreset(data['name'], data['nozzle_temp'],
                                      data['bed_temp'])
            sendMessage(id)
コード例 #10
0
ファイル: system.py プロジェクト: pamxy/AstroBox
	def saveConnectionSettings(self,data,sendResponse):
		port = data['port']
		baudrate = data['baudrate']
		driver = data['driver']

		if port:
			s = settings()

			s.set(["serial", "port"], port)

			if baudrate:
				s.setInt(["serial", "baudrate"], baudrate)

			s.save()

			pp = printerProfileManager()
			pp.set({'driver': driver})
			pp.save()

			printerManager().connect(port, baudrate)

			sendResponse({'success': 'no_error'})
			return

		sendResponse('invalid_printer_connection_settings',True)
コード例 #11
0
def connection_settings():
    connectionOptions = printerManager().getConnectionOptions()

    if connectionOptions:

        plugins = pluginManager().getPluginsByProvider('printerComms')

        driverChoices = {("plugin:%s" % k): plugins[k].definition['name']
                         for k in plugins}

        driverChoices.update({
            'marlin': 'GCODE - Marlin / Repetier Firmware',
            's3g': 'X3G - Sailfish / Makerbot Firmware'
        })

        response = {
            "driver": printerProfileManager().data['driver'],
            "driverChoices": driverChoices,
            "port": connectionOptions["portPreference"],
            "baudrate": connectionOptions["baudratePreference"],
            "portOptions": connectionOptions["ports"].items(),
            "baudrateOptions": connectionOptions["baudrates"]
        }

        return jsonify(response)

    return make_response("Connection options not available", 400)
コード例 #12
0
    def initial_state(self, data, clientId, done):
        printer = printerManager()
        cm = cameraManager()
        softwareManager = swManager()

        state = {
            'printing': printer.isPrinting(),
            'heatingUp': printer.isHeatingUp(),
            'operational': printer.isOperational(),
            'paused': printer.isPaused(),
            'camera': printer.isCameraConnected(),
            'printCapture': cm.timelapseInfo,
            'profile': printerProfileManager().data,
            'remotePrint': True,
            'capabilities': softwareManager.capabilities() + cm.capabilities,
            'tool':
            printer.getSelectedTool() if printer.isOperational() else None
        }

        if state['printing'] or state['paused']:
            #Let's add info about the ongoing print job
            state['job'] = printer._stateMonitor._jobData
            state['progress'] = printer._stateMonitor._progress

        done(state)
コード例 #13
0
def getStatus():
	printer = printerManager()
	cm = cameraManager()
	softwareManager = swManager()
	ppm = printerProfileManager()

	fileName = None

	if printer.isPrinting():
		currentJob = printer.getCurrentJob()
		fileName = currentJob["file"]["name"]

	return Response(
		json.dumps({
			'id': boxrouterManager().boxId,
			'name': networkManager().getHostname(),
			'printing': printer.isPrinting(),
			'fileName': fileName,
			'printerModel': ppm.data['printer_model'] if ppm.data['printer_model']['id'] else None,
			'filament' : ppm.data['filament'],
			'material': None,
			'operational': printer.isOperational(),
			'paused': printer.isPaused(),
			'camera': cm.isCameraConnected(),
			#'printCapture': cm.timelapseInfo,
			'remotePrint': True,
			'capabilities': softwareManager.capabilities() + cm.capabilities
		}),
		mimetype= 'application/json',
		headers= {
			'Access-Control-Allow-Origin': '*'
		} if settings().getBoolean(['api', 'allowCrossOrigin']) else None
	)
コード例 #14
0
ファイル: printer.py プロジェクト: AstroPrint/AstroBox
	def getStatus(self):
		printer = printerManager()
		cm = cameraManager()
		ppm = printerProfileManager()

		fileName = None

		if printer.isPrinting():
			currentJob = printer.getCurrentJob()
			fileName = currentJob["file"]["name"]

		return {
				'id': boxrouterManager().boxId,
				'name': networkManager().getHostname(),
				'printing': printer.isPrinting(),
				'fileName': fileName,
				'printerModel': ppm.data['printer_model'] if ppm.data['printer_model']['id'] else None,
				'filament' : ppm.data['filament'],
				'material': None,
				'operational': printer.isOperational(),
				'paused': printer.isPaused(),
				'camera': cm.isCameraConnected(),
				#'printCapture': cm.timelapseInfo,
				'remotePrint': True,
				'capabilities': ['remotePrint'] + cm.capabilities
			}
コード例 #15
0
ファイル: settings.py プロジェクト: italocjs/AstroBox
def handlePrinterSettings():
    s = settings()
    pm = printerManager()
    ppm = printerProfileManager()
    connectionOptions = pm.getConnectionOptions()

    if request.method == "POST":
        if "application/json" in request.headers["Content-Type"]:
            data = request.json

            if "serial" in data.keys():
                if "port" in data["serial"].keys():
                    s.set(["serial", "port"], data["serial"]["port"])
                if "baudrate" in data["serial"].keys():
                    s.setInt(["serial", "baudrate"],
                             data["serial"]["baudrate"])

            s.save()

    driverName = ppm.data['driver']
    driverInfo = ppm.driverChoices().get(driverName)
    if driverInfo:
        driverName = driverInfo['name']

    return jsonify({
        "driver": ppm.data['driver'],
        "driverName": driverName,
        "serial": {
            "port": connectionOptions["portPreference"],
            "baudrate": connectionOptions["baudratePreference"],
            "portOptions": connectionOptions["ports"].items(),
            "baudrateOptions": connectionOptions["baudrates"]
        }
    })
コード例 #16
0
def index():
    s = settings()
    loggedUsername = s.get(["cloudSlicer", "loggedUser"])

    if (s.getBoolean(["server", "firstRun"])):
        # we need to get the user to sign into their AstroPrint account
        return render_template("setup.jinja2",
                               debug=debug,
                               uiApiKey=UI_API_KEY,
                               version=VERSION,
                               variantData=variantManager().data,
                               astroboxName=networkManager().getHostname(),
                               settings=s)

    elif softwareManager.updatingRelease or softwareManager.forceUpdateInfo:
        return render_template(
            "updating.jinja2",
            uiApiKey=UI_API_KEY,
            showForceUpdate=softwareManager.forceUpdateInfo != None,
            releaseInfo=softwareManager.updatingRelease
            or softwareManager.forceUpdateInfo,
            lastCompletionPercent=softwareManager.lastCompletionPercent,
            lastMessage=softwareManager.lastMessage,
            variantData=variantManager().data,
            astroboxName=networkManager().getHostname())

    elif loggedUsername and (current_user is None
                             or not current_user.is_authenticated()
                             or current_user.get_id() != loggedUsername):
        if current_user.is_authenticated():
            logout_user()

        return render_template("locked.jinja2",
                               username=loggedUsername,
                               uiApiKey=UI_API_KEY,
                               astroboxName=networkManager().getHostname(),
                               variantData=variantManager().data)

    else:
        pm = printerManager()
        nm = networkManager()

        paused = pm.isPaused()
        printing = pm.isPrinting()
        online = nm.isOnline()

        return render_template("app.jinja2",
                               user_email=loggedUsername,
                               version=VERSION,
                               printing=printing,
                               paused=paused,
                               online=online,
                               print_capture=cameraManager().timelapseInfo
                               if printing or paused else None,
                               printer_profile=printerProfileManager().data,
                               uiApiKey=UI_API_KEY,
                               astroboxName=nm.getHostname(),
                               variantData=variantManager().data,
                               serialLogActive=s.getBoolean(['serial', 'log']))
コード例 #17
0
ファイル: printerprofile.py プロジェクト: italocjs/AstroBox
def temp_preset_create():
	ppm = printerProfileManager()

	name = request.values.get('name', None)
	nozzle_temp = request.values.get('nozzle_temp', None)
	bed_temp = request.values.get('bed_temp', None)

	return jsonify( {'id' : ppm.createTempPreset(name, nozzle_temp, bed_temp)} )
コード例 #18
0
def printer_profile_patch():
	changes = request.json

	ppm = printerProfileManager()
	ppm.set(changes)
	ppm.save()

	return jsonify()
コード例 #19
0
def printer_profile_patch():
    changes = request.json

    ppm = printerProfileManager()
    ppm.set(changes)
    ppm.save()

    return jsonify()
コード例 #20
0
ファイル: printerprofile.py プロジェクト: AstroPrint/AstroBox
def temp_preset_create():
	ppm = printerProfileManager()

	name = request.values.get('name', None)
	nozzle_temp = request.values.get('nozzle_temp', None)
	bed_temp = request.values.get('bed_temp', None)

	return jsonify( {'id' : ppm.createTempPreset(name, nozzle_temp, bed_temp)} )
コード例 #21
0
ファイル: printer.py プロジェクト: AstroPrint/AstroBox
	def getNumberOfExtruders(self,data,sendResponse=None):
		ppm = printerProfileManager()

		extruderCount = ppm.data.get('extruder_count')

		if sendResponse:
			sendResponse(extruderCount)

		return extruderCount
コード例 #22
0
ファイル: printer.py プロジェクト: bula87/AstroBox
    def getNumberOfExtruders(self, data, sendResponse=None):
        ppm = printerProfileManager()

        extruderCount = ppm.data.get('extruder_count')

        if sendResponse:
            sendResponse(extruderCount)

        return extruderCount
コード例 #23
0
ファイル: __init__.py プロジェクト: nerginer/AstroBox
def index():
	s = settings()
	loggedUsername = s.get(["cloudSlicer", "loggedUser"])

	if (s.getBoolean(["server", "firstRun"])):
		# we need to get the user to sign into their AstroPrint account
		return render_template(
			"setup.jinja2",
			debug= debug,
			uiApiKey= UI_API_KEY,
			version= VERSION,
			variantData= variantManager().data,
			astroboxName= networkManager.getHostname(),
			settings=s
		)

	elif softwareManager.updatingRelease or softwareManager.forceUpdateInfo:
		return render_template(
			"updating.jinja2",
			uiApiKey= UI_API_KEY,
			showForceUpdate=  softwareManager.forceUpdateInfo != None,
			releaseInfo= softwareManager.updatingRelease or softwareManager.forceUpdateInfo,
			variantData= variantManager().data,
			astroboxName= networkManager.getHostname()
		)

	elif loggedUsername and (current_user is None or not current_user.is_authenticated() or current_user.get_id() != loggedUsername):
		if current_user.is_authenticated():
			logout_user()

		return render_template(
			"locked.jinja2",
			username= loggedUsername,
			uiApiKey= UI_API_KEY,
			astroboxName= networkManager.getHostname(),
			variantData= variantManager().data
		)

	else:
		paused = printer.isPaused()
		printing = printer.isPrinting()
		online = networkManager.isOnline()
		
		return render_template(
			"app.jinja2",
			user_email= loggedUsername,
			version= VERSION,
			printing= printing,
			paused= paused,
			online= online,
			print_capture= cameraManager().timelapseInfo if printing or paused else None,
			printer_profile= printerProfileManager().data,
			uiApiKey= UI_API_KEY,
			astroboxName= networkManager.getHostname(),
			variantData= variantManager().data
		)
コード例 #24
0
ファイル: software.py プロジェクト: italocjs/AstroBox
	def capabilities(self):
		ppm = printerProfileManager()
		capabilities = ['remotePrint',     	# Indicates whether this device supports starting a print job remotely
		 								'multiExtruders',  	# Support for multiple extruders
										'allowPrintFile',  	# Support for printing a printfile not belonging to any design
										'acceptPrintJobId' # Accept created print job from cloud,
									]
		if ppm.data['check_clear_bed']:
			capabilities.append('cleanState') # Support bed not clean state
		return capabilities
コード例 #25
0
def save_printer_profile_settings():
    driver = request.values.get('driver', None)

    if driver:
        pp = printerProfileManager()
        pp.set({'driver': driver})
        pp.save()

        return make_response("OK", 200)

    return make_response('Invalid Connection Settings', 400)
コード例 #26
0
ファイル: printerprofile.py プロジェクト: IceForgTW/AstroBox
def printer_profile_patch():
	changes = request.json

	if 'cancel_gcode' in changes:
		changes['cancel_gcode'] = changes['cancel_gcode'].strip().split('\n');

	ppm = printerProfileManager()
	ppm.set(changes)
	ppm.save()

	return jsonify()
コード例 #27
0
ファイル: printerprofile.py プロジェクト: maxreaper/AstroBox
def printer_profile_patch():
    changes = request.json

    if 'cancel_gcode' in changes:
        changes['cancel_gcode'] = changes['cancel_gcode'].strip().split('\n')

    ppm = printerProfileManager()
    ppm.set(changes)
    ppm.save()

    return jsonify()
コード例 #28
0
ファイル: __init__.py プロジェクト: MiniguyBrendan/AstroBox
    def __init__(self):
        self._profileManager = printerProfileManager()

        self._fileManager = printFileManagerMap[self._fileManagerClass.name]()
        self._fileManager.registerCallback(self)
        self._state = self.STATE_NONE

        self._temp = {}
        self._bedTemp = None
        self._temps = deque([], 300)

        self._messages = deque([], 300)

        self._cameraManager = cameraManager()

        # callbacks
        self._callbacks = []
        #self._lastProgressReport = None

        self._stateMonitor = StateMonitor(
            ratelimit=1.0,
            updateCallback=self._sendCurrentDataCallbacks,
            addTemperatureCallback=self._sendAddTemperatureCallbacks,
            addLogCallback=self._sendAddLogCallbacks,
            addMessageCallback=self._sendAddMessageCallbacks)

        self._stateMonitor.reset(state={
            "text": self.getStateString(),
            "flags": self._getStateFlags()
        },
                                 jobData={
                                     "file": {
                                         "name": None,
                                         "size": None,
                                         "origin": None,
                                         "date": None
                                     },
                                     "estimatedPrintTime": None,
                                     "filament": {
                                         "length": None,
                                         "volume": None
                                     }
                                 },
                                 progress={
                                     "completion": None,
                                     "filepos": None,
                                     "printTime": None,
                                     "printTimeLeft": None
                                 },
                                 currentZ=None)

        eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED,
                                 self.onMetadataAnalysisFinished)
コード例 #29
0
ファイル: __init__.py プロジェクト: cronos45/AstroBox
	def __init__(self, hostname, router):
		self._weakRefRouter = weakref.ref(router)
		self._printerListener = None
		self._lastReceived = 0
		self._subscribers = 0
		self._silentReconnect = False
		self._profileManager = printerProfileManager()
		self._logger = logging.getLogger(__name__)
		self._lineCheck = None
		self._error = False
		self._condition = threading.Condition()
		super(AstroprintBoxRouterClient, self).__init__(hostname)
コード例 #30
0
ファイル: __init__.py プロジェクト: maxreaper/AstroBox
 def __init__(self, hostname, router):
     self._weakRefRouter = weakref.ref(router)
     self._printerListener = None
     self._lastReceived = 0
     self._subscribers = 0
     self._silentReconnect = False
     self._profileManager = printerProfileManager()
     self._logger = logging.getLogger(__name__)
     self._lineCheck = None
     self._error = False
     self._condition = threading.Condition()
     super(AstroprintBoxRouterClient, self).__init__(hostname)
コード例 #31
0
ファイル: virtual.py プロジェクト: bula87/AstroBox
        def doConnect():
            if not self._shutdown:
                self._changeState(self.STATE_OPERATIONAL)
                self._temperatureChanger = TempsChanger(self)
                self._temperatureChanger.start()

                #set initial temps
                extruder_count = (
                    printerProfileManager().data.get('extruder_count'))
                for i in range(extruder_count):
                    self.setTemperature('tool' + str(i), 25)
                self.setTemperature('bed', 25)
コード例 #32
0
ファイル: printerprofile.py プロジェクト: madhuni/Ray
def printer_profile_patch():
	ppm = printerProfileManager()

	if request.method == "PATCH":
		changes = request.json

		ppm.set(changes)
		ppm.save()

		return jsonify()

	else:
		return jsonify(ppm.data)
コード例 #33
0
ファイル: requesthandler.py プロジェクト: IceForgTW/AstroBox
	def initial_state(self, data, clientId, done):
		printer = printerManager()
		cm = cameraManager()

		done({
			'printing': printer.isPrinting(),
			'operational': printer.isOperational(),
			'paused': printer.isPaused(),
			'camera': printer.isCameraConnected(),
			'printCapture': cm.timelapseInfo,
			'profile': printerProfileManager().data,
			'remotePrint': True,
			'capabilities': ['remotePrint'] + cm.capabilities
		})
コード例 #34
0
ファイル: requesthandler.py プロジェクト: italocjs/AstroBox
	def set_filament(self, data, clientId, done):

		filament = {}
		filament['filament'] = {}

		if data['filament'] and data['filament']['name'] and data['filament']['color']:
			filament['filament']['name'] = data['filament']['name']
			#Better to make sure that are getting right color codes
			if re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', data['filament']['color']):
				filament['filament']['color'] = data['filament']['color']
			else:
				done({
					'error': True,
					'message': 'Invalid color code'
				})

		else:
			filament['filament']['name'] = None
			filament['filament']['color'] = None

		printerProfileManager().set(filament)
		printerProfileManager().save()
		done(None)
コード例 #35
0
ファイル: requesthandler.py プロジェクト: IceForgTW/AstroBox
    def initial_state(self, data, clientId, done):
        printer = printerManager()
        cm = cameraManager()

        done({
            'printing': printer.isPrinting(),
            'operational': printer.isOperational(),
            'paused': printer.isPaused(),
            'camera': printer.isCameraConnected(),
            'printCapture': cm.timelapseInfo,
            'profile': printerProfileManager().data,
            'remotePrint': True,
            'capabilities': ['remotePrint'] + cm.capabilities
        })
コード例 #36
0
ファイル: setup.py プロジェクト: KyleXYY/MPrintBox
def save_printer_profile_settings():
	driver = request.values.get('driver', None)

	if driver:
		pp = printerProfileManager()
		pp.data['driver'] = driver
		pp.save()

		#swap the printerManager here
		printerManager(driver)

		return make_response("OK", 200)

	return make_response('Invalid Connection Settings', 400)
コード例 #37
0
ファイル: setup.py プロジェクト: marianoronchi/AstroBox
def save_printer_profile_settings():
    driver = request.values.get('driver', None)

    if driver:
        pp = printerProfileManager()
        pp.data['driver'] = driver
        pp.save()

        #swap the printerManager here
        printerManager(driver)

        return make_response("OK", 200)

    return make_response('Invalid Connection Settings', 400)
コード例 #38
0
ファイル: requesthandler.py プロジェクト: AstroPrint/AstroBox
	def set_filament(self, data, clientId, done):

		filament = {}
		filament['filament'] = {}

		if data['filament'] and data['filament']['name'] and data['filament']['color']:
			filament['filament']['name'] = data['filament']['name']
			#Better to make sure that are getting right color codes
			if re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', data['filament']['color']):
				filament['filament']['color'] = data['filament']['color']
			else:
				done({
					'error': True,
					'message': 'Invalid color code'
				})

		else:
			filament['filament']['name'] = None
			filament['filament']['color'] = None

		printerProfileManager().set(filament)
		printerProfileManager().save()
		done(None)
コード例 #39
0
ファイル: __init__.py プロジェクト: AstroPrint/AstroBox
	def processAuthenticate(self, data):
		if data:
			self._silentReconnect = False

			if 'error' in data:
				self._logger.warn(data['message'] if 'message' in data else 'Unkonwn authentication error')
				self.status = self.STATUS_ERROR
				self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)
				self.close()

			elif 'success' in data:
				self._logger.info("Connected to astroprint service")
				self.authenticated = True
				self._retries = 0
				self._retryTimer = None
				self.status = self.STATUS_CONNECTED
				self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)

			return None

		else:
			from octoprint.server import VERSION
			from astroprint.printerprofile import printerProfileManager

			nm = networkManager()
			sm = softwareManager()
			ppm = printerProfileManager()

			authData = {
				'silentReconnect': self._silentReconnect,
				'boxId': self.boxId,
				'variantId': sm.variant['id'],
				'boxName': nm.getHostname(),
				'swVersion': VERSION,
				'platform': sm.platform,
				'localIpAddress': nm.activeIpAddress,
				'publicKey': self._publicKey,
				'privateKey': self._privateKey,
				'printerModel': ppm.data['printer_model'] if ppm.data['printer_model']['id'] else None
			}

			pkgId = sm.mfPackageId
			if pkgId:
				authData['mfPackageId'] = pkgId

			return {
				'type': 'auth',
				'data': authData
			}
コード例 #40
0
ファイル: setup.py プロジェクト: marianoronchi/AstroBox
def connection_settings():
    connectionOptions = printerManager().getConnectionOptions()

    if connectionOptions:
        response = {
            "driver": printerProfileManager().data['driver'],
            "port": connectionOptions["portPreference"],
            "baudrate": connectionOptions["baudratePreference"],
            "portOptions": connectionOptions["ports"].items(),
            "baudrateOptions": connectionOptions["baudrates"]
        }

        return jsonify(response)

    return make_response("Connection options not available", 400)
コード例 #41
0
ファイル: __init__.py プロジェクト: nerginer/AstroBox
	def __init__(self, hostname, router):
		#it needs to be imported here because on the main body 'printer' is None
		from octoprint.server import printer

		self._router = router
		self._printer = printer
		self._printerListener = None
		self._lastReceived = 0
		self._subscribers = 0
		self._silentReconnect = False
		self._cameraManager = cameraManager()
		self._profileManager = printerProfileManager()
		self._logger = logging.getLogger(__name__)
		self._lineCheck = None
		super(AstroprintBoxRouterClient, self).__init__(hostname)
コード例 #42
0
ファイル: __init__.py プロジェクト: nerginer/AstroBox
    def __init__(self, hostname, router):
        #it needs to be imported here because on the main body 'printer' is None
        from octoprint.server import printer

        self._router = router
        self._printer = printer
        self._printerListener = None
        self._lastReceived = 0
        self._subscribers = 0
        self._silentReconnect = False
        self._cameraManager = cameraManager()
        self._profileManager = printerProfileManager()
        self._logger = logging.getLogger(__name__)
        self._lineCheck = None
        super(AstroprintBoxRouterClient, self).__init__(hostname)
コード例 #43
0
ファイル: setup.py プロジェクト: KyleXYY/MPrintBox
def connection_settings():
	connectionOptions = printerManager().getConnectionOptions()

	if connectionOptions:
		response = {
			"driver": printerProfileManager().data['driver'],
			"port": connectionOptions["portPreference"],
			"baudrate": connectionOptions["baudratePreference"],
			"portOptions": connectionOptions["ports"].items(),
			"baudrateOptions": connectionOptions["baudrates"]
		}

		return jsonify(response)

	return make_response("Connection options not available", 400)
コード例 #44
0
ファイル: __init__.py プロジェクト: KyleXYY/MPrintBox
	def __init__(self):
		self._profileManager = printerProfileManager()

		self._fileManager= printFileManagerMap[self._fileManagerClass.name]()
		self._fileManager.registerCallback(self)
		self._state = self.STATE_NONE
		self._logger = logging.getLogger(__name__)

		self._temp = {}
		self._bedTemp = None
		self._temps = deque([], 300)

		self._messages = deque([], 300)

		self._cameraManager = cameraManager()

		# callbacks
		self._callbacks = []
		#self._lastProgressReport = None

		self._stateMonitor = StateMonitor(
			ratelimit= 1.0,
			updateCallback= self._sendCurrentDataCallbacks,
			addTemperatureCallback= self._sendAddTemperatureCallbacks,
			addLogCallback= self._sendAddLogCallbacks,
			addMessageCallback= self._sendAddMessageCallbacks
		)

		self._stateMonitor.reset(
			state={"text": self.getStateString(), "flags": self._getStateFlags()},
			jobData={
				"file": {
					"name": None,
					"size": None,
					"origin": None,
					"date": None
				},
				"estimatedPrintTime": None,
				"filament": {
					"length": None,
					"volume": None
				}
			},
			progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None},
			currentZ=None
		)

		eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished);
コード例 #45
0
ファイル: printerprofile.py プロジェクト: AstroPrint/AstroBox
def printer_profile_patch():
	ppm = printerProfileManager()

	if request.method == "PATCH":
		changes = request.json
		ppm.set(changes)
		ppm.save()

		return jsonify()

	else:

		result = ppm.data.copy()
		result.update( {"driverChoices": ppm.driverChoices()} )

		return jsonify( result )
コード例 #46
0
def printer_profile_patch():
    ppm = printerProfileManager()

    if request.method == "PATCH":
        changes = request.json
        ppm.set(changes)
        ppm.save()

        return jsonify()

    else:

        result = ppm.data.copy()
        result.update({"driverChoices": ppm.driverChoices()})

        return jsonify(result)
コード例 #47
0
ファイル: virtual.py プロジェクト: bula87/AstroBox
    def run(self):
        self._pausedEvent.set()

        while not self._stopped and self._percentCompleted < 1:
            self._pausedEvent.wait()

            if self._stopped:
                break

            self._timeElapsed += 1
            self._filePos += 1
            self._currentLayer += 1
            self._consumedFilament[0] += 10
            self._percentCompleted = self._timeElapsed / self._jobLength
            self._pm.mcLayerChange(self._currentLayer)
            self._pm.mcProgress()

            time.sleep(1)

        self._pm._changeState(self._pm.STATE_OPERATIONAL)

        extruder_count = (printerProfileManager().data.get('extruder_count'))
        for i in range(extruder_count):
            self._pm.setTemperature('tool' + str(i), 0)
        self._pm.setTemperature('bed', 0)

        payload = {
            "file": self._file['filename'],
            "filename": os.path.basename(self._file['filename']),
            "origin": self._file['origin'],
            "time": self._timeElapsed,
            "layerCount": self._currentLayer
        }

        if self._percentCompleted >= 1:
            self._pm.mcPrintjobDone()
            self._pm._fileManager.printSucceeded(payload['filename'],
                                                 payload['time'],
                                                 payload['layerCount'])
            eventManager().fire(Events.PRINT_DONE, payload)
        else:
            self._pm.printJobCancelled()
            eventManager().fire(Events.PRINT_CANCELLED, payload)
            self._pm._fileManager.printFailed(payload['filename'],
                                              payload['time'])

        self._pm = None
コード例 #48
0
def printer_profile_patch():
    ppm = printerProfileManager()

    if request.method == "PATCH":
        changes = request.json

        if 'cancel_gcode' in changes:
            changes['cancel_gcode'] = changes['cancel_gcode'].strip().split(
                '\n')

        ppm.set(changes)
        ppm.save()

        return jsonify()

    else:
        return jsonify(ppm.data)
コード例 #49
0
ファイル: __init__.py プロジェクト: daftscience/AstroBox
def index():
	s = settings()

	if (s.getBoolean(["server", "firstRun"])):
		# we need to get the user to sign into their AstroPrint account
		return render_template(
			"setup.jinja2",
			debug= debug,
			uiApiKey= UI_API_KEY,
			version= VERSION,
			variantData= variantManager().data
		)

	elif softwareManager.updatingRelease or softwareManager.forceUpdateInfo:
		return render_template(
			"updating.jinja2",
			uiApiKey= UI_API_KEY,
			showForceUpdate=  softwareManager.forceUpdateInfo != None,
			releaseInfo= softwareManager.updatingRelease or softwareManager.forceUpdateInfo,
			variantData= variantManager().data
		)

	else:
		paused = printer.isPaused()
		printing = printer.isPrinting()
		
		return render_template(
			"app.jinja2",
			user_email= s.get(["cloudSlicer", "email"]),
			version= VERSION,
			printing= printing,
			paused= paused,
			print_capture= cameraManager().timelapseInfo if printing or paused else None,
			printer_profile= printerProfileManager().data,
			uiApiKey= UI_API_KEY,
			astroboxName= networkManager.getHostname(),
			variantData= variantManager().data
		)
コード例 #50
0
ファイル: manager.py プロジェクト: AstroPrint/AstroBox
def printerManager(driver = None):
	global _instance

	if driver is not None and _instance is not None and _instance.driverName != driver:
		_instance.rampdown()
		_instance = None

	if _instance is None and driver:
		if driver.startswith('plugin:'):
			from astroprint.printer.plugin import PrinterWithPlugin, NoPluginException

			try:
				_instance = PrinterWithPlugin(driver[7:])

			except NoPluginException:
				#The plugin is gone. Pick the default
				from astroprint.printerprofile import printerProfileManager
				ppm = printerProfileManager()
				ppm.set({'driver': DEFAULT_MANAGER})
				ppm.save()

		else:
			import importlib

			try:
				# driver name to class map. format is (module, classname)
				classInfo = {
					'marlin': ('.marlin', 'PrinterMarlin'),
					's3g': ('.s3g', 'PrinterS3g')
				}[driver]

			except KeyError:
				classInfo = ('.marlin', 'PrinterMarlin')

			module = importlib.import_module(classInfo[0], 'astroprint.printer')
			_instance = getattr(module, classInfo[1])()

	return _instance
コード例 #51
0
ファイル: setup.py プロジェクト: KyleXYY/MPrintBox
def save_connection_settings():
	port = request.values.get('port', None)
	baudrate = request.values.get('baudrate', None)
	driver = request.values.get('driver', None)

	if port and ( baudrate or driver == 's3g'):
		s = settings()

		s.set(["serial", "port"], port)
		if baudrate:
			s.setInt(["serial", "baudrate"], baudrate)
		s.save()

		pp = printerProfileManager()
		pp.data['driver'] = driver
		pp.save()

		pm = printerManager(driver)
		pm.connect()

		return make_response("OK", 200)

	return make_response('Invalid Connection Settings', 400)
コード例 #52
0
ファイル: __init__.py プロジェクト: IceForgTW/AstroBox
def index():
	s = settings()
	loggedUsername = s.get(["cloudSlicer", "loggedUser"])

	if (s.getBoolean(["server", "firstRun"])):
		swm = swManager()

		# we need to get the user to sign into their AstroPrint account
		return render_template(
			"setup.jinja2",
			debug= debug,
			uiApiKey= UI_API_KEY,
			version= VERSION,
			commit= swm.commit,
			variantData= variantManager().data,
			astroboxName= networkManager().getHostname(),
			checkSoftware= swm.shouldCheckForNew,
			settings=s
		)

	elif softwareManager.updatingRelease or softwareManager.forceUpdateInfo:
		return render_template(
			"updating.jinja2",
			uiApiKey= UI_API_KEY,
			showForceUpdate=  softwareManager.forceUpdateInfo != None,
			releaseInfo= softwareManager.updatingRelease or softwareManager.forceUpdateInfo,
			lastCompletionPercent= softwareManager.lastCompletionPercent,
			lastMessage= softwareManager.lastMessage,
			variantData= variantManager().data,
			astroboxName= networkManager().getHostname()
		)

	elif loggedUsername and (current_user is None or not current_user.is_authenticated() or current_user.get_id() != loggedUsername):
		if current_user.is_authenticated():
			logout_user()

		return render_template(
			"locked.jinja2",
			username= loggedUsername,
			uiApiKey= UI_API_KEY,
			astroboxName= networkManager().getHostname(),
			variantData= variantManager().data
		)

	else:
		pm = printerManager()
		nm = networkManager()
		swm = swManager()
		cm = cameraManager()

		paused = pm.isPaused()
		printing = pm.isPrinting()
		online = nm.isOnline()

		return render_template(
			"app.jinja2",
			user_email= loggedUsername,
			version= VERSION,
			commit= swm.commit,
			printing= printing,
			paused= paused,
			online= online,
			print_capture= cm.timelapseInfo if printing or paused else None,
			printer_profile= printerProfileManager().data,
			uiApiKey= UI_API_KEY,
			astroboxName= nm.getHostname(),
			variantData= variantManager().data,
			checkSoftware= swm.shouldCheckForNew,
			serialLogActive= s.getBoolean(['serial', 'log']),
			cameraManager= cm.name
		)
コード例 #53
0
ファイル: printer.py プロジェクト: nerginer/AstroBox
	def __init__(self, gcodeManager):
		from collections import deque

		self._gcodeManager = gcodeManager
		self._gcodeManager.registerCallback(self)
		self._cameraManager = cameraManager()
		self._profileManager = printerProfileManager()

		# state
		# TODO do we really need to hold the temperature here?
		self._temp = None
		self._bedTemp = None
		self._targetTemp = None
		self._targetBedTemp = None
		self._temps = deque([], 300)
		self._tempBacklog = []

		self._latestMessage = None
		self._messages = deque([], 300)
		self._messageBacklog = []

		self._latestLog = None
		self._log = deque([], 300)
		self._logBacklog = []

		self._state = None

		self._currentZ = None

		self._progress = None
		self._printTime = None
		self._printTimeLeft = None
		self._currentLayer = None
		self._layerCount = None
		self._estimatedPrintTime = None

		self._printId = None

		self._printAfterSelect = False

		# sd handling
		self._sdPrinting = False
		self._sdStreaming = False
		self._sdFilelistAvailable = threading.Event()
		self._streamingFinishedCallback = None

		self._selectedFile = None

		# comm
		self._comm = None

		# callbacks
		self._callbacks = []
		self._lastProgressReport = None

		self._stateMonitor = StateMonitor(
			ratelimit=1.0,
			updateCallback=self._sendCurrentDataCallbacks,
			addTemperatureCallback=self._sendAddTemperatureCallbacks,
			addLogCallback=self._sendAddLogCallbacks,
			addMessageCallback=self._sendAddMessageCallbacks
		)
		self._stateMonitor.reset(
			state={"text": self.getStateString(), "flags": self._getStateFlags()},
			jobData={
				"file": {
					"name": None,
					"size": None,
					"origin": None,
					"date": None
				},
				"estimatedPrintTime": None,
				"filament": {
					"length": None,
					"volume": None
				}
			},
			progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None},
			currentZ=None
		)

		eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished);