Exemplo n.º 1
0
    def peerSession(self, data, sendResponse):

        action = data['action']

        if data and 'sessionId' in data:
            sessionId = data['sessionId']

            if action == 'init_peer_session':
                #Initialize the peer session
                if cameraManager().startLocalVideoSession(sessionId):
                    sendResponse({'success': 'no-error'})
                else:
                    sendResponse('error_init_peer_session', True)

            #elif request.method == 'DELETE':
            elif action == 'close_peer_session':
                #Close peer session
                if cameraManager().closeLocalVideoSession(sessionId):
                    sendResponse({'success': 'no-error'})

                else:
                    sendResponse('error_close_peer_session', True)

        else:
            sendResponse('error_no_session_id', True)
Exemplo n.º 2
0
	def startPrint(self):
		"""
		 Starts the currently loaded print job.
		 Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
		"""
		if not self.isConnected() or not self.isOperational() or self.isPrinting():
			return False

		if self._selectedFile is None:
			return False

		self._setCurrentZ(None)
		cameraManager().open_camera()

		kwargs = {
			'print_file_name': os.path.basename(self._selectedFile['filename'])
		}

		if self._selectedFile['cloudId']:
			kwargs['print_file_id'] = self._selectedFile['cloudId']

		#tell astroprint that we started a print
		result = astroprintCloud().print_job(**kwargs)

		if result and "id" in result:
			self._currentPrintJobId = result['id']

		return True
Exemplo n.º 3
0
    def startPrint(self):
        """
		 Starts the currently loaded print job.
		 Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
		"""
        if not self.isConnected() or not self.isOperational(
        ) or self.isPrinting():
            return False

        if self._selectedFile is None:
            return False

        self._setCurrentZ(None)
        cameraManager().open_camera()

        kwargs = {
            'print_file_name': os.path.basename(self._selectedFile['filename'])
        }

        if self._selectedFile['cloudId']:
            kwargs['print_file_id'] = self._selectedFile['cloudId']

        #tell astroprint that we started a print
        result = astroprintCloud().print_job(**kwargs)

        if result and "id" in result:
            self._currentPrintJobId = result['id']

        return True
Exemplo n.º 4
0
    def mcPrintjobDone(self):
        # stop timelapse if there was one
        # True makes it take one last photo
        cameraManager().stop_timelapse(True)

        # Not sure if this is the best way to get the layer count
        self._setProgressData(1.0, self._selectedFile["filesize"],
                              self.getPrintTime(), 0, self._layerCount)
        self._stateMonitor.setState({
            "state": self._state,
            "text": self.getStateString(),
            "flags": self._getStateFlags()
        })

        consumedMaterial = self.getTotalConsumedFilament()

        if self._currentPrintJobId:
            astroprintCloud().print_job(self._currentPrintJobId,
                                        status='success',
                                        materialUsed=consumedMaterial)
            self._currentPrintJobId = None

        self._logger.info(
            "Print job [%s] COMPLETED. Filament used: %f" % \
            (os.path.split(
                self._selectedFile['filename'])[1] if self._selectedFile else 'unknown', consumedMaterial))
Exemplo n.º 5
0
	def peerSession(self,data,sendResponse):

		action = data['action']

		if data and 'sessionId' in data:
			sessionId = data['sessionId']

			#if request.method == 'POST':
			if action == 'init_peer_session':
				#Initialize the peer session
				if cameraManager().startLocalVideoSession(sessionId):
					sendResponse({'success': 'no-error'})
				else:
					sendResponse('error_init_peer_session',True)

			#elif request.method == 'DELETE':
			elif action == 'close_peer_session':
				#Close peer session
				if cameraManager().closeLocalVideoSession(sessionId):
					sendResponse({'success': 'no-error'})

				else:
					sendResponse('error_close_peer_session',True)

		else:
			sendResponse('error_no_session_id',True)
Exemplo n.º 6
0
	def cancelPrint(self, disableMotorsAndHeater=True):
		"""
		 Cancel the current printjob.
		"""

		if self.isConnected() and (self.isPrinting() or self.isPaused()):
			activePrintJob = None

			cameraManager().stop_timelapse()

			consumedMaterial = self.getTotalConsumedFilament()

			if self._currentPrintJobId:
				astroprintCloud().print_job(self._currentPrintJobId, status='failed', materialUsed= consumedMaterial)
				activePrintJob = self._currentPrintJobId
				self._currentPrintJobId = None

			self._logger.info("Print job [%s] CANCELED. Filament used: %f" % (os.path.split(self._selectedFile['filename'])[1] if self._selectedFile else 'unknown', consumedMaterial))

			self.executeCancelCommands(disableMotorsAndHeater)

			return {'print_job_id': activePrintJob}

		else:
			return {'error': 'no_print_job', 'message': 'No active print job to cancel'}
Exemplo n.º 7
0
	def cancelPrint(self, disableMotorsAndHeater=True):
		"""
		 Cancel the current printjob.
		"""

		if self.isConnected() and (self.isPrinting() or self.isPaused()):
			activePrintJob = None

			cameraManager().stop_timelapse()

			consumedMaterial = self.getTotalConsumedFilament()

			if self._currentPrintJobId:
				astroprintCloud().print_job(self._currentPrintJobId, status='failed', materialUsed= consumedMaterial)
				activePrintJob = self._currentPrintJobId
				self._currentPrintJobId = None

			self._logger.info("Print job [%s] CANCELED. Filament used: %f" % (os.path.split(self._selectedFile['filename'])[1] if self._selectedFile else 'unknown', consumedMaterial))

			self.executeCancelCommands(disableMotorsAndHeater)

			return {'print_job_id': activePrintJob}

		else:
			return {'error': 'no_print_job', 'message': 'No active print job to cancel'}
Exemplo n.º 8
0
	def restartServer(self):
		if platform == "linux" or platform == "linux2":
			actions = self._settings.get(["system", "actions"])
			for a in actions:
				if a['action'] == 'astrobox-restart':
					#Call to Popen will start the restart command but return inmediately before it completes
					threading.Timer(1.0, subprocess.Popen, [a['command'].split(' ')]).start()
					self._logger.info('Restart command scheduled')

					from astroprint.boxrouter import boxrouterManager
					from astroprint.printer.manager import printerManager
					from astroprint.camera import cameraManager
					from astroprint.network.manager import networkManagerShutdown

					#let's be nice about shutthing things down
					boxrouterManager().boxrouter_disconnect()
					printerManager().disconnect()
					cameraManager().close_camera()
					networkManagerShutdown()

					return True

			return False

		return True
Exemplo n.º 9
0
    def closePeerSession(self, sessionId):
        with self._peerCondition:
            if len(self._connectedPeers.keys()) > 0:

                try:
                    peer = self._connectedPeers[sessionId]
                except KeyError:
                    self._logger.warning('Session [%s] for peer not found' %
                                         sessionId)
                    peer = None

                if peer:
                    peer.streamingPlugin.send_message({
                        'request': 'destroy',
                        'id': sessionId
                    })
                    peer.close()
                    peer.sendEventToPeer('stopConnection')
                    del self._connectedPeers[sessionId]

                self._logger.info("There are %d peers left.",
                                  len(self._connectedPeers))

                if len(self._connectedPeers.keys()) == 0:
                    #last session
                    self.stopJanus()
                    cameraManager().stop_video_stream()
Exemplo n.º 10
0
    def photo(self, data, clientId, done):
        def doneWithPhoto(pic):
            if pic is not None:
                done({'success': True, 'image_data': base64.b64encode(pic)})
            else:
                done({'success': False, 'image_data': ''})

        cameraManager().get_pic_async(doneWithPhoto)
Exemplo n.º 11
0
	def startVideoStream(self):
		#Start Video Stream
		def startDone(success):
			if not success:
				self._logger.error('Managing GStreamer error in WebRTC object')
				self.stopJanus()

		cameraManager().start_video_stream(startDone)
Exemplo n.º 12
0
    def startVideoStream(self):
        #Start Video Stream
        def startDone(success):
            if not success:
                self._logger.error('Managing GStreamer error in WebRTC object')
                self.stopJanus()

        cameraManager().start_video_stream(startDone)
Exemplo n.º 13
0
	def cleanup(self):
		global discoveryManager
		
		discoveryManager.shutdown()
		discoveryManager = None
		boxrouterManager().shutdown()
		cameraManager().shutdown()

		from astroprint.network.manager import networkManagerShutdown
		networkManagerShutdown()
Exemplo n.º 14
0
	def mcPrintjobDone(self):
		#stop timelapse if there was one
		cameraManager().stop_timelapse(True) #True makes it take one last photo 

		#Not sure if this is the best way to get the layer count
		self._setProgressData(1.0, self._selectedFile["filesize"], self.getPrintTime(), 0, self._layerCount)
		self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()})

		if self._currentPrintJobId:
			astroprintCloud().print_job(self._currentPrintJobId, status='success')
			self._currentPrintJobId = None
Exemplo n.º 15
0
	def cleanup(self):
		global discoveryManager
		
		discoveryManager.shutdown()
		discoveryManager = None
		boxrouterManager().shutdown()
		cameraManager().shutdown()

		from astroprint.network.manager import networkManagerShutdown
		networkManagerShutdown()
		
		logging.getLogger(__name__).info("Goodbye!")
Exemplo n.º 16
0
	def on_close(self):
		self._logger.info("Client connection closed [Session id: %s]", self.session.session_id)

		printer = printerManager()

		printer.unregisterCallback(self)
		printer.fileManager.unregisterCallback(self)
		cameraManager().closeLocalVideoSession(self.session.session_id)

		self._eventManager.fire(Events.CLIENT_CLOSED)
		for event in PrinterStateConnection.EVENTS:
			self._eventManager.unsubscribe(event, self._onEvent)
Exemplo n.º 17
0
	def on_close(self):
		self._logger.info("Client connection closed [Session id: %s]", self.session.session_id)

		printer = printerManager()

		printer.unregisterCallback(self)
		printer.fileManager.unregisterCallback(self)
		cameraManager().closeLocalVideoSession(self.session.session_id)
		#octoprint.timelapse.unregisterCallback(self)

		self._eventManager.fire(Events.CLIENT_CLOSED)
		for event in PrinterStateConnection.EVENTS:
			self._eventManager.unsubscribe(event, self._onEvent)
Exemplo n.º 18
0
    def cleanup(self):
        global discoveryManager

        pluginManager().shutdown()
        downloadManager().shutdown()
        printerManager().rampdown()
        discoveryManager.shutdown()
        discoveryManager = None
        boxrouterManager().shutdown()
        cameraManager().shutdown()
        externalDriveManager().shutdown()

        from astroprint.network.manager import networkManagerShutdown
        networkManagerShutdown()
Exemplo n.º 19
0
	def cancelPrint(self, disableMotorsAndHeater=True):
		"""
		 Cancel the current printjob.
		"""
		if self._comm is None:
			return False

		cameraManager().stop_timelapse()

		if self._currentPrintJobId:
			astroprintCloud().print_job(self._currentPrintJobId, status='failed')
			self._currentPrintJobId = None

		return True
Exemplo n.º 20
0
    def cancelPrint(self, disableMotorsAndHeater=True):
        """
		 Cancel the current printjob.
		"""
        if self._comm is None:
            return False

        cameraManager().stop_timelapse()

        if self._currentPrintJobId:
            astroprintCloud().print_job(self._currentPrintJobId,
                                        status='failed')
            self._currentPrintJobId = None

        return True
Exemplo n.º 21
0
	def mcPrintjobDone(self):
		#stop timelapse if there was one
		cameraManager().stop_timelapse(True) #True makes it take one last photo

		#Not sure if this is the best way to get the layer count
		self._setProgressData(1.0, self._selectedFile["filesize"], self.getPrintTime(), 0, self._layerCount)
		self.refreshStateData()

		consumedMaterial = self.getTotalConsumedFilament()

		if self._currentPrintJobId:
			astroprintCloud().print_job(self._currentPrintJobId, status= 'success', materialUsed= consumedMaterial)
			self._currentPrintJobId = None

		self._logger.info("Print job [%s] COMPLETED. Filament used: %f" % (os.path.split(self._selectedFile['filename'])[1] if self._selectedFile else 'unknown', consumedMaterial))
Exemplo n.º 22
0
	def photo(self, data, clientId, done):

		def doneWithPhoto(pic):
			if pic is not None:
				done({
					'success': True,
					'image_data': base64.b64encode(pic)
				})
			else:
				done({
					'success': False,
					'image_data': ''
				})

		cameraManager().get_pic_async(doneWithPhoto)
Exemplo n.º 23
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(),
			'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)
Exemplo n.º 24
0
    def togglePausePrint(self):
        """
		 Pause the current printjob.
		"""
        if self._comm is None:
            return

        wasPaused = self.isPaused()

        self.setPause(not wasPaused)

        #the functions already check if there's a timelapse in progress
        if wasPaused:
            cameraManager().resume_timelapse()
        else:
            cameraManager().pause_timelapse()
Exemplo n.º 25
0
def cameraSettings():
    s = settings()
    cm = cameraManager()

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

            if "size" in data:
                s.set(['camera', 'size'], data['size'])

            if "encoding" in data:
                s.set(['camera', 'encoding'], data['encoding'])

            if "framerate" in data:
                s.set(['camera', 'framerate'], data['framerate'])

            if "format" in data:
                s.set(['camera', 'format'], data['format'])

            s.save()

            cm.settingsChanged({
                'size': s.get(['camera', 'size']),
                'encoding': s.get(['camera', 'encoding']),
                'framerate': s.get(['camera', 'framerate']),
                'format': s.get(['camera', 'format'])
            })

    return jsonify(encoding=s.get(['camera', 'encoding']),
                   size=s.get(['camera', 'size']),
                   framerate=s.get(['camera', 'framerate']),
                   format=s.get(['camera', 'format']),
                   structure=cm.settingsStructure())
Exemplo n.º 26
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
	)
Exemplo n.º 27
0
    def connected(self, sendResponse):
        cm = cameraManager()

        return sendResponse({
            "isCameraConnected": cm.isCameraConnected(),
            "cameraName": cm.cameraName
        })
Exemplo n.º 28
0
	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
			}
Exemplo n.º 29
0
def camera_snapshot():
	cameraMgr = cameraManager()
	pic_buf = cameraMgr.get_pic(text=request.args.get('text'))
	if pic_buf:
		return Response(pic_buf, mimetype='image/jpeg', headers={"Access-Control-Allow-Origin": "*"})
	else:
		return 'Camera not ready', 404
Exemplo n.º 30
0
	def printCapture(self, data, clientId, done):
		freq = data['freq']
		if freq:
			cm = cameraManager()

			if cm.timelapseInfo:
				if not cm.update_timelapse(freq):
					done({
						'error': True,
						'message': 'Error updating the print capture'
					})
					return

			else:
				r = cm.start_timelapse(freq)
				if r != 'success':
					done({
						'error': True,
						'message': 'Error creating the print capture: %s' % r
					})
					return
		else:
			done({
				'error': True,
				'message': 'Frequency required'
			})
			return

		done(None)
Exemplo n.º 31
0
	def mcPhotoCommand(self):
		cm = cameraManager()

		if not cm.is_timelapse_active():
			cm.start_timelapse('gcode')

		cm.addPhotoToActiveTimelapse()
Exemplo n.º 32
0
    def printCapture(self, data, clientId, done):
        freq = data['freq']
        if freq:
            cm = cameraManager()

            if cm.timelapseInfo:
                if not cm.update_timelapse(freq):
                    done({
                        'error': True,
                        'message': 'Error updating the print capture'
                    })
                    return

            else:
                r = cm.start_timelapse(freq)
                if r != 'success':
                    done({
                        'error': True,
                        'message': 'Error creating the print capture: %s' % r
                    })
                    return
        else:
            done({'error': True, 'message': 'Frequency required'})
            return

        done(None)
Exemplo n.º 33
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,
            '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)
Exemplo n.º 34
0
def camera_snapshot():
	cameraMgr = cameraManager()
	pic_buf = cameraMgr.get_pic(text=request.args.get('text'))
	if pic_buf:
		return Response(pic_buf, mimetype='image/jpeg')
	else:
		return 'Camera not ready', 404
Exemplo n.º 35
0
def camera_snapshot():
    cameraMgr = cameraManager()
    pic_buf = cameraMgr.get_pic(text=request.args.get('text'))
    if pic_buf:
        return Response(pic_buf, mimetype='image/jpeg')
    else:
        return 'Camera not ready', 404
Exemplo n.º 36
0
def isCameraConnected():
    cm = cameraManager()

    return jsonify({
        "isCameraConnected": cm.isCameraConnected(),
        "cameraName": cm.cameraName
    })
Exemplo n.º 37
0
	def togglePausePrint(self):
		"""
		 Pause the current printjob.
		"""
		if self._comm is None:
			return

		wasPaused = self.isPaused()

		self.setPause(not wasPaused)

		#the functions already check if there's a timelapse in progress
		if wasPaused:
			cameraManager().resume_timelapse()
		else:
			cameraManager().pause_timelapse()
Exemplo n.º 38
0
def cameraSettings():
    s = settings()
    cm = cameraManager()

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

            if "source" in data:
                s.set(['camera', 'source'], data['source'])

            if "size" in data:
                s.set(['camera', 'size'], data['size'])

            if "encoding" in data:
                s.set(['camera', 'encoding'], data['encoding'])

            if "format" in data:
                s.set(['camera', 'format'], data['format'])

            if "framerate" in data:
                s.set(['camera', 'framerate'], data['framerate'])

            if "video_rotation" in data:
                s.set(['camera', 'video-rotation'],
                      int(data['video_rotation']))

            if "idle_timeout" in data:
                s.setFloat(['camera', 'inactivitySecs'], data['idle_timeout'])

            if "time_lapse" in data:
                s.set(['camera', 'freq'], data['time_lapse'])

            s.save()

            cm.settingsChanged({
                'size':
                s.get(['camera', 'size']),
                'encoding':
                s.get(['camera', 'encoding']),
                'framerate':
                s.get(['camera', 'framerate']),
                'source':
                s.get(['camera', 'source']),
                'format':
                s.get(['camera', 'format']),
                'video_rotation':
                s.get(['camera', 'video-rotation'])
            })

    return jsonify(encoding=s.get(['camera', 'encoding']),
                   size=s.get(['camera', 'size']),
                   framerate=s.get(['camera', 'framerate']),
                   format=s.get(['camera', 'format']),
                   source=s.get(['camera', 'source']),
                   video_rotation=s.getInt(['camera', 'video-rotation']),
                   structure=cm.settingsStructure(),
                   time_lapse=s.get(['camera', 'freq']),
                   idle_timeout=s.get(['camera', 'inactivitySecs']))
Exemplo n.º 39
0
    def cameraSettings(self, data, sendMessage):
        s = settings()
        cm = cameraManager()

        if data:
            if "source" in data:
                s.set(['camera', 'source'], data['source'])

            if "size" in data:
                s.set(['camera', 'size'], data['size'])

            if "encoding" in data:
                s.set(['camera', 'encoding'], data['encoding'])

            if "format" in data:
                s.set(['camera', 'format'], data['format'])

            if "framerate" in data:
                s.set(['camera', 'framerate'], data['framerate'])

            if "video_rotation" in data:
                s.set(['camera', 'video-rotation'],
                      int(data['video_rotation']))

            s.save()

            cm.settingsChanged({
                'size':
                s.get(['camera', 'size']),
                'encoding':
                s.get(['camera', 'encoding']),
                'framerate':
                s.get(['camera', 'framerate']),
                'source':
                s.get(['camera', 'source']),
                'format':
                s.get(['camera', 'format']),
                'video_rotation':
                s.get(['camera', 'video-rotation'])
            })

        sendMessage({
            'encoding':
            s.get(['camera', 'encoding']),
            'size':
            s.get(['camera', 'size']),
            'framerate':
            s.get(['camera', 'framerate']),
            'format':
            s.get(['camera', 'format']),
            'source':
            s.get(['camera', 'source']),
            'video_rotation':
            str(s.getInt(['camera', 'video-rotation'])),
            'structure':
            cm.settingsStructure()
        })

        return
Exemplo n.º 40
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']))
Exemplo n.º 41
0
    def mcPrintjobDone(self):
        #stop timelapse if there was one
        cameraManager().stop_timelapse(True)

        #Not sure if this is the best way to get the layer count
        self._setProgressData(1.0, self._selectedFile["filesize"],
                              self.getPrintTime(), 0, self._layerCount)
        self._stateMonitor.setState({
            "state": self._state,
            "stateString": self.getStateString(),
            "flags": self._getStateFlags()
        })

        if self._currentPrintJobId:
            astroprintCloud().print_job(self._currentPrintJobId,
                                        status='success')
            self._currentPrintJobId = None
Exemplo n.º 42
0
    def stopStreaming(self, data, sendResponse):

        if cameraManager().closeLocalVideoSession(sessionId):
            sendResponse({'success': 'no-error'})

            return

        else:
            sendResponse({'stop_streaming_error': True})
Exemplo n.º 43
0
	def stopStreaming(self,data,sendResponse):

		if cameraManager().closeLocalVideoSession(sessionId):
			sendResponse({'success': 'no-error'})

			return

		else:
			sendResponse({'stop_streaming_error': True})
Exemplo n.º 44
0
    def closeAllSessions(self, sender=None, message=None):
        self._logger.info("Closing all streaming sessions")

        #closing local streaming sessions
        cameraManager().removeAllLocalPeerReqs()

        for sessionId in self._connectedPeers.keys():
            peer = self._connectedPeers[sessionId]
            #if peer != 'local':
            if isinstance(peer, ConnectionPeer):
                if message:
                    peer.sendEventToPeer("cameraError", message)

                self.closePeerSession(sessionId)
            else:
                self.closeLocalSession(sessionId)

        return self.stopJanus()
Exemplo n.º 45
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,
			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
		)
Exemplo n.º 46
0
	def ensureGstreamerRunning(self):
		cam = cameraManager()
		if cam.open_camera():
			if not cam.start_video_stream():
				self._logger.error('Managing Gstreamer error in WebRTC object')
				#Janus is forced to be closed
				self.stopJanus()
				return False
			return False
		else:
			return True	
Exemplo n.º 47
0
	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._subscribers = 0
		self._cameraManager = cameraManager()
		self._logger = logging.getLogger(__name__)
		WebSocketClient.__init__(self, hostname)
Exemplo n.º 48
0
 def ensureGstreamerRunning(self):
     cam = cameraManager()
     if cam.open_camera():
         if not cam.start_video_stream():
             self._logger.error('Managing Gstreamer error in WebRTC object')
             #Janus is forced to be closed
             self.stopJanus()
             return False
         return False
     else:
         return True
Exemplo n.º 49
0
	def closeLocalSession(self, sessionId):
		with self._peerCondition:
			if len(self._connectedPeers.keys()) > 0:
				try:
					peer = self._connectedPeers[sessionId]
				except KeyError:
					self._logger.warning('Session [%s] for peer not found' % sessionId)
					peer = None

				if peer:
					del self._connectedPeers[sessionId]

				self._logger.info("There are %d peers left.", len(self._connectedPeers))

				if len(self._connectedPeers) == 0:
					#last session
					self.stopJanus()
					cameraManager().stop_video_stream()

			return True
Exemplo n.º 50
0
	def startPeerSession(self, clientId):
		with self._peerCondition:
			if len(self._connectedPeers.keys()) == 0:
				#first session
				self.startJanus()

			peer = ConnectionPeer(clientId, self)

			sessionId = peer.start()

			if sessionId:
				self._connectedPeers[sessionId] = peer
				return sessionId

			else:
				#something went wrong, no session started. Do we still need Janus up?
				if len(self._connectedPeers.keys()) == 0:
					self.stopJanus()
					cameraManager().stop_video_stream()

				return None
Exemplo n.º 51
0
    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)
Exemplo n.º 52
0
def peer_session():
	data = request.json
	if data and 'sessionId' in data:
		sessionId = data['sessionId']

		if request.method == 'POST':
			#Initialize the peer session
			if cameraManager().startLocalVideoSession(sessionId):
				return jsonify(SUCCESS)

			abort(500)

		elif request.method == 'DELETE':
			#Close peer session
			if cameraManager().closeLocalVideoSession(sessionId):
				return jsonify(SUCCESS)

			else:
				abort(500)

	else:
		abort(400)
Exemplo n.º 53
0
	def closePeerSession(self, sessionId):
		with self._peerCondition:
			if len(self._connectedPeers.keys()) > 0:

				try:
					peer = self._connectedPeers[sessionId]
				except KeyError:
					self._logger.warning('Session [%s] for peer not found' % sessionId)
					peer = None

				if peer:
					peer.streamingPlugin.send_message({'request':'destroy', 'id': sessionId})
					peer.close()
					peer.sendEventToPeer('stopConnection')
					del self._connectedPeers[sessionId]

				self._logger.info("There are %d peers left.", len(self._connectedPeers))

				if len(self._connectedPeers.keys()) == 0:
					#last session
					self.stopJanus()
					cameraManager().stop_video_stream()
Exemplo n.º 54
0
	def restartServer(self):
		if platform == "linux" or platform == "linux2":
			from astroprint.boxrouter import boxrouterManager
			from astroprint.printer.manager import printerManager
			from astroprint.camera import cameraManager

			#let's be nice about shutthing things down
			br = boxrouterManager()

			br.boxrouter_disconnect()
			printerManager().disconnect()
			cameraManager().close_camera()

			actions = self._settings.get(["system", "actions"])
			for a in actions:
				if a['action'] == 'astrobox-restart':
					subprocess.call(a['command'].split(' '))
					return True

			subprocess.call(['restart', 'astrobox'])

		return True
Exemplo n.º 55
0
	def __init__(self, hostname, router):
		self._router = router
		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
		self._error = False
		self._condition = threading.Condition()
		super(AstroprintBoxRouterClient, self).__init__(hostname)
Exemplo n.º 56
0
	def cameraSettings(self,sendResponse):
		s = settings()
		cm = cameraManager()

		sendResponse({
				'encoding': s.get(['camera', 'encoding']),
				'size': s.get(['camera', 'size']),
				'framerate': s.get(['camera', 'framerate']),
				'format': s.get(['camera', 'format']),
				'source': s.get(['camera', 'source']),
				'video_rotation': s.getInt(['camera', 'video-rotation']),
				'structure': cm.settingsStructure()
			}
		)
Exemplo n.º 57
0
	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
		})