Exemplo n.º 1
0
	def initial_state(self, data, clientId, done):
		printer = printerManager()
		cm = cameraManager()
		softwareManager = swManager()

		state = {
			'printing': printer.isPrinting() or printer.isPaused(),
			'heatingUp': printer.isHeatingUp(),
			'operational': printer.isOperational(),
			'paused': printer.isPaused(),
			'camera': printer.isCameraConnected(),
			'filament' : printerProfileManager().data['filament'],
			'printCapture': cm.timelapseInfo,
			'profile': printerProfileManager().data,
			'remotePrint': True,
			'capabilities': softwareManager.capabilities() + cm.capabilities,
			'tool': printer.getSelectedTool() if printer.isOperational() else None,
			'printSpeed': printer.getPrintingSpeed(),
			'printFlow': printer.getPrintingFlow()
		}

		if state['printing'] or state['paused']:
			#Let's add info about the ongoing print job
			state['job'] = printer._stateMonitor._jobData
			state['progress'] = printer._stateMonitor._progress

		done(state)
Exemplo n.º 2
0
def handlePrinterSettings():
    s = settings()
    pm = printerManager()
    ppm = printerProfileManager()
    connectionOptions = pm.getConnectionOptions()

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

            if "serial" in data.keys():
                if "port" in data["serial"].keys():
                    s.set(["serial", "port"], data["serial"]["port"])
                if "baudrate" in data["serial"].keys():
                    s.setInt(["serial", "baudrate"],
                             data["serial"]["baudrate"])

            s.save()

    driverName = ppm.data['driver']
    driverInfo = ppm.driverChoices().get(driverName)
    if driverInfo:
        driverName = driverInfo['name']

    return jsonify({
        "driver": ppm.data['driver'],
        "driverName": driverName,
        "serial": {
            "port": connectionOptions["portPreference"],
            "baudrate": connectionOptions["baudratePreference"],
            "portOptions": connectionOptions["ports"].items(),
            "baudrateOptions": connectionOptions["baudrates"]
        }
    })
Exemplo n.º 3
0
    def saveTempPreset(self, data, sendMessage):
        ppm = printerProfileManager()

        if data:
            id = ppm.createTempPreset(data['name'], data['nozzle_temp'],
                                      data['bed_temp'])
            sendMessage(id)
Exemplo n.º 4
0
def connection_settings():
    connectionOptions = printerManager().getConnectionOptions()

    if connectionOptions:

        plugins = pluginManager().getPluginsByProvider('printerComms')

        driverChoices = {("plugin:%s" % k): plugins[k].definition['name']
                         for k in plugins}

        driverChoices.update({
            'marlin': 'GCODE - Marlin / Repetier Firmware',
            's3g': 'X3G - Sailfish / Makerbot Firmware'
        })

        response = {
            "driver": printerProfileManager().data['driver'],
            "driverChoices": driverChoices,
            "port": connectionOptions["portPreference"],
            "baudrate": connectionOptions["baudratePreference"],
            "portOptions": connectionOptions["ports"].items(),
            "baudrateOptions": connectionOptions["baudrates"]
        }

        return jsonify(response)

    return make_response("Connection options not available", 400)
Exemplo n.º 5
0
	def processAuthenticate(self, data):
		if data:
			self._silentReconnect = False

			if 'error' in data:
				self._logger.warn(data['message'] if 'message' in data else 'Unkonwn authentication error')
				self.status = self.STATUS_ERROR
				self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)
				self.close()

				if data.get('should_retry'):
					self._doRetry()

				elif data.get('type') == 'unable_to_authenticate':
					self._logger.info("Unuable to authenticate user in fleet box. Logout")
					astroprintCloud().remove_logged_user()

			elif 'success' in data:
				self._logger.info("Connected to astroprint service")
				self.authenticated = True
				if 'groupId' in data:
					astroprintCloud().updateFleetInfo(data['orgId'], data['groupId'])
					self._eventManager.fire(Events.FLEET_STATUS, data)

				self._retries = 0
				self._retryTimer = None
				self.status = self.STATUS_CONNECTED
				self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)

			return None

		else:
			from octoprint.server import VERSION
			from octoprint_WBCustom.astroprint.printerprofile import printerProfileManager

			nm = networkManager()
			sm = softwareManager()
			ppm = printerProfileManager()

			authData = {
				'silentReconnect': self._silentReconnect,
				'boxId': self.boxId,
				'variantId': sm.variant['id'],
				'boxName': nm.getHostname(),
				'swVersion': VERSION,
				'platform': sm.platform,
				'localIpAddress': nm.activeIpAddress,
				'publicKey': self._publicKey,
				'privateKey': self._privateKey,
				'printerModel': ppm.data['printer_model'] if ppm.data['printer_model']['id'] else None
			}

			pkgId = sm.mfPackageId
			if pkgId:
				authData['mfPackageId'] = pkgId

			return {
				'type': 'auth',
				'data': authData
			}
Exemplo n.º 6
0
    def printerConnectionDriver(self, data, sendMessage):

        s = settings()
        pm = printerManager()
        ppm = printerProfileManager()
        connectionOptions = pm.getConnectionOptions()

        if data and data['settings']:
            if "serial" in data.keys():
                if "port" in data["serial"].keys():
                    s.set(["serial", "port"], data["serial"]["port"])
                if "baudrate" in data["serial"].keys():
                    s.setInt(["serial", "baudrate"],
                             data["serial"]["baudrate"])

            s.save()

        driverName = ppm.data['driver']
        driverInfo = ppm.driverChoices().get(driverName)
        if driverInfo:
            driverName = driverInfo['name']

        sendMessage({
            "driver": ppm.data['driver'],
            "driverName": driverName,
            "fileFormat": pm.fileManager.fileFormat,
            "serial": {
                "port": connectionOptions["portPreference"],
                "baudrate": connectionOptions["baudratePreference"],
                "portOptions": connectionOptions["ports"],
                "baudrateOptions": connectionOptions["baudrates"]
            }
        })
Exemplo n.º 7
0
    def saveConnectionSettings(self, data, sendResponse):
        port = data['port']
        baudrate = data['baudrate']
        driver = data['driver']

        if port:
            s = settings()

            s.set(["serial", "port"], port)

            if baudrate:
                s.setInt(["serial", "baudrate"], baudrate)

            s.save()

            pp = printerProfileManager()
            pp.set({'driver': driver})
            pp.save()

            printerManager().connect(port, baudrate)

            sendResponse({'success': 'no_error'})
            return

        sendResponse('invalid_printer_connection_settings', True)
Exemplo n.º 8
0
	def getStatus(self):
		printer = printerManager()
		cm = cameraManager()
		ppm = printerProfileManager()
		cloudInstance = astroprintCloud()

		fileName = None

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

		return {
				'id': boxrouterManager().boxId,
				'name': networkManager().getHostname(),
				'orgId' : cloudInstance.orgId,
				'groupId' : cloudInstance.groupId,
				'printing': printer.isPrinting(),
				'fileName': fileName,
				'printerModel': ppm.data['printer_model'] if ppm.data['printer_model']['id'] else None,
				'filament' : ppm.data['filament'],
				'material': None,
				'operational': printer.isOperational(),
				'paused': printer.isPaused(),
				'camera': cm.isCameraConnected(),
				#'printCapture': cm.timelapseInfo,
				'remotePrint': True,
				'capabilities': ['remotePrint'] + cm.capabilities
			}
Exemplo n.º 9
0
def temp_preset_create():
    ppm = printerProfileManager()

    name = request.values.get('name', None)
    nozzle_temp = request.values.get('nozzle_temp', None)
    bed_temp = request.values.get('bed_temp', None)

    return jsonify({'id': ppm.createTempPreset(name, nozzle_temp, bed_temp)})
Exemplo n.º 10
0
	def getNumberOfExtruders(self,data,sendResponse=None):
		ppm = printerProfileManager()

		extruderCount = ppm.data.get('extruder_count')

		if sendResponse:
			sendResponse(extruderCount)

		return extruderCount
Exemplo n.º 11
0
def save_printer_profile_settings():
    driver = request.values.get('driver', None)

    if driver:
        pp = printerProfileManager()
        pp.set({'driver': driver})
        pp.save()

        return make_response("OK", 200)

    return make_response('Invalid Connection Settings', 400)
Exemplo n.º 12
0
	def set_filament(self, data, clientId, done):

		filament = {}
		filament['filament'] = {}

		if data['filament'] and data['filament']['name'] and data['filament']['color']:
			filament['filament']['name'] = data['filament']['name']
			#Better to make sure that are getting right color codes
			if re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', data['filament']['color']):
				filament['filament']['color'] = data['filament']['color']
			else:
				done({
					'error': True,
					'message': 'Invalid color code'
				})

		else:
			filament['filament']['name'] = None
			filament['filament']['color'] = None

		printerProfileManager().set(filament)
		printerProfileManager().save()
		done(None)
Exemplo n.º 13
0
def printer_profile_patch():
    ppm = printerProfileManager()

    if request.method == "PATCH":
        changes = request.json
        ppm.set(changes)
        ppm.save()

        return jsonify()

    else:

        result = ppm.data.copy()
        result.update({"driverChoices": ppm.driverChoices()})

        return jsonify(result)
Exemplo n.º 14
0
def printerManager(driver=None):
    global _instance

    if driver is not None and _instance is not None and _instance.driverName != driver:
        _instance.rampdown()
        _instance = None

    if _instance is None and driver:
        if driver.startswith('plugin:'):
            from octoprint_WBCustom.astroprint.printer.plugin import PrinterWithPlugin, NoPluginException

            try:
                _instance = PrinterWithPlugin(driver[7:])

            except NoPluginException:
                #The plugin is gone. Pick the default
                from octoprint_WBCustom.astroprint.printerprofile import printerProfileManager
                ppm = printerProfileManager()
                ppm.set({'driver': DEFAULT_MANAGER})
                ppm.save()

        else:
            import importlib

            try:
                # driver name to class map. format is (module, classname)
                classInfo = {
                    'marlin': ('.marlin', 'PrinterMarlin'),
                    's3g': ('.s3g', 'PrinterS3g')
                }[driver]

            except KeyError:
                classInfo = ('.marlin', 'PrinterMarlin')

            module = importlib.import_module(classInfo[0],
                                             'astroprint.printer')
            _instance = getattr(module, classInfo[1])()

    return _instance
Exemplo n.º 15
0
    def __init__(self):
        self.systemPlugin = False

        self._logger = logging.getLogger('Plugin::%s' %
                                         self.__class__.__name__)
        self._definition = None
        self._settings = settings()
        self._pluginEventListeners = {}
        self._profileManager = printerProfileManager()

        #Read it's definition file - plugin.yaml -
        pluginPath = os.path.dirname(sys.modules[self.__module__].__file__)
        definitionFile = os.path.join(pluginPath, 'plugin.yaml')
        if os.path.exists(definitionFile):
            try:
                with open(definitionFile, "r") as f:
                    self._definition = yaml.safe_load(f)

            except Exception as e:
                raise e  #Raise parse exception here

            if all(key in self._definition for key in REQUIRED_PLUGIN_KEYS):
                min_api_version = int(self._definition['min_api_version'])

                if PLUGIN_API_VERSION >= min_api_version:
                    self.initialize()
                else:
                    raise Exception(
                        "AstroBox API version [%d] is lower than minimum required by %s [%d]"
                        % (PLUGIN_API_VERSION, self._definition['id'],
                           min_api_version))

            else:
                raise Exception("Invalid plugin definition found in %s" %
                                definitionFile)

        else:
            raise Exception("No plugin definition file exists in %s" %
                            pluginPath)
Exemplo n.º 16
0
    def printerProfile(self, data, sendMessage):

        ppm = printerProfileManager()
        pm = printerManager()
        if data:
            if 'driverChoices' in data:
                del data['driverChoices']

            if 'allowTerminal' in data:
                del data['allowTerminal']

            ppm.set(data)
            ppm.save()

            sendMessage({'success': 'no_error'})
        else:

            result = ppm.data.copy()

            result.update({"allowTerminal": pm.allowTerminal})
            result.update({"driverChoices": ppm.driverChoices()})

            sendMessage(result)
Exemplo n.º 17
0
def save_connection_settings():
    port = request.values.get('port', None)
    baudrate = request.values.get('baudrate', None)
    driver = request.values.get('driver', None)

    if port:
        s = settings()

        s.set(["serial", "port"], port)

        if baudrate:
            s.setInt(["serial", "baudrate"], baudrate)

        s.save()

        pp = printerProfileManager()
        pp.set({'driver': driver})
        pp.save()

        printerManager().connect(port, baudrate)

        return make_response("OK", 200)

    return make_response('Invalid Connection Settings', 400)
Exemplo n.º 18
0
    def __init__(self):
        self.broadcastTraffic = 0  #Number of clients that wish to receive serial link traffic
        self.doIdleTempReports = True  #Let's the client know if periodic temperature reports should be queries to the printer

        self._comm = None
        self._currentFile = None
        self._selectedFile = None
        self._currentZ = None  # This should probably be deprecated
        self._progress = None
        self._printTime = None
        self._printTimeLeft = None
        self._currentLayer = None
        self._currentPrintJobId = None
        self._timeStarted = 0
        self._secsPaused = 0
        self._pausedSince = None

        self._profileManager = printerProfileManager()

        self._fileManager = printFileManagerMap[self._fileManagerClass.name]()
        self._fileManager.registerCallback(self)
        self._state = self.STATE_NONE
        self._logger = logging.getLogger(__name__)

        self._temp = {}
        self._bedTemp = None
        self._temps = deque([], 300)
        self._shutdown = False

        self._messages = deque([], 300)

        self.printedLayersCounter = 0

        # callbacks
        self._callbacks = []
        #self._lastProgressReport = None

        self._stateMonitor = StateMonitor(
            ratelimit=1.0,
            updateCallback=self._sendCurrentDataCallbacks,
            addTemperatureCallback=self._sendAddTemperatureCallbacks,
            addLogCallback=self._sendAddLogCallbacks,
            addMessageCallback=self._sendAddMessageCallbacks)

        self._stateMonitor.reset(state={
            "text": self.getStateString(),
            "flags": self._getStateFlags()
        },
                                 jobData={
                                     "file": {
                                         "name": None,
                                         "size": None,
                                         "origin": None,
                                         "date": None
                                     },
                                     "estimatedPrintTime": None,
                                     "filament": {
                                         "length": None,
                                         "volume": None
                                     }
                                 },
                                 progress={
                                     "completion": None,
                                     "filepos": None,
                                     "printTime": None,
                                     "printTimeLeft": None
                                 },
                                 currentZ=None)

        eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED,
                                 self.onMetadataAnalysisFinished)