diff --git a/octoprint/events.py b/octoprint/events.py index 37db50c18..2a3f31365 100644 --- a/octoprint/events.py +++ b/octoprint/events.py @@ -46,7 +46,10 @@ class EventManager(object): eventListeners = self._registeredListeners[event] for listener in eventListeners: self._logger.debug("Sending action to %r" % listener) - listener(event, payload) + try: + listener(event, payload) + except: + self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener)) def subscribe(self, event, callback): diff --git a/octoprint/gcodefiles.py b/octoprint/gcodefiles.py index 7cc024d55..3b3712138 100644 --- a/octoprint/gcodefiles.py +++ b/octoprint/gcodefiles.py @@ -65,8 +65,8 @@ class GcodeManager: dirty = True if gcode.extrusionAmount: analysisResult["filament"] = "%.2fm" % (gcode.extrusionAmount / 1000) - if gcode.extrusionVolume: - analysisResult["filament"] += " / %.2fcm³" % gcode.extrusionVolume + if gcode.calculateVolumeCm3(): + analysisResult["filament"] += " / %.2fcm³" % gcode.calculateVolumeCm3() dirty = True if dirty: diff --git a/octoprint/printer.py b/octoprint/printer.py index d5fc445f6..323546add 100644 --- a/octoprint/printer.py +++ b/octoprint/printer.py @@ -171,9 +171,19 @@ class Printer(): """ Sends multiple gcode commands (provided as a list) to the printer. """ + if self._comm is None: + return + for command in commands: self._comm.sendCommand(command) + def setTemperatureOffset(self, extruder, bed): + if self._comm is None: + return + + self._comm.setTemperatureOffset(extruder, bed) + self._stateMonitor.setTempOffsets(extruder, bed) + def selectFile(self, filename, sd, printAfterSelect=False): if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()): return @@ -503,14 +513,22 @@ class Printer(): return currentData["job"] def getCurrentTemperatures(self): + if self._comm is not None: + (tempOffset, bedTempOffset) = self._comm.getOffsets() + else: + tempOffset = 0 + bedTempOffset = 0 + return { "extruder": { "current": self._temp, - "target": self._targetTemp + "target": self._targetTemp, + "offset": tempOffset }, "bed": { "current": self._bedTemp, - "target": self._targetBedTemp + "target": self._targetBedTemp, + "offset": bedTempOffset } } @@ -627,6 +645,9 @@ class StateMonitor(object): self._currentZ = None self._progress = None + self._tempOffset = 0 + self._bedTempOffset = 0 + self._changeEvent = threading.Event() self._lastUpdate = time.time() @@ -668,6 +689,13 @@ class StateMonitor(object): self._progress = progress self._changeEvent.set() + def setTempOffsets(self, tempOffset, bedTempOffset): + if tempOffset is not None: + self._tempOffset = tempOffset + if bedTempOffset is not None: + self._bedTempOffset = bedTempOffset + self._changeEvent.set() + def _work(self): while True: self._changeEvent.wait() @@ -688,6 +716,7 @@ class StateMonitor(object): "state": self._state, "job": self._jobData, "currentZ": self._currentZ, - "progress": self._progress + "progress": self._progress, + "offsets": (self._tempOffset, self._bedTempOffset) } diff --git a/octoprint/server.py b/octoprint/server.py index f4b3113c7..54ff8baa4 100644 --- a/octoprint/server.py +++ b/octoprint/server.py @@ -2,8 +2,8 @@ __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -from werkzeug.utils import secure_filename -import tornadio2 +from werkzeug.utils import secure_filename, redirect +from sockjs.tornado import SockJSRouter, SockJSConnection from flask import Flask, request, render_template, jsonify, send_from_directory, url_for, current_app, session, abort, make_response from flask.ext.login import LoginManager, login_user, logout_user, login_required, current_user from flask.ext.principal import Principal, Permission, RoleNeed, Identity, identity_changed, AnonymousIdentity, identity_loaded, UserNeed @@ -14,6 +14,7 @@ import os import threading import logging, logging.config import subprocess +import netaddr from octoprint.printer import Printer, getConnectionOptions from octoprint.settings import settings, valid_boolean_trues @@ -33,6 +34,7 @@ app = Flask("octoprint") # In order that threads don't start too early when running as a Daemon printer = None timelapse = None +debug = False gcodeManager = None userManager = None @@ -45,9 +47,9 @@ user_permission = Permission(RoleNeed("user")) #~~ Printer state -class PrinterStateConnection(tornadio2.SocketConnection): - def __init__(self, printer, gcodeManager, userManager, eventManager, session, endpoint=None): - tornadio2.SocketConnection.__init__(self, session, endpoint) +class PrinterStateConnection(SockJSConnection): + def __init__(self, printer, gcodeManager, userManager, eventManager, session): + SockJSConnection.__init__(self, session) self._logger = logging.getLogger(__name__) @@ -63,20 +65,29 @@ class PrinterStateConnection(tornadio2.SocketConnection): self._userManager = userManager self._eventManager = eventManager + def _getRemoteAddress(self, info): + forwardedFor = info.headers.get("X-Forwarded-For") + if forwardedFor is not None: + return forwardedFor.split(",")[0] + return info.ip + def on_open(self, info): - self._logger.info("New connection from client") - # Use of global here is smelly + self._logger.info("New connection from client: %s" % self._getRemoteAddress(info)) self._printer.registerCallback(self) self._gcodeManager.registerCallback(self) + octoprint.timelapse.registerCallback(self) self._eventManager.fire("ClientOpened") self._eventManager.subscribe("MovieDone", self._onMovieDone) + global timelapse + octoprint.timelapse.notifyCallbacks(timelapse) + def on_close(self): self._logger.info("Closed client connection") - # Use of global here is smelly self._printer.unregisterCallback(self) self._gcodeManager.unregisterCallback(self) + octoprint.timelapse.unregisterCallback(self) self._eventManager.fire("ClientClosed") self._eventManager.unsubscribe("MovieDone", self._onMovieDone) @@ -103,16 +114,19 @@ class PrinterStateConnection(tornadio2.SocketConnection): "logs": logs, "messages": messages }) - self.emit("current", data) + self._emit("current", data) def sendHistoryData(self, data): - self.emit("history", data) + self._emit("history", data) def sendUpdateTrigger(self, type): - self.emit("updateTrigger", type) + self._emit("updateTrigger", type) def sendFeedbackCommandOutput(self, name, output): - self.emit("feedbackCommandOutput", {"name": name, "output": output}) + self._emit("feedbackCommandOutput", {"name": name, "output": output}) + + def sendTimelapseConfig(self, timelapseConfig): + self._emit("timelapse", timelapseConfig) def addLog(self, data): with self._logBacklogMutex: @@ -129,6 +143,9 @@ class PrinterStateConnection(tornadio2.SocketConnection): def _onMovieDone(self, event, payload): self.sendUpdateTrigger("timelapseFiles") + def _emit(self, type, payload): + self.send({type: payload}) + def restricted_access(func): """ If you decorate a view with this, it will ensure that first setup has been @@ -160,16 +177,20 @@ def index(): except: pass + global debug + return render_template( "index.jinja2", ajaxBaseUrl=BASEURL, webcamStream=settings().get(["webcam", "stream"]), enableTimelapse=(settings().get(["webcam", "snapshot"]) is not None and settings().get(["webcam", "ffmpeg"]) is not None), enableGCodeVisualizer=settings().get(["feature", "gCodeVisualizer"]), + enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]), enableSystemMenu=settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None and len(settings().get(["system", "actions"])) > 0, enableAccessControl=userManager is not None, enableSdSupport=settings().get(["feature", "sdSupport"]), firstRun=settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized()), + debug=debug, gitBranch=branch, gitCommit=commit ) @@ -256,6 +277,24 @@ def setTargetTemperature(): bedTemp = request.values["bedTemp"] printer.command("M140 S" + bedTemp) + if "tempOffset" in request.values.keys(): + # set target temperature offset + try: + tempOffset = float(request.values["tempOffset"]) + if tempOffset >= -50 and tempOffset <= 50: + printer.setTemperatureOffset(tempOffset, None) + except: + pass + + if "bedTempOffset" in request.values.keys(): + # set target bed temperature offset + try: + bedTempOffset = float(request.values["bedTempOffset"]) + if bedTempOffset >= -50 and bedTempOffset <= 50: + printer.setTemperatureOffset(None, bedTempOffset) + except: + pass + return jsonify(SUCCESS) @app.route(BASEURL + "control/jog", methods=["POST"]) @@ -333,7 +372,7 @@ def readGcodeFiles(): @app.route(BASEURL + "gcodefiles/", methods=["GET"]) def readGcodeFile(filename): - return send_from_directory(settings().getBaseFolder("uploads"), filename, as_attachment=True) + return redirectToTornado(request, "/downloads/gcode/" + filename) @app.route(BASEURL + "gcodefiles/upload", methods=["POST"]) @restricted_access @@ -492,7 +531,7 @@ def getTimelapseData(): files = octoprint.timelapse.getFinishedTimelapses() for file in files: - file["url"] = url_for("downloadTimelapse", filename=file["name"]) + file["url"] = "/downloads/timelapse/" + file["name"] return jsonify({ "type": type, @@ -502,8 +541,7 @@ def getTimelapseData(): @app.route(BASEURL + "timelapse/", methods=["GET"]) def downloadTimelapse(filename): - if util.isAllowedFile(filename, set(["mpg"])): - return send_from_directory(settings().getBaseFolder("timelapse"), filename, as_attachment=True) + return redirectToTornado(request, "/downloads/timelapse/" + filename) @app.route(BASEURL + "timelapse/", methods=["DELETE"]) @restricted_access @@ -517,28 +555,56 @@ def deleteTimelapse(filename): @app.route(BASEURL + "timelapse", methods=["POST"]) @restricted_access def setTimelapseConfig(): - global timelapse - if request.values.has_key("type"): - type = request.values["type"] - if type in ["zchange", "timed"]: - # valid timelapse type, check if there is an old one we need to stop first - if timelapse is not None: - timelapse.unload() - timelapse = None - if "zchange" == type: - timelapse = octoprint.timelapse.ZTimelapse() - elif "timed" == type: + config = { + "type": request.values["type"], + "options": {} + } + + if request.values.has_key("interval"): interval = 10 - if request.values.has_key("interval"): - try: - interval = int(request.values["interval"]) - except ValueError: - pass - timelapse = octoprint.timelapse.TimedTimelapse(interval) + try: + interval = int(request.values["interval"]) + except ValueError: + pass + + config["options"] = { + "interval": interval + } + + if admin_permission.can() and request.values.has_key("save") and request.values["save"] in valid_boolean_trues: + _configureTimelapse(config, True) + else: + _configureTimelapse(config) return getTimelapseData() +def _configureTimelapse(config=None, persist=False): + global timelapse + + if config is None: + config = settings().get(["webcam", "timelapse"]) + + if timelapse is not None: + timelapse.unload() + + type = config["type"] + if type is None or "off" == type: + timelapse = None + elif "zchange" == type: + timelapse = octoprint.timelapse.ZTimelapse() + elif "timed" == type: + interval = 10 + if "options" in config and "interval" in config["options"]: + interval = config["options"]["interval"] + timelapse = octoprint.timelapse.TimedTimelapse(interval) + + octoprint.timelapse.notifyCallbacks(timelapse) + + if persist: + settings().set(["webcam", "timelapse"], config) + settings().save() + #~~ settings @app.route(BASEURL + "settings", methods=["GET"]) @@ -575,9 +641,11 @@ def getSettings(): }, "feature": { "gcodeViewer": s.getBoolean(["feature", "gCodeVisualizer"]), + "temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]), "waitForStart": s.getBoolean(["feature", "waitForStartOnConnect"]), "alwaysSendChecksum": s.getBoolean(["feature", "alwaysSendChecksum"]), - "sdSupport": s.getBoolean(["feature", "sdSupport"]) + "sdSupport": s.getBoolean(["feature", "sdSupport"]), + "swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]) }, "serial": { "port": connectionOptions["portPreference"], @@ -602,7 +670,8 @@ def getSettings(): "system": { "actions": s.get(["system", "actions"]), "events": s.get(["system", "events"]) - } + }, + "terminalFilters": s.get(["terminalFilters"]) }) @app.route(BASEURL + "settings", methods=["POST"]) @@ -638,9 +707,11 @@ def setSettings(): if "feature" in data.keys(): if "gcodeViewer" in data["feature"].keys(): s.setBoolean(["feature", "gCodeVisualizer"], data["feature"]["gcodeViewer"]) + if "temperatureGraph" in data["feature"].keys(): s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"]) if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"]) if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"]) if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"]) + if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"]) if "serial" in data.keys(): if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"]) @@ -670,6 +741,9 @@ def setSettings(): if "temperature" in data.keys(): if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"]) + if "terminalFilters" in data.keys(): + s.set(["terminalFilters"], data["terminalFilters"]) + if "system" in data.keys(): if "actions" in data["system"].keys(): s.set(["system", "actions"], data["system"]["actions"]) if "events" in data["system"].keys(): s.set(["system", "events"], data["system"]["events"]) @@ -857,6 +931,26 @@ def login(): if user is not None and not user.is_anonymous(): identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) return jsonify(user.asDict()) + elif settings().getBoolean(["accessControl", "autologinLocal"]) \ + and settings().get(["accessControl", "autologinAs"]) is not None \ + and settings().get(["accessControl", "localNetworks"]) is not None: + + autologinAs = settings().get(["accessControl", "autologinAs"]) + localNetworks = netaddr.IPSet([]) + for ip in settings().get(["accessControl", "localNetworks"]): + localNetworks.add(ip) + + try: + remoteAddr = util.getRemoteAddress(request) + if netaddr.IPAddress(remoteAddr) in localNetworks: + user = userManager.findUser(autologinAs) + if user is not None: + login_user(user) + identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) + return jsonify(user.asDict()) + except: + logger = logging.getLogger(__name__) + logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks)) return jsonify(SUCCESS) @app.route(BASEURL + "logout", methods=["POST"]) @@ -888,6 +982,93 @@ def load_user(id): return userManager.findUser(id) return users.DummyUser() +def redirectToTornado(request, target): + requestUrl = request.url + appBaseUrl = requestUrl[:requestUrl.find(BASEURL)] + + redirectUrl = appBaseUrl + target + if "?" in requestUrl: + fragment = requestUrl[requestUrl.rfind("?"):] + redirectUrl += fragment + return redirect(redirectUrl) + +#~~ customized large response handler + +from tornado.web import StaticFileHandler, HTTPError +import datetime, stat, mimetypes, email, time + +class LargeResponseHandler(StaticFileHandler): + + CHUNK_SIZE = 16 * 1024 + + def initialize(self, path, default_filename=None, as_attachment=False): + StaticFileHandler.initialize(self, path, default_filename) + self._as_attachment = as_attachment + + def get(self, path, include_body=True): + path = self.parse_url_path(path) + abspath = os.path.abspath(os.path.join(self.root, path)) + # os.path.abspath strips a trailing / + # it needs to be temporarily added back for requests to root/ + if not (abspath + os.path.sep).startswith(self.root): + raise HTTPError(403, "%s is not in root static directory", path) + if os.path.isdir(abspath) and self.default_filename is not None: + # need to look at the request.path here for when path is empty + # but there is some prefix to the path that was already + # trimmed by the routing + if not self.request.path.endswith("/"): + self.redirect(self.request.path + "/") + return + abspath = os.path.join(abspath, self.default_filename) + if not os.path.exists(abspath): + raise HTTPError(404) + if not os.path.isfile(abspath): + raise HTTPError(403, "%s is not a file", path) + + stat_result = os.stat(abspath) + modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME]) + + self.set_header("Last-Modified", modified) + + mime_type, encoding = mimetypes.guess_type(abspath) + if mime_type: + self.set_header("Content-Type", mime_type) + + cache_time = self.get_cache_time(path, modified, mime_type) + + if cache_time > 0: + self.set_header("Expires", datetime.datetime.utcnow() + + datetime.timedelta(seconds=cache_time)) + self.set_header("Cache-Control", "max-age=" + str(cache_time)) + + self.set_extra_headers(path) + + # Check the If-Modified-Since, and don't send the result if the + # content has not been modified + ims_value = self.request.headers.get("If-Modified-Since") + if ims_value is not None: + date_tuple = email.utils.parsedate(ims_value) + if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple)) + if if_since >= modified: + self.set_status(304) + return + + if not include_body: + assert self.request.method == "HEAD" + self.set_header("Content-Length", stat_result[stat.ST_SIZE]) + else: + with open(abspath, "rb") as file: + while True: + data = file.read(LargeResponseHandler.CHUNK_SIZE) + if not data: + break + self.write(data) + self.flush() + + def set_extra_headers(self, path): + if self._as_attachment: + self.set_header("Content-Disposition", "attachment") + #~~ startup code class Server(): def __init__(self, configfile=None, basedir=None, host="0.0.0.0", port=5000, debug=False, allowRoot=False): @@ -909,11 +1090,14 @@ class Server(): global userManager global eventManager global loginManager + global debug from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop - from tornado.web import Application, FallbackHandler + from tornado.web import Application, FallbackHandler, StaticFileHandler + + debug = self._debug # first initialize the settings singleton and make sure it uses given configfile and basedir if available self._initSettings(self._configfile, self._basedir) @@ -926,6 +1110,9 @@ class Server(): gcodeManager = gcodefiles.GcodeManager() printer = Printer(gcodeManager) + # configure timelapse + _configureTimelapse() + # setup system and gcode command triggers events.SystemCommandTrigger(printer) events.GcodeCommandTrigger(printer) @@ -957,10 +1144,12 @@ class Server(): logger.info("Listening on http://%s:%d" % (self._host, self._port)) app.debug = self._debug - self._router = tornadio2.TornadioRouter(self._createSocketConnection) + self._router = SockJSRouter(self._createSocketConnection, "/sockjs") self._tornado_app = Application(self._router.urls + [ - (".*", FallbackHandler, {"fallback": WSGIContainer(app)}) + (r"/downloads/timelapse/([^/]*\.mpg)", LargeResponseHandler, {"path": settings().getBaseFolder("timelapse"), "as_attachment": True}), + (r"/downloads/gcode/([^/]*\.(gco|gcode))", LargeResponseHandler, {"path": settings().getBaseFolder("uploads"), "as_attachment": True}), + (r".*", FallbackHandler, {"fallback": WSGIContainer(app)}) ]) self._server = HTTPServer(self._tornado_app) self._server.listen(self._port, address=self._host) @@ -971,11 +1160,15 @@ class Server(): connectionOptions = getConnectionOptions() if port in connectionOptions["ports"]: printer.connect(port, baudrate) - IOLoop.instance().start() + try: + IOLoop.instance().start() + except: + logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!") + logger.exception("Stacktrace follows:") - def _createSocketConnection(self, session, endpoint=None): + def _createSocketConnection(self, session): global printer, gcodeManager, userManager, eventManager - return PrinterStateConnection(printer, gcodeManager, userManager, eventManager, session, endpoint) + return PrinterStateConnection(printer, gcodeManager, userManager, eventManager, session) def _checkForRoot(self): if "geteuid" in dir(os) and os.geteuid() == 0: diff --git a/octoprint/settings.py b/octoprint/settings.py index cdc7cc4d9..7e0fab732 100644 --- a/octoprint/settings.py +++ b/octoprint/settings.py @@ -32,7 +32,8 @@ default_settings = { "detection": 0.5, "connection": 2, "communication": 5 - } + }, + "additionalPorts": [] }, "server": { "host": "0.0.0.0", @@ -46,13 +47,19 @@ default_settings = { "bitrate": "5000k", "watermark": True, "flipH": False, - "flipV": False + "flipV": False, + "timelapse": { + "type": "off", + "options": {} + } }, "feature": { "gCodeVisualizer": True, + "temperatureGraph": True, "waitForStartOnConnect": False, "alwaysSendChecksum": False, - "sdSupport": True + "sdSupport": True, + "swallowOkAfterResend": False }, "folder": { "uploads": None, @@ -88,7 +95,10 @@ default_settings = { "accessControl": { "enabled": True, "userManager": "octoprint.users.FilebasedUserManager", - "userfile": None + "userfile": None, + "autologinLocal": False, + "localNetworks": ["127.0.0.0/8"], + "autologinAs": None }, "events": { "systemCommandTrigger": { @@ -101,6 +111,18 @@ default_settings = { "api": { "enabled": False, "key": ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes) + }, + "terminalFilters": [ + { "name": "Suppress M105 requests/responses", "regex": "(Send: M105)|(Recv: ok T:)" }, + { "name": "Suppress M27 requests/responses", "regex": "(Send: M27)|(Recv: SD printing byte)" } + ], + "devel": { + "virtualPrinter": { + "enabled": False, + "okAfterResend": False, + "forceChecksum": False, + "okWithLinenumber": False + } } } @@ -245,7 +267,7 @@ class Settings(object): return feedbackControls def _getFeedbackControls(self, control=None): - if control["type"] == "feedback_command": + if control["type"] == "feedback_command" or control["type"] == "feedback": pattern = control["regex"] try: matcher = re.compile(pattern) diff --git a/octoprint/static/css/octoprint.less b/octoprint/static/css/octoprint.less index 05ad83e8a..835e7d787 100644 --- a/octoprint/static/css/octoprint.less +++ b/octoprint/static/css/octoprint.less @@ -200,12 +200,18 @@ body { table { table-layout: fixed; + .popover-title { + text-overflow: ellipsis; + word-break: break-all; + } + th, td { overflow: hidden; // gcode files &.gcode_files_name { text-overflow: ellipsis; + white-space: nowrap; text-align: left; } diff --git a/octoprint/static/js/app/dataupdater.js b/octoprint/static/js/app/dataupdater.js new file mode 100644 index 000000000..919ea763d --- /dev/null +++ b/octoprint/static/js/app/dataupdater.js @@ -0,0 +1,123 @@ +function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewModel, temperatureViewModel, controlViewModel, terminalViewModel, gcodeFilesViewModel, timelapseViewModel, gcodeViewModel) { + var self = this; + + self.loginStateViewModel = loginStateViewModel; + self.connectionViewModel = connectionViewModel; + self.printerStateViewModel = printerStateViewModel; + self.temperatureViewModel = temperatureViewModel; + self.controlViewModel = controlViewModel; + self.terminalViewModel = terminalViewModel; + self.gcodeFilesViewModel = gcodeFilesViewModel; + self.timelapseViewModel = timelapseViewModel; + self.gcodeViewModel = gcodeViewModel; + + self._socket = undefined; + self._autoReconnecting = false; + self._autoReconnectTrial = 0; + self._autoReconnectTimeouts = [1, 1, 2, 3, 5, 8, 13, 20, 40, 100]; + + self.connect = function() { + var options = {}; + if (SOCKJS_DEBUG) { + options["debug"] = true; + } + + self._socket = new SockJS(SOCKJS_URI, undefined, options); + self._socket.onopen = self._onconnect; + self._socket.onclose = self._onclose; + self._socket.onmessage = self._onmessage; + } + + self.reconnect = function() { + delete self._socket; + self.connect(); + } + + self._onconnect = function() { + self._autoReconnecting = false; + self._autoReconnectTrial = 0; + + if ($("#offline_overlay").is(":visible")) { + $("#offline_overlay").hide(); + self.timelapseViewModel.requestData(); + $("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime()); + self.loginStateViewModel.requestData(); + self.gcodeFilesViewModel.requestData(); + } + } + + self._onclose = function() { + $("#offline_overlay_message").html( + "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect " + + "automatically over the next couple of minutes, however you are welcome to try a manual reconnect " + + "anytime using the button below." + ); + if (!$("#offline_overlay").is(":visible")) + $("#offline_overlay").show(); + + if (self._autoReconnectTrial < self._autoReconnectTimeouts.length) { + var timeout = self._autoReconnectTimeouts[self._autoReconnectTrial]; + console.log("Reconnect trial #" + self._autoReconnectTrial + ", waiting " + timeout + "s"); + setTimeout(self.reconnect, timeout * 1000); + self._autoReconnectTrial++; + } else { + self._onreconnectfailed(); + } + } + + self._onreconnectfailed = function() { + $("#offline_overlay_message").html( + "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, " + + "but you may try a manual reconnect using the button below." + ); + } + + self._onmessage = function(e) { + for (var prop in e.data) { + var payload = e.data[prop]; + + switch (prop) { + case "history": { + self.connectionViewModel.fromHistoryData(payload); + self.printerStateViewModel.fromHistoryData(payload); + self.temperatureViewModel.fromHistoryData(payload); + self.controlViewModel.fromHistoryData(payload); + self.terminalViewModel.fromHistoryData(payload); + self.timelapseViewModel.fromHistoryData(payload); + self.gcodeViewModel.fromHistoryData(payload); + self.gcodeFilesViewModel.fromCurrentData(payload); + break; + } + case "current": { + self.connectionViewModel.fromCurrentData(payload); + self.printerStateViewModel.fromCurrentData(payload); + self.temperatureViewModel.fromCurrentData(payload); + self.controlViewModel.fromCurrentData(payload); + self.terminalViewModel.fromCurrentData(payload); + self.timelapseViewModel.fromCurrentData(payload); + self.gcodeViewModel.fromCurrentData(payload); + self.gcodeFilesViewModel.fromCurrentData(payload); + break; + } + case "updateTrigger": { + if (payload == "gcodeFiles") { + gcodeFilesViewModel.requestData(); + } else if (payload == "timelapseFiles") { + timelapseViewModel.requestData(); + } + break; + } + case "feedbackCommandOutput": { + self.controlViewModel.fromFeedbackCommandData(payload); + break; + } + case "timelapse": { + self.printerStateViewModel.fromTimelapseData(payload); + break; + } + } + } + } + + self.connect(); +} diff --git a/octoprint/static/js/app/helpers.js b/octoprint/static/js/app/helpers.js new file mode 100644 index 000000000..16a7ee3b9 --- /dev/null +++ b/octoprint/static/js/app/helpers.js @@ -0,0 +1,275 @@ +function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSorting, defaultFilters, exclusiveFilters, filesPerPage) { + var self = this; + + self.listType = listType; + self.supportedSorting = supportedSorting; + self.supportedFilters = supportedFilters; + self.defaultSorting = defaultSorting; + self.defaultFilters = defaultFilters; + self.exclusiveFilters = exclusiveFilters; + + self.allItems = []; + + self.items = ko.observableArray([]); + self.pageSize = ko.observable(filesPerPage); + self.currentPage = ko.observable(0); + self.currentSorting = ko.observable(self.defaultSorting); + self.currentFilters = ko.observableArray(self.defaultFilters); + self.selectedItem = ko.observable(undefined); + + //~~ item handling + + self.updateItems = function(items) { + self.allItems = items; + self._updateItems(); + } + + self.selectItem = function(matcher) { + var itemList = self.items(); + for (var i = 0; i < itemList.length; i++) { + if (matcher(itemList[i])) { + self.selectedItem(itemList[i]); + break; + } + } + } + + self.selectNone = function() { + self.selectedItem(undefined); + } + + self.isSelected = function(data) { + return self.selectedItem() == data; + } + + self.isSelectedByMatcher = function(matcher) { + return matcher(self.selectedItem()); + } + + //~~ pagination + + self.paginatedItems = ko.dependentObservable(function() { + if (self.items() == undefined) { + return []; + } else { + var from = Math.max(self.currentPage() * self.pageSize(), 0); + var to = Math.min(from + self.pageSize(), self.items().length); + return self.items().slice(from, to); + } + }) + self.lastPage = ko.dependentObservable(function() { + return Math.ceil(self.items().length / self.pageSize()) - 1; + }) + self.pages = ko.dependentObservable(function() { + var pages = []; + if (self.lastPage() < 7) { + for (var i = 0; i < self.lastPage() + 1; i++) { + pages.push({ number: i, text: i+1 }); + } + } else { + pages.push({ number: 0, text: 1 }); + if (self.currentPage() < 5) { + for (var i = 1; i < 5; i++) { + pages.push({ number: i, text: i+1 }); + } + pages.push({ number: -1, text: "…"}); + } else if (self.currentPage() > self.lastPage() - 5) { + pages.push({ number: -1, text: "…"}); + for (var i = self.lastPage() - 4; i < self.lastPage(); i++) { + pages.push({ number: i, text: i+1 }); + } + } else { + pages.push({ number: -1, text: "…"}); + for (var i = self.currentPage() - 1; i <= self.currentPage() + 1; i++) { + pages.push({ number: i, text: i+1 }); + } + pages.push({ number: -1, text: "…"}); + } + pages.push({ number: self.lastPage(), text: self.lastPage() + 1}) + } + return pages; + }) + + self.switchToItem = function(matcher) { + var pos = -1; + var itemList = self.items(); + for (var i = 0; i < itemList.length; i++) { + if (matcher(itemList[i])) { + pos = i; + break; + } + } + + if (pos > -1) { + var page = Math.floor(pos / self.pageSize()); + self.changePage(page); + } + } + + self.changePage = function(newPage) { + if (newPage < 0 || newPage > self.lastPage()) + return; + self.currentPage(newPage); + } + self.prevPage = function() { + if (self.currentPage() > 0) { + self.currentPage(self.currentPage() - 1); + } + } + self.nextPage = function() { + if (self.currentPage() < self.lastPage()) { + self.currentPage(self.currentPage() + 1); + } + } + + self.getItem = function(matcher) { + var itemList = self.items(); + for (var i = 0; i < itemList.length; i++) { + if (matcher(itemList[i])) { + return itemList[i]; + } + } + + return undefined; + } + + //~~ sorting + + self.changeSorting = function(sorting) { + if (!_.contains(_.keys(self.supportedSorting), sorting)) + return; + + self.currentSorting(sorting); + self._saveCurrentSortingToLocalStorage(); + + self.changePage(0); + self._updateItems(); + } + + //~~ filtering + + self.toggleFilter = function(filter) { + if (!_.contains(_.keys(self.supportedFilters), filter)) + return; + + if (_.contains(self.currentFilters(), filter)) { + self.removeFilter(filter); + } else { + self.addFilter(filter); + } + } + + self.addFilter = function(filter) { + if (!_.contains(_.keys(self.supportedFilters), filter)) + return; + + for (var i = 0; i < self.exclusiveFilters.length; i++) { + if (_.contains(self.exclusiveFilters[i], filter)) { + for (var j = 0; j < self.exclusiveFilters[i].length; j++) { + if (self.exclusiveFilters[i][j] == filter) + continue; + self.removeFilter(self.exclusiveFilters[i][j]); + } + } + } + + var filters = self.currentFilters(); + filters.push(filter); + self.currentFilters(filters); + self._saveCurrentFiltersToLocalStorage(); + + self.changePage(0); + self._updateItems(); + } + + self.removeFilter = function(filter) { + if (!_.contains(_.keys(self.supportedFilters), filter)) + return; + + var filters = self.currentFilters(); + filters.pop(filter); + self.currentFilters(filters); + self._saveCurrentFiltersToLocalStorage(); + + self.changePage(0); + self._updateItems(); + } + + //~~ update for sorted and filtered view + + self._updateItems = function() { + // determine comparator + var comparator = undefined; + var currentSorting = self.currentSorting(); + if (typeof currentSorting !== undefined && typeof self.supportedSorting[currentSorting] !== undefined) { + comparator = self.supportedSorting[currentSorting]; + } + + // work on all items + var result = self.allItems; + + // filter if necessary + var filters = self.currentFilters(); + _.each(filters, function(filter) { + if (typeof filter !== undefined && typeof supportedFilters[filter] !== undefined) + result = _.filter(result, supportedFilters[filter]); + }); + + // sort if necessary + if (typeof comparator !== undefined) + result.sort(comparator); + + // set result list + self.items(result); + } + + //~~ local storage + + self._saveCurrentSortingToLocalStorage = function() { + if ( self._initializeLocalStorage() ) { + var currentSorting = self.currentSorting(); + if (currentSorting !== undefined) + localStorage[self.listType + "." + "currentSorting"] = currentSorting; + else + localStorage[self.listType + "." + "currentSorting"] = undefined; + } + } + + self._loadCurrentSortingFromLocalStorage = function() { + if ( self._initializeLocalStorage() ) { + if (_.contains(_.keys(supportedSorting), localStorage[self.listType + "." + "currentSorting"])) + self.currentSorting(localStorage[self.listType + "." + "currentSorting"]); + else + self.currentSorting(defaultSorting); + } + } + + self._saveCurrentFiltersToLocalStorage = function() { + if ( self._initializeLocalStorage() ) { + var filters = _.intersection(_.keys(self.supportedFilters), self.currentFilters()); + localStorage[self.listType + "." + "currentFilters"] = JSON.stringify(filters); + } + } + + self._loadCurrentFiltersFromLocalStorage = function() { + if ( self._initializeLocalStorage() ) { + self.currentFilters(_.intersection(_.keys(self.supportedFilters), JSON.parse(localStorage[self.listType + "." + "currentFilters"]))); + } + } + + self._initializeLocalStorage = function() { + if (!Modernizr.localstorage) + return false; + + if (localStorage[self.listType + "." + "currentSorting"] !== undefined && localStorage[self.listType + "." + "currentFilters"] !== undefined && JSON.parse(localStorage[self.listType + "." + "currentFilters"]) instanceof Array) + return true; + + localStorage[self.listType + "." + "currentSorting"] = self.defaultSorting; + localStorage[self.listType + "." + "currentFilters"] = JSON.stringify(self.defaultFilters); + + return true; + } + + self._loadCurrentFiltersFromLocalStorage(); + self._loadCurrentSortingFromLocalStorage(); +} diff --git a/octoprint/static/js/app/main.js b/octoprint/static/js/app/main.js new file mode 100644 index 000000000..ee11483fd --- /dev/null +++ b/octoprint/static/js/app/main.js @@ -0,0 +1,271 @@ +$(function() { + + //~~ Initialize view models + var loginStateViewModel = new LoginStateViewModel(); + var usersViewModel = new UsersViewModel(loginStateViewModel); + var settingsViewModel = new SettingsViewModel(loginStateViewModel, usersViewModel); + var connectionViewModel = new ConnectionViewModel(loginStateViewModel, settingsViewModel); + var timelapseViewModel = new TimelapseViewModel(loginStateViewModel); + var printerStateViewModel = new PrinterStateViewModel(loginStateViewModel, timelapseViewModel); + var appearanceViewModel = new AppearanceViewModel(settingsViewModel); + var temperatureViewModel = new TemperatureViewModel(loginStateViewModel, settingsViewModel); + var controlViewModel = new ControlViewModel(loginStateViewModel, settingsViewModel); + var terminalViewModel = new TerminalViewModel(loginStateViewModel, settingsViewModel); + var gcodeFilesViewModel = new GcodeFilesViewModel(printerStateViewModel, loginStateViewModel); + var gcodeViewModel = new GcodeViewModel(loginStateViewModel); + var navigationViewModel = new NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel); + + var dataUpdater = new DataUpdater( + loginStateViewModel, + connectionViewModel, + printerStateViewModel, + temperatureViewModel, + controlViewModel, + terminalViewModel, + gcodeFilesViewModel, + timelapseViewModel, + gcodeViewModel + ); + + // work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at + // http://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results + $.ajaxSetup({ + type: 'POST', + headers: { "cache-control": "no-cache" } + }); + + //~~ Show settings - to ensure centered + $('#navbar_show_settings').click(function() { + $('#settings_dialog').modal() + .css({ + width: 'auto', + 'margin-left': function() { return -($(this).width() /2); } + }); + return false; + }); + + //~~ Temperature + + $('#tabs a[data-toggle="tab"]').on('shown', function (e) { + temperatureViewModel.updatePlot(); + terminalViewModel.updateOutput(); + }); + + //~~ Gcode upload + + function gcode_upload_done(e, data) { + gcodeFilesViewModel.fromResponse(data.result); + $("#gcode_upload_progress .bar").css("width", "0%"); + $("#gcode_upload_progress").removeClass("progress-striped").removeClass("active"); + $("#gcode_upload_progress .bar").text(""); + } + + function gcode_upload_fail(e, data) { + $.pnotify({ + title: "Upload failed", + text: "

Could not upload the file. Make sure it is a GCODE file and has one of the following extensions: .gcode, .gco

Server reported:

" + data.jqXHR.responseText + "

", + type: "error", + hide: false + }); + $("#gcode_upload_progress .bar").css("width", "0%"); + $("#gcode_upload_progress").removeClass("progress-striped").removeClass("active"); + $("#gcode_upload_progress .bar").text(""); + } + + function gcode_upload_progress(e, data) { + var progress = parseInt(data.loaded / data.total * 100, 10); + $("#gcode_upload_progress .bar").css("width", progress + "%"); + $("#gcode_upload_progress .bar").text("Uploading ..."); + if (progress >= 100) { + $("#gcode_upload_progress").addClass("progress-striped").addClass("active"); + $("#gcode_upload_progress .bar").text("Saving ..."); + } + } + + var localTarget; + if (CONFIG_SD_SUPPORT) { + localTarget = $("#drop_locally"); + } else { + localTarget = $("#drop"); + } + + $("#gcode_upload").fileupload({ + dataType: "json", + dropZone: localTarget, + formData: {target: "local"}, + done: gcode_upload_done, + fail: gcode_upload_fail, + progressall: gcode_upload_progress + }); + + if (CONFIG_SD_SUPPORT) { + $("#gcode_upload_sd").fileupload({ + dataType: "json", + dropZone: $("#drop_sd"), + formData: {target: "sd"}, + done: gcode_upload_done, + fail: gcode_upload_fail, + progressall: gcode_upload_progress + }); + } + + $(document).bind("dragover", function (e) { + var dropOverlay = $("#drop_overlay"); + var dropZone = $("#drop"); + var dropZoneLocal = $("#drop_locally"); + var dropZoneSd = $("#drop_sd"); + var dropZoneBackground = $("#drop_background"); + var dropZoneLocalBackground = $("#drop_locally_background"); + var dropZoneSdBackground = $("#drop_sd_background"); + var timeout = window.dropZoneTimeout; + + if (!timeout) { + dropOverlay.addClass('in'); + } else { + clearTimeout(timeout); + } + + var foundLocal = false; + var foundSd = false; + var found = false + var node = e.target; + do { + if (dropZoneLocal && node === dropZoneLocal[0]) { + foundLocal = true; + break; + } else if (dropZoneSd && node === dropZoneSd[0]) { + foundSd = true; + break; + } else if (dropZone && node === dropZone[0]) { + found = true; + break; + } + node = node.parentNode; + } while (node != null); + + if (foundLocal) { + dropZoneLocalBackground.addClass("hover"); + dropZoneSdBackground.removeClass("hover"); + } else if (foundSd) { + dropZoneSdBackground.addClass("hover"); + dropZoneLocalBackground.removeClass("hover"); + } else if (found) { + dropZoneBackground.addClass("hover"); + } else { + if (dropZoneLocalBackground) dropZoneLocalBackground.removeClass("hover"); + if (dropZoneSdBackground) dropZoneSdBackground.removeClass("hover"); + if (dropZoneBackground) dropZoneBackground.removeClass("hover"); + } + + window.dropZoneTimeout = setTimeout(function () { + window.dropZoneTimeout = null; + dropOverlay.removeClass("in"); + if (dropZoneLocal) dropZoneLocalBackground.removeClass("hover"); + if (dropZoneSd) dropZoneSdBackground.removeClass("hover"); + if (dropZone) dropZoneBackground.removeClass("hover"); + }, 100); + }); + + //~~ Offline overlay + $("#offline_overlay_reconnect").click(function() {dataUpdater.reconnect()}); + + //~~ knockout.js bindings + + ko.bindingHandlers.popover = { + init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var val = ko.utils.unwrapObservable(valueAccessor()); + + var options = { + title: val.title, + animation: val.animation, + placement: val.placement, + trigger: val.trigger, + delay: val.delay, + content: val.content, + html: val.html + }; + $(element).popover(options); + } + } + + ko.applyBindings(connectionViewModel, document.getElementById("connection_accordion")); + ko.applyBindings(printerStateViewModel, document.getElementById("state_accordion")); + ko.applyBindings(gcodeFilesViewModel, document.getElementById("files_accordion")); + ko.applyBindings(temperatureViewModel, document.getElementById("temp")); + ko.applyBindings(controlViewModel, document.getElementById("control")); + ko.applyBindings(terminalViewModel, document.getElementById("term")); + var gcode = document.getElementById("gcode"); + if (gcode) { + ko.applyBindings(gcodeViewModel, gcode); + } + ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog")); + ko.applyBindings(navigationViewModel, document.getElementById("navbar")); + ko.applyBindings(appearanceViewModel, document.getElementsByTagName("head")[0]); + ko.applyBindings(loginStateViewModel, document.getElementById("drop_overlay")); + + var timelapseElement = document.getElementById("timelapse"); + if (timelapseElement) { + ko.applyBindings(timelapseViewModel, timelapseElement); + } + var gCodeVisualizerElement = document.getElementById("gcode"); + if (gCodeVisualizerElement) { + gcodeViewModel.initialize(); + } + + //~~ startup commands + + loginStateViewModel.requestData(); + connectionViewModel.requestData(); + controlViewModel.requestData(); + gcodeFilesViewModel.requestData(); + timelapseViewModel.requestData(); + + loginStateViewModel.subscribe(function(change, data) { + if ("login" == change) { + $("#gcode_upload").fileupload("enable"); + + settingsViewModel.requestData(); + if (data.admin) { + usersViewModel.requestData(); + } + } else { + $("#gcode_upload").fileupload("disable"); + } + }); + + //~~ UI stuff + + $(".accordion-toggle[href='#files']").click(function() { + if ($("#files").hasClass("in")) { + $("#files").removeClass("overflow_visible"); + } else { + setTimeout(function() { + $("#files").addClass("overflow_visible"); + }, 1000); + } + }) + + $.pnotify.defaults.history = false; + + $.fn.modal.defaults.maxHeight = function(){ + // subtract the height of the modal header and footer + return $(window).height() - 165; + } + + // Fix input element click problem on login dialog + $(".dropdown input, .dropdown label").click(function(e) { + e.stopPropagation(); + }); + + $(document).bind("drop dragover", function (e) { + e.preventDefault(); + }); + + if (CONFIG_FIRST_RUN) { + var firstRunViewModel = new FirstRunViewModel(); + ko.applyBindings(firstRunViewModel, document.getElementById("first_run_dialog")); + firstRunViewModel.showDialog(); + } + } +); + diff --git a/octoprint/static/js/app/viewmodels/appearance.js b/octoprint/static/js/app/viewmodels/appearance.js new file mode 100644 index 000000000..fc09c9ee4 --- /dev/null +++ b/octoprint/static/js/app/viewmodels/appearance.js @@ -0,0 +1,20 @@ +function AppearanceViewModel(settingsViewModel) { + var self = this; + + self.name = settingsViewModel.appearance_name; + self.color = settingsViewModel.appearance_color; + + self.brand = ko.computed(function() { + if (self.name()) + return "OctoPrint: " + self.name(); + else + return "OctoPrint"; + }) + + self.title = ko.computed(function() { + if (self.name()) + return self.name() + " [OctoPrint]"; + else + return "OctoPrint"; + }) +} diff --git a/octoprint/static/js/app/viewmodels/connection.js b/octoprint/static/js/app/viewmodels/connection.js new file mode 100644 index 000000000..9baa9c4f7 --- /dev/null +++ b/octoprint/static/js/app/viewmodels/connection.js @@ -0,0 +1,115 @@ +function ConnectionViewModel(loginStateViewModel, settingsViewModel) { + var self = this; + + self.loginState = loginStateViewModel; + self.settings = settingsViewModel; + + self.portOptions = ko.observableArray(undefined); + self.baudrateOptions = ko.observableArray(undefined); + self.selectedPort = ko.observable(undefined); + self.selectedBaudrate = ko.observable(undefined); + self.saveSettings = ko.observable(undefined); + + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); + + self.buttonText = ko.computed(function() { + if (self.isErrorOrClosed()) + return "Connect"; + else + return "Disconnect"; + }) + + self.previousIsOperational = undefined; + + self.requestData = function() { + $.ajax({ + url: AJAX_BASEURL + "control/connection/options", + method: "GET", + dataType: "json", + success: function(response) { + self.fromResponse(response); + } + }) + } + + self.fromResponse = function(response) { + self.portOptions(response.ports); + self.baudrateOptions(response.baudrates); + + if (!self.selectedPort() && response.ports && response.ports.indexOf(response.portPreference) >= 0) + self.selectedPort(response.portPreference); + if (!self.selectedBaudrate() && response.baudrates && response.baudrates.indexOf(response.baudratePreference) >= 0) + self.selectedBaudrate(response.baudratePreference); + + self.saveSettings(false); + } + + self.fromHistoryData = function(data) { + self._processStateData(data.state); + } + + self.fromCurrentData = function(data) { + self._processStateData(data.state); + } + + self._processStateData = function(data) { + self.previousIsOperational = self.isOperational(); + + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isLoading(data.flags.loading); + + var connectionTab = $("#connection"); + if (self.previousIsOperational != self.isOperational()) { + if (self.isOperational() && connectionTab.hasClass("in")) { + // connection just got established, close connection tab for now + connectionTab.collapse("hide"); + } else if (!connectionTab.hasClass("in")) { + // connection just dropped, make sure connection tab is open + connectionTab.collapse("show"); + } + } + } + + self.connect = function() { + if (self.isErrorOrClosed()) { + var data = { + "command": "connect", + "port": self.selectedPort(), + "baudrate": self.selectedBaudrate() + }; + + if (self.saveSettings()) + data["save"] = true; + + $.ajax({ + url: AJAX_BASEURL + "control/connection", + type: "POST", + dataType: "json", + data: data + }) + + self.settings.serial_port(self.selectedPort()) + self.settings.serial_baudrate(self.selectedBaudrate()) + self.settings.saveData(); + } else { + self.requestData(); + $.ajax({ + url: AJAX_BASEURL + "control/connection", + type: "POST", + dataType: "json", + data: {"command": "disconnect"} + }) + } + } +} diff --git a/octoprint/static/js/app/viewmodels/control.js b/octoprint/static/js/app/viewmodels/control.js new file mode 100644 index 000000000..3f89d570d --- /dev/null +++ b/octoprint/static/js/app/viewmodels/control.js @@ -0,0 +1,172 @@ +function ControlViewModel(loginStateViewModel, settingsViewModel) { + var self = this; + + self.loginState = loginStateViewModel; + self.settings = settingsViewModel; + + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); + + self.extrusionAmount = ko.observable(undefined); + self.controls = ko.observableArray([]); + + self.feedbackControlLookup = {}; + + self.fromCurrentData = function(data) { + self._processStateData(data.state); + } + + self.fromHistoryData = function(data) { + self._processStateData(data.state); + } + + self._processStateData = function(data) { + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isLoading(data.flags.loading); + } + + self.fromFeedbackCommandData = function(data) { + if (data.name in self.feedbackControlLookup) { + self.feedbackControlLookup[data.name](data.output); + } + } + + self.requestData = function() { + $.ajax({ + url: AJAX_BASEURL + "control/custom", + method: "GET", + dataType: "json", + success: function(response) { + self._fromResponse(response); + } + }); + } + + self._fromResponse = function(response) { + self.controls(self._processControls(response.controls)); + } + + self._processControls = function(controls) { + for (var i = 0; i < controls.length; i++) { + controls[i] = self._processControl(controls[i]); + } + return controls; + } + + self._processControl = function(control) { + if (control.type == "parametric_command" || control.type == "parametric_commands") { + for (var i = 0; i < control.input.length; i++) { + control.input[i].value = control.input[i].default; + } + } else if (control.type == "feedback_command" || control.type == "feedback") { + control.output = ko.observable(""); + self.feedbackControlLookup[control.name] = control.output; + } else if (control.type == "section") { + control.children = self._processControls(control.children); + } + return control; + } + + self.sendJogCommand = function(axis, multiplier, distance) { + if (typeof distance === "undefined") + distance = $('#jog_distance button.active').data('distance'); + $.ajax({ + url: AJAX_BASEURL + "control/jog", + type: "POST", + dataType: "json", + data: axis + "=" + ( distance * multiplier ) + }) + } + + self.sendHomeCommand = function(axis) { + $.ajax({ + url: AJAX_BASEURL + "control/jog", + type: "POST", + dataType: "json", + data: "home" + axis + }) + } + + self.sendExtrudeCommand = function() { + self._sendECommand(1); + } + + self.sendRetractCommand = function() { + self._sendECommand(-1); + } + + self._sendECommand = function(dir) { + var length = self.extrusionAmount(); + if (!length) + length = 5; + $.ajax({ + url: AJAX_BASEURL + "control/jog", + type: "POST", + dataType: "json", + data: "extrude=" + (dir * length) + }) + } + + self.sendCustomCommand = function(command) { + if (!command) + return; + + var data = undefined; + if (command.type == "command" || command.type == "parametric_command" || command.type == "feedback_command") { + // single command + data = {"command" : command.command}; + } else if (command.type == "commands" || command.type == "parametric_commands") { + // multi command + data = {"commands": command.commands}; + } + + if (command.type == "parametric_command" || command.type == "parametric_commands") { + // parametric command(s) + data["parameters"] = {}; + for (var i = 0; i < command.input.length; i++) { + data["parameters"][command.input[i].parameter] = command.input[i].value; + } + } + + if (!data) + return; + + $.ajax({ + url: AJAX_BASEURL + "control/command", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data) + }) + } + + self.displayMode = function(customControl) { + switch (customControl.type) { + case "section": + return "customControls_sectionTemplate"; + case "command": + case "commands": + return "customControls_commandTemplate"; + case "parametric_command": + case "parametric_commands": + return "customControls_parametricCommandTemplate"; + case "feedback_command": + return "customControls_feedbackCommandTemplate"; + case "feedback": + return "customControls_feedbackTemplate"; + default: + return "customControls_emptyTemplate"; + } + } + +} diff --git a/octoprint/static/js/app/viewmodels/firstrun.js b/octoprint/static/js/app/viewmodels/firstrun.js new file mode 100644 index 000000000..8697547e3 --- /dev/null +++ b/octoprint/static/js/app/viewmodels/firstrun.js @@ -0,0 +1,75 @@ +function FirstRunViewModel() { + var self = this; + + self.username = ko.observable(undefined); + self.password = ko.observable(undefined); + self.confirmedPassword = ko.observable(undefined); + + self.passwordMismatch = ko.computed(function() { + return self.password() != self.confirmedPassword(); + }); + + self.validUsername = ko.computed(function() { + return self.username() && self.username().trim() != ""; + }); + + self.validPassword = ko.computed(function() { + return self.password() && self.password().trim() != ""; + }); + + self.validData = ko.computed(function() { + return !self.passwordMismatch() && self.validUsername() && self.validPassword(); + }); + + self.keepAccessControl = function() { + if (!self.validData()) return; + + var data = { + "ac": true, + "user": self.username(), + "pass1": self.password(), + "pass2": self.confirmedPassword() + }; + self._sendData(data); + }; + + self.disableAccessControl = function() { + $("#confirmation_dialog .confirmation_dialog_message").html("If you disable Access Control and your OctoPrint " + + "installation is accessible from the internet, your printer will be accessible by everyone - " + + "that also includes the bad guys!"); + $("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) { + e.preventDefault(); + $("#confirmation_dialog").modal("hide"); + + var data = { + "ac": false + }; + self._sendData(data, function() { + // if the user indeed disables access control, we'll need to reload the page for this to take effect + location.reload(); + }); + }); + $("#confirmation_dialog").modal("show"); + }; + + self._sendData = function(data, callback) { + $.ajax({ + url: AJAX_BASEURL + "setup", + type: "POST", + dataType: "json", + data: data, + success: function() { + self.closeDialog(); + if (callback) callback(); + } + }); + } + + self.showDialog = function() { + $("#first_run_dialog").modal("show"); + } + + self.closeDialog = function() { + $("#first_run_dialog").modal("hide"); + } +} diff --git a/octoprint/static/js/app/viewmodels/gcode.js b/octoprint/static/js/app/viewmodels/gcode.js new file mode 100644 index 000000000..80f362a0a --- /dev/null +++ b/octoprint/static/js/app/viewmodels/gcode.js @@ -0,0 +1,75 @@ +function GcodeViewModel(loginStateViewModel) { + var self = this; + + self.loginState = loginStateViewModel; + + self.loadedFilename = undefined; + self.loadedFileMTime = undefined; + self.status = 'idle'; + self.enabled = false; + + self.errorCount = 0; + + self.initialize = function(){ + self.enabled = true; + GCODE.ui.initHandlers(); + } + + self.loadFile = function(filename, mtime){ + if (self.status == 'idle' && self.errorCount < 3) { + self.status = 'request'; + $.ajax({ + url: "/downloads/gcode/" + filename, + data: { "mtime": mtime }, + type: "GET", + success: function(response, rstatus) { + if(rstatus === 'success'){ + self.showGCodeViewer(response, rstatus); + self.loadedFilename=filename; + self.loadedFileMTime=mtime; + self.status = 'idle'; + } + }, + error: function() { + self.status = 'idle'; + self.errorCount++; + } + }) + } + } + + self.showGCodeViewer = function(response, rstatus) { + var par = {}; + par.target = {}; + par.target.result = response; + GCODE.gCodeReader.loadFile(par); + } + + self.fromHistoryData = function(data) { + self._processData(data); + } + + self.fromCurrentData = function(data) { + self._processData(data); + } + + self._processData = function(data) { + if (!self.enabled) return; + if (!data.job.filename) return; + + if(self.loadedFilename && self.loadedFilename == data.job.filename && + self.loadedFileMTime == data.job.mtime) { + if (data.state.flags && (data.state.flags.printing || data.state.flags.paused)) { + var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(data.progress.progress * 100); + if(cmdIndex){ + GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd); + GCODE.ui.updateLayerInfo(cmdIndex.layer); + } + } + self.errorCount = 0 + } else if (data.job.filename) { + self.loadFile(data.job.filename, data.job.mtime); + } + } + +} diff --git a/octoprint/static/js/app/viewmodels/gcodefiles.js b/octoprint/static/js/app/viewmodels/gcodefiles.js new file mode 100644 index 000000000..fdf2c4115 --- /dev/null +++ b/octoprint/static/js/app/viewmodels/gcodefiles.js @@ -0,0 +1,202 @@ +function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) { + var self = this; + + self.printerState = printerStateViewModel; + self.loginState = loginStateViewModel; + + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); + self.isSdReady = ko.observable(undefined); + + self.freeSpace = ko.observable(undefined); + + // initialize list helper + self.listHelper = new ItemListHelper( + "gcodeFiles", + { + "name": function(a, b) { + // sorts ascending + if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; + if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; + return 0; + }, + "upload": function(a, b) { + // sorts descending + if (b["date"] === undefined || a["date"] > b["date"]) return -1; + if (a["date"] < b["date"]) return 1; + return 0; + }, + "size": function(a, b) { + // sorts descending + if (b["bytes"] === undefined || a["bytes"] > b["bytes"]) return -1; + if (a["bytes"] < b["bytes"]) return 1; + return 0; + } + }, + { + "printed": function(file) { + return !(file["prints"] && file["prints"]["success"] && file["prints"]["success"] > 0); + }, + "sd": function(file) { + return file["origin"] && file["origin"] == "sd"; + }, + "local": function(file) { + return !(file["origin"] && file["origin"] == "sd"); + } + }, + "name", + [], + [["sd", "local"]], + CONFIG_GCODEFILESPERPAGE + ); + + self.isLoadActionPossible = ko.computed(function() { + return self.loginState.isUser() && !self.isPrinting() && !self.isPaused() && !self.isLoading(); + }); + + self.isLoadAndPrintActionPossible = ko.computed(function() { + return self.loginState.isUser() && self.isOperational() && self.isLoadActionPossible(); + }); + + self.printerState.filename.subscribe(function(newValue) { + self.highlightFilename(newValue); + }); + + self.highlightFilename = function(filename) { + if (filename == undefined) { + self.listHelper.selectNone(); + } else { + self.listHelper.selectItem(function(item) { + return item.name == filename; + }) + } + } + + self.fromCurrentData = function(data) { + self._processStateData(data.state); + } + + self.fromHistoryData = function(data) { + self._processStateData(data.state); + } + + self._processStateData = function(data) { + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isLoading(data.flags.loading); + self.isSdReady(data.flags.sdReady); + } + + self.requestData = function() { + $.ajax({ + url: AJAX_BASEURL + "gcodefiles", + method: "GET", + dataType: "json", + success: function(response) { + self.fromResponse(response); + } + }); + } + + self.fromResponse = function(response) { + self.listHelper.updateItems(response.files); + + if (response.filename) { + // got a file to scroll to + self.listHelper.switchToItem(function(item) {return item.name == response.filename}); + } + + self.freeSpace(response.free); + + self.highlightFilename(self.printerState.filename()); + } + + self.loadFile = function(filename, printAfterLoad) { + var file = self.listHelper.getItem(function(item) {return item.name == filename}); + if (!file) return; + + $.ajax({ + url: AJAX_BASEURL + "gcodefiles/load", + type: "POST", + dataType: "json", + data: {filename: filename, print: printAfterLoad, target: file.origin} + }) + } + + self.removeFile = function(filename) { + var file = self.listHelper.getItem(function(item) {return item.name == filename}); + if (!file) return; + + $.ajax({ + url: AJAX_BASEURL + "gcodefiles/delete", + type: "POST", + dataType: "json", + data: {filename: filename, target: file.origin}, + success: self.fromResponse + }) + } + + self.initSdCard = function() { + self._sendSdCommand("init"); + } + + self.releaseSdCard = function() { + self._sendSdCommand("release"); + } + + self.refreshSdFiles = function() { + self._sendSdCommand("refresh"); + } + + self._sendSdCommand = function(command) { + $.ajax({ + url: AJAX_BASEURL + "control/sd", + type: "POST", + dataType: "json", + data: {command: command} + }); + } + + self.getPopoverContent = function(data) { + var output = "

Uploaded: " + data["date"] + "

"; + if (data["gcodeAnalysis"]) { + output += "

"; + output += "Filament: " + data["gcodeAnalysis"]["filament"] + "
"; + output += "Estimated Print Time: " + data["gcodeAnalysis"]["estimatedPrintTime"]; + output += "

"; + } + if (data["prints"] && data["prints"]["last"]) { + output += "

"; + output += "Last Print: " + data["prints"]["last"]["date"] + ""; + output += "

"; + } + return output; + } + + self.getSuccessClass = function(data) { + if (!data["prints"] || !data["prints"]["last"]) { + return ""; + } + return data["prints"]["last"]["success"] ? "text-success" : "text-error"; + } + + self.enableRemove = function(data) { + return self.loginState.isUser() && !(self.listHelper.isSelected(data) && (self.isPrinting() || self.isPaused())); + } + + self.enableSelect = function(data, printAfterSelect) { + var isLoadActionPossible = self.loginState.isUser() && self.isOperational() && !(self.isPrinting() || self.isPaused() || self.isLoading()); + return isLoadActionPossible && !self.listHelper.isSelected(data); + } + +} + diff --git a/octoprint/static/js/app/viewmodels/loginstate.js b/octoprint/static/js/app/viewmodels/loginstate.js new file mode 100644 index 000000000..75882b686 --- /dev/null +++ b/octoprint/static/js/app/viewmodels/loginstate.js @@ -0,0 +1,89 @@ +function LoginStateViewModel() { + var self = this; + + self.loggedIn = ko.observable(false); + self.username = ko.observable(undefined); + self.isAdmin = ko.observable(false); + self.isUser = ko.observable(false); + + self.currentUser = ko.observable(undefined); + + self.userMenuText = ko.computed(function() { + if (self.loggedIn()) { + return "\"" + self.username() + "\""; + } else { + return "Login"; + } + }) + + self.subscribers = []; + self.subscribe = function(callback) { + if (callback === undefined) return; + self.subscribers.push(callback); + } + + self.requestData = function() { + $.ajax({ + url: AJAX_BASEURL + "login", + type: "POST", + data: {"passive": true}, + success: self.fromResponse + }) + } + + self.fromResponse = function(response) { + if (response && response.name) { + self.loggedIn(true); + self.username(response.name); + self.isUser(response.user); + self.isAdmin(response.admin); + + self.currentUser(response); + + _.each(self.subscribers, function(callback) { callback("login", response); }); + } else { + self.loggedIn(false); + self.username(undefined); + self.isUser(false); + self.isAdmin(false); + + self.currentUser(undefined); + + _.each(self.subscribers, function(callback) { callback("logout", {}); }); + } + } + + self.login = function() { + var username = $("#login_user").val(); + var password = $("#login_pass").val(); + var remember = $("#login_remember").is(":checked"); + + $("#login_user").val(""); + $("#login_pass").val(""); + $("#login_remember").prop("checked", false); + + $.ajax({ + url: AJAX_BASEURL + "login", + type: "POST", + data: {"user": username, "pass": password, "remember": remember}, + success: function(response) { + $.pnotify({title: "Login successful", text: "You are now logged in as \"" + response.name + "\"", type: "success"}); + self.fromResponse(response); + }, + error: function(jqXHR, textStatus, errorThrown) { + $.pnotify({title: "Login failed", text: "User unknown or wrong password", type: "error"}); + } + }) + } + + self.logout = function() { + $.ajax({ + url: AJAX_BASEURL + "logout", + type: "POST", + success: function(response) { + $.pnotify({title: "Logout successful", text: "You are now logged out", type: "success"}); + self.fromResponse(response); + } + }) + } +} diff --git a/octoprint/static/js/app/viewmodels/navigation.js b/octoprint/static/js/app/viewmodels/navigation.js new file mode 100644 index 000000000..c12ce0ed5 --- /dev/null +++ b/octoprint/static/js/app/viewmodels/navigation.js @@ -0,0 +1,33 @@ +function NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel) { + var self = this; + + self.loginState = loginStateViewModel; + self.appearance = appearanceViewModel; + self.systemActions = settingsViewModel.system_actions; + self.users = usersViewModel; + + self.triggerAction = function(action) { + var callback = function() { + $.ajax({ + url: AJAX_BASEURL + "system", + type: "POST", + dataType: "json", + data: "action=" + action.action, + success: function() { + $.pnotify({title: "Success", text: "The command \""+ action.name +"\" executed successfully", type: "success"}); + }, + error: function(jqXHR, textStatus, errorThrown) { + $.pnotify({title: "Error", text: "

The command \"" + action.name + "\" could not be executed.

Reason:

" + jqXHR.responseText + "

", type: "error"}); + } + }) + } + if (action.confirm) { + $("#confirmation_dialog .confirmation_dialog_message").text(action.confirm); + $("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {e.preventDefault(); $("#confirmation_dialog").modal("hide"); callback(); }); + $("#confirmation_dialog").modal("show"); + } else { + callback(); + } + } +} + diff --git a/octoprint/static/js/app/viewmodels/printerstate.js b/octoprint/static/js/app/viewmodels/printerstate.js new file mode 100644 index 000000000..6779d15b2 --- /dev/null +++ b/octoprint/static/js/app/viewmodels/printerstate.js @@ -0,0 +1,153 @@ +function PrinterStateViewModel(loginStateViewModel) { + var self = this; + + self.loginState = loginStateViewModel; + + self.stateString = ko.observable(undefined); + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); + self.isSdReady = ko.observable(undefined); + + self.filename = ko.observable(undefined); + self.progress = ko.observable(undefined); + self.filesize = ko.observable(undefined); + self.filepos = ko.observable(undefined); + self.printTime = ko.observable(undefined); + self.printTimeLeft = ko.observable(undefined); + self.sd = ko.observable(undefined); + self.timelapse = ko.observable(undefined); + + self.filament = ko.observable(undefined); + self.estimatedPrintTime = ko.observable(undefined); + + self.currentHeight = ko.observable(undefined); + + self.byteString = ko.computed(function() { + if (!self.filesize()) + return "-"; + var filepos = self.filepos() ? self.filepos() : "-"; + return filepos + " / " + self.filesize(); + }); + self.heightString = ko.computed(function() { + if (!self.currentHeight()) + return "-"; + return self.currentHeight(); + }) + self.progressString = ko.computed(function() { + if (!self.progress()) + return 0; + return self.progress(); + }); + self.pauseString = ko.computed(function() { + if (self.isPaused()) + return "Continue"; + else + return "Pause"; + }); + + self.timelapseString = ko.computed(function() { + var timelapse = self.timelapse(); + + if (!timelapse || !timelapse.hasOwnProperty("type")) + return "-"; + + var type = timelapse["type"]; + if (type == "zchange") { + return "On Z Change"; + } else if (type == "timed") { + return "Timed (" + timelapse["options"]["interval"] + "s)"; + } else { + return "-"; + } + }); + + self.fromCurrentData = function(data) { + self._fromData(data); + } + + self.fromHistoryData = function(data) { + self._fromData(data); + } + + self.fromTimelapseData = function(data) { + self.timelapse(data); + } + + self._fromData = function(data) { + self._processStateData(data.state) + self._processJobData(data.job); + self._processProgressData(data.progress); + self._processZData(data.currentZ); + } + + self._processStateData = function(data) { + self.stateString(data.stateString); + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isSdReady(data.flags.sdReady); + } + + self._processJobData = function(data) { + self.filename(data.filename); + self.filesize(data.filesize); + self.estimatedPrintTime(data.estimatedPrintTime); + self.filament(data.filament); + self.sd(data.sd); + } + + self._processProgressData = function(data) { + if (data.progress) { + self.progress(Math.round(data.progress * 100)); + } else { + self.progress(undefined); + } + self.filepos(data.filepos); + self.printTime(data.printTime); + self.printTimeLeft(data.printTimeLeft); + } + + self._processZData = function(data) { + self.currentHeight(data); + } + + self.print = function() { + var printAction = function() { + self._jobCommand("start"); + } + + if (self.isPaused()) { + $("#confirmation_dialog .confirmation_dialog_message").text("This will restart the print job from the beginning."); + $("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {e.preventDefault(); $("#confirmation_dialog").modal("hide"); printAction(); }); + $("#confirmation_dialog").modal("show"); + } else { + printAction(); + } + + } + + self.pause = function() { + self._jobCommand("pause"); + } + + self.cancel = function() { + self._jobCommand("cancel"); + } + + self._jobCommand = function(command) { + $.ajax({ + url: AJAX_BASEURL + "control/job", + type: "POST", + dataType: "json", + data: {command: command} + }); + } +} diff --git a/octoprint/static/js/app/viewmodels/settings.js b/octoprint/static/js/app/viewmodels/settings.js new file mode 100644 index 000000000..c8cdd2149 --- /dev/null +++ b/octoprint/static/js/app/viewmodels/settings.js @@ -0,0 +1,201 @@ +function SettingsViewModel(loginStateViewModel, usersViewModel) { + var self = this; + + self.loginState = loginStateViewModel; + self.users = usersViewModel; + + self.api_enabled = ko.observable(undefined); + self.api_key = ko.observable(undefined); + + self.appearance_name = ko.observable(undefined); + self.appearance_color = ko.observable(undefined); + + /* I did attempt to allow arbitrary gradients but cross browser support via knockout or jquery was going to be horrible */ + self.appearance_available_colors = ko.observable(["default", "red", "orange", "yellow", "green", "blue", "violet", "black"]); + + self.printer_movementSpeedX = ko.observable(undefined); + self.printer_movementSpeedY = ko.observable(undefined); + self.printer_movementSpeedZ = ko.observable(undefined); + self.printer_movementSpeedE = ko.observable(undefined); + + self.webcam_streamUrl = ko.observable(undefined); + self.webcam_snapshotUrl = ko.observable(undefined); + self.webcam_ffmpegPath = ko.observable(undefined); + self.webcam_bitrate = ko.observable(undefined); + self.webcam_watermark = ko.observable(undefined); + self.webcam_flipH = ko.observable(undefined); + self.webcam_flipV = ko.observable(undefined); + + self.feature_gcodeViewer = ko.observable(undefined); + self.feature_temperatureGraph = ko.observable(undefined); + self.feature_waitForStart = ko.observable(undefined); + self.feature_alwaysSendChecksum = ko.observable(undefined); + self.feature_sdSupport = ko.observable(undefined); + self.feature_swallowOkAfterResend = ko.observable(undefined); + + self.serial_port = ko.observable(); + self.serial_baudrate = ko.observable(); + self.serial_portOptions = ko.observableArray([]); + self.serial_baudrateOptions = ko.observableArray([]); + self.serial_autoconnect = ko.observable(undefined); + self.serial_timeoutConnection = ko.observable(undefined); + self.serial_timeoutDetection = ko.observable(undefined); + self.serial_timeoutCommunication = ko.observable(undefined); + self.serial_log = ko.observable(undefined); + + self.folder_uploads = ko.observable(undefined); + self.folder_timelapse = ko.observable(undefined); + self.folder_timelapseTmp = ko.observable(undefined); + self.folder_logs = ko.observable(undefined); + + self.temperature_profiles = ko.observableArray(undefined); + + self.system_actions = ko.observableArray([]); + + self.terminalFilters = ko.observableArray([]); + + self.addTemperatureProfile = function() { + self.temperature_profiles.push({name: "New", extruder:0, bed:0}); + }; + + self.removeTemperatureProfile = function(profile) { + self.temperature_profiles.remove(profile); + }; + + self.addTerminalFilter = function() { + self.terminalFilters.push({name: "New", regex: "(Send: M105)|(Recv: ok T:)"}) + }; + + self.removeTerminalFilter = function(filter) { + self.terminalFilters.remove(filter); + }; + + self.requestData = function() { + $.ajax({ + url: AJAX_BASEURL + "settings", + type: "GET", + dataType: "json", + success: self.fromResponse + }); + } + + self.fromResponse = function(response) { + self.api_enabled(response.api.enabled); + self.api_key(response.api.key); + + self.appearance_name(response.appearance.name); + self.appearance_color(response.appearance.color); + + self.printer_movementSpeedX(response.printer.movementSpeedX); + self.printer_movementSpeedY(response.printer.movementSpeedY); + self.printer_movementSpeedZ(response.printer.movementSpeedZ); + self.printer_movementSpeedE(response.printer.movementSpeedE); + + self.webcam_streamUrl(response.webcam.streamUrl); + self.webcam_snapshotUrl(response.webcam.snapshotUrl); + self.webcam_ffmpegPath(response.webcam.ffmpegPath); + self.webcam_bitrate(response.webcam.bitrate); + self.webcam_watermark(response.webcam.watermark); + self.webcam_flipH(response.webcam.flipH); + self.webcam_flipV(response.webcam.flipV); + + self.feature_gcodeViewer(response.feature.gcodeViewer); + self.feature_temperatureGraph(response.feature.temperatureGraph); + self.feature_waitForStart(response.feature.waitForStart); + self.feature_alwaysSendChecksum(response.feature.alwaysSendChecksum); + self.feature_sdSupport(response.feature.sdSupport); + self.feature_swallowOkAfterResend(response.feature.swallowOkAfterResend); + + self.serial_port(response.serial.port); + self.serial_baudrate(response.serial.baudrate); + self.serial_portOptions(response.serial.portOptions); + self.serial_baudrateOptions(response.serial.baudrateOptions); + self.serial_autoconnect(response.serial.autoconnect); + self.serial_timeoutConnection(response.serial.timeoutConnection); + self.serial_timeoutDetection(response.serial.timeoutDetection); + self.serial_timeoutCommunication(response.serial.timeoutCommunication); + self.serial_log(response.serial.log); + + self.folder_uploads(response.folder.uploads); + self.folder_timelapse(response.folder.timelapse); + self.folder_timelapseTmp(response.folder.timelapseTmp); + self.folder_logs(response.folder.logs); + + self.temperature_profiles(response.temperature.profiles); + + self.system_actions(response.system.actions); + + self.terminalFilters(response.terminalFilters); + } + + self.saveData = function() { + var data = { + "api" : { + "enabled": self.api_enabled(), + "key": self.api_key() + }, + "appearance" : { + "name": self.appearance_name(), + "color": self.appearance_color() + }, + "printer": { + "movementSpeedX": self.printer_movementSpeedX(), + "movementSpeedY": self.printer_movementSpeedY(), + "movementSpeedZ": self.printer_movementSpeedZ(), + "movementSpeedE": self.printer_movementSpeedE() + }, + "webcam": { + "streamUrl": self.webcam_streamUrl(), + "snapshotUrl": self.webcam_snapshotUrl(), + "ffmpegPath": self.webcam_ffmpegPath(), + "bitrate": self.webcam_bitrate(), + "watermark": self.webcam_watermark(), + "flipH": self.webcam_flipH(), + "flipV": self.webcam_flipV() + }, + "feature": { + "gcodeViewer": self.feature_gcodeViewer(), + "temperatureGraph": self.feature_temperatureGraph(), + "waitForStart": self.feature_waitForStart(), + "alwaysSendChecksum": self.feature_alwaysSendChecksum(), + "sdSupport": self.feature_sdSupport(), + "swallowOkAfterResend": self.feature_swallowOkAfterResend() + }, + "serial": { + "port": self.serial_port(), + "baudrate": self.serial_baudrate(), + "autoconnect": self.serial_autoconnect(), + "timeoutConnection": self.serial_timeoutConnection(), + "timeoutDetection": self.serial_timeoutDetection(), + "timeoutCommunication": self.serial_timeoutCommunication(), + "log": self.serial_log() + }, + "folder": { + "uploads": self.folder_uploads(), + "timelapse": self.folder_timelapse(), + "timelapseTmp": self.folder_timelapseTmp(), + "logs": self.folder_logs() + }, + "temperature": { + "profiles": self.temperature_profiles() + }, + "system": { + "actions": self.system_actions() + }, + "terminalFilters": self.terminalFilters() + } + + $.ajax({ + url: AJAX_BASEURL + "settings", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data), + success: function(response) { + self.fromResponse(response); + $("#settings_dialog").modal("hide"); + } + }) + } + +} diff --git a/octoprint/static/js/app/viewmodels/temperature.js b/octoprint/static/js/app/viewmodels/temperature.js new file mode 100644 index 000000000..6890914e4 --- /dev/null +++ b/octoprint/static/js/app/viewmodels/temperature.js @@ -0,0 +1,222 @@ +function TemperatureViewModel(loginStateViewModel, settingsViewModel) { + var self = this; + + self.loginState = loginStateViewModel; + + self.temp = ko.observable(undefined); + self.bedTemp = ko.observable(undefined); + self.targetTemp = ko.observable(undefined); + self.bedTargetTemp = ko.observable(undefined); + + self.newTemp = ko.observable(undefined); + self.newBedTemp = ko.observable(undefined); + + self.newTempOffset = ko.observable(undefined); + self.tempOffset = ko.observable(0); + self.newBedTempOffset = ko.observable(undefined); + self.bedTempOffset = ko.observable(0); + + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); + + self.temperature_profiles = settingsViewModel.temperature_profiles; + + self.tempString = ko.computed(function() { + if (!self.temp()) + return "-"; + return self.temp() + " °C"; + }); + self.bedTempString = ko.computed(function() { + if (!self.bedTemp()) + return "-"; + return self.bedTemp() + " °C"; + }); + self.targetTempString = ko.computed(function() { + if (!self.targetTemp()) + return "-"; + return self.targetTemp() + " °C"; + }); + self.bedTargetTempString = ko.computed(function() { + if (!self.bedTargetTemp()) + return "-"; + return self.bedTargetTemp() + " °C"; + }); + + self.temperatures = []; + self.plotOptions = { + yaxis: { + min: 0, + max: 310, + ticks: 10 + }, + xaxis: { + mode: "time", + minTickSize: [2, "minute"], + tickFormatter: function(val, axis) { + if (val == undefined || val == 0) + return ""; // we don't want to display the minutes since the epoch if not connected yet ;) + + // current time in milliseconds in UTC + var timestampUtc = Date.now(); + + // calculate difference in milliseconds + var diff = timestampUtc - val; + + // convert to minutes + var diffInMins = Math.round(diff / (60 * 1000)); + if (diffInMins == 0) + return "just now"; + else + return "- " + diffInMins + " min"; + } + }, + legend: { + noColumns: 4 + } + } + + self.fromCurrentData = function(data) { + self._processStateData(data.state); + self._processTemperatureUpdateData(data.temperatures); + self._processOffsetData(data.offsets); + } + + self.fromHistoryData = function(data) { + self._processStateData(data.state); + self._processTemperatureHistoryData(data.temperatureHistory); + self._processOffsetData(data.offsets); + } + + self._processStateData = function(data) { + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isLoading(data.flags.loading); + } + + self._processTemperatureUpdateData = function(data) { + if (data.length == 0) + return; + + self.temp(data[data.length - 1].temp); + self.bedTemp(data[data.length - 1].bedTemp); + self.targetTemp(data[data.length - 1].targetTemp); + self.bedTargetTemp(data[data.length - 1].targetBedTemp); + + if (!CONFIG_TEMPERATURE_GRAPH) return; + + if (!self.temperatures) + self.temperatures = []; + if (!self.temperatures.actual) + self.temperatures.actual = []; + if (!self.temperatures.target) + self.temperatures.target = []; + if (!self.temperatures.actualBed) + self.temperatures.actualBed = []; + if (!self.temperatures.targetBed) + self.temperatures.targetBed = []; + + _.each(data, function(d) { + var time = d.currentTime; + self.temperatures.actual.push([time, d.temp]); + self.temperatures.target.push([time, d.targetTemp]); + self.temperatures.actualBed.push([time, d.bedTemp]); + self.temperatures.targetBed.push([time, d.targetBedTemp]); + }); + + self.temperatures.actual = self.temperatures.actual.slice(-300); + self.temperatures.target = self.temperatures.target.slice(-300); + self.temperatures.actualBed = self.temperatures.actualBed.slice(-300); + self.temperatures.targetBed = self.temperatures.targetBed.slice(-300); + + self.updatePlot(); + } + + self._processTemperatureHistoryData = function(data) { + self.temperatures = data; + self.updatePlot(); + } + + self._processOffsetData = function(data) { + self.tempOffset(data[0]); + self.bedTempOffset(data[1]); + } + + self.updatePlot = function() { + var graph = $("#temperature-graph"); + if (graph.length) { + var data = [ + {label: "Actual", color: "#FF4040", data: self.temperatures.actual}, + {label: "Target", color: "#FFA0A0", data: self.temperatures.target}, + {label: "Bed Actual", color: "#4040FF", data: self.temperatures.actualBed}, + {label: "Bed Target", color: "#A0A0FF", data: self.temperatures.targetBed} + ] + + $.plot(graph, data, self.plotOptions); + } + } + + self.setTempFromProfile = function(profile) { + if (!profile) + return; + self._updateTemperature(profile.extruder, "temp"); + } + + self.setTemp = function() { + self._updateTemperature(self.newTemp(), "temp", function(){self.targetTemp(self.newTemp()); self.newTemp("");}); + }; + + self.setTempToZero = function() { + self._updateTemperature(0, "temp", function(){self.targetTemp(0); self.newTemp("");}); + } + + self.setTempOffset = function() { + self._updateTemperature(self.newTempOffset(), "tempOffset", function() {self.tempOffset(self.newTempOffset()); self.newTempOffset("");}); + } + + self.setBedTempFromProfile = function(profile) { + self._updateTemperature(profile.bed, "bedTemp"); + } + + self.setBedTemp = function() { + self._updateTemperature(self.newBedTemp(), "bedTemp", function() {self.bedTargetTemp(self.newBedTemp()); self.newBedTemp("");}); + }; + + self.setBedTempToZero = function() { + self._updateTemperature(0, "bedTemp", function() {self.bedTargetTemp(0); self.newBedTemp("");}); + } + + self.setBedTempOffset = function() { + self._updateTemperature(self.newBedTempOffset(), "bedTempOffset", function() {self.bedTempOffset(self.newBedTempOffset()); self.newBedTempOffset("");}); + } + + self._updateTemperature = function(temp, type, callback) { + var data = {}; + data[type] = temp; + + $.ajax({ + url: AJAX_BASEURL + "control/temperature", + type: "POST", + data: data, + success: function() { if (callback !== undefined) callback(); } + }); + } + + self.handleEnter = function(event, type) { + if (event.keyCode == 13) { + if (type == "temp") { + self.setTemp(); + } else if (type == "bedTemp") { + self.setBedTemp(); + } + } + } +} diff --git a/octoprint/static/js/app/viewmodels/terminal.js b/octoprint/static/js/app/viewmodels/terminal.js new file mode 100644 index 000000000..01eab23b9 --- /dev/null +++ b/octoprint/static/js/app/viewmodels/terminal.js @@ -0,0 +1,119 @@ +function TerminalViewModel(loginStateViewModel, settingsViewModel) { + var self = this; + + self.loginState = loginStateViewModel; + self.settings = settingsViewModel; + + self.log = []; + + self.command = ko.observable(undefined); + + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); + + self.autoscrollEnabled = ko.observable(true); + + self.filters = self.settings.terminalFilters; + self.filterRegex = undefined; + + self.activeFilters = ko.observableArray([]); + self.activeFilters.subscribe(function(e) { + self.updateFilterRegex(); + self.updateOutput(); + }); + + self.fromCurrentData = function(data) { + self._processStateData(data.state); + self._processCurrentLogData(data.logs); + } + + self.fromHistoryData = function(data) { + self._processStateData(data.state); + self._processHistoryLogData(data.logHistory); + } + + self._processCurrentLogData = function(data) { + if (!self.log) + self.log = [] + self.log = self.log.concat(data) + self.log = self.log.slice(-300) + self.updateOutput(); + } + + self._processHistoryLogData = function(data) { + self.log = data; + self.updateOutput(); + } + + self._processStateData = function(data) { + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isLoading(data.flags.loading); + } + + self.updateFilterRegex = function() { + var filterRegexStr = self.activeFilters().join("|").trim(); + if (filterRegexStr == "") { + self.filterRegex = undefined; + } else { + self.filterRegex = new RegExp(filterRegexStr); + } + console.log("Terminal filter regex: " + filterRegexStr); + } + + self.updateOutput = function() { + if (!self.log) + return; + + var output = ""; + for (var i = 0; i < self.log.length; i++) { + if (self.filterRegex !== undefined && self.log[i].match(self.filterRegex)) continue; + output += self.log[i] + "\n"; + } + + var container = $("#terminal-output"); + container.text(output); + + if (self.autoscrollEnabled()) { + container.scrollTop(container[0].scrollHeight - container.height()) + } + } + + self.sendCommand = function() { + /* + var re = /^([gm][0-9]+)(\s.*)?/; + var commandMatch = command.match(re); + if (commandMatch != null) { + command = commandMatch[1].toUpperCase() + ((commandMatch[2] !== undefined) ? commandMatch[2] : ""); + } + */ + + var command = self.command(); + if (command) { + $.ajax({ + url: AJAX_BASEURL + "control/command", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({"command": command}) + }); + self.command(""); + } + } + + self.handleEnter = function(event) { + if (event.keyCode == 13) { + self.sendCommand(); + } + } + +} diff --git a/octoprint/static/js/app/viewmodels/timelapse.js b/octoprint/static/js/app/viewmodels/timelapse.js new file mode 100644 index 000000000..a882df948 --- /dev/null +++ b/octoprint/static/js/app/viewmodels/timelapse.js @@ -0,0 +1,137 @@ +function TimelapseViewModel(loginStateViewModel) { + var self = this; + + self.loginState = loginStateViewModel; + + self.timelapseType = ko.observable(undefined); + self.timelapseTimedInterval = ko.observable(undefined); + + self.persist = ko.observable(false); + self.isDirty = ko.observable(false); + + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); + + self.intervalInputEnabled = ko.computed(function() { + return ("timed" == self.timelapseType()); + }); + self.saveButtonEnabled = ko.computed(function() { + return self.isDirty() && self.isOperational() && !self.isPrinting() && self.loginState.isUser(); + }); + + self.isOperational.subscribe(function(newValue) { + self.requestData(); + }); + + self.timelapseType.subscribe(function(newValue) { + self.isDirty(true); + }); + self.timelapseTimedInterval.subscribe(function(newValue) { + self.isDirty(true); + }); + + // initialize list helper + self.listHelper = new ItemListHelper( + "timelapseFiles", + { + "name": function(a, b) { + // sorts ascending + if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; + if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; + return 0; + }, + "creation": function(a, b) { + // sorts descending + if (a["date"] > b["date"]) return -1; + if (a["date"] < b["date"]) return 1; + return 0; + }, + "size": function(a, b) { + // sorts descending + if (a["bytes"] > b["bytes"]) return -1; + if (a["bytes"] < b["bytes"]) return 1; + return 0; + } + }, + { + }, + "name", + [], + [], + CONFIG_TIMELAPSEFILESPERPAGE + ); + + self.requestData = function() { + $.ajax({ + url: AJAX_BASEURL + "timelapse", + type: "GET", + dataType: "json", + success: self.fromResponse + }); + }; + + self.fromResponse = function(response) { + self.timelapseType(response.type); + self.listHelper.updateItems(response.files); + + if (response.type == "timed" && response.config && response.config.interval) { + self.timelapseTimedInterval(response.config.interval); + } else { + self.timelapseTimedInterval(undefined); + } + + self.persist(false); + self.isDirty(false); + } + + self.fromCurrentData = function(data) { + self._processStateData(data.state); + } + + self.fromHistoryData = function(data) { + self._processStateData(data.state); + } + + self._processStateData = function(data) { + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isLoading(data.flags.loading); + } + + self.removeFile = function(filename) { + $.ajax({ + url: AJAX_BASEURL + "timelapse/" + filename, + type: "DELETE", + dataType: "json", + success: self.requestData + }); + } + + self.save = function(data, event) { + var data = { + "type": self.timelapseType(), + "save": self.persist() + } + + if (self.timelapseType() == "timed") { + data["interval"] = self.timelapseTimedInterval(); + } + + $.ajax({ + url: AJAX_BASEURL + "timelapse", + type: "POST", + dataType: "json", + data: data, + success: self.fromResponse + }); + } +} diff --git a/octoprint/static/js/app/viewmodels/users.js b/octoprint/static/js/app/viewmodels/users.js new file mode 100644 index 000000000..70c8534a0 --- /dev/null +++ b/octoprint/static/js/app/viewmodels/users.js @@ -0,0 +1,190 @@ +function UsersViewModel(loginStateViewModel) { + var self = this; + + self.loginState = loginStateViewModel; + + // initialize list helper + self.listHelper = new ItemListHelper( + "users", + { + "name": function(a, b) { + // sorts ascending + if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; + if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; + return 0; + } + }, + {}, + "name", + [], + [], + CONFIG_USERSPERPAGE + ); + + self.emptyUser = {name: "", admin: false, active: false}; + + self.currentUser = ko.observable(self.emptyUser); + + self.editorUsername = ko.observable(undefined); + self.editorPassword = ko.observable(undefined); + self.editorRepeatedPassword = ko.observable(undefined); + self.editorAdmin = ko.observable(undefined); + self.editorActive = ko.observable(undefined); + + self.currentUser.subscribe(function(newValue) { + if (newValue === undefined) { + self.editorUsername(undefined); + self.editorAdmin(undefined); + self.editorActive(undefined); + } else { + self.editorUsername(newValue.name); + self.editorAdmin(newValue.admin); + self.editorActive(newValue.active); + } + self.editorPassword(undefined); + self.editorRepeatedPassword(undefined); + }); + + self.editorPasswordMismatch = ko.computed(function() { + return self.editorPassword() != self.editorRepeatedPassword(); + }); + + self.requestData = function() { + if (!CONFIG_ACCESS_CONTROL) return; + + $.ajax({ + url: AJAX_BASEURL + "users", + type: "GET", + dataType: "json", + success: self.fromResponse + }); + } + + self.fromResponse = function(response) { + self.listHelper.updateItems(response.users); + } + + self.showAddUserDialog = function() { + if (!CONFIG_ACCESS_CONTROL) return; + + self.currentUser(undefined); + self.editorActive(true); + $("#settings-usersDialogAddUser").modal("show"); + } + + self.confirmAddUser = function() { + if (!CONFIG_ACCESS_CONTROL) return; + + var user = {name: self.editorUsername(), password: self.editorPassword(), admin: self.editorAdmin(), active: self.editorActive()}; + self.addUser(user, function() { + // close dialog + self.currentUser(undefined); + $("#settings-usersDialogAddUser").modal("hide"); + }); + } + + self.showEditUserDialog = function(user) { + if (!CONFIG_ACCESS_CONTROL) return; + + self.currentUser(user); + $("#settings-usersDialogEditUser").modal("show"); + } + + self.confirmEditUser = function() { + if (!CONFIG_ACCESS_CONTROL) return; + + var user = self.currentUser(); + user.active = self.editorActive(); + user.admin = self.editorAdmin(); + + // make AJAX call + self.updateUser(user, function() { + // close dialog + self.currentUser(undefined); + $("#settings-usersDialogEditUser").modal("hide"); + }); + } + + self.showChangePasswordDialog = function(user) { + if (!CONFIG_ACCESS_CONTROL) return; + + self.currentUser(user); + $("#settings-usersDialogChangePassword").modal("show"); + } + + self.confirmChangePassword = function() { + if (!CONFIG_ACCESS_CONTROL) return; + + self.updatePassword(self.currentUser().name, self.editorPassword(), function() { + // close dialog + self.currentUser(undefined); + $("#settings-usersDialogChangePassword").modal("hide"); + }); + } + + //~~ AJAX calls + + self.addUser = function(user, callback) { + if (!CONFIG_ACCESS_CONTROL) return; + if (user === undefined) return; + + $.ajax({ + url: AJAX_BASEURL + "users", + type: "POST", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(user), + success: function(response) { + self.fromResponse(response); + callback(); + } + }); + } + + self.removeUser = function(user, callback) { + if (!CONFIG_ACCESS_CONTROL) return; + if (user === undefined) return; + + if (user.name == loginStateViewModel.username()) { + // we do not allow to delete ourselves + $.pnotify({title: "Not possible", text: "You may not delete your own account.", type: "error"}); + return; + } + + $.ajax({ + url: AJAX_BASEURL + "users/" + user.name, + type: "DELETE", + success: function(response) { + self.fromResponse(response); + callback(); + } + }); + } + + self.updateUser = function(user, callback) { + if (!CONFIG_ACCESS_CONTROL) return; + if (user === undefined) return; + + $.ajax({ + url: AJAX_BASEURL + "users/" + user.name, + type: "PUT", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(user), + success: function(response) { + self.fromResponse(response); + callback(); + } + }); + } + + self.updatePassword = function(username, password, callback) { + if (!CONFIG_ACCESS_CONTROL) return; + + $.ajax({ + url: AJAX_BASEURL + "users/" + username + "/password", + type: "PUT", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({password: password}), + success: callback + }); + } +} diff --git a/octoprint/static/js/avltree.js b/octoprint/static/js/lib/avltree.js similarity index 100% rename from octoprint/static/js/avltree.js rename to octoprint/static/js/lib/avltree.js diff --git a/octoprint/static/js/bootstrap/bootstrap-modal.js b/octoprint/static/js/lib/bootstrap/bootstrap-modal.js similarity index 100% rename from octoprint/static/js/bootstrap/bootstrap-modal.js rename to octoprint/static/js/lib/bootstrap/bootstrap-modal.js diff --git a/octoprint/static/js/bootstrap/bootstrap-modalmanager.js b/octoprint/static/js/lib/bootstrap/bootstrap-modalmanager.js similarity index 100% rename from octoprint/static/js/bootstrap/bootstrap-modalmanager.js rename to octoprint/static/js/lib/bootstrap/bootstrap-modalmanager.js diff --git a/octoprint/static/js/bootstrap/bootstrap.js b/octoprint/static/js/lib/bootstrap/bootstrap.js similarity index 100% rename from octoprint/static/js/bootstrap/bootstrap.js rename to octoprint/static/js/lib/bootstrap/bootstrap.js diff --git a/octoprint/static/js/bootstrap/bootstrap.min.js b/octoprint/static/js/lib/bootstrap/bootstrap.min.js similarity index 100% rename from octoprint/static/js/bootstrap/bootstrap.min.js rename to octoprint/static/js/lib/bootstrap/bootstrap.min.js diff --git a/octoprint/static/js/jquery/jquery.fileupload.js b/octoprint/static/js/lib/jquery/jquery.fileupload.js similarity index 100% rename from octoprint/static/js/jquery/jquery.fileupload.js rename to octoprint/static/js/lib/jquery/jquery.fileupload.js diff --git a/octoprint/static/js/jquery/jquery.flot.js b/octoprint/static/js/lib/jquery/jquery.flot.js similarity index 100% rename from octoprint/static/js/jquery/jquery.flot.js rename to octoprint/static/js/lib/jquery/jquery.flot.js diff --git a/octoprint/static/js/jquery/jquery.iframe-transport.js b/octoprint/static/js/lib/jquery/jquery.iframe-transport.js similarity index 100% rename from octoprint/static/js/jquery/jquery.iframe-transport.js rename to octoprint/static/js/lib/jquery/jquery.iframe-transport.js diff --git a/octoprint/static/js/jquery/jquery.min.js b/octoprint/static/js/lib/jquery/jquery.min.js similarity index 100% rename from octoprint/static/js/jquery/jquery.min.js rename to octoprint/static/js/lib/jquery/jquery.min.js diff --git a/octoprint/static/js/jquery/jquery.pnotify.min.js b/octoprint/static/js/lib/jquery/jquery.pnotify.min.js similarity index 100% rename from octoprint/static/js/jquery/jquery.pnotify.min.js rename to octoprint/static/js/lib/jquery/jquery.pnotify.min.js diff --git a/octoprint/static/js/jquery/jquery.ui.core.js b/octoprint/static/js/lib/jquery/jquery.ui.core.js similarity index 100% rename from octoprint/static/js/jquery/jquery.ui.core.js rename to octoprint/static/js/lib/jquery/jquery.ui.core.js diff --git a/octoprint/static/js/jquery/jquery.ui.mouse.js b/octoprint/static/js/lib/jquery/jquery.ui.mouse.js similarity index 100% rename from octoprint/static/js/jquery/jquery.ui.mouse.js rename to octoprint/static/js/lib/jquery/jquery.ui.mouse.js diff --git a/octoprint/static/js/jquery/jquery.ui.slider.js b/octoprint/static/js/lib/jquery/jquery.ui.slider.js similarity index 100% rename from octoprint/static/js/jquery/jquery.ui.slider.js rename to octoprint/static/js/lib/jquery/jquery.ui.slider.js diff --git a/octoprint/static/js/jquery/jquery.ui.widget.js b/octoprint/static/js/lib/jquery/jquery.ui.widget.js similarity index 100% rename from octoprint/static/js/jquery/jquery.ui.widget.js rename to octoprint/static/js/lib/jquery/jquery.ui.widget.js diff --git a/octoprint/static/js/knockout.js b/octoprint/static/js/lib/knockout.js similarity index 100% rename from octoprint/static/js/knockout.js rename to octoprint/static/js/lib/knockout.js diff --git a/octoprint/static/js/less-1.3.3.min.js b/octoprint/static/js/lib/less-1.3.3.min.js similarity index 100% rename from octoprint/static/js/less-1.3.3.min.js rename to octoprint/static/js/lib/less-1.3.3.min.js diff --git a/octoprint/static/js/modernizr.custom.js b/octoprint/static/js/lib/modernizr.custom.js similarity index 100% rename from octoprint/static/js/modernizr.custom.js rename to octoprint/static/js/lib/modernizr.custom.js diff --git a/octoprint/static/js/lib/sockjs-0.3.4.min.js b/octoprint/static/js/lib/sockjs-0.3.4.min.js new file mode 100644 index 000000000..baae37641 --- /dev/null +++ b/octoprint/static/js/lib/sockjs-0.3.4.min.js @@ -0,0 +1,27 @@ +/* SockJS client, version 0.3.4, http://sockjs.org, MIT License + +Copyright (c) 2011-2012 VMware, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +// JSON2 by Douglas Crockford (minified). +var JSON;JSON||(JSON={}),function(){function str(a,b){var c,d,e,f,g=gap,h,i=b[a];i&&typeof i=="object"&&typeof i.toJSON=="function"&&(i=i.toJSON(a)),typeof rep=="function"&&(i=rep.call(b,a,i));switch(typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i)return"null";gap+=indent,h=[];if(Object.prototype.toString.apply(i)==="[object Array]"){f=i.length;for(c=0;c1?this._listeners[a]=d.slice(0,e).concat(d.slice(e+1)):delete this._listeners[a];return}return},d.prototype.dispatchEvent=function(a){var b=a.type,c=Array.prototype.slice.call(arguments,0);this["on"+b]&&this["on"+b].apply(this,c);if(this._listeners&&b in this._listeners)for(var d=0;d=3e3&&a<=4999},c.countRTO=function(a){var b;return a>100?b=3*a:b=a+200,b},c.log=function(){b.console&&console.log&&console.log.apply&&console.log.apply(console,arguments)},c.bind=function(a,b){return a.bind?a.bind(b):function(){return a.apply(b,arguments)}},c.flatUrl=function(a){return a.indexOf("?")===-1&&a.indexOf("#")===-1},c.amendUrl=function(b){var d=a.location;if(!b)throw new Error("Wrong url for SockJS");if(!c.flatUrl(b))throw new Error("Only basic urls are supported in SockJS");return b.indexOf("//")===0&&(b=d.protocol+b),b.indexOf("/")===0&&(b=d.protocol+"//"+d.host+b),b=b.replace(/[/]+$/,""),b},c.arrIndexOf=function(a,b){for(var c=0;c=0},c.delay=function(a,b){return typeof a=="function"&&(b=a,a=0),setTimeout(b,a)};var i=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,j={"\0":"\\u0000","\x01":"\\u0001","\x02":"\\u0002","\x03":"\\u0003","\x04":"\\u0004","\x05":"\\u0005","\x06":"\\u0006","\x07":"\\u0007","\b":"\\b","\t":"\\t","\n":"\\n","\x0b":"\\u000b","\f":"\\f","\r":"\\r","\x0e":"\\u000e","\x0f":"\\u000f","\x10":"\\u0010","\x11":"\\u0011","\x12":"\\u0012","\x13":"\\u0013","\x14":"\\u0014","\x15":"\\u0015","\x16":"\\u0016","\x17":"\\u0017","\x18":"\\u0018","\x19":"\\u0019","\x1a":"\\u001a","\x1b":"\\u001b","\x1c":"\\u001c","\x1d":"\\u001d","\x1e":"\\u001e","\x1f":"\\u001f",'"':'\\"',"\\":"\\\\","\x7f":"\\u007f","\x80":"\\u0080","\x81":"\\u0081","\x82":"\\u0082","\x83":"\\u0083","\x84":"\\u0084","\x85":"\\u0085","\x86":"\\u0086","\x87":"\\u0087","\x88":"\\u0088","\x89":"\\u0089","\x8a":"\\u008a","\x8b":"\\u008b","\x8c":"\\u008c","\x8d":"\\u008d","\x8e":"\\u008e","\x8f":"\\u008f","\x90":"\\u0090","\x91":"\\u0091","\x92":"\\u0092","\x93":"\\u0093","\x94":"\\u0094","\x95":"\\u0095","\x96":"\\u0096","\x97":"\\u0097","\x98":"\\u0098","\x99":"\\u0099","\x9a":"\\u009a","\x9b":"\\u009b","\x9c":"\\u009c","\x9d":"\\u009d","\x9e":"\\u009e","\x9f":"\\u009f","\xad":"\\u00ad","\u0600":"\\u0600","\u0601":"\\u0601","\u0602":"\\u0602","\u0603":"\\u0603","\u0604":"\\u0604","\u070f":"\\u070f","\u17b4":"\\u17b4","\u17b5":"\\u17b5","\u200c":"\\u200c","\u200d":"\\u200d","\u200e":"\\u200e","\u200f":"\\u200f","\u2028":"\\u2028","\u2029":"\\u2029","\u202a":"\\u202a","\u202b":"\\u202b","\u202c":"\\u202c","\u202d":"\\u202d","\u202e":"\\u202e","\u202f":"\\u202f","\u2060":"\\u2060","\u2061":"\\u2061","\u2062":"\\u2062","\u2063":"\\u2063","\u2064":"\\u2064","\u2065":"\\u2065","\u2066":"\\u2066","\u2067":"\\u2067","\u2068":"\\u2068","\u2069":"\\u2069","\u206a":"\\u206a","\u206b":"\\u206b","\u206c":"\\u206c","\u206d":"\\u206d","\u206e":"\\u206e","\u206f":"\\u206f","\ufeff":"\\ufeff","\ufff0":"\\ufff0","\ufff1":"\\ufff1","\ufff2":"\\ufff2","\ufff3":"\\ufff3","\ufff4":"\\ufff4","\ufff5":"\\ufff5","\ufff6":"\\ufff6","\ufff7":"\\ufff7","\ufff8":"\\ufff8","\ufff9":"\\ufff9","\ufffa":"\\ufffa","\ufffb":"\\ufffb","\ufffc":"\\ufffc","\ufffd":"\\ufffd","\ufffe":"\\ufffe","\uffff":"\\uffff"},k=/[\x00-\x1f\ud800-\udfff\ufffe\uffff\u0300-\u0333\u033d-\u0346\u034a-\u034c\u0350-\u0352\u0357-\u0358\u035c-\u0362\u0374\u037e\u0387\u0591-\u05af\u05c4\u0610-\u0617\u0653-\u0654\u0657-\u065b\u065d-\u065e\u06df-\u06e2\u06eb-\u06ec\u0730\u0732-\u0733\u0735-\u0736\u073a\u073d\u073f-\u0741\u0743\u0745\u0747\u07eb-\u07f1\u0951\u0958-\u095f\u09dc-\u09dd\u09df\u0a33\u0a36\u0a59-\u0a5b\u0a5e\u0b5c-\u0b5d\u0e38-\u0e39\u0f43\u0f4d\u0f52\u0f57\u0f5c\u0f69\u0f72-\u0f76\u0f78\u0f80-\u0f83\u0f93\u0f9d\u0fa2\u0fa7\u0fac\u0fb9\u1939-\u193a\u1a17\u1b6b\u1cda-\u1cdb\u1dc0-\u1dcf\u1dfc\u1dfe\u1f71\u1f73\u1f75\u1f77\u1f79\u1f7b\u1f7d\u1fbb\u1fbe\u1fc9\u1fcb\u1fd3\u1fdb\u1fe3\u1feb\u1fee-\u1fef\u1ff9\u1ffb\u1ffd\u2000-\u2001\u20d0-\u20d1\u20d4-\u20d7\u20e7-\u20e9\u2126\u212a-\u212b\u2329-\u232a\u2adc\u302b-\u302c\uaab2-\uaab3\uf900-\ufa0d\ufa10\ufa12\ufa15-\ufa1e\ufa20\ufa22\ufa25-\ufa26\ufa2a-\ufa2d\ufa30-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4e\ufff0-\uffff]/g,l,m=JSON&&JSON.stringify||function(a){return i.lastIndex=0,i.test(a)&&(a=a.replace(i,function(a){return j[a]})),'"'+a+'"'},n=function(a){var b,c={},d=[];for(b=0;b<65536;b++)d.push(String.fromCharCode(b));return a.lastIndex=0,d.join("").replace(a,function(a){return c[a]="\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4),""}),a.lastIndex=0,c};c.quote=function(a){var b=m(a);return k.lastIndex=0,k.test(b)?(l||(l=n(k)),b.replace(k,function(a){return l[a]})):b};var o=["websocket","xdr-streaming","xhr-streaming","iframe-eventsource","iframe-htmlfile","xdr-polling","xhr-polling","iframe-xhr-polling","jsonp-polling"];c.probeProtocols=function(){var a={};for(var b=0;b0&&h(a)};return c.websocket!==!1&&h(["websocket"]),d["xhr-streaming"]&&!c.null_origin?e.push("xhr-streaming"):d["xdr-streaming"]&&!c.cookie_needed&&!c.null_origin?e.push("xdr-streaming"):h(["iframe-eventsource","iframe-htmlfile"]),d["xhr-polling"]&&!c.null_origin?e.push("xhr-polling"):d["xdr-polling"]&&!c.cookie_needed&&!c.null_origin?e.push("xdr-polling"):h(["iframe-xhr-polling","jsonp-polling"]),e};var p="_sockjs_global";c.createHook=function(){var a="a"+c.random_string(8);if(!(p in b)){var d={};b[p]=function(a){return a in d||(d[a]={id:a,del:function(){delete d[a]}}),d[a]}}return b[p](a)},c.attachMessage=function(a){c.attachEvent("message",a)},c.attachEvent=function(c,d){typeof b.addEventListener!="undefined"?b.addEventListener(c,d,!1):(a.attachEvent("on"+c,d),b.attachEvent("on"+c,d))},c.detachMessage=function(a){c.detachEvent("message",a)},c.detachEvent=function(c,d){typeof b.addEventListener!="undefined"?b.removeEventListener(c,d,!1):(a.detachEvent("on"+c,d),b.detachEvent("on"+c,d))};var q={},r=!1,s=function(){for(var a in q)q[a](),delete q[a]},t=function(){if(r)return;r=!0,s()};c.attachEvent("unload",t),c.unload_add=function(a){var b=c.random_string(8);return q[b]=a,r&&c.delay(s),b},c.unload_del=function(a){a in q&&delete q[a]},c.createIframe=function(b,d){var e=a.createElement("iframe"),f,g,h=function(){clearTimeout(f);try{e.onload=null}catch(a){}e.onerror=null},i=function(){e&&(h(),setTimeout(function(){e&&e.parentNode.removeChild(e),e=null},0),c.unload_del(g))},j=function(a){e&&(i(),d(a))},k=function(a,b){try{e&&e.contentWindow&&e.contentWindow.postMessage(a,b)}catch(c){}};return e.src=b,e.style.display="none",e.style.position="absolute",e.onerror=function(){j("onerror")},e.onload=function(){clearTimeout(f),f=setTimeout(function(){j("onload timeout")},2e3)},a.body.appendChild(e),f=setTimeout(function(){j("timeout")},15e3),g=c.unload_add(i),{post:k,cleanup:i,loaded:h}},c.createHtmlfile=function(a,d){var e=new ActiveXObject("htmlfile"),f,g,i,j=function(){clearTimeout(f)},k=function(){e&&(j(),c.unload_del(g),i.parentNode.removeChild(i),i=e=null,CollectGarbage())},l=function(a){e&&(k(),d(a))},m=function(a,b){try{i&&i.contentWindow&&i.contentWindow.postMessage(a,b)}catch(c){}};e.open(),e.write(' - + + {% endif %}

                             
-                            
-                            
+                            
+ +
{% if enableTimelapse %} @@ -533,13 +559,19 @@
- + sec
+
+ +
+
- +
@@ -598,24 +630,46 @@ {% include 'settings.jinja2' %} {% include 'dialogs.jinja2' %} - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/octoprint/templates/settings.jinja2 b/octoprint/templates/settings.jinja2 index 0bed27c97..f543793d2 100644 --- a/octoprint/templates/settings.jinja2 +++ b/octoprint/templates/settings.jinja2 @@ -10,6 +10,7 @@
  • Serial Connection
  • Printer Parameters
  • Temperatures
  • +
  • Terminal filters
  • Features
  • Webcam
  • @@ -167,6 +168,13 @@
    +
    +
    + +
    +
    +
    +
    + +
    +
    @@ -256,6 +271,32 @@
    +
    +
    +
    +

    Name

    +

    RegExp ?

    +
    +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    +
    + +
    +
    +
    +
    diff --git a/octoprint/timelapse.py b/octoprint/timelapse.py index 8f0af98a6..a7fb95b81 100644 --- a/octoprint/timelapse.py +++ b/octoprint/timelapse.py @@ -33,6 +33,26 @@ def getFinishedTimelapses(): }) return files +validTimelapseTypes = ["off", "timed", "zchange"] + +updateCallbacks = [] +def registerCallback(callback): + if not callback in updateCallbacks: + updateCallbacks.append(callback) + +def unregisterCallback(callback): + if callback in updateCallbacks: + updateCallbacks.remove(callback) + +def notifyCallbacks(timelapse): + for callback in updateCallbacks: + if timelapse is None: + config = None + else: + config = timelapse.configData() + try: callback.sendTimelapseConfig(config) + except: pass + class Timelapse(object): def __init__(self): self._logger = logging.getLogger(__name__) @@ -51,6 +71,7 @@ class Timelapse(object): eventManager().subscribe("PrintStarted", self.onPrintStarted) eventManager().subscribe("PrintFailed", self.onPrintDone) eventManager().subscribe("PrintDone", self.onPrintDone) + eventManager().subscribe("PrintResumed", self.onPrintResumed) for (event, callback) in self.eventSubscriptions(): eventManager().subscribe(event, callback) @@ -62,6 +83,7 @@ class Timelapse(object): eventManager().unsubscribe("PrintStarted", self.onPrintStarted) eventManager().unsubscribe("PrintFailed", self.onPrintDone) eventManager().unsubscribe("PrintDone", self.onPrintDone) + eventManager().unsubscribe("PrintResumed", self.onPrintResumed) for (event, callback) in self.eventSubscriptions(): eventManager().unsubscribe(event, callback) @@ -77,17 +99,35 @@ class Timelapse(object): """ self.stopTimelapse() + def onPrintResumed(self, event, payload): + """ + Override this to perform additional actions upon the pausing of a print job. + """ + if not self._inTimelapse: + self.startTimelapse(payload) + def eventSubscriptions(self): """ Override this method to subscribe to additional events by returning an array of (event, callback) tuples. Events that are already subscribed: * PrintStarted - self.onPrintStarted + * PrintResumed - self.onPrintResumed * PrintFailed - self.onPrintDone * PrintDone - self.onPrintDone """ return [] + def configData(self): + """ + Override this method to return the current timelapse configuration data. The data should have the following + form: + + type: "", + options: { } + """ + return None + def startTimelapse(self, gcodeFile): self._logger.debug("Starting timelapse for %s" % gcodeFile) self.cleanCaptureDir() @@ -202,6 +242,11 @@ class ZTimelapse(Timelapse): ("ZChange", self._onZChange) ] + def configData(self): + return { + "type": "zchange" + } + def _onZChange(self, event, payload): self.captureImage() @@ -217,6 +262,14 @@ class TimedTimelapse(Timelapse): def interval(self): return self._interval + def configData(self): + return { + "type": "timed", + "options": { + "interval": self._interval + } + } + def onPrintStarted(self, event, payload): Timelapse.onPrintStarted(self, event, payload) if self._timerThread is not None: diff --git a/octoprint/util/README b/octoprint/util/README index 145ef8608..80d68639b 100644 --- a/octoprint/util/README +++ b/octoprint/util/README @@ -2,6 +2,5 @@ The code in this sub package mostly originates from the Cura project (https://gi slightly reorganized and adapted. The mapping to the original Cura source is the following: * avr_isp.* => Cura.avr_isp.* -* comm => Cura.util.machineCom +* comm => Cura.util.machineCom (highly modified now) * gcodeInterpreter => Cura.util.gcodeInterpreter -* util3d => Cura.util.util3d \ No newline at end of file diff --git a/octoprint/util/__init__.py b/octoprint/util/__init__.py index 77b046faa..23d8a238f 100644 --- a/octoprint/util/__init__.py +++ b/octoprint/util/__init__.py @@ -104,3 +104,9 @@ def getFreeBytes(path): st = os.statvfs(path) return st.f_bavail * st.f_frsize + +def getRemoteAddress(request): + forwardedFor = request.headers.get("X-Forwarded-For", None) + if forwardedFor is not None: + return forwardedFor.split(",")[0] + return request.remote_addr diff --git a/octoprint/util/comm.py b/octoprint/util/comm.py index 87a001b43..bb3f9aab7 100644 --- a/octoprint/util/comm.py +++ b/octoprint/util/comm.py @@ -45,11 +45,16 @@ def serialList(): + glob.glob("/dev/tty.usb*") \ + glob.glob("/dev/cu.*") \ + glob.glob("/dev/rfcomm*") + + additionalPorts = settings().get(["serial", "additionalPorts"]) + for additional in additionalPorts: + baselist += glob.glob(additional) + prev = settings().get(["serial", "port"]) if prev in baselist: baselist.remove(prev) baselist.insert(0, prev) - if isDevVersion(): + if settings().getBoolean(["devel", "virtualPrinter", "enabled"]): baselist.append("VIRTUAL") return baselist @@ -115,13 +120,15 @@ class MachineCom(object): self._bedTemp = 0 self._targetTemp = 0 self._bedTargetTemp = 0 + self._tempOffset = 0 + self._bedTempOffset = 0 self._commandQueue = queue.Queue() self._currentZ = None self._heatupWaitStartTime = 0 self._heatupWaitTimeLost = 0.0 self._alwaysSendChecksum = settings().getBoolean(["feature", "alwaysSendChecksum"]) - self._currentLine = 0 + self._currentLine = 1 self._resendDelta = None self._lastLines = deque([], 50) @@ -280,6 +287,9 @@ class MachineCom(object): def getBedTemp(self): return self._bedTemp + def getOffsets(self): + return (self._tempOffset, self._bedTempOffset) + ##~~ external interface def close(self, isError = False): @@ -299,6 +309,13 @@ class MachineCom(object): eventManager().fire("PrintFailed") eventManager().fire("Disconnected") + def setTemperatureOffset(self, extruder=None, bed=None): + if extruder is not None: + self._tempOffset = extruder + + if bed is not None: + self._bedTempOffset = bed + def sendCommand(self, cmd): cmd = cmd.encode('ascii', 'replace') if self.isPrinting() and not self.isSdFileSelected(): @@ -352,7 +369,7 @@ class MachineCom(object): return self.sendCommand("M23 %s" % filename) else: - self._currentFile = PrintingGcodeFileInformation(filename) + self._currentFile = PrintingGcodeFileInformation(filename, self.getOffsets) eventManager().fire("FileSelected", filename) self._callback.mcFileSelected(filename, self._currentFile.getFilesize(), False) @@ -386,6 +403,7 @@ class MachineCom(object): self.sendCommand("M24") else: self._sendNext() + eventManager().fire("PrintResumed", self._currentFile.getFilename()) if pause and self.isPrinting(): self._changeState(self.STATE_PAUSED) if self.isSdFileSelected(): @@ -448,6 +466,7 @@ class MachineCom(object): def _monitor(self): feedbackControls = settings().getFeedbackControls() pauseTriggers = settings().getPauseTriggers() + feedbackErrors = [] #Open the serial port. if self._port == 'AUTO': @@ -497,6 +516,7 @@ class MachineCom(object): sdStatusRequestTimeout = timeout startSeen = not settings().getBoolean(["feature", "waitForStartOnConnect"]) heatingUp = False + swallowOk = False while True: try: line = self._readline() @@ -606,9 +626,18 @@ class MachineCom(object): try: match = matcher.search(line) if match is not None: - self._callback.mcReceivedRegisteredMessage(name, str.format(template, *(match.groups("n/a")))) + format = None + if isinstance(template, str): + format = str.format + elif isinstance(template, unicode): + format = unicode.format + + if format is not None: + self._callback.mcReceivedRegisteredMessage(name, format(template, *(match.groups("n/a")))) except: - # ignored on purpose + if not name in feedbackErrors: + self._logger.info("Something went wrong with feedbackControl \"%s\": " % name, exc_info=True) + feedbackErrors.append(name) pass ##~~ Parsing for pause triggers @@ -693,6 +722,8 @@ class MachineCom(object): tempRequestTimeout = getNewTimeout("communication") # resend -> start resend procedure from requested line elif line.lower().startswith("resend") or line.lower().startswith("rs"): + if settings().get(["feature", "swallowOkAfterResend"]): + swallowOk = True self._handleResendRequest(line) ### Printing @@ -718,7 +749,9 @@ class MachineCom(object): self._commandQueue.put("M105") tempRequestTimeout = getNewTimeout("communication") - if 'ok' in line: + if "ok" in line and swallowOk: + swallowOk = False + elif "ok" in line: timeout = getNewTimeout("communication") if self._resendDelta is not None: self._resendNextCommand() @@ -727,6 +760,8 @@ class MachineCom(object): else: self._sendNext() elif line.lower().startswith("resend") or line.lower().startswith("rs"): + if settings().get(["feature", "swallowOkAfterResend"]): + swallowOk = True self._handleResendRequest(line) except: self._logger.exception("Something crashed inside the serial connection loop, please report this in OctoPrint's bug tracker:") @@ -771,10 +806,6 @@ class MachineCom(object): eventManager().fire("PrintDone", self._currentFile.getFilename()) return - if type(line) is tuple: - self._printSection = line[1] - line = line[0] - self._sendCommand(line, True) self._callback.mcProgress() @@ -788,7 +819,7 @@ class MachineCom(object): if lineToResend is not None: self._resendDelta = self._currentLine - lineToResend - if self._resendDelta > len(self._lastLines) or len(self._lastLines) == 0: + if self._resendDelta > len(self._lastLines) or len(self._lastLines) == 0 or self._resendDelta <= 0: self._errorValue = "Printer requested line %d but no sufficient history is available, can't resend" % lineToResend self._logger.warn(self._errorValue) if self.isPrinting(): @@ -1042,12 +1073,14 @@ class PrintingGcodeFileInformation(PrintingFileInformation): that the file is closed in case of an error. """ - def __init__(self, filename): + def __init__(self, filename, offsetCallback): PrintingFileInformation.__init__(self, filename) self._filehandle = None self._lineCount = None self._firstLine = None - self._prevLineType = None + + self._offsetCallback = offsetCallback + self._tempCommandPattern = re.compile("^\s*M(104|109|140|190)\s+S([0-9\.]+)") if not os.path.exists(self._filename) or not os.path.isfile(self._filename): raise IOError("File %s does not exist" % self._filename) @@ -1059,7 +1092,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation): """ self._filehandle = open(self._filename, "r") self._lineCount = None - self._prevLineType = "CUSTOM" + self._startTime = None def getNext(self): """ @@ -1097,17 +1130,28 @@ class PrintingGcodeFileInformation(PrintingFileInformation): raise e def _processLine(self, line): - lineType = self._prevLineType - if line.startswith(";TYPE:"): - lineType = line[6:].strip() if ";" in line: line = line[0:line.find(";")] line = line.strip() if len(line) > 0: - if self._prevLineType != lineType: - return line, lineType - else: - return line + (tempOffset, bedTempOffset) = self._offsetCallback() + if tempOffset != 0 or bedTempOffset != 0: + tempMatch = self._tempCommandPattern.match(line) + if tempMatch is not None: + if tempMatch.group(1) == "104" or tempMatch.group(1) == "109": + offset = tempOffset + elif tempMatch.group(1) == "140" or tempMatch.group(1) == "190": + offset = bedTempOffset + else: + offset = 0 + + try: + temp = float(tempMatch.group(2)) + newTemp = temp + offset + line = line.replace("S" + tempMatch.group(2), "S%f" % newTemp) + except ValueError: + pass + return line else: return None diff --git a/octoprint/util/gcodeInterpreter.py b/octoprint/util/gcodeInterpreter.py index eebdd55b5..b324dfe8b 100644 --- a/octoprint/util/gcodeInterpreter.py +++ b/octoprint/util/gcodeInterpreter.py @@ -1,14 +1,13 @@ from __future__ import absolute_import +__copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License" -import sys import math -import re import os import base64 import zlib import logging -from octoprint.util import util3d +from octoprint.settings import settings preferences = { "extruder_offset_x1": -22.0, @@ -28,300 +27,208 @@ def getPreference(key, default=None): class AnalysisAborted(Exception): pass -class gcodePath(object): - def __init__(self, newType, pathType, layerThickness, startPoint): - self.type = newType - self.pathType = pathType - self.layerThickness = layerThickness - self.list = [startPoint] - class gcode(object): def __init__(self): self._logger = logging.getLogger(__name__) - self.regMatch = {} - self.layerList = [] + self.layerList = None self.extrusionAmount = 0 - self.extrusionVolume = None self.totalMoveTimeMinute = 0 + self.filename = None self.progressCallback = None self._abort = False + self._filamentDiameter = 0 def load(self, filename): if os.path.isfile(filename): + self.filename = filename self._fileSize = os.stat(filename).st_size - gcodeFile = open(filename, 'r') - self._load(gcodeFile) - gcodeFile.close() - - def loadList(self, l): - self._load(l) + with open(filename, "r") as f: + self._load(f) def abort(self): self._abort = True - + + def calculateVolumeCm3(self): + radius = self._filamentDiameter / 2 + return (self.extrusionAmount * (math.pi * radius * radius)) / 1000 + def _load(self, gcodeFile): filePos = 0 - pos = util3d.Vector3() - posOffset = util3d.Vector3() + pos = [0.0, 0.0, 0.0] + posOffset = [0.0, 0.0, 0.0] currentE = 0.0 totalExtrusion = 0.0 maxExtrusion = 0.0 currentExtruder = 0 - extrudeAmountMultiply = 1.0 totalMoveTimeMinute = 0.0 - filamentDiameter = 0.0 + absoluteE = True scale = 1.0 posAbs = True - posAbsExtruder = True; - feedRate = 3600 - layerThickness = 0.1 - pathType = 'CUSTOM'; - currentLayer = [] - unknownGcodes={} - unknownMcodes={} - currentPath = gcodePath('move', pathType, layerThickness, pos.copy()) - currentPath.list[0].e = totalExtrusion - currentPath.list[0].extrudeAmountMultiply = extrudeAmountMultiply - currentLayer.append(currentPath) + feedRateXY = settings().getFloat(["printerParameters", "movementSpeed", "x"]) + for line in gcodeFile: if self._abort: raise AnalysisAborted() - if type(line) is tuple: - line = line[0] - if self.progressCallback != None: - if isinstance(gcodeFile, (file)): - self.progressCallback(float(filePos) / float(self._fileSize)) - elif isinstance(gcodeFile, (list)): - self.progressCallback(float(filePos) / float(len(gcodeFile))) - filePos += 1 + filePos += 1 + + try: + if self.progressCallback is not None and (filePos % 1000 == 0): + if isinstance(gcodeFile, (file)): + self.progressCallback(float(gcodeFile.tell()) / float(self._fileSize)) + elif isinstance(gcodeFile, (list)): + self.progressCallback(float(filePos) / float(len(gcodeFile))) + except: + pass - #Parse Cura_SF comments - if line.startswith(';TYPE:'): - pathType = line[6:].strip() - if pathType != "CUSTOM": - startCodeDone = True - if ';' in line: - # Slic3r GCode comment parser comment = line[line.find(';')+1:].strip() - if comment == 'fill': - pathType = 'FILL' - elif comment == 'perimeter': - pathType = 'WALL-INNER' - elif comment == 'skirt': - pathType = 'SKIRT' - elif comment.startswith("filament_diameter"): - filamentDiameter = float(line.split("=", 1)[1].strip()) - - # Cura Gcode comment parser - if comment.startswith('LAYER:'): - self.layerList.append(currentLayer) - currentLayer = [] + if comment.startswith("filament_diameter"): + self._filamentDiameter = float(comment.split("=", 1)[1].strip()) elif comment.startswith("CURA_PROFILE_STRING"): curaOptions = self._parseCuraProfileString(comment) - - if "filament_diameter" in curaOptions.keys(): + if "filament_diameter" in curaOptions: try: - filamentDiameter = float(curaOptions["filament_diameter"]) + self._filamentDiameter = float(curaOptions["filament_diameter"]) except: - filamentDiameter = 0.0 + self._filamentDiameter = 0.0 line = line[0:line.find(';')] - T = self.getCodeInt(line, 'T') + + T = getCodeInt(line, 'T') if T is not None: if currentExtruder > 0: - posOffset.x -= getPreference('extruder_offset_x%d' % (currentExtruder), 0.0) - posOffset.y -= getPreference('extruder_offset_y%d' % (currentExtruder), 0.0) + posOffset[0] -= getPreference('extruder_offset_x%d' % (currentExtruder), 0.0) + posOffset[1] -= getPreference('extruder_offset_y%d' % (currentExtruder), 0.0) currentExtruder = T if currentExtruder > 0: - posOffset.x += getPreference('extruder_offset_x%d' % (currentExtruder), 0.0) - posOffset.y += getPreference('extruder_offset_y%d' % (currentExtruder), 0.0) + posOffset[0] += getPreference('extruder_offset_x%d' % (currentExtruder), 0.0) + posOffset[1] += getPreference('extruder_offset_y%d' % (currentExtruder), 0.0) - G = self.getCodeInt(line, 'G') + G = getCodeInt(line, 'G') if G is not None: if G == 0 or G == 1: #Move - x = self.getCodeFloat(line, 'X') - y = self.getCodeFloat(line, 'Y') - z = self.getCodeFloat(line, 'Z') - e = self.getCodeFloat(line, 'E') - f = self.getCodeFloat(line, 'F') - oldPos = pos.copy() - if x is not None: - if posAbs: - pos.x = x * scale + posOffset.x - else: - pos.x += x * scale - if y is not None: - if posAbs: - pos.y = y * scale + posOffset.y - else: - pos.y += y * scale - if z is not None: - if posAbs: - pos.z = z * scale + posOffset.z - else: - pos.z += z * scale + x = getCodeFloat(line, 'X') + y = getCodeFloat(line, 'Y') + z = getCodeFloat(line, 'Z') + e = getCodeFloat(line, 'E') + f = getCodeFloat(line, 'F') + oldPos = pos + pos = pos[:] + if posAbs: + if x is not None: + pos[0] = x * scale + posOffset[0] + if y is not None: + pos[1] = y * scale + posOffset[1] + if z is not None: + pos[2] = z * scale + posOffset[2] + else: + if x is not None: + pos[0] += x * scale + if y is not None: + pos[1] += y * scale + if z is not None: + pos[2] += z * scale if f is not None: - feedRate = f + feedRateXY = f if x is not None or y is not None or z is not None: - totalMoveTimeMinute += (oldPos - pos).vsize() / feedRate + diffX = oldPos[0] - pos[0] + diffY = oldPos[1] - pos[1] + totalMoveTimeMinute += math.sqrt(diffX * diffX + diffY * diffY) / feedRateXY moveType = 'move' if e is not None: - if posAbsExtruder: - if e > currentE: - moveType = 'extrude' - if e < currentE: - moveType = 'retract' - totalExtrusion += e - currentE - currentE = e - else: - if e > 0: - moveType = 'extrude' - if e < 0: - moveType = 'retract' - totalExtrusion += e - currentE += e + if absoluteE: + e -= currentE + if e > 0.0: + moveType = 'extrude' + if e < 0.0: + moveType = 'retract' + totalExtrusion += e + currentE += e if totalExtrusion > maxExtrusion: maxExtrusion = totalExtrusion - if moveType == 'move' and oldPos.z != pos.z: - if oldPos.z > pos.z and abs(oldPos.z - pos.z) > 5.0 and pos.z < 1.0: - oldPos.z = 0.0 - layerThickness = abs(oldPos.z - pos.z) - if currentPath.type != moveType or currentPath.pathType != pathType: - currentPath = gcodePath(moveType, pathType, layerThickness, currentPath.list[-1]) - currentLayer.append(currentPath) - newPos = pos.copy() - newPos.e = totalExtrusion - newPos.extrudeAmountMultiply = extrudeAmountMultiply - currentPath.list.append(newPos) + else: + e = 0.0 + if moveType == 'move' and oldPos[2] != pos[2]: + if oldPos[2] > pos[2] and abs(oldPos[2] - pos[2]) > 5.0 and pos[2] < 1.0: + oldPos[2] = 0.0 elif G == 4: #Delay - S = self.getCodeFloat(line, 'S') + S = getCodeFloat(line, 'S') if S is not None: - totalMoveTimeMinute += S / 60 - P = self.getCodeFloat(line, 'P') + totalMoveTimeMinute += S / 60.0 + P = getCodeFloat(line, 'P') if P is not None: - totalMoveTimeMinute += P / 60 / 1000 + totalMoveTimeMinute += P / 60.0 / 1000.0 elif G == 20: #Units are inches scale = 25.4 elif G == 21: #Units are mm scale = 1.0 elif G == 28: #Home - x = self.getCodeFloat(line, 'X') - y = self.getCodeFloat(line, 'Y') - z = self.getCodeFloat(line, 'Z') + x = getCodeFloat(line, 'X') + y = getCodeFloat(line, 'Y') + z = getCodeFloat(line, 'Z') + center = [0.0,0.0,0.0] if x is None and y is None and z is None: - pos = util3d.Vector3() + pos = center else: + pos = pos[:] if x is not None: - pos.x = 0.0 + pos[0] = center[0] if y is not None: - pos.y = 0.0 + pos[1] = center[1] if z is not None: - pos.z = 0.0 + pos[2] = center[2] elif G == 90: #Absolute position posAbs = True - posAbsExtruder = True elif G == 91: #Relative position posAbs = False - posAbsExtruder = False elif G == 92: - x = self.getCodeFloat(line, 'X') - y = self.getCodeFloat(line, 'Y') - z = self.getCodeFloat(line, 'Z') - e = self.getCodeFloat(line, 'E') + x = getCodeFloat(line, 'X') + y = getCodeFloat(line, 'Y') + z = getCodeFloat(line, 'Z') + e = getCodeFloat(line, 'E') if e is not None: currentE = e if x is not None: - posOffset.x = pos.x - x + posOffset[0] = pos[0] - x if y is not None: - posOffset.y = pos.y - y + posOffset[1] = pos[1] - y if z is not None: - posOffset.z = pos.z - z - else: - if G not in unknownGcodes: - self._logger.info("Unknown G code: %r" % G) - unknownGcodes[G] = True + posOffset[2] = pos[2] - z else: - M = self.getCodeInt(line, 'M') + M = getCodeInt(line, 'M') if M is not None: - if M == 1: #Message with possible wait (ignored) - pass - elif M == 80: #Enable power supply - pass - elif M == 81: #Suicide/disable power supply - pass - elif M == 82: # Use absolute extruder positions - posAbsExtruder = True - elif M == 83: # Use relative extruder positions - posAbsExtruder = False - elif M == 84: #Disable step drivers - pass - elif M == 92: #Set steps per unit - pass - elif M == 101: #Enable extruder - pass - elif M == 103: #Disable extruder - pass - elif M == 104: #Set temperature, no wait - pass - elif M == 105: #Get temperature - pass - elif M == 106: #Enable fan - pass - elif M == 107: #Disable fan - pass - elif M == 108: #Extruder RPM (these should not be in the final GCode, but they are) - pass - elif M == 109: #Set temperature, wait - pass - elif M == 110: #Reset N counter - pass - elif M == 113: #Extruder PWM (these should not be in the final GCode, but they are) - pass - elif M == 140: #Set bed temperature - pass - elif M == 190: #Set bed temperature & wait - pass - elif M == 221: #Extrude amount multiplier - s = self.getCodeFloat(line, 'S') - if s != None: - extrudeAmountMultiply = s / 100.0 - else: - if M not in unknownMcodes: - self._logger.info("Unknown M code: %r" % M) - unknownMcodes[M] = True - self.layerList.append(currentLayer) + if M == 82: #Absolute E + absoluteE = True + elif M == 83: #Relative E + absoluteE = False + if self.progressCallback is not None: + self.progressCallback(100.0) self.extrusionAmount = maxExtrusion - if filamentDiameter is not None and filamentDiameter > 0: - self.extrusionVolume = math.pi * math.pow(filamentDiameter / 2.0, 2) * maxExtrusion / 1000.0 self.totalMoveTimeMinute = totalMoveTimeMinute - def getCodeInt(self, line, code): - if code not in self.regMatch: - self.regMatch[code] = re.compile(code + '([^\s]+)') - m = self.regMatch[code].search(line) - if m == None: - return None - try: - return int(m.group(1)) - except: - return None - - def getCodeFloat(self, line, code): - if code not in self.regMatch: - self.regMatch[code] = re.compile(code + '([^\s]+)') - m = self.regMatch[code].search(line) - if m == None: - return None - try: - return float(m.group(1)) - except: - return None - def _parseCuraProfileString(self, comment): return {key: value for (key, value) in map(lambda x: x.split("=", 1), zlib.decompress(base64.b64decode(comment[len("CURA_PROFILE_STRING:"):])).split("\b"))} -if __name__ == '__main__': - for filename in sys.argv[1:]: - gcode().load(filename) +def getCodeInt(line, code): + n = line.find(code) + 1 + if n < 1: + return None + m = line.find(' ', n) + try: + if m < 0: + return int(line[n:]) + return int(line[n:m]) + except: + return None +def getCodeFloat(line, code): + n = line.find(code) + 1 + if n < 1: + return None + m = line.find(' ', n) + try: + if m < 0: + return float(line[n:]) + return float(line[n:m]) + except: + return None diff --git a/octoprint/util/util3d.py b/octoprint/util/util3d.py deleted file mode 100644 index e59944783..000000000 --- a/octoprint/util/util3d.py +++ /dev/null @@ -1,317 +0,0 @@ -from __future__ import absolute_import - -import math -import numpy - -class Vector3(object): - def __init__(self, x=0.0, y=0.0, z=0.0): - self.x = x - self.y = y - self.z = z - - def __copy__(self): - return Vector3(self.x, self.y, self.z) - - def copy(self): - return Vector3(self.x, self.y, self.z) - - def __repr__(self): - return 'V[%s, %s, %s]' % ( self.x, self.y, self.z ) - - def __add__(self, v): - return Vector3( self.x + v.x, self.y + v.y, self.z + v.z ) - - def __sub__(self, v): - return Vector3( self.x - v.x, self.y - v.y, self.z - v.z ) - - def __mul__(self, v): - return Vector3( self.x * v, self.y * v, self.z * v ) - - def __div__(self, v): - return Vector3( self.x / v, self.y / v, self.z / v ) - __truediv__ = __div__ - - def __neg__(self): - return Vector3( - self.x, - self.y, - self.z ) - - def __iadd__(self, v): - self.x += v.x - self.y += v.y - self.z += v.z - return self - - def __isub__(self, v): - self.x += v.x - self.y += v.y - self.z += v.z - return self - - def __imul__(self, v): - self.x *= v - self.y *= v - self.z *= v - return self - - def __idiv__(self, v): - self.x /= v - self.y /= v - self.z /= v - return self - - def almostEqual(self, v): - return (abs(self.x - v.x) + abs(self.y - v.y) + abs(self.z - v.z)) < 0.00001 - - def cross(self, v): - return Vector3(self.y * v.z - self.z * v.y, -self.x * v.z + self.z * v.x, self.x * v.y - self.y * v.x) - - def vsize(self): - return math.sqrt( self.x * self.x + self.y * self.y + self.z * self.z ) - - def normalize(self): - f = self.vsize() - if f != 0.0: - self.x /= f - self.y /= f - self.z /= f - - def min(self, v): - return Vector3(min(self.x, v.x), min(self.y, v.y), min(self.z, v.z)) - - def max(self, v): - return Vector3(max(self.x, v.x), max(self.y, v.y), max(self.z, v.z)) - -class AABB(object): - def __init__(self, vMin, vMax): - self.vMin = vMin - self.vMax = vMax - self.perimeter = numpy.sum(self.vMax - self.vMin) - - def combine(self, aabb): - return AABB(numpy.minimum(self.vMin, aabb.vMin), numpy.maximum(self.vMax, aabb.vMax)) - - def overlap(self, aabb): - if aabb.vMin[0] - self.vMax[0] > 0.0 or aabb.vMin[1] - self.vMax[1] > 0.0 or aabb.vMin[2] - self.vMax[2] > 0.0: - return False - if self.vMin[0] - aabb.vMax[0] > 0.0 or self.vMin[1] - aabb.vMax[1] > 0.0 or self.vMin[2] - aabb.vMax[2] > 0.0: - return False - return True - - def __repr__(self): - return "AABB:%s - %s" % (str(self.vMin), str(self.vMax)) - -class _AABBNode(object): - def __init__(self, aabb): - self.child1 = None - self.child2 = None - self.parent = None - self.height = 0 - self.aabb = aabb - - def isLeaf(self): - return self.child1 == None - -class AABBTree(object): - def __init__(self): - self.root = None - - def insert(self, aabb): - newNode = _AABBNode(aabb) - if self.root == None: - self.root = newNode - return - - node = self.root - while not node.isLeaf(): - child1 = node.child1 - child2 = node.child2 - - area = node.aabb.perimeter - combinedAABB = node.aabb.combine(aabb) - combinedArea = combinedAABB.perimeter - - cost = 2.0 * combinedArea - inheritanceCost = 2.0 * (combinedArea - area) - - if child1.isLeaf(): - cost1 = aabb.combine(child1.aabb).perimeter + inheritanceCost - else: - oldArea = child1.aabb.perimeter - newArea = aabb.combine(child1.aabb).perimeter - cost1 = (newArea - oldArea) + inheritanceCost - - if child2.isLeaf(): - cost2 = aabb.combine(child1.aabb).perimeter + inheritanceCost - else: - oldArea = child2.aabb.perimeter - newArea = aabb.combine(child2.aabb).perimeter - cost2 = (newArea - oldArea) + inheritanceCost - - if cost < cost1 and cost < cost2: - break - - if cost1 < cost2: - node = child1 - else: - node = child2 - - sibling = node - - # Create a new parent. - oldParent = sibling.parent - newParent = _AABBNode(aabb.combine(sibling.aabb)) - newParent.parent = oldParent - newParent.height = sibling.height + 1 - - if oldParent != None: - # The sibling was not the root. - if oldParent.child1 == sibling: - oldParent.child1 = newParent - else: - oldParent.child2 = newParent - - newParent.child1 = sibling - newParent.child2 = newNode - sibling.parent = newParent - newNode.parent = newParent - else: - # The sibling was the root. - newParent.child1 = sibling - newParent.child2 = newNode - sibling.parent = newParent - newNode.parent = newParent - self.root = newParent - - # Walk back up the tree fixing heights and AABBs - node = newNode.parent - while node != None: - node = self._balance(node) - - child1 = node.child1 - child2 = node.child2 - - node.height = 1 + max(child1.height, child2.height) - node.aabb = child1.aabb.combine(child2.aabb) - - node = node.parent - - def _balance(self, A): - if A.isLeaf() or A.height < 2: - return A - - B = A.child1 - C = A.child2 - - balance = C.height - B.height - - # Rotate C up - if balance > 1: - F = C.child1; - G = C.child2; - - # Swap A and C - C.child1 = A; - C.parent = A.parent; - A.parent = C; - - # A's old parent should point to C - if C.parent != None: - if C.parent.child1 == A: - C.parent.child1 = C - else: - C.parent.child2 = C - else: - self.root = C - - # Rotate - if F.height > G.height: - C.child2 = F - A.child2 = G - G.parent = A - A.aabb = B.aabb.combine(G.aabb) - C.aabb = A.aabb.combine(F.aabb) - - A.height = 1 + max(B.height, G.height) - C.height = 1 + max(A.height, F.height) - else: - C.child2 = G - A.child2 = F - F.parent = A - A.aabb = B.aabb.combine(F.aabb) - C.aabb = A.aabb.combine(G.aabb) - - A.height = 1 + max(B.height, F.height) - C.height = 1 + max(A.height, G.height) - - return C; - - # Rotate B up - if balance < -1: - D = B.child1 - E = B.child2 - - # Swap A and B - B.child1 = A - B.parent = A.parent - A.parent = B - - # A's old parent should point to B - if B.parent != None: - if B.parent.child1 == A: - B.parent.child1 = B - else: - B.parent.child2 = B - else: - self.root = B - - # Rotate - if D.height > E.height: - B.child2 = D - A.child1 = E - E.parent = A - A.aabb = C.aabb.combine(E.aabb) - B.aabb = A.aabb.combine(D.aabb) - - A.height = 1 + max(C.height, E.height) - B.height = 1 + max(A.height, D.height) - else: - B.child2 = E - A.child1 = D - D.parent = A - A.aabb = C.aabb.combine(D.aabb) - B.aabb = A.aabb.combine(E.aabb) - - A.height = 1 + max(C.height, D.height) - B.height = 1 + max(A.height, E.height) - - return B - - return A - - def query(self, aabb): - resultList = [] - if self.root != None: - self._query(self.root, aabb, resultList) - return resultList - - def _query(self, node, aabb, resultList): - if not aabb.overlap(node.aabb): - return - if node.isLeaf(): - resultList.append(node.aabb) - else: - self._query(node.child1, aabb, resultList) - self._query(node.child2, aabb, resultList) - - def __repr__(self): - s = "AABBTree:\n" - s += str(self.root.aabb) - return s - -if __name__ == '__main__': - tree = AABBTree() - tree.insert(AABB(Vector3(0,0,0), Vector3(0,0,0))) - tree.insert(AABB(Vector3(1,1,1), Vector3(1,1,1))) - tree.insert(AABB(Vector3(0.5,0.5,0.5), Vector3(0.5,0.5,0.5))) - print(tree) - print(tree.query(AABB(Vector3(0,0,0), Vector3(0,0,0)))) - diff --git a/octoprint/util/virtual.py b/octoprint/util/virtual.py index cf699f6c5..6a4455939 100644 --- a/octoprint/util/virtual.py +++ b/octoprint/util/virtual.py @@ -32,6 +32,7 @@ class VirtualPrinter(): self._newSdFilePos = None self.currentLine = 0 + self.lastN = 0 waitThread = threading.Thread(target=self._sendWaitAfterTimeout) waitThread.start() @@ -40,18 +41,49 @@ class VirtualPrinter(): if self.readList is None: return - # strip checksum data = data.strip() + + # strip checksum if "*" in data: data = data[:data.rfind("*")] self.currentLine += 1 + elif settings().getBoolean(["devel", "virtualPrinter", "forceChecksum"]): + self.readList.append("Error: Missing checksum") + return + + # track N = N + 1 + if data.startswith("N") and "M110" in data: + linenumber = int(re.search("N([0-9]+)", data).group(1)) + self.lastN = linenumber + self.currentLine = linenumber + return + elif data.startswith("N"): + linenumber = int(re.search("N([0-9]+)", data).group(1)) + expected = self.lastN + 1 + if linenumber != expected: + self.readList.append("Error: expected line %d got %d" % (expected, linenumber)) + self.readList.append("Resend:%d" % expected) + if settings().getBoolean(["devel", "virtualPrinter", "okAfterResend"]): + self.readList.append("ok") + return + elif self.currentLine == 100: + # simulate a resend at line 100 of the last 5 lines + self.lastN = 94 + self.readList.append("Error: Line Number is not Last Line Number\n") + self.readList.append("rs %d\n" % (self.currentLine - 5)) + if settings().getBoolean(["devel", "virtualPrinter", "okAfterResend"]): + self.readList.append("ok") + return + else: + self.lastN = linenumber + data += "\n" # shortcut for writing to SD if self._writingToSd and not self._selectedSdFile is None and not "M29" in data: with open(self._selectedSdFile, "a") as f: f.write(data) - self.readList.append("ok") + self._sendOk() return #print "Send: %s" % (data.rstrip()) @@ -105,11 +137,6 @@ class VirtualPrinter(): if self._sdCardReady: filename = data.split(None, 1)[1].strip() self._deleteSdFile(filename) - elif "M110" in data: - # reset current line - self.currentLine = int(re.search('^N([0-9]+)', data).group(1)) - self.readList.append("reset line to %r\n" % self.currentLine) - self.readList.append("ok\n") elif "M114" in data: # send dummy position report self.readList.append("ok C: X:10.00 Y:3.20 Z:5.20 E:1.24") @@ -119,19 +146,15 @@ class VirtualPrinter(): elif "M999" in data: # mirror Marlin behaviour self.readList.append("Resend: 1") - elif self.currentLine == 100: - # simulate a resend at line 100 of the last 5 lines - self.readList.append("Error: Line Number is not Last Line Number\n") - self.readList.append("rs %d\n" % (self.currentLine - 5)) elif len(data.strip()) > 0: - self.readList.append("ok\n") + self._sendOk() def _listSd(self): self.readList.append("Begin file list") for osFile in os.listdir(self._virtualSd): self.readList.append(osFile.upper()) self.readList.append("End file list") - self.readList.append("ok") + self._sendOk() def _selectSdFile(self, filename): file = os.path.join(self._virtualSd, filename).lower() @@ -149,11 +172,11 @@ class VirtualPrinter(): self._sdPrinter = threading.Thread(target=self._sdPrintingWorker) self._sdPrinter.start() self._sdPrintingSemaphore.set() - self.readList.append("ok") + self._sendOk() def _pauseSdPrint(self): self._sdPrintingSemaphore.clear() - self.readList.append("ok") + self._sendOk() def _setSdPos(self, pos): self._newSdFilePos = pos @@ -175,12 +198,12 @@ class VirtualPrinter(): self._writingToSd = True self._selectedSdFile = file self.readList.append("Writing to file: %s" % filename) - self.readList.append("ok") + self._sendOk() def _finishSdFile(self): self._writingToSd = False self._selectedSdFile = None - self.readList.append("ok") + self._sendOk() def _sdPrintingWorker(self): self._selectedSdFilePos = 0 @@ -220,7 +243,7 @@ class VirtualPrinter(): file = os.path.join(self._virtualSd, filename) if os.path.exists(file) and os.path.isfile(file): os.remove(file) - self.readList.append("ok") + self._sendOk() def readline(self): if self.readList is None: @@ -249,7 +272,14 @@ class VirtualPrinter(): def close(self): self.readList = None + def _sendOk(self): + if settings().getBoolean(["devel", "virtualPrinter", "okWithLinenumber"]): + self.readList.append("ok %d" % self.lastN) + else: + self.readList.append("ok") + def _sendWaitAfterTimeout(self, timeout=5): time.sleep(timeout) - self.readList.append("wait") + if self.readList is not None: + self.readList.append("wait") diff --git a/requirements-bbb.txt b/requirements-bbb.txt index 6bf2a2dd2..aa0930931 100644 --- a/requirements-bbb.txt +++ b/requirements-bbb.txt @@ -1,7 +1,8 @@ flask==0.9 werkzeug==0.8.3 tornado==3.0.2 -tornadio2==0.0.4 +sockjs-tornado>=1.0.0 PyYAML==3.10 Flask-Login==0.2.2 Flask-Principal==0.3.5 +netaddr>=0.7.10 diff --git a/requirements.txt b/requirements.txt index 7c644b5ec..9c5b0cddb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,9 +1,10 @@ flask==0.9 werkzeug==0.8.3 tornado==3.0.2 -tornadio2==0.0.4 +sockjs-tornado>=1.0.0 PyYAML==3.10 Flask-Login==0.2.2 Flask-Principal==0.3.5 numpy>=1.6.2 pyserial>=2.6 +netaddr>=0.7.10