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)
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
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
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))
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)
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'}
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
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()
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)
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)
def cleanup(self): global discoveryManager discoveryManager.shutdown() discoveryManager = None boxrouterManager().shutdown() cameraManager().shutdown() from astroprint.network.manager import networkManagerShutdown networkManagerShutdown()
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
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!")
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)
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)
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()
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
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))
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)
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)
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()
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())
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 )
def connected(self, sendResponse): cm = cameraManager() return sendResponse({ "isCameraConnected": cm.isCameraConnected(), "cameraName": cm.cameraName })
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 }
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
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)
def mcPhotoCommand(self): cm = cameraManager() if not cm.is_timelapse_active(): cm.start_timelapse('gcode') cm.addPhotoToActiveTimelapse()
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)
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)
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
def isCameraConnected(): cm = cameraManager() return jsonify({ "isCameraConnected": cm.isCameraConnected(), "cameraName": cm.cameraName })
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']))
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
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']))
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
def stopStreaming(self, data, sendResponse): if cameraManager().closeLocalVideoSession(sessionId): sendResponse({'success': 'no-error'}) return else: sendResponse({'stop_streaming_error': True})
def stopStreaming(self,data,sendResponse): if cameraManager().closeLocalVideoSession(sessionId): sendResponse({'success': 'no-error'}) return else: sendResponse({'stop_streaming_error': True})
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()
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 )
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
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)
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
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
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)
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)
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()
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
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)
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() } )
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 })