예제 #1
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()
            timeElapsed = self.getPrintTime()

            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, Time elapsed: %f"
                % (os.path.split(self._selectedFile['filename'])[1]
                   if self._selectedFile else 'unknown', consumedMaterial,
                   timeElapsed))

            self.executeCancelCommands(disableMotorsAndHeater)

            return {'print_job_id': activePrintJob}

        else:
            return {
                'error': 'no_print_job',
                'message': 'No active print job to cancel'
            }
예제 #2
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)
예제 #3
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()
예제 #4
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)
예제 #5
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)
예제 #6
0
	def getStatus(self):
		printer = printerManager()
		cm = cameraManager()
		ppm = printerProfileManager()
		cloudInstance = astroprintCloud()

		fileName = None

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

		return {
				'id': boxrouterManager().boxId,
				'name': networkManager().getHostname(),
				'orgId' : cloudInstance.orgId,
				'groupId' : cloudInstance.groupId,
				'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
			}
예제 #7
0
	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(),
			'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)
예제 #8
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)
예제 #9
0
def isCameraConnected():
    cm = cameraManager()

    return jsonify({
        "isCameraConnected": cm.isCameraConnected(),
        "cameraName": cm.cameraName
    })
예제 #10
0
    def connected(self, sendResponse):
        cm = cameraManager()

        return sendResponse({
            "isCameraConnected": cm.isCameraConnected(),
            "cameraName": cm.cameraName
        })
예제 #11
0
    def mcPhotoCommand(self):
        cm = cameraManager()

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

        cm.addPhotoToActiveTimelapse()
예제 #12
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']))
예제 #13
0
    def stopStreaming(self, data, sendResponse):

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

            return

        else:
            sendResponse({'stop_streaming_error': True})
예제 #14
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()
예제 #15
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
예제 #16
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)
예제 #17
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
예제 #18
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']),
            'freq': s.get(['camera', 'freq']),
            'format': s.get(['camera', 'format']),
            'source': s.get(['camera', 'source']),
            'video_rotation': s.getInt(['camera', 'video-rotation']),
            'structure': cm.settingsStructure()
        })
예제 #19
0
    def restartServer(self):
        if platformStr == "linux" or platformStr == "linux2":
            actions = self._settings.get(["system", "actions"])
            for a in actions:
                if a['action'] == 'reboot':
                    #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 octoprint_WBCustom.astroprint.printer.manager import printerManager
                    from octoprint_WBCustom.astroprint.camera import cameraManager
                    from octoprint_WBCustom.astroprint.network.manager import networkManagerShutdown

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

                    return True

            return False

        return True
예제 #20
0
    def mcPrintjobDone(self):
        #stop timelapse if there was one
        cameraManager().stop_timelapse(
            True)  #True makes it take one last photo

        timeElapsed = self.getPrintTime()

        #Not sure if this is the best way to get the layer count
        self._setProgressData(1.0, self._selectedFile["filesize"], timeElapsed,
                              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, Time elapsed: %f" %
            (os.path.split(self._selectedFile['filename'])[1] if
             self._selectedFile else 'unknown', consumedMaterial, timeElapsed))
예제 #21
0
    def startPrint(self, printJobId=None):
        """
		 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)

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

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

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

        #start time lapse if is set
        s = settings()
        c = cameraManager()
        freq = s.get(['camera', 'freq'])

        if freq and c.isCameraConnected():
            c.start_timelapse(freq)

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

        self._timeStarted = time.time()
        self._secsPaused = 0
        self._pausedSince = None

        self._currentLayer = 0

        self.printedLayersCounter = 0

        return True
예제 #22
0
	def setTimelapse(self,data,sendResponse):
		freq = data['freq']
		if freq:
			cm = cameraManager()

			if cm.timelapseInfo:
				if not cm.update_timelapse(freq):
					sendResponse('error_updating_timelapse',True)
					return

			else:
				r = cm.start_timelapse(freq)
				if r != 'success':
					sendResponse('error_starting_timelapse',True)
					return
		else:
			sendResponse('erro_no_frequency',True)
			return

		sendResponse({'success': 'no_error'})
예제 #23
0
def update_timelapse():
    freq = request.values.get('freq')

    if freq:
        cm = cameraManager()
        if cm.timelapseInfo:
            if cm.update_timelapse(freq):
                return jsonify(SUCCESS)

        else:
            timelapse = cm.start_timelapse(freq)
            if timelapse == 'success':
                return jsonify(SUCCESS)
            if timelapse == 'no_storage':
                return make_response('No Storage', 402)
            else:
                abort(500)

    else:
        abort(400)

    abort(500)
예제 #24
0
    def togglePausePrint(self):
        """
		 Pause the current printjob.
		"""
        if not self.isConnected():
            return

        wasPaused = self.isPaused()

        if wasPaused:
            if self._pausedSince is not None:
                self._secsPaused += (time.time() - self._pausedSince)
                self._pausedSince = None
        else:
            self._pausedSince = time.time()

        self.setPause(not wasPaused)

        cm = cameraManager()
        if cm.is_timed_timelapse_active():
            if wasPaused:
                cm.resume_timelapse()
            else:
                cm.pause_timelapse()
예제 #25
0
    def hasCameraProperties(self, sendResponse):
        cm = cameraManager()

        return sendResponse({"hasCameraProperties": cm.hasCameraProperties()})
예제 #26
0
	def getTimelapse(self,data,sendResponse):
		sendResponse(cameraManager().timelapseInfo)
예제 #27
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']))

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

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

            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']),
            'freq':
            s.get(['camera', 'freq']),
            'idle_timeout':
            s.get(['camera', 'inactivitySecs']),
            'format':
            s.get(['camera', 'format']),
            'source':
            s.get(['camera', 'source']),
            'video_rotation':
            str(s.getInt(['camera', 'video-rotation'])),
            'structure':
            cm.settingsStructure()
        })
예제 #28
0
 def isResolutionSupported(self, size, sendMessage):
     cm = cameraManager()
     sendMessage({"isResolutionSupported": cm.isResolutionSupported(size)})
예제 #29
0
 def refreshPluggedCamera(self, data, sendMessage):
     cm = cameraManager()
     sendMessage({"camera_plugged": cm.reScan()})
예제 #30
0
    def isCameraSupportedByAstrobox(self, sendResponse):
        cm = cameraManager()

        return sendResponse(
            {"isCameraSupported": cm.settingsStructure() is not None})