def set(self, changes): for k in changes: if k in self.data: if self.data[k] != changes[k]: if k == 'driver': #change printer object from astroprint.printer.manager import printerManager try: printerManager(changes['driver']) except Exception as e: self._logger.error("Error selecting driver %s: %s" % (changes['driver'], e)) #revent to previous driver printerManager(self.data['driver']) raise e elif k == 'printer_model': data = { "printerModel": changes[k] } astroprintCloud().updateBoxrouterData(data) self.data[k] = self._clean(k, changes[k]) # Send astrobox event from octoprint.events import eventManager, Events if k == 'filament': eventManager().fire(Events.FILAMENT_CHANGE, { k: self.data[k]}) eventManager().fire(Events.PRINTERPROFILE_CHANGE, { k: self.data[k]}) else: self._logger.error("trying to set unkonwn printer profile field %s to %s" % (k, str(changes[k])))
def set_private_key(): email = request.values.get('email', None) password = request.values.get('password', None) private_key = request.values.get('private_key', None) if email and password: try: if astroprintCloud().signin(email, password): return jsonify(SUCCESS) except (AstroPrintCloudNoConnectionException, ConnectionError): abort(503, "AstroPrint.com can't be reached") elif email and private_key: try: cloudInfo = astroprintCloud().signinWithKey(email, private_key) if cloudInfo: if cloudInfo is True: return jsonify(SUCCESS) else: return jsonify(cloudInfo) except (AstroPrintCloudNoConnectionException, ConnectionError): abort(503, "AstroPrint.com can't be reached") else: abort(400) abort(401)
def login(): if octoprint.server.userManager is not None and "user" in request.values.keys( ) and "pass" in request.values.keys(): username = request.values["user"] password = request.values["pass"] if "remember" in request.values.keys( ) and request.values["remember"] == "true": remember = True else: remember = False user = octoprint.server.userManager.findUser(username) if user is not None: if user.has_password(): if astroprintCloud().validatePassword(username, password): login_user(user, remember=remember) identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) return jsonify(user.asDict()) else: try: if astroprintCloud().signin(username, password): return jsonify(current_user) except (AstroPrintCloudNoConnectionException, ConnectionError): return make_response( ("AstroPrint.com can't be reached", 503, [])) return make_response(("User unknown or password incorrect", 401, [])) elif "passive" in request.values.keys(): user = current_user if user is not None and not user.is_anonymous: identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) return jsonify(user.asDict()) elif s().getBoolean(["accessControl", "autologinLocal"]) \ and s().get(["accessControl", "autologinAs"]) is not None \ and s().get(["accessControl", "localNetworks"]) is not None: autologinAs = s().get(["accessControl", "autologinAs"]) localNetworks = netaddr.IPSet([]) for ip in s().get(["accessControl", "localNetworks"]): localNetworks.add(ip) try: remoteAddr = util.getRemoteAddress(request) if netaddr.IPAddress(remoteAddr) in localNetworks: user = octoprint.server.userManager.findUser(autologinAs) if user is not None: login_user(user) identity_changed.send( current_app._get_current_object(), identity=Identity(user.get_id())) return jsonify(user.asDict()) except: logger = logging.getLogger(__name__) logger.exception( "Could not autologin user %s for networks %r" % (autologinAs, localNetworks)) return NO_CONTENT
def login(self, data,callback): email = private_key = password = None if 'email' in data: email = data['email'] if 'password' in data: password = data['password'] if 'private_key' in data: private_key = data['private_key'] if email and password: try: if astroprintCloud().signin(email, password, hasSessionContext= False): callback('login_success') except Exception as e: self._logger.error("Error Signing into AstroPrint Cloud: %s" % e) callback('astroprint_unrechable',True) elif email and private_key: try: if astroprintCloud().signinWithKey(email, private_key, hasSessionContext= False): callback('login_success') except Exception as e: self._logger.error('user unsuccessfully logged in',exc_info = True) callback('no_login',True) else: self._logger.error('Invalid data received for login') callback('invalid_data',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 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 set_private_key(): email = request.values.get('email', None) password = request.values.get('password', None) private_key = request.values.get('private_key', None) if email and password: try: if astroprintCloud().signin(email, password): return jsonify(SUCCESS) except (AstroPrintCloudNoConnectionException, ConnectionError): abort(503, "AstroPrint.com can't be reached") elif email and private_key: try: if astroprintCloud().signinWithKey(email, private_key): return jsonify(SUCCESS) except (AstroPrintCloudNoConnectionException, ConnectionError): abort(503, "AstroPrint.com can't be reached") else: abort(400) abort(401)
def set(self, changes): for k in changes: if k in self.data: if self.data[k] != changes[k]: if k == 'driver': #change printer object from astroprint.printer.manager import printerManager try: printerManager(changes['driver']) except Exception as e: self._logger.error( "Error selecting driver %s: %s" % (changes['driver'], e)) #revent to previous driver printerManager(self.data['driver']) raise e elif k == 'printer_model': data = {"printerModel": changes[k]} astroprintCloud().updateBoxrouterData(data) self.data[k] = self._clean(k, changes[k]) # Send astrobox event from octoprint.events import eventManager, Events if k == 'filament': eventManager().fire(Events.FILAMENT_CHANGE, {k: self.data[k]}) eventManager().fire(Events.PRINTERPROFILE_CHANGE, {k: self.data[k]}) else: self._logger.error( "trying to set unkonwn printer profile field %s to %s" % (k, str(changes[k])))
def logout(self, data, callback): try: astroprintCloud().signout(hasSessionContext= False) callback('user successfully logged out') except Exception as e: self._logger.error('user unsuccessfully logged out', exc_info = True) callback('logged_out_unsuccess',True)
def mcPrintjobDone(self): #stop timelapse if there was one self._cameraManager.stop_timelapse() #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 resetFactorySettings(): from astroprint.cloud import astroprintCloud from shutil import copy logger = logging.getLogger(__name__) logger.warning("Executing a Restore Factory Settings operation") #We log out first astroprintCloud().signout() s = settings() emptyFolder(s.get(['folder', 'uploads']) or s.getBaseFolder('uploads')) emptyFolder(s.get(['folder', 'timelapse']) or s.getBaseFolder('timelapse')) emptyFolder( s.get(['folder', 'timelapse_tmp']) or s.getBaseFolder('timelapse_tmp')) emptyFolder(s.get(['folder', 'virtualSd']) or s.getBaseFolder('virtualSd')) networkManager().forgetWifiNetworks() configFolder = s.getConfigFolder() #replace config.yaml with config.factory config_file = s._configfile config_factory = os.path.join(configFolder, "config.factory") if config_file and os.path.exists(config_file): if os.path.exists(config_factory): copy(config_factory, config_file) else: os.unlink(config_file) #replace printer-profile.yaml with printer-profile.factory p_profile_file = os.path.join(configFolder, "printer-profile.yaml") p_profile_factory = os.path.join(configFolder, "printer-profile.factory") if os.path.exists(p_profile_file): if os.path.exists(p_profile_factory): copy(p_profile_factory, p_profile_file) else: os.unlink(p_profile_file) #remove info about users user_file = s.get(["accessControl", "userfile"]) or os.path.join( configFolder, "users.yaml") if user_file and os.path.exists(user_file): os.unlink(user_file) logger.info("Restore completed, rebooting...") #We should reboot the whole device if softwareManager.restartServer(): return jsonify() else: return ("There was an error rebooting.", 500)
def cancelPrint(self, disableMotorsAndHeater=True): """ Cancel the current printjob. """ if self._comm is None: return False self._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 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 _setJobData(self, filename, filesize, sd): if filename is not None: self._selectedFile = { "filename": filename, "filesize": filesize, "sd": sd, "cloudId": None } else: self._selectedFile = None estimatedPrintTime = None date = None filament = None layerCount = None cloudId = None renderedImage = None if filename: # Use a string for mtime because it could be float and the # javascript needs to exact match date = int(os.stat(filename).st_ctime) fileData = self._fileManager.getFileData(filename) if fileData is not None and "gcodeAnalysis" in fileData.keys(): fileDataProps = fileData["gcodeAnalysis"].keys() if "print_time" in fileDataProps: estimatedPrintTime = fileData["gcodeAnalysis"][ "print_time"] if "filament_lenght" in fileDataProps: filament = fileData["gcodeAnalysis"]["filament_length"] if "layer_count" in fileDataProps: layerCount = fileData["gcodeAnalysis"]['layer_count'] cloudId = self._fileManager.getFileCloudId(filename) if cloudId: if self._selectedFile: self._selectedFile['cloudId'] = cloudId printFile = astroprintCloud().getPrintFile(cloudId) if printFile: renderedImage = printFile['images']['square'] self._stateMonitor.setJobData({ "file": { "name": os.path.basename(filename) if filename is not None else None, "origin": FileDestinations.LOCAL, "size": filesize, "date": date, "cloudId": cloudId, "rendered_image": renderedImage }, "estimatedPrintTime": estimatedPrintTime, "layerCount": layerCount, "filament": filament, }) self._layerCount = layerCount self._estimatedPrintTime = estimatedPrintTime
def designs(): slicer = astroprintCloud() forceSyncCloud = request.args.get('forceSyncCloud') cloud_files = json.loads(slicer.print_files(forceSyncCloud)) local_files = list(gcodeManager.getAllFileData()) if cloud_files: for p in cloud_files: p['local_filename'] = None for i in range(len(local_files)): if "cloud_id" in local_files[i] and p['id'] == local_files[i]['cloud_id']: local_file = local_files[i] p['local_filename'] = local_file['name'] p['local_only'] = False del local_files[i] break sorted_cloud_files = sorted(cloud_files, key=lambda e: e['local_filename'] is None) else: sorted_cloud_files = [] if local_files: for p in local_files: p['id'] = uuid.uuid4().hex p['local_filename'] = p['name'] p['local_only'] = True p['info'] = p['gcodeAnalysis'] del p['gcodeAnalysis'] return json.dumps(local_files + sorted_cloud_files)
def login_astroprint(): data = request.get_json() if data: machineId = data.get('machineId') accessCode = data.get('accessCode') else: return make_response('No Credentials given', 400) if machineId and accessCode: ap = astroprintCloud() try: if ap.signin(machineId, accessCode): s = settings() s.set(['setup', 'machineId'], machineId) s.set(['setup', 'accessCode'], accessCode) s.save() _logger.info("setting printer id to: %s", machineId) boxrouterManager() boxrouterManager().boxId = machineId _logger.info("Checking for updates") softwareManager().checkForcedUpdate() return make_response("OK", 200) except (AstroPrintCloudNoConnectionException, ConnectionError) as e: _logger.error(e) return make_response("AstroPrint.com can't be reached", 503) return make_response('Invalid Credentials', 400)
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) self._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 __init__(self): self._astroprint = astroprintCloud() self._eventManager = eventManager() self._printer = None self.timelapseWorker = None self.timelapseInfo = None
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 designs(): forceSyncCloud = request.args.get('forceSyncCloud') cloud_files = json.loads(astroprintCloud().print_files(forceSyncCloud)) local_files = list(printerManager().fileManager.getAllFileData()) if cloud_files: for p in cloud_files: p['local_filename'] = None p['last_print'] = None for i in range(len(local_files)): if "cloud_id" in local_files[i] and p['id'] == local_files[i][ 'cloud_id']: local_file = local_files[i] p['local_filename'] = local_file['name'] p['local_only'] = False if 'prints' in local_file \ and 'last' in local_file['prints'] \ and local_file['prints']['last'] \ and 'date' in local_file['prints']['last']: p['last_print'] = local_file['prints']['last']['date'] del local_files[i] break cloud_files = sorted(cloud_files, key=lambda e: e['local_filename'] is None) else: cloud_files = [] if local_files: for p in local_files: p['id'] = uuid.uuid4().hex p['local_filename'] = p['name'] p['local_only'] = True p['last_print'] = None if 'gcodeAnalysis' in p: p['info'] = p['gcodeAnalysis'] del p['gcodeAnalysis'] else: p['info'] = None if 'prints' in p \ and 'last' in p['prints'] \ and p['prints']['last'] \ and 'date' in p['prints']['last']: p['last_print'] = p['prints']['last']['date'] del p['prints'] else: local_files = [] files = sorted(local_files + cloud_files, key=lambda e: e['last_print'], reverse=True) return json.dumps(files)
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 upload_data(): filePath = request.args.get('file', None) if filePath: url, params, redirect_url = astroprintCloud().get_upload_info(filePath) return jsonify(url=url, params=params, redirect=redirect_url) abort(400)
def _setJobData(self, filename, filesize, sd): if filename is not None: self._selectedFile = { "filename": filename, "filesize": filesize, "sd": sd, "cloudId": None } else: self._selectedFile = None estimatedPrintTime = None date = None filament = None layerCount = None cloudId = None if filename: # Use a string for mtime because it could be float and the # javascript needs to exact match date = int(os.stat(filename).st_ctime) fileData = self._fileManager.getFileData(filename) if fileData is not None and "gcodeAnalysis" in fileData.keys(): fileDataProps = fileData["gcodeAnalysis"].keys() if "print_time" in fileDataProps: estimatedPrintTime = fileData["gcodeAnalysis"]["print_time"] if "filament_lenght" in fileDataProps: filament = fileData["gcodeAnalysis"]["filament_length"] if "layer_count" in fileDataProps: layerCount = fileData["gcodeAnalysis"]['layer_count'] cloudId = self._fileManager.getFileCloudId(filename) renderedIimage = None if cloudId: if self._selectedFile: self._selectedFile['cloudId'] = cloudId printFile = astroprintCloud().getPrintFile(cloudId) if printFile: renderedIimage = printFile['images']['square'] self._stateMonitor.setJobData({ "file": { "name": os.path.basename(filename) if filename is not None else None, "origin": FileDestinations.LOCAL, "size": filesize, "date": date, "cloudId": cloudId, "rendered_image": renderedIimage }, "estimatedPrintTime": estimatedPrintTime, "layerCount": layerCount, "filament": filament, }) self._layerCount = layerCount self._estimatedPrintTime = estimatedPrintTime
def get_login_key(): try: key = astroprintCloud().get_login_key() if key: return jsonify(key) except (AstroPrintCloudNoConnectionException, ConnectionError): abort(503, "AstroPrint.com can't be reached") abort(401)
def designs(): forceSyncCloud = request.args.get('forceSyncCloud') cloud_files = json.loads(astroprintCloud().print_files(forceSyncCloud)) local_files = list(printerManager().fileManager.getAllFileData()) if cloud_files: for p in cloud_files: p['local_filename'] = None p['last_print'] = None for i in range(len(local_files)): if "cloud_id" in local_files[i] and p['id'] == local_files[i]['cloud_id']: local_file = local_files[i] p['local_filename'] = local_file['name'] p['local_only'] = False if 'prints' in local_file \ and 'last' in local_file['prints'] \ and local_file['prints']['last'] \ and 'date' in local_file['prints']['last']: p['last_print'] = local_file['prints']['last']['date'] del local_files[i] break cloud_files = sorted(cloud_files, key=lambda e: e['local_filename'] is None) else: cloud_files = [] if local_files: for p in local_files: p['id'] = uuid.uuid4().hex p['local_filename'] = p['name'] p['local_only'] = True p['last_print'] = None if 'gcodeAnalysis' in p: p['info'] = p['gcodeAnalysis'] del p['gcodeAnalysis'] else: p['info'] = None if 'prints' in p \ and 'last' in p['prints'] \ and p['prints']['last'] \ and 'date' in p['prints']['last']: p['last_print'] = p['prints']['last']['date'] del p['prints'] else: local_files = [] files = sorted(local_files + cloud_files, key=lambda e: e['last_print'], reverse=True) return json.dumps(files)
def design_download(print_file_id): if current_user is None or not current_user.is_authenticated() or not current_user.publicKey: abort(401) em = eventManager() def progressCb(progress): em.fire( Events.CLOUD_DOWNLOAD, { "type": "progress", "id": print_file_id, "progress": progress } ) def successCb(destFile, fileInfo): if printerManager().fileManager.saveCloudPrintFile(destFile, fileInfo, FileDestinations.LOCAL): em.fire( Events.CLOUD_DOWNLOAD, { "type": "success", "id": print_file_id, "filename": printerManager().fileManager._getBasicFilename(destFile), "info": fileInfo["info"] } ) else: errorCb(destFile, "Couldn't save the file") def errorCb(destFile, error): if error == 'cancelled': em.fire( Events.CLOUD_DOWNLOAD, { "type": "cancelled", "id": print_file_id } ) else: em.fire( Events.CLOUD_DOWNLOAD, { "type": "error", "id": print_file_id, "reason": error } ) if destFile and os.path.exists(destFile): os.remove(destFile) if astroprintCloud().download_print_file(print_file_id, progressCb, successCb, errorCb): return jsonify(SUCCESS) return abort(400)
def _checkAuth(self): if current_user and current_user.is_authenticated and not current_user.is_anonymous: privateKey = current_user.privateKey publicKey = current_user.publicKey if privateKey and publicKey: from astroprint.cloud import astroprintCloud return astroprintCloud().hmacAuth return None
def login_astroprint(): email = request.values.get('email', None) password = request.values.get('password', None) if email and password: ap = astroprintCloud() if ap.signin(email, password): return make_response("OK", 200) return make_response('Invalid Credentials', 400)
def manufacturers(self, data, sendMessage): from astroprint.cloud import astroprintCloud import json try: manufacturers = json.loads(astroprintCloud().manufacturers()) sendMessage(manufacturers) except Exception as e: self._logger.error('There was an error getting manufacturers', exc_info=True) sendMessage("error_getting_manufacturers", True)
def set_private_key(): email = request.values.get('email', None) password = request.values.get('password', None) if email and password: if astroprintCloud().signin(email, password): return jsonify(SUCCESS) else: abort(400) abort(401)
def resetFactorySettings(): from astroprint.cloud import astroprintCloud logger = logging.getLogger(__name__) logger.warning("Executing a Restore Factory Settings operation") #We log out first astroprintCloud().signout() s = settings() #empty all folders def emptyFolder(folder): if folder and os.path.exists(folder): for f in os.listdir(folder): p = os.path.join(folder, f) try: if os.path.isfile(p): os.unlink(p) except Exception, e: pass
def start_timelapse(self, freq): if freq == '0': return False if not self._printer: from octoprint.server import printer self._printer = printer if self.timelapseWorker: self.stop_timelapse() #check that there's a print ongoing otherwise don't start selectedFile = self._printer._selectedFile if not selectedFile: return False if not self.isCameraAvailable(): if not self.open_camera(): return False timelapseId = astroprintCloud().startPrintCapture( os.path.split(selectedFile["filename"])[1]) if timelapseId: self.timelapseInfo = { 'id': timelapseId, 'freq': freq, 'paused': False, 'last_photo': None } if freq == 'layer': # send first pic and subscribe to layer change events self.addPhotoToTimelapse(timelapseId) self._eventManager.subscribe(Events.LAYER_CHANGE, self._onLayerChange) else: try: freq = float(freq) except ValueError: return False self.timelapseInfo['freq'] = freq self.timelapseWorker = TimelapseWorker(self, timelapseId, freq) self.timelapseWorker.start() self._eventManager.fire(Events.CAPTURE_INFO_CHANGED, self.timelapseInfo) return True return False
def manufacturers(self, data, sendMessage): try: manufacturers = astroprintCloud().manufacturers() if 'error' in manufacturers: sendMessage("error_getting_manufacturers", True) else: sendMessage(manufacturers) except Exception: self._logger.error('There was an error getting manufacturers', exc_info=True) sendMessage("error_getting_manufacturers", True)
def design_download(print_file_id): if current_user is None or not current_user.is_authenticated or not current_user.publicKey: abort(401) em = eventManager() def progressCb(progress): em.fire( Events.CLOUD_DOWNLOAD, { "type": "progress", "id": print_file_id, "progress": progress } ) def successCb(destFile, fileInfo): if fileInfo is True: #This means the files was already on the device em.fire( Events.CLOUD_DOWNLOAD, { "type": "success", "id": print_file_id } ) def errorCb(destFile, error): if error == 'cancelled': em.fire( Events.CLOUD_DOWNLOAD, { "type": "cancelled", "id": print_file_id } ) else: em.fire( Events.CLOUD_DOWNLOAD, { "type": "error", "id": print_file_id, "reason": error } ) if destFile and os.path.exists(destFile): os.remove(destFile) if astroprintCloud().download_print_file(print_file_id, progressCb, successCb, errorCb) is True: return jsonify(SUCCESS) return abort(400)
def getStatus(): printer = printerManager() cm = cameraManager() softwareManager = swManager() ppm = printerProfileManager() cloudInstance = astroprintCloud() fileName = None if printer.isPrinting(): currentJob = printer.getCurrentJob() fileName = currentJob["file"]["name"] return Response( json.dumps({ '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': softwareManager.capabilities() + cm.capabilities, 'ready_to_print': printer.isReadyToPrint() }), mimetype='application/json', headers={'Access-Control-Allow-Origin': '*'} if settings().getBoolean(['api', 'allowCrossOrigin']) else None)
def getFileInfo(self, filename): estimatedPrintTime = None date = None filament = None layerCount = None cloudId = None renderedImage = None printFileName = None if filename: # Use a string for mtime because it could be float and the # javascript needs to exact match date = int(os.stat(filename).st_ctime) fileData = self._fileManager.getFileData(filename) if fileData is not None: gcodeAnalysis = fileData.get('gcodeAnalysis') if gcodeAnalysis: estimatedPrintTime = gcodeAnalysis.get('print_time') filament = gcodeAnalysis.get('filament_length') layerCount = gcodeAnalysis.get('layer_count') renderedImage = fileData.get('image') cloudId = self._fileManager.getFileCloudId(filename) if cloudId: if self._selectedFile: self._selectedFile['cloudId'] = cloudId printFile = astroprintCloud().getPrintFile(cloudId) if printFile: renderedImage = printFile['images']['square'] if fileData is not None and "printFileName" in fileData.keys(): printFileName = fileData["printFileName"] return { "file": { "name": os.path.basename(filename) if filename is not None else None, "printFileName": printFileName, "origin": FileDestinations.LOCAL, "date": date, "cloudId": cloudId, "rendered_image": renderedImage }, "estimatedPrintTime": estimatedPrintTime, "layerCount": layerCount, "filament": filament, }
def set_private_key(): boxid = request.values.get('email') access_key = request.values.get('password') if boxid and access_key: try: if astroprintCloud().signin(boxid, access_key): return jsonify(SUCCESS) except (AstroPrintCloudNoConnectionException, ConnectionError): abort(503, "AstroPrint.com can't be reached") else: abort(400) abort(401)
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 ) )
def getAccessKeys(self, data, sendResponse): publicKey = email = accessKey = None if 'email' in data: email = data['email'] if 'accessKey' in data: accessKey = data['accessKey'] userLogged = settings().get(["cloudSlicer", "loggedUser"]) #### # - nobody logged: None # - any log: email if email and accessKey:#somebody is logged in the remote client if userLogged:#Somebody logged in Astrobox if userLogged == email:#I am the user logged online = networkManager().isOnline() if online: publicKey = astroprintCloud().get_public_key(email, accessKey) if not publicKey: self._logger.error('error getting public key', exc_info = True) sendResponse('error_getting_public_key',True) return else: user = userManager.findUser(email) if user.get_private_key() != accessKey: self._logger.error('incorrect logged user', exc_info = True) sendResponse('incorrect_logged_user',True) return else:#I am NOT the logged user self._logger.error('incorrect logged user', exc_info = True) sendResponse('incorrect_logged_user',True) return else:#nodody is logged in the remote client if userLogged: self._logger.error('any user logged', exc_info = True) sendResponse('no_user_logged',True) return sendResponse({ 'api_key': UI_API_KEY, 'ws_token': create_ws_token(publicKey) })
def start_timelapse(self, freq): if freq == '0': return False if not self._printer: from octoprint.server import printer self._printer = printer if self.timelapseWorker: self.stop_timelapse() #check that there's a print ongoing otherwise don't start selectedFile = self._printer._selectedFile if not selectedFile: return False if not self.isCameraAvailable(): if not self.open_camera(): return False timelapseId = astroprintCloud().startPrintCapture(os.path.split(selectedFile["filename"])[1]) if timelapseId: self.timelapseInfo = { 'id': timelapseId, 'freq': freq, 'paused': False, 'last_photo': None } if freq == 'layer': # send first pic and subscribe to layer change events self.addPhotoToTimelapse(timelapseId) self._eventManager.subscribe(Events.LAYER_CHANGE, self._onLayerChange) else: try: freq = float(freq) except ValueError: return False self.timelapseInfo['freq'] = freq self.timelapseWorker = TimelapseWorker(self, timelapseId, freq) self.timelapseWorker.start() self._eventManager.fire(Events.CAPTURE_INFO_CHANGED, self.timelapseInfo) return True return False
def login_astroprint(): email = request.values.get('email', None) password = request.values.get('password', None) if email and password: ap = astroprintCloud() try: if ap.signin(email, password): return make_response("OK", 200) except AstroPrintCloudNoConnectionException: return make_response("Your device is not connected to AstroPrint.com", 503) return make_response('Invalid Credentials', 400)
def login_astroprint(): email = request.values.get('email', None) password = request.values.get('password', None) if email and password: ap = astroprintCloud() try: if ap.signin(email, password): return make_response("OK", 200) except (AstroPrintCloudNoConnectionException, ConnectionError): return make_response("AstroPrint.com can't be reached", 503) return make_response('Invalid Credentials', 400)
def set_private_key(): email = request.values.get('email', None) password = request.values.get('password', None) if email and password: try: if astroprintCloud().signin(email, password): return jsonify(SUCCESS) except AstroPrintCloudNoConnectionException: abort(503, "Your device is not connected to AstroPrint.com") else: abort(400) abort(401)
def design_download(print_file_id): if not bool(settings().get(["cloudSlicer", "publicKey"])): abort(401) slicer = astroprintCloud() em = eventManager() def progressCb(progress): em.fire( Events.CLOUD_DOWNLOAD, { "type": "progress", "id": print_file_id, "progress": progress } ) def successCb(destFile, fileInfo): if gcodeManager.saveCloudGcode(destFile, fileInfo, FileDestinations.LOCAL): em.fire( Events.CLOUD_DOWNLOAD, { "type": "success", "id": print_file_id, "filename": gcodeManager._getBasicFilename(destFile), "info": fileInfo["info"] } ) else: errorCb(destFile, "Couldn't save the file") def errorCb(destFile, error): em.fire( Events.CLOUD_DOWNLOAD, { "type": "error", "id": print_file_id, "reason": error } ) if destFile and os.path.exists(destFile): os.remove(destFile) if slicer.download_print_file(print_file_id, progressCb, successCb, errorCb): return jsonify(SUCCESS) return abort(400)
def upload_data(): filePath = request.args.get('file', None) if filePath: uploadInfo = astroprintCloud().get_upload_info(filePath) if uploadInfo: if 'error' in uploadInfo: if uploadInfo['error'] == 'no_user': abort(401) else: abort(500) else: return json.dumps(uploadInfo) else: abort(500) abort(400)
def addPhotoToTimelapse(self, timelapseId): #Build text printerData = printerManager().getCurrentData() text = "%d%% - Layer %s%s" % ( printerData['progress']['completion'], str(printerData['progress']['currentLayer']) if printerData['progress']['currentLayer'] else '--', "/%s" % str(printerData['job']['layerCount'] if printerData['job']['layerCount'] else '') ) picBuf = self.get_pic(text=text) if picBuf: picData = astroprintCloud().uploadImageFile(timelapseId, picBuf) if picData: self.timelapseInfo['last_photo'] = picData['url'] self._eventManager.fire(Events.CAPTURE_INFO_CHANGED, self.timelapseInfo) return True return False
def update_cancel_reason(print_job_id): if not "application/json" in request.headers["Content-Type"]: return abort(400) data = request.json #get reason reason = {} if 'reason' in data: reason['reason_id'] = data['reason'] if 'other_text' in data: reason['other_text'] = data['other_text'] if reason: if not astroprintCloud().updateCancelReason(print_job_id, reason): return abort(500) else: return jsonify(SUCCESS) else: return abort(400)
def validate(self, data, callback): email = private_key = password = None if 'email' in data: email = data['email'] if 'password' in data: password = data['password'] if email and password: try: if astroprintCloud().validatePassword(email, password): callback('validate_success') else: callback('invalid_data',True) except Exception as e: self._logger.error("Error validating passwrod with AstroPrint Cloud: %s" % e) callback('astroprint_unrechable',True) else: self._logger.error('Invalid data received for login') callback('invalid_data',True)