def propertiesChanged(self, properties): if "ActiveConnections" in properties: if len(properties['ActiveConnections']) == 0: self._setOnline(False) return elif not self._monitorActivatingListener: for c in properties['ActiveConnections']: if c.State == NetworkManager.NM_ACTIVE_CONNECTION_STATE_ACTIVATING: if self._monitorActivatingListener: self._monitorActivatingListener.remove() eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'connecting'}) self._activatingConnection = c.Connection self._monitorActivatingListener = c.Devices[0].connect_to_signal('StateChanged', self.monitorActivatingConnection) settings = c.Connection.GetSettings() if settings: logger.info('Activating Connection %s' % settings['connection']['id']) return if "State" in properties and properties["State"] == NetworkManager.NM_STATE_CONNECTED_GLOBAL: self._setOnline(True)
def propertiesChanged(self, nm, properties, interface, signal): if "ActiveConnections" in properties: #if len(properties['ActiveConnections']) == 0: # self._setOnline(False) # return #elif not self._monitorActivatingListener: if not self._monitorActivatingListener: for c in properties['ActiveConnections']: try: if hasattr(c, 'State') and c.State == NetworkManager.NM_ACTIVE_CONNECTION_STATE_ACTIVATING: if self._monitorActivatingListener: NetworkManager.SignalDispatcher.remove_signal_receiver(self._monitorActivatingListener) eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'connecting'}) self._activatingConnection = c.Connection self._justActivatedConnection = False self._monitorActivatingListener = c.Devices[0].OnStateChanged(self.monitorActivatingConnection) settings = c.Connection.GetSettings() if settings: logger.info('Activating Connection %s' % settings['connection']['id']) return except NetworkManager.ObjectVanished: pass if "State" in properties and properties["State"] == NetworkManager.NM_STATE_CONNECTED_GLOBAL: self._setOnline(True)
def _setOnline(self, value): with self._setOnlineCondition: if value == self._online: return if value: d = self.getActiveConnectionDevice() if d: self._activeDevice = d if self._devicePropertiesListener: self._devicePropertiesListener.remove() if self._activeDevice: self._currentIpv4Address = self._activeDevice.Ip4Address self._devicePropertiesListener = d.Dhcp4Config.connect_to_signal('PropertiesChanged', self.activeDeviceConfigChanged) logger.info('Active Connection is now %s (%s)' % (d.IpInterface, self._currentIpv4Address)) self._online = True eventManager.fire(Events.NETWORK_STATUS, 'online') else: self._online = False self._currentIpv4Address = None eventManager.fire(Events.NETWORK_STATUS, 'offline') if self._manager.isHotspotActive() is False: #isHotspotActive returns None if not possible logger.info('AstroBox is offline. Starting hotspot...') result = self._manager.startHotspot() if result is True: logger.info('Hostspot started') else: logger.error('Failed to start hostspot: %s' % result)
def propertiesChanged(self, properties): if "ActiveConnections" in properties: if len(properties['ActiveConnections']) == 0: self._setOnline(False) return elif not self._monitorActivatingListener: for c in properties['ActiveConnections']: if c.State == NetworkManager.NM_ACTIVE_CONNECTION_STATE_ACTIVATING: if self._monitorActivatingListener: self._monitorActivatingListener.remove() eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'connecting'}) self._activatingConnection = c.Connection self._monitorActivatingListener = c.Devices[ 0].connect_to_signal( 'StateChanged', self.monitorActivatingConnection) settings = c.Connection.GetSettings() if settings: logger.info('Activating Connection %s' % settings['connection']['id']) return if "State" in properties and properties[ "State"] == NetworkManager.NM_STATE_CONNECTED_GLOBAL: self._setOnline(True)
def _setOnline(self, value): with self._setOnlineCondition: if value == self._online: return if value: d = self.getActiveConnectionDevice() if d: self._activeDevice = d if self._devicePropertiesListener: self._devicePropertiesListener.remove() if self._activeDevice: self._currentIpv4Address = self._activeDevice.Ip4Address self._devicePropertiesListener = d.Dhcp4Config.connect_to_signal('PropertiesChanged', self.activeDeviceConfigChanged) logger.info('Active Connection changed to %s (%s)' % (d.IpInterface, self._currentIpv4Address)) self._online = True eventManager.fire(Events.NETWORK_STATUS, 'online') else: self._online = False self._currentIpv4Address = None eventManager.fire(Events.NETWORK_STATUS, 'offline') if self._manager.isHotspotActive() is False: #isHotspotActive returns None if not possible logger.info('AstroBox is offline. Starting hotspot...') result = self._manager.startHotspot() if result is True: logger.info('Hostspot started') else: logger.error('Failed to start hostspot: %s' % result)
def activeDeviceConfigChanged(self, properties): if "Options" in properties and "ip_address" in properties[ "Options"] and properties["Options"][ "ip_address"] != self._currentIpv4Address: self._currentIpv4Address = properties["Options"]["ip_address"] self._setOnline(True) eventManager.fire(Events.NETWORK_IP_CHANGED, self._currentIpv4Address)
def action(): eventManager.fire( Events.INTERNET_CONNECTING_STATUS, {'status': 'connecting'}) time.sleep(2) eventManager.fire( Events.INTERNET_CONNECTING_STATUS, { 'status': 'failed', 'reason': "no_connection" })
def deleteStoredWifiNetwork(self, networkId): for i in range(0, len(self._storedWiFiNetworks)): n = self._storedWiFiNetworks[i] if n['id'] == networkId: if n['active']: self._goOffline() eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'disconnected'}) del self._storedWiFiNetworks[i] self.logger.info("Network [%s] with id [%s] deleted." % (n['name'], n['id'])) return n['id']
def action(): eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'connecting'}) time.sleep(1) eventManager.fire(Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'type': 'wifi', 'signal': network['signal'], 'name': network['name'], 'ip': '127.0.0.1:5000' } }) self._goOnline()
def monitorActivatingConnection(self, nm, new_state, old_state, reason, interface, signal): try: logger.info('Activating State Change %s -> %s' % (NetworkManager.const('device_state', old_state),NetworkManager.const('device_state', new_state))) if self._activatingConnection: if new_state == NetworkManager.NM_DEVICE_STATE_ACTIVATED: if self._monitorActivatingListener: NetworkManager.SignalDispatcher.remove_signal_receiver(self._monitorActivatingListener) self._monitorActivatingListener = None d = self.getActiveConnectionDevice(self._activatingConnection) if isinstance(d, NetworkManager.Wired): eventManager.fire(Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'type': 'ethernet', 'ip': self._manager._getIpAddress(d) } }) else: ap = d.ActiveAccessPoint eventManager.fire(Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'type': 'wifi', 'signal': ap.Strength, 'name': ap.Ssid, 'ip': self._manager._getIpAddress(d) } }) self._activatingConnection = None self._justActivatedConnection = True self._setOnline(True) elif new_state in [NetworkManager.NM_DEVICE_STATE_FAILED, NetworkManager.NM_DEVICE_STATE_UNKNOWN]: logger.warn('Connection reached state %s, reason: %s' % (NetworkManager.const('device_state', new_state), NetworkManager.const('device_state_reason', reason) ) ) #It has reached and end state. self._activatingConnection = None if self._monitorActivatingListener: NetworkManager.SignalDispatcher.remove_signal_receiver(self._monitorActivatingListener) self._monitorActivatingListener = None eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'failed', 'reason': NetworkManager.const('device_state_reason', reason)}) elif new_state == NetworkManager.NM_DEVICE_STATE_DISCONNECTED: if self._monitorActivatingListener: NetworkManager.SignalDispatcher.remove_signal_receiver(self._monitorActivatingListener) self._monitorActivatingListener = None eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'disconnected'}) self._activatingConnection = None #check the global connection status before setting it to false #if NetworkManager.NetworkManager.state() != NetworkManager.NM_STATE_CONNECTED_GLOBAL: # self._setOnline(False) except Exception as e: logger.error(e, exc_info= True)
def monitorActivatingConnection(self, nm, new_state, old_state, reason, interface, signal): try: logger.info('Activating State Change %s -> %s' % (NetworkManager.const('device_state', old_state),NetworkManager.const('device_state', new_state))) if self._activatingConnection: if new_state == NetworkManager.NM_DEVICE_STATE_ACTIVATED: if self._monitorActivatingListener: NetworkManager.SignalDispatcher.remove_signal_receiver(self._monitorActivatingListener) self._monitorActivatingListener = None d = self.getActiveConnectionDevice(self._activatingConnection) if isinstance(d, NetworkManager.Wired): eventManager.fire(Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'type': 'ethernet', 'ip': self._manager._getIpAddress(d) } }) else: ap = d.ActiveAccessPoint eventManager.fire(Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'type': 'wifi', 'signal': ap.Strength, 'name': ap.Ssid, 'ip': self._manager._getIpAddress(d) } }) self._activatingConnection = None self._justActivatedConnection = True self._setOnline(True) elif new_state in [NetworkManager.NM_DEVICE_STATE_FAILED, NetworkManager.NM_DEVICE_STATE_UNKNOWN]: logger.warn('Connection reached state %s, reason: %s' % (NetworkManager.const('device_state', new_state), NetworkManager.const('device_state_reason', reason) ) ) #It has reached and end state. self._activatingConnection = None if self._monitorActivatingListener: NetworkManager.SignalDispatcher.remove_signal_receiver(self._monitorActivatingListener) self._monitorActivatingListener = None eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'failed', 'reason': NetworkManager.const('device_state_reason', reason)}) elif new_state == NetworkManager.NM_DEVICE_STATE_DISCONNECTED: if self._monitorActivatingListener: NetworkManager.SignalDispatcher.remove_signal_receiver(self._monitorActivatingListener) self._monitorActivatingListener = None eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'disconnected'}) self._activatingConnection = None #check the global connection status before setting it to false #if NetworkManager.NetworkManager.state() != NetworkManager.NM_STATE_CONNECTED_GLOBAL: # self._setOnline(False) except Exception, e: logger.error(e, exc_info= True)
def _setOnline(self, value): with self._setOnlineCondition: if value == self._online: return if value: try: d = self.getActiveConnectionDevice() if d: self._activeDevice = d if self._devicePropertiesListener: NetworkManager.SignalDispatcher.remove_signal_receiver( self._devicePropertiesListener) self._devicePropertiesListener = None # in case something fails on reconnection so it's not wrongly thinking we're still listening self._currentIpv4Address = self._manager._getIpAddress( d) try: self._devicePropertiesListener = d.Dhcp4Config.OnPropertiesChanged( self.activeDeviceConfigChanged) except AttributeError: logger.warn('DHCP4 Config not avaialable') logger.info('Active Connection is now %s (%s)' % (d.IpInterface, self._currentIpv4Address)) self._online = True eventManager.fire(Events.NETWORK_STATUS, 'online') except Exception as e: logger.error(e, exc_info=1) else: self._online = False self._currentIpv4Address = None eventManager.fire(Events.NETWORK_STATUS, 'offline') if self._manager.isHotspotActive( ) is False: #isHotspotActive returns None if not possible logger.info('AstroBox is offline. Starting hotspot...') result = self._manager.startHotspot() if result is True: logger.info('Hostspot started') else: logger.error('Failed to start hostspot: %s' % result)
def _setOnline(self, value): with self._setOnlineCondition: if value == self._online: return if value: try: d = self.getActiveConnectionDevice() if d: self._activeDevice = d if self._devicePropertiesListener: NetworkManager.SignalDispatcher.remove_signal_receiver(self._devicePropertiesListener) self._devicePropertiesListener = None # in case something fails on reconnection so it's not wrongly thinking we're still listening self._currentIpv4Address = self._manager._getIpAddress(d) try: self._devicePropertiesListener = d.Dhcp4Config.OnPropertiesChanged(self.activeDeviceConfigChanged) except AttributeError: logger.warn('DHCP4 Config not avaialable') logger.info('Active Connection is now %s (%s)' % (d.IpInterface, self._currentIpv4Address)) self._online = True eventManager.fire(Events.NETWORK_STATUS, 'online') except Exception as e: logger.error(e, exc_info=1) else: self._online = False self._currentIpv4Address = None eventManager.fire(Events.NETWORK_STATUS, 'offline') if self._manager.isHotspotActive() is False: #isHotspotActive returns None if not possible logger.info('AstroBox is offline. Starting hotspot...') result = self._manager.startHotspot() if result is True: logger.info('Hostspot started') else: logger.error('Failed to start hostspot: %s' % result)
def monitorActivatingConnection(self, new_state, old_state, reason): logger.info('Activating State Change %s -> %s' % (NetworkManager.const('device_state', old_state),NetworkManager.const('device_state', new_state))) if self._activatingConnection: if new_state == NetworkManager.NM_DEVICE_STATE_ACTIVATED: if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None d = self.getActiveConnectionDevice() if d.DeviceType == NetworkManager.NM_DEVICE_TYPE_ETHERNET: eventManager.fire(Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'type': 'ethernet', 'ip': d.Ip4Address } }) else: ap = d.SpecificDevice().ActiveAccessPoint eventManager.fire(Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'type': 'wifi', 'signal': ap.Strength, 'name': ap.Ssid, 'ip': d.Ip4Address } }) self._activatingConnection = None self._setOnline(True) elif new_state in [NetworkManager.NM_DEVICE_STATE_FAILED, NetworkManager.NM_DEVICE_STATE_UNKNOWN]: logger.warn('Connection reached state %s, reason: %s' % (NetworkManager.const('device_state', new_state), NetworkManager.const('device_state_reason', reason) ) ) eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'failed', 'reason': NetworkManager.const('device_state_reason', reason)}) # we should probably remove the connection self._activatingConnection.Delete() elif new_state == NetworkManager.NM_DEVICE_STATE_DISCONNECTED: if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'disconnected'}) self._activatingConnection = None #check the global connection status before setting it to false if NetworkManager.NetworkManager.state() != NetworkManager.NM_STATE_CONNECTED_GLOBAL: self._setOnline(False)
def printersetCommand2(): valid_commands = { "save": [], } command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response if command == "save": if printer.piflag == 1: upload_dir = "/root/.octoprint/uploads/" # tempfile.mkdtemp() else: upload_dir = "/home/maxchen/.octoprint/uploads/" # tempfile.mkdtemp() f = open(upload_dir+data["filename"], 'w') # Header information f.write(data["content"]) f.close() #added_file = fileManager.add_file(FileDestinations.LOCAL, data["filename"], data["content"], allow_overwrite=True) eventManager.fire(Events.UPLOAD, {"file": data["filename"], "target": "local"}) eventManager.fire(Events.UPDATED_FILES, dict(type="printables")) return NO_CONTENT
def monitorActivatingConnection(self, new_state, old_state, reason): logger.info('Activating State Change %s -> %s' % (NetworkManager.const('device_state', old_state), NetworkManager.const('device_state', new_state))) if self._activatingConnection: if new_state == NetworkManager.NM_DEVICE_STATE_ACTIVATED: if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None d = self.getActiveConnectionDevice() ap = d.SpecificDevice().ActiveAccessPoint eventManager.fire( Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'signal': ord(ap.Strength), 'name': ap.Ssid, 'ip': d.Ip4Address } }) self._activatingConnection = None self._setOnline(True) elif new_state in [ NetworkManager.NM_DEVICE_STATE_FAILED, NetworkManager.NM_DEVICE_STATE_UNKNOWN ]: logger.warn( 'Connection reached state %s, reason: %s' % (NetworkManager.const('device_state', new_state), NetworkManager.const('device_state_reason', reason))) eventManager.fire( Events.INTERNET_CONNECTING_STATUS, { 'status': 'failed', 'reason': NetworkManager.const('device_state_reason', reason) }) # we should probably remove the connection self._activatingConnection.Delete() elif new_state == NetworkManager.NM_DEVICE_STATE_DISCONNECTED: if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'disconnected'}) self._activatingConnection = None self._setOnline(False)
def uploadGcodeFile(target): if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: return make_response("Unknown target: %s" % target, 404) if not "file" in request.files.keys(): return make_response("No file included", 400) if target == FileDestinations.SDCARD and not settings().getBoolean( ["feature", "sdSupport"]): return make_response("SD card support is disabled", 404) file = request.files["file"] sd = target == FileDestinations.SDCARD selectAfterUpload = "select" in request.values.keys( ) and request.values["select"] in valid_boolean_trues printAfterSelect = "print" in request.values.keys( ) and request.values["print"] in valid_boolean_trues if sd: # validate that all preconditions for SD upload are met before attempting it if not (printer.isOperational() and not (printer.isPrinting() or printer.isPaused())): return make_response( "Can not upload to SD card, printer is either not operational or already busy", 409) if not printer.isSdReady(): return make_response( "Can not upload to SD card, not yet initialized", 409) # determine current job currentFilename = None currentSd = None currentJob = printer.getCurrentJob() if currentJob is not None and "filename" in currentJob.keys( ) and "sd" in currentJob.keys(): currentFilename = currentJob["filename"] currentSd = currentJob["sd"] # determine future filename of file to be uploaded, abort if it can't be uploaded futureFilename = gcodeManager.getFutureFilename(file) if futureFilename is None or ( not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)): return make_response( "Can not upload file %s, wrong format?" % file.filename, 415) # prohibit overwriting currently selected file while it's being printed if futureFilename == currentFilename and sd == currentSd and printer.isPrinting( ) or printer.isPaused(): return make_response( "Trying to overwrite file that is currently being printed: %s" % currentFilename, 409) filename = None def fileProcessingFinished(filename, absFilename, destination): """ Callback for when the file processing (upload, optional slicing, addition to analysis queue) has finished. Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. """ if destination == FileDestinations.SDCARD: return filename, printer.addSdFile(filename, absFilename, selectAndOrPrint) else: selectAndOrPrint(absFilename, destination) return filename def selectAndOrPrint(nameToSelect, destination): """ Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only the case after they have finished streaming to the printer, which is why this callback is also used for the corresponding call to addSdFile. Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the exact file is already selected, such reloading it. """ sd = destination == FileDestinations.SDCARD if selectAfterUpload or printAfterSelect or ( currentFilename == filename and currentSd == sd): printer.selectFile(nameToSelect, sd, printAfterSelect) destination = FileDestinations.SDCARD if sd else FileDestinations.LOCAL filename, done = gcodeManager.addFile(file, destination, fileProcessingFinished) if filename is None: return make_response("Could not upload the file %s" % file.filename, 500) sdFilename = None if isinstance(filename, tuple): filename, sdFilename = filename eventManager.fire(Events.UPLOAD, {"file": filename, "target": target}) files = {} if done: files.update({ FileDestinations.LOCAL: { "name": filename, "origin": FileDestinations.LOCAL, "refs": { "resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True), "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename } } }) if sd and sdFilename: files.update({ FileDestinations.SDCARD: { "name": sdFilename, "origin": FileDestinations.SDCARD, "refs": { "resource": url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True) } } }) return make_response(jsonify(files=files, done=done), 201)
def uploadGcodeFile(target): input_name = "file" input_upload_name = (input_name + "." + settings().get(["server", "uploads", "nameSuffix"])) input_upload_path = (input_name + "." + settings().get(["server", "uploads", "pathSuffix"])) if input_upload_name in request.values and input_upload_path in request.values: if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: abort(404) upload = octoprint.filemanager.util.DiskFileWrapper( request.values[input_upload_name], request.values[input_upload_path]) # Store any additional user data the caller may have passed. userdata = None if "userdata" in request.values: import json try: userdata = json.loads(request.values["userdata"]) except Exception: abort(400, description="userdata contains invalid JSON") if target == FileDestinations.SDCARD and not settings().getBoolean( ["feature", "sdSupport"]): abort(404) sd = target == FileDestinations.SDCARD selectAfterUpload = ("select" in request.values and request.values["select"] in valid_boolean_trues and Permissions.FILES_SELECT.can()) printAfterSelect = ("print" in request.values and request.values["print"] in valid_boolean_trues and Permissions.PRINT.can()) if sd: # validate that all preconditions for SD upload are met before attempting it if not (printer.is_operational() and not (printer.is_printing() or printer.is_paused())): abort( 409, description= "Can not upload to SD card, printer is either not operational or already busy", ) if not printer.is_sd_ready(): abort( 409, description="Can not upload to SD card, not yet initialized" ) # determine future filename of file to be uploaded, abort if it can't be uploaded try: # FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet canonPath, canonFilename = fileManager.canonicalize( FileDestinations.LOCAL, upload.filename) if request.values.get("path"): canonPath = request.values.get("path") if request.values.get("filename"): canonFilename = request.values.get("filename") futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, canonPath) futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, canonFilename) except Exception: canonFilename = None futurePath = None futureFilename = None if futureFilename is None: abort(415, description="Can not upload file, wrong format?") # prohibit overwriting currently selected file while it's being printed futureFullPath = fileManager.join_path(FileDestinations.LOCAL, futurePath, futureFilename) futureFullPathInStorage = fileManager.path_in_storage( FileDestinations.LOCAL, futureFullPath) if not printer.can_modify_file(futureFullPathInStorage, sd): abort( 409, description= "Trying to overwrite file that is currently being printed", ) if (fileManager.file_exists(FileDestinations.LOCAL, futureFullPathInStorage) and request.values.get("noOverwrite") in valid_boolean_trues): abort(409, description="File already exists and noOverwrite was set") reselect = printer.is_current_file(futureFullPathInStorage, sd) user = current_user.get_name() def fileProcessingFinished(filename, absFilename, destination): """ Callback for when the file processing (upload, optional slicing, addition to analysis queue) has finished. Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. """ if (destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type( filename, "machinecode")): return filename, printer.add_sd_file( filename, absFilename, on_success=selectAndOrPrint, tags={"source:api", "api:files.sd"}, ) else: selectAndOrPrint(filename, absFilename, destination) return filename def selectAndOrPrint(filename, absFilename, destination): """ Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only the case after they have finished streaming to the printer, which is why this callback is also used for the corresponding call to addSdFile. Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the exact file is already selected, such reloading it. """ if octoprint.filemanager.valid_file_type( added_file, "gcode") and (selectAfterUpload or printAfterSelect or reselect): printer.select_file( absFilename, destination == FileDestinations.SDCARD, printAfterSelect, user, ) try: added_file = fileManager.add_file( FileDestinations.LOCAL, futureFullPathInStorage, upload, allow_overwrite=True, display=canonFilename, ) except octoprint.filemanager.storage.StorageError as e: if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE: abort(400, description="Could not upload file, invalid type") else: abort(500, description="Could not upload file") if octoprint.filemanager.valid_file_type(added_file, "stl"): filename = added_file done = True else: filename = fileProcessingFinished( added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target, ) done = not sd if userdata is not None: # upload included userdata, add this now to the metadata fileManager.set_additional_metadata(FileDestinations.LOCAL, added_file, "userdata", userdata) sdFilename = None if isinstance(filename, tuple): filename, sdFilename = filename payload = { "name": futureFilename, "path": filename, "target": target, "select": selectAfterUpload, "print": printAfterSelect, } if userdata is not None: payload["userdata"] = userdata eventManager.fire(Events.UPLOAD, payload) files = {} location = url_for( ".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True, ) files.update({ FileDestinations.LOCAL: { "name": futureFilename, "path": filename, "origin": FileDestinations.LOCAL, "refs": { "resource": location, "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + urlquote(filename), }, } }) if sd and sdFilename: location = url_for( ".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True, ) files.update({ FileDestinations.SDCARD: { "name": sdFilename, "path": sdFilename, "origin": FileDestinations.SDCARD, "refs": { "resource": location }, } }) r = make_response(jsonify(files=files, done=done), 201) r.headers["Location"] = location return r elif "foldername" in request.values: foldername = request.values["foldername"] if target not in [FileDestinations.LOCAL]: abort(400, description="target is invalid") canonPath, canonName = fileManager.canonicalize(target, foldername) futurePath = fileManager.sanitize_path(target, canonPath) futureName = fileManager.sanitize_name(target, canonName) if not futureName or not futurePath: abort(400, description="folder name is empty") if "path" in request.values and request.values["path"]: futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, request.values["path"]) futureFullPath = fileManager.join_path(target, futurePath, futureName) if octoprint.filemanager.valid_file_type(futureName): abort(409, description="Can't create folder, please try another name") try: added_folder = fileManager.add_folder(target, futureFullPath, display=canonName) except octoprint.filemanager.storage.StorageError as e: if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY: abort(400, description="Could not create folder, invalid directory") else: abort(500, description="Could not create folder") location = url_for( ".readGcodeFile", target=FileDestinations.LOCAL, filename=added_folder, _external=True, ) folder = { "name": futureName, "path": added_folder, "origin": target, "refs": { "resource": location }, } r = make_response(jsonify(folder=folder, done=True), 201) r.headers["Location"] = location return r else: abort(400, description="No file to upload and no folder to create")
def uploadFastBotSDCARD(target): print("lkj uploadFastBotSDCARD target:%s" % str(target)) #target = FileDestinations.FastbotSDCARD print("lkj post request.values:%s" % str(request.values)) print("lkj post request.files:%s" % str(request.files)) input_name = "file" input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"]) input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"]) if input_upload_name in request.values and input_upload_path in request.values: import shutil upload = util.Object() upload.filename = request.values[input_upload_name] upload.save = lambda new_path: shutil.move(request.values[input_upload_path], new_path) elif input_name in request.files: upload = request.files[input_name] else: return make_response("No file included", 400) print("lkj post upload:%s" % str(upload)) if target == FileDestinations.FastbotSDCARD and not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD card support is disabled", 404) print("lkj uploadGcodeFile 2") sd = target == FileDestinations.FastbotSDCARD selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues print("lkj uploadGcodeFile 3") # determine current job currentFilename = None currentOrigin = None currentJob = printer.getCurrentJob() if currentJob is not None and "file" in currentJob.keys(): currentJobFile = currentJob["file"] if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys(): currentFilename = currentJobFile["name"] currentOrigin = currentJobFile["origin"] # determine future filename of file to be uploaded, abort if it can't be uploaded try: futureFilename = fileManager.sanitize_name(FileDestinations.FastbotSDCARD, upload.filename) except: futureFilename = None if futureFilename is None or not (slicingManager.slicing_enabled or octoprint.filemanager.valid_file_type(futureFilename, type="gcode")): return make_response("Can not upload file %s, wrong format?" % upload.filename, 415) print("lkj uploadGcodeFile 4") # prohibit overwriting currently selected file while it's being printed if futureFilename == currentFilename and target == currentOrigin and printer.isPrinting() or printer.isPaused(): return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409) print("lkj uploadGcodeFile 5") def fileProcessingFinished(filename, absFilename, destination): """ Callback for when the file processing (upload, optional slicing, addition to analysis queue) has finished. Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. """ selectAndOrPrint(filename, absFilename, destination) return filename def selectAndOrPrint(filename, absFilename, destination): """ Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only the case after they have finished streaming to the printer, which is why this callback is also used for the corresponding call to addSdFile. Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the exact file is already selected, such reloading it. """ if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)): printer.selectFile(absFilename, destination == FileDestinations.FastbotSDCARD, printAfterSelect) print("lkj uploadGcodeFile 6") added_file = fileManager.add_file(FileDestinations.FastbotSDCARD, upload.filename, upload, allow_overwrite=True) if added_file is None: return make_response("Could not upload the file %s" % upload.filename, 500) print("lkj uploadGcodeFile 6.0, added_file:%s" % str(added_file)) if octoprint.filemanager.valid_file_type(added_file, "stl"): filename = added_file done = True print("lkj uploadGcodeFile 6.1") else: filename = fileProcessingFinished(added_file, fileManager.get_absolute_path(FileDestinations.FastbotSDCARD, added_file), target) done = True sdFilename = filename eventManager.fire(Events.UPLOAD, {"file": filename, "target": target}) files = {} ''' location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True) files.update({ FileDestinations.LOCAL: { "name": filename, "origin": FileDestinations.LOCAL, "refs": { "resource": location, "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename } } }) ''' print("lkj uploadGcodeFile 7 sdFilename:%s" % sdFilename) if sd and sdFilename: print("lkj uploadGcodeFile 7.1") location = url_for(".readGcodeFile", target=FileDestinations.FastbotSDCARD, filename=sdFilename, _external=True) files.update({ FileDestinations.FastbotSDCARD: { "name": sdFilename, "origin": FileDestinations.FastbotSDCARD, "refs": { "resource": location } } }) print("lkj uploadFastBotSDCARD 8") r = make_response(jsonify(files=files, done=done), 201) r.headers["Location"] = location return r
def uploadGcodeFile(target): if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: return make_response("Unknown target: %s" % target, 404) if not "file" in request.files.keys(): return make_response("No file included", 400) if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD card support is disabled", 404) file = request.files["file"] sd = target == FileDestinations.SDCARD selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues if sd: # validate that all preconditions for SD upload are met before attempting it if not (printer.isOperational() and not (printer.isPrinting() or printer.isPaused())): return make_response("Can not upload to SD card, printer is either not operational or already busy", 409) if not printer.isSdReady(): return make_response("Can not upload to SD card, not yet initialized", 409) # determine current job currentFilename = None currentSd = None currentJob = printer.getCurrentJob() if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys(): currentFilename = currentJob["filename"] currentSd = currentJob["sd"] # determine future filename of file to be uploaded, abort if it can't be uploaded futureFilename = gcodeManager.getFutureFilename(file) if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)): return make_response("Can not upload file %s, wrong format?" % file.filename, 415) # prohibit overwriting currently selected file while it's being printed if futureFilename == currentFilename and sd == currentSd and printer.isPrinting() or printer.isPaused(): return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409) filename = None def fileProcessingFinished(filename, absFilename, destination): """ Callback for when the file processing (upload, optional slicing, addition to analysis queue) has finished. Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. """ if destination == FileDestinations.SDCARD: return filename, printer.addSdFile(filename, absFilename, selectAndOrPrint) else: selectAndOrPrint(absFilename, destination) return filename def selectAndOrPrint(nameToSelect, destination): """ Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only the case after they have finished streaming to the printer, which is why this callback is also used for the corresponding call to addSdFile. Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the exact file is already selected, such reloading it. """ sd = destination == FileDestinations.SDCARD if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentSd == sd): printer.selectFile(nameToSelect, sd, printAfterSelect) destination = FileDestinations.SDCARD if sd else FileDestinations.LOCAL filename, done = gcodeManager.addFile(file, destination, fileProcessingFinished) if filename is None: return make_response("Could not upload the file %s" % file.filename, 500) sdFilename = None if isinstance(filename, tuple): filename, sdFilename = filename eventManager.fire(Events.UPLOAD, {"file": filename, "target": target}) files = {} if done: files.update({ FileDestinations.LOCAL: { "name": filename, "origin": FileDestinations.LOCAL, "refs": { "resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True), "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename } } }) if sd and sdFilename: files.update({ FileDestinations.SDCARD: { "name": sdFilename, "origin": FileDestinations.SDCARD, "refs": { "resource": url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True) } } }) return make_response(jsonify(files=files, done=done), 201)
def uploadGcodeFile(target): if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: return make_response("Unknown target: %s" % target, 404) input_name = "file" input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"]) input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"]) if input_upload_name in request.values and input_upload_path in request.values: upload = octoprint.filemanager.util.DiskFileWrapper(request.values[input_upload_name], request.values[input_upload_path]) else: return make_response("No file included", 400) # Store any additional user data the caller may have passed. userdata = None if "userdata" in request.values: import json try: userdata = json.loads(request.values["userdata"]) except: return make_response("userdata contains invalid JSON", 400) if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD card support is disabled", 404) sd = target == FileDestinations.SDCARD selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues if sd: # validate that all preconditions for SD upload are met before attempting it if not (printer.is_operational() and not (printer.is_printing() or printer.is_paused())): return make_response("Can not upload to SD card, printer is either not operational or already busy", 409) if not printer.is_sd_ready(): return make_response("Can not upload to SD card, not yet initialized", 409) # determine current job currentFilename = None currentOrigin = None currentJob = printer.get_current_job() if currentJob is not None and "file" in currentJob.keys(): currentJobFile = currentJob["file"] if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys(): currentFilename = currentJobFile["name"] currentOrigin = currentJobFile["origin"] # determine future filename of file to be uploaded, abort if it can't be uploaded try: futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, upload.filename) except: futureFilename = None if futureFilename is None: return make_response("Can not upload file %s, wrong format?" % upload.filename, 415) # prohibit overwriting currently selected file while it's being printed if futureFilename == currentFilename and target == currentOrigin and printer.is_printing() or printer.is_paused(): return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409) def fileProcessingFinished(filename, absFilename, destination): """ Callback for when the file processing (upload, optional slicing, addition to analysis queue) has finished. Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. """ if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "gcode"): return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint) else: selectAndOrPrint(filename, absFilename, destination) return filename def selectAndOrPrint(filename, absFilename, destination): """ Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only the case after they have finished streaming to the printer, which is why this callback is also used for the corresponding call to addSdFile. Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the exact file is already selected, such reloading it. """ if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)): printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect) added_file = fileManager.add_file(FileDestinations.LOCAL, upload.filename, upload, allow_overwrite=True) if added_file is None: return make_response("Could not upload the file %s" % upload.filename, 500) if octoprint.filemanager.valid_file_type(added_file, "stl"): filename = added_file done = True else: filename = fileProcessingFinished(added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target) done = not sd if userdata is not None: # upload included userdata, add this now to the metadata fileManager.set_additional_metadata(FileDestinations.LOCAL, added_file, "userdata", userdata) sdFilename = None if isinstance(filename, tuple): filename, sdFilename = filename eventManager.fire(Events.UPLOAD, {"file": filename, "target": target}) files = {} location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True) files.update({ FileDestinations.LOCAL: { "name": filename, "origin": FileDestinations.LOCAL, "refs": { "resource": location, "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename } } }) if sd and sdFilename: location = url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True) files.update({ FileDestinations.SDCARD: { "name": sdFilename, "origin": FileDestinations.SDCARD, "refs": { "resource": location } } }) r = make_response(jsonify(files=files, done=done), 201) r.headers["Location"] = location return r
def uploadGcodeFile(target): if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: return make_response("Invalid target: %s" % target, 400) if "gcode_file" in request.files.keys(): file = request.files["gcode_file"] sd = target == FileDestinations.SDCARD selectAfterUpload = "select" in request.values.keys( ) and request.values["select"] in valid_boolean_trues printAfterSelect = "print" in request.values.keys( ) and request.values["print"] in valid_boolean_trues # determine current job currentFilename = None currentSd = None currentJob = printer.getCurrentJob() if currentJob is not None and "filename" in currentJob.keys( ) and "sd" in currentJob.keys(): currentFilename = currentJob["filename"] currentSd = currentJob["sd"] # determine future filename of file to be uploaded, abort if it can't be uploaded futureFilename = gcodeManager.getFutureFilename(file) if futureFilename is None or ( not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)): return make_response( "Can not upload file %s, wrong format?" % file.filename, 400) # prohibit overwriting currently selected file while it's being printed if futureFilename == currentFilename and sd == currentSd and printer.isPrinting( ) or printer.isPaused(): return make_response( "Trying to overwrite file that is currently being printed: %s" % currentFilename, 403) filename = None def fileProcessingFinished(filename, absFilename, destination): """ Callback for when the file processing (upload, optional slicing, addition to analysis queue) has finished. Depending on the file's destination triggers either streaming to SD card or directly calls selectOrPrint. """ sd = destination == FileDestinations.SDCARD if sd: printer.addSdFile(filename, absFilename, selectAndOrPrint) else: selectAndOrPrint(absFilename, destination) def selectAndOrPrint(nameToSelect, destination): """ Callback for when the file is ready to be selected and optionally printed. For SD file uploads this only the case after they have finished streaming to the printer, which is why this callback is also used for the corresponding call to addSdFile. Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the exact file is already selected, such reloading it. """ sd = destination == FileDestinations.SDCARD if selectAfterUpload or printAfterSelect or ( currentFilename == filename and currentSd == sd): printer.selectFile(nameToSelect, sd, printAfterSelect) destination = FileDestinations.SDCARD if sd else FileDestinations.LOCAL filename, done = gcodeManager.addFile(file, destination, fileProcessingFinished) if filename is None: return make_response( "Could not upload the file %s" % file.filename, 500) eventManager.fire("Upload", filename) return jsonify(files=gcodeManager.getAllFileData(), filename=filename, done=done) else: return make_response("No gcode_file included", 400)
def monitorActivatingConnection(self, new_state, old_state, reason): logger.info('Activating State Change %s -> %s' % (NetworkManager.const('device_state', old_state), NetworkManager.const('device_state', new_state))) if self._activatingConnection: if new_state == NetworkManager.NM_DEVICE_STATE_ACTIVATED: if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None d = self.getActiveConnectionDevice() if d.DeviceType == NetworkManager.NM_DEVICE_TYPE_ETHERNET: eventManager.fire( Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'type': 'ethernet', 'ip': d.Ip4Address } }) else: ap = d.SpecificDevice().ActiveAccessPoint eventManager.fire( Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'type': 'wifi', 'signal': ap.Strength, 'name': ap.Ssid, 'ip': d.Ip4Address } }) self._activatingConnection = None self._justActivatedConnection = True self._setOnline(True) elif new_state in [ NetworkManager.NM_DEVICE_STATE_FAILED, NetworkManager.NM_DEVICE_STATE_UNKNOWN ]: logger.warn( 'Connection reached state %s, reason: %s' % (NetworkManager.const('device_state', new_state), NetworkManager.const('device_state_reason', reason))) #It has reached and end state. self._activatingConnection = None if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None eventManager.fire( Events.INTERNET_CONNECTING_STATUS, { 'status': 'failed', 'reason': NetworkManager.const('device_state_reason', reason) }) elif new_state == NetworkManager.NM_DEVICE_STATE_DISCONNECTED: if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'disconnected'}) self._activatingConnection = None
def action(): eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'connecting'}) time.sleep(2) eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'failed', 'reason': "no_connection"})
def _goOnline(self): self._online = True eventManager.fire(Events.NETWORK_STATUS, 'online')
def uploadFastBotSDCARD(target): print("lkj uploadFastBotSDCARD target:%s" % str(target)) #target = FileDestinations.FastbotSDCARD print("lkj post request.values:%s" % str(request.values)) print("lkj post request.files:%s" % str(request.files)) input_name = "file" input_upload_name = input_name + "." + settings().get( ["server", "uploads", "nameSuffix"]) input_upload_path = input_name + "." + settings().get( ["server", "uploads", "pathSuffix"]) if input_upload_name in request.values and input_upload_path in request.values: import shutil upload = util.Object() upload.filename = request.values[input_upload_name] upload.save = lambda new_path: shutil.move( request.values[input_upload_path], new_path) elif input_name in request.files: upload = request.files[input_name] else: return make_response("No file included", 400) print("lkj post upload:%s" % str(upload)) if target == FileDestinations.FastbotSDCARD and not settings().getBoolean( ["feature", "sdSupport"]): return make_response("SD card support is disabled", 404) print("lkj uploadGcodeFile 2") sd = target == FileDestinations.FastbotSDCARD selectAfterUpload = "select" in request.values.keys( ) and request.values["select"] in valid_boolean_trues printAfterSelect = "print" in request.values.keys( ) and request.values["print"] in valid_boolean_trues print("lkj uploadGcodeFile 3") # determine current job currentFilename = None currentOrigin = None currentJob = printer.getCurrentJob() if currentJob is not None and "file" in currentJob.keys(): currentJobFile = currentJob["file"] if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys( ): currentFilename = currentJobFile["name"] currentOrigin = currentJobFile["origin"] # determine future filename of file to be uploaded, abort if it can't be uploaded try: futureFilename = fileManager.sanitize_name( FileDestinations.FastbotSDCARD, upload.filename) except: futureFilename = None if futureFilename is None or not (slicingManager.slicing_enabled or octoprint.filemanager.valid_file_type( futureFilename, type="gcode")): return make_response( "Can not upload file %s, wrong format?" % upload.filename, 415) print("lkj uploadGcodeFile 4") # prohibit overwriting currently selected file while it's being printed if futureFilename == currentFilename and target == currentOrigin and printer.isPrinting( ) or printer.isPaused(): return make_response( "Trying to overwrite file that is currently being printed: %s" % currentFilename, 409) print("lkj uploadGcodeFile 5") def fileProcessingFinished(filename, absFilename, destination): """ Callback for when the file processing (upload, optional slicing, addition to analysis queue) has finished. Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. """ selectAndOrPrint(filename, absFilename, destination) return filename def selectAndOrPrint(filename, absFilename, destination): """ Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only the case after they have finished streaming to the printer, which is why this callback is also used for the corresponding call to addSdFile. Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the exact file is already selected, such reloading it. """ if octoprint.filemanager.valid_file_type(added_file, "gcode") and ( selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)): printer.selectFile(absFilename, destination == FileDestinations.FastbotSDCARD, printAfterSelect) print("lkj uploadGcodeFile 6") added_file = fileManager.add_file(FileDestinations.FastbotSDCARD, upload.filename, upload, allow_overwrite=True) if added_file is None: return make_response("Could not upload the file %s" % upload.filename, 500) print("lkj uploadGcodeFile 6.0, added_file:%s" % str(added_file)) if octoprint.filemanager.valid_file_type(added_file, "stl"): filename = added_file done = True print("lkj uploadGcodeFile 6.1") else: filename = fileProcessingFinished( added_file, fileManager.get_absolute_path(FileDestinations.FastbotSDCARD, added_file), target) done = True sdFilename = filename eventManager.fire(Events.UPLOAD, {"file": filename, "target": target}) files = {} ''' location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True) files.update({ FileDestinations.LOCAL: { "name": filename, "origin": FileDestinations.LOCAL, "refs": { "resource": location, "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename } } }) ''' print("lkj uploadGcodeFile 7 sdFilename:%s" % sdFilename) if sd and sdFilename: print("lkj uploadGcodeFile 7.1") location = url_for(".readGcodeFile", target=FileDestinations.FastbotSDCARD, filename=sdFilename, _external=True) files.update({ FileDestinations.FastbotSDCARD: { "name": sdFilename, "origin": FileDestinations.FastbotSDCARD, "refs": { "resource": location } } }) print("lkj uploadFastBotSDCARD 8") r = make_response(jsonify(files=files, done=done), 201) r.headers["Location"] = location return r
def uploadGcodeFile(target): if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: return make_response("Invalid target: %s" % target, 400) if "gcode_file" in request.files.keys(): file = request.files["gcode_file"] sd = target == FileDestinations.SDCARD selectAfterUpload = "select" in request.values.keys( ) and request.values["select"] in valid_boolean_trues printAfterSelect = "print" in request.values.keys( ) and request.values["print"] in valid_boolean_trues # determine current job currentFilename = None currentSd = None currentJob = printer.getCurrentJob() if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys(): currentFilename = currentJob["filename"] currentSd = currentJob["sd"] # determine future filename of file to be uploaded, abort if it can't # be uploaded futureFilename = gcodeManager.getFutureFilename(file) if futureFilename is None or (not settings.get("cura", "enabled") and not gcodefiles.isGcodeFileName(futureFilename)): return make_response("Can not upload file %s, wrong format?" % file.filename, 400) # prohibit overwriting currently selected file while it's being printed if futureFilename == currentFilename and sd == currentSd and printer.isPrinting() or printer.isPaused(): return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 403) filename = None def fileProcessingFinished(filename, absFilename, destination): """ Callback for when the file processing (upload, optional slicing, addition to analysis queue) has finished. Depending on the file's destination triggers either streaming to SD card or directly calls selectOrPrint. """ sd = destination == FileDestinations.SDCARD if sd: printer.addSdFile(filename, absFilename, selectAndOrPrint) else: selectAndOrPrint(absFilename, destination) def selectAndOrPrint(nameToSelect, destination): """ Callback for when the file is ready to be selected and optionally printed. For SD file uploads this only the case after they have finished streaming to the printer, which is why this callback is also used for the corresponding call to addSdFile. Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the exact file is already selected, such reloading it. """ sd = destination == FileDestinations.SDCARD if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentSd == sd): printer.selectFile(nameToSelect, sd, printAfterSelect) destination = FileDestinations.SDCARD if sd else FileDestinations.LOCAL filename, done = gcodeManager.addFile( file, destination, fileProcessingFinished) if filename is None: return make_response("Could not upload the file %s" % file.filename, 500) eventManager.fire("Upload", filename) return jsonify(files=gcodeManager.getAllFileData(), filename=filename, done=done) else: return make_response("No gcode_file included", 400)
def _goOffline(self): self._online = False eventManager.fire(Events.NETWORK_STATUS, 'offline')
def uploadGcodeFile(target): if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: return make_response("Unknown target: %s" % target, 404) input_name = "file" input_upload_name = input_name + "." + settings().get( ["server", "uploads", "nameSuffix"]) input_upload_path = input_name + "." + settings().get( ["server", "uploads", "pathSuffix"]) if input_upload_name in request.values and input_upload_path in request.values: upload = octoprint.filemanager.util.DiskFileWrapper( request.values[input_upload_name], request.values[input_upload_path]) else: return make_response("No file included", 400) # Store any additional user data the caller may have passed. userdata = None if "userdata" in request.values: import json try: userdata = json.loads(request.values["userdata"]) except: return make_response("userdata contains invalid JSON", 400) if target == FileDestinations.SDCARD and not settings().getBoolean( ["feature", "sdSupport"]): return make_response("SD card support is disabled", 404) sd = target == FileDestinations.SDCARD selectAfterUpload = "select" in request.values.keys( ) and request.values["select"] in valid_boolean_trues printAfterSelect = "print" in request.values.keys( ) and request.values["print"] in valid_boolean_trues if sd: # validate that all preconditions for SD upload are met before attempting it if not (printer.is_operational() and not (printer.is_printing() or printer.is_paused())): return make_response( "Can not upload to SD card, printer is either not operational or already busy", 409) if not printer.is_sd_ready(): return make_response( "Can not upload to SD card, not yet initialized", 409) # determine current job currentFilename = None currentOrigin = None currentJob = printer.get_current_job() if currentJob is not None and "file" in currentJob.keys(): currentJobFile = currentJob["file"] if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys( ): currentFilename = currentJobFile["name"] currentOrigin = currentJobFile["origin"] # determine future filename of file to be uploaded, abort if it can't be uploaded try: futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, upload.filename) except: futureFilename = None if futureFilename is None: return make_response( "Can not upload file %s, wrong format?" % upload.filename, 415) # prohibit overwriting currently selected file while it's being printed if futureFilename == currentFilename and target == currentOrigin and printer.is_printing( ) or printer.is_paused(): return make_response( "Trying to overwrite file that is currently being printed: %s" % currentFilename, 409) def fileProcessingFinished(filename, absFilename, destination): """ Callback for when the file processing (upload, optional slicing, addition to analysis queue) has finished. Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. """ if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type( filename, "gcode"): return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint) else: selectAndOrPrint(filename, absFilename, destination) return filename def selectAndOrPrint(filename, absFilename, destination): """ Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only the case after they have finished streaming to the printer, which is why this callback is also used for the corresponding call to addSdFile. Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the exact file is already selected, such reloading it. """ if octoprint.filemanager.valid_file_type(added_file, "gcode") and ( selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)): printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect) added_file = fileManager.add_file(FileDestinations.LOCAL, upload.filename, upload, allow_overwrite=True) if added_file is None: return make_response("Could not upload the file %s" % upload.filename, 500) if octoprint.filemanager.valid_file_type(added_file, "stl"): filename = added_file done = True else: filename = fileProcessingFinished( added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target) done = True if userdata is not None: # upload included userdata, add this now to the metadata fileManager.set_additional_metadata(FileDestinations.LOCAL, added_file, "userdata", userdata) sdFilename = None if isinstance(filename, tuple): filename, sdFilename = filename eventManager.fire(Events.UPLOAD, {"file": filename, "target": target}) files = {} location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True) files.update({ FileDestinations.LOCAL: { "name": filename, "origin": FileDestinations.LOCAL, "refs": { "resource": location, "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename } } }) if sd and sdFilename: location = url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True) files.update({ FileDestinations.SDCARD: { "name": sdFilename, "origin": FileDestinations.SDCARD, "refs": { "resource": location } } }) r = make_response(jsonify(files=files, done=done), 201) r.headers["Location"] = location return r
def uploadGcodeFile(target): input_name = "file" input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"]) input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"]) if input_upload_name in request.values and input_upload_path in request.values: if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: return make_response("Unknown target: %s" % target, 404) upload = octoprint.filemanager.util.DiskFileWrapper(request.values[input_upload_name], request.values[input_upload_path]) # Store any additional user data the caller may have passed. userdata = None if "userdata" in request.values: import json try: userdata = json.loads(request.values["userdata"]) except: return make_response("userdata contains invalid JSON", 400) if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD card support is disabled", 404) sd = target == FileDestinations.SDCARD selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues if sd: # validate that all preconditions for SD upload are met before attempting it if not (printer.is_operational() and not (printer.is_printing() or printer.is_paused())): return make_response("Can not upload to SD card, printer is either not operational or already busy", 409) if not printer.is_sd_ready(): return make_response("Can not upload to SD card, not yet initialized", 409) # determine future filename of file to be uploaded, abort if it can't be uploaded try: # FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet canonPath, canonFilename = fileManager.canonicalize(FileDestinations.LOCAL, upload.filename) futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, canonPath) futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, canonFilename) except: canonFilename = None futurePath = None futureFilename = None if futureFilename is None: return make_response("Can not upload file %s, wrong format?" % upload.filename, 415) if "path" in request.values and request.values["path"]: # we currently only support uploads to sdcard via local, so first target is local instead of "target" futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, request.values["path"]) # prohibit overwriting currently selected file while it's being printed futureFullPath = fileManager.join_path(FileDestinations.LOCAL, futurePath, futureFilename) futureFullPathInStorage = fileManager.path_in_storage(FileDestinations.LOCAL, futureFullPath) if not printer.can_modify_file(futureFullPathInStorage, sd): return make_response("Trying to overwrite file that is currently being printed: %s" % futureFullPath, 409) reselect = printer.is_current_file(futureFullPathInStorage, sd) user = current_user.get_name() def fileProcessingFinished(filename, absFilename, destination): """ Callback for when the file processing (upload, optional slicing, addition to analysis queue) has finished. Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. """ if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "machinecode"): return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint, tags={"source:api", "api:files.sd"}) else: selectAndOrPrint(filename, absFilename, destination) return filename def selectAndOrPrint(filename, absFilename, destination): """ Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only the case after they have finished streaming to the printer, which is why this callback is also used for the corresponding call to addSdFile. Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the exact file is already selected, such reloading it. """ if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or reselect): printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect, user) try: added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPathInStorage, upload, allow_overwrite=True, display=canonFilename) except octoprint.filemanager.storage.StorageError as e: if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE: return make_response("Could not upload the file \"{}\", invalid type".format(upload.filename), 400) else: return make_response("Could not upload the file \"{}\"".format(upload.filename), 500) if octoprint.filemanager.valid_file_type(added_file, "stl"): filename = added_file done = True else: filename = fileProcessingFinished(added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target) done = not sd if userdata is not None: # upload included userdata, add this now to the metadata fileManager.set_additional_metadata(FileDestinations.LOCAL, added_file, "userdata", userdata) sdFilename = None if isinstance(filename, tuple): filename, sdFilename = filename eventManager.fire(Events.UPLOAD, {"name": futureFilename, "path": filename, "target": target, # TODO deprecated, remove in 1.4.0 "file": filename}) files = {} location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True) files.update({ FileDestinations.LOCAL: { "name": futureFilename, "path": filename, "origin": FileDestinations.LOCAL, "refs": { "resource": location, "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename } } }) if sd and sdFilename: location = url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True) files.update({ FileDestinations.SDCARD: { "name": sdFilename, "path": sdFilename, "origin": FileDestinations.SDCARD, "refs": { "resource": location } } }) r = make_response(jsonify(files=files, done=done), 201) r.headers["Location"] = location return r elif "foldername" in request.values: foldername = request.values["foldername"] if not target in [FileDestinations.LOCAL]: return make_response("Unknown target: %s" % target, 400) canonPath, canonName = fileManager.canonicalize(target, foldername) futurePath = fileManager.sanitize_path(target, canonPath) futureName = fileManager.sanitize_name(target, canonName) if not futureName or not futurePath: return make_response("Can't create a folder with an empty name", 400) if "path" in request.values and request.values["path"]: futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, request.values["path"]) futureFullPath = fileManager.join_path(target, futurePath, futureName) if octoprint.filemanager.valid_file_type(futureName): return make_response("Can't create a folder named %s, please try another name" % futureName, 409) try: added_folder = fileManager.add_folder(target, futureFullPath, display=canonName) except octoprint.filemanager.storage.StorageError as e: if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY: return make_response("Could not create folder {}, invalid directory".format(futureName)) else: return make_response("Could not create folder {}".format(futureName)) location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=added_folder, _external=True) folder = dict(name=futureName, path=added_folder, origin=target, refs=dict(resource=location)) r = make_response(jsonify(folder=folder, done=True), 201) r.headers["Location"] = location return r else: return make_response("No file to upload and no folder to create", 400)
def uploadGcodeFile(target): input_name = "file" input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"]) input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"]) if input_upload_name in request.values and input_upload_path in request.values: if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: return make_response("Unknown target: %s" % target, 404) upload = octoprint.filemanager.util.DiskFileWrapper(request.values[input_upload_name], request.values[input_upload_path]) # Store any additional user data the caller may have passed. userdata = None if "userdata" in request.values: import json try: userdata = json.loads(request.values["userdata"]) except: return make_response("userdata contains invalid JSON", 400) if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD card support is disabled", 404) sd = target == FileDestinations.SDCARD selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues if sd: # validate that all preconditions for SD upload are met before attempting it if not (printer.is_operational() and not (printer.is_printing() or printer.is_paused())): return make_response("Can not upload to SD card, printer is either not operational or already busy", 409) if not printer.is_sd_ready(): return make_response("Can not upload to SD card, not yet initialized", 409) # determine future filename of file to be uploaded, abort if it can't be uploaded try: # FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet futurePath, futureFilename = fileManager.sanitize(FileDestinations.LOCAL, upload.filename) except: futurePath = None futureFilename = None if futureFilename is None: return make_response("Can not upload file %s, wrong format?" % upload.filename, 415) if "path" in request.values and request.values["path"]: # we currently only support uploads to sdcard via local, so first target is local instead of "target" futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, request.values["path"]) # prohibit overwriting currently selected file while it's being printed futureFullPath = fileManager.join_path(FileDestinations.LOCAL, futurePath, futureFilename) futureFullPathInStorage = fileManager.path_in_storage(FileDestinations.LOCAL, futureFullPath) if not printer.can_modify_file(futureFullPathInStorage, sd): return make_response("Trying to overwrite file that is currently being printed: %s" % futureFullPath, 409) reselect = printer.is_current_file(futureFullPathInStorage, sd) def fileProcessingFinished(filename, absFilename, destination): """ Callback for when the file processing (upload, optional slicing, addition to analysis queue) has finished. Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. """ if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "gcode"): return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint) else: selectAndOrPrint(filename, absFilename, destination) return filename def selectAndOrPrint(filename, absFilename, destination): """ Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only the case after they have finished streaming to the printer, which is why this callback is also used for the corresponding call to addSdFile. Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the exact file is already selected, such reloading it. """ if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or reselect): printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect) try: added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPathInStorage, upload, allow_overwrite=True) except octoprint.filemanager.storage.StorageError as e: if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE: return make_response("Could not upload the file \"{}\", invalid type".format(upload.filename), 400) else: return make_response("Could not upload the file \"{}\"".format(upload.filename), 500) if octoprint.filemanager.valid_file_type(added_file, "stl"): filename = added_file done = True else: filename = fileProcessingFinished(added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target) done = not sd if userdata is not None: # upload included userdata, add this now to the metadata fileManager.set_additional_metadata(FileDestinations.LOCAL, added_file, "userdata", userdata) sdFilename = None if isinstance(filename, tuple): filename, sdFilename = filename eventManager.fire(Events.UPLOAD, {"name": futureFilename, "path": filename, "target": target, # TODO deprecated, remove in 1.4.0 "file": filename}) files = {} location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True) files.update({ FileDestinations.LOCAL: { "name": futureFilename, "path": filename, "origin": FileDestinations.LOCAL, "refs": { "resource": location, "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename } } }) if sd and sdFilename: location = url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True) files.update({ FileDestinations.SDCARD: { "name": sdFilename, "path": sdFilename, "origin": FileDestinations.SDCARD, "refs": { "resource": location } } }) r = make_response(jsonify(files=files, done=done), 201) r.headers["Location"] = location return r elif "foldername" in request.values: foldername = request.values["foldername"] if not target in [FileDestinations.LOCAL]: return make_response("Unknown target: %s" % target, 400) futurePath, futureName = fileManager.sanitize(target, foldername) if not futureName or not futurePath: return make_response("Can't create a folder with an empty name", 400) if "path" in request.values and request.values["path"]: futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, request.values["path"]) futureFullPath = fileManager.join_path(target, futurePath, futureName) if octoprint.filemanager.valid_file_type(futureName): return make_response("Can't create a folder named %s, please try another name" % futureName, 409) try: added_folder = fileManager.add_folder(target, futureFullPath) except octoprint.filemanager.storage.StorageError as e: if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY: return make_response("Could not create folder {}, invalid directory".format(futureName)) else: return make_response("Could not create folder {}".format(futureName)) location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=added_folder, _external=True) folder = dict(name=futureName, path=added_folder, origin=target, refs=dict(resource=location)) r = make_response(jsonify(folder=folder, done=True), 201) r.headers["Location"] = location return r else: return make_response("No file to upload and no folder to create", 400)
def activeDeviceConfigChanged(self, properties): if "Options" in properties and "ip_address" in properties["Options"] and properties["Options"]["ip_address"] != self._currentIpv4Address: self._currentIpv4Address = properties["Options"]["ip_address"] self._setOnline(True) eventManager.fire(Events.NETWORK_IP_CHANGED, self._currentIpv4Address)