Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f9a9a405cd | ||
|
|
fa564c6029 | ||
|
|
36d1522f01 | ||
|
|
536e17eac4 | ||
|
|
887ec45b6b | ||
|
|
deb38f8455 | ||
|
|
293611287e | ||
|
|
7ebbf5911c | ||
|
|
d7e37cf658 | ||
|
|
e068012cfb | ||
|
|
d7f2075b1d | ||
|
|
e5ac94a16f | ||
|
|
f09d44d8a0 | ||
|
|
89cae22b91 | ||
|
|
0747336c0f | ||
|
|
bba625a68f | ||
|
|
b282a18f6b | ||
|
|
0fd9b3354a | ||
|
|
765b941472 | ||
|
|
64084bb628 | ||
|
|
df269eb4f7 | ||
|
|
722b03dca8 | ||
|
|
3ddfc93c1b | ||
|
|
5eb70fa57d | ||
|
|
ae3e474c92 | ||
|
|
297d101f5f | ||
|
|
4d2213544e | ||
|
|
895d077d85 | ||
|
|
35b010b059 | ||
|
|
fdfa433243 | ||
|
|
aa69d181bf | ||
|
|
e9f218208d | ||
|
|
8ca3baee04 | ||
|
|
3c68353c57 | ||
|
|
fe37ab3cd8 | ||
|
|
f2b0bfb7dc | ||
|
|
f7f8c09a77 | ||
|
|
37c949e83b | ||
|
|
b35258fad6 | ||
|
|
1a6030c737 | ||
|
|
9008a2fb7f | ||
|
|
47f8ab24d9 | ||
|
|
4b41a47f93 | ||
|
|
5d69ee8abc | ||
|
|
edd801aa7b | ||
|
|
ef8787acf9 | ||
|
|
29a9ee40d5 | ||
|
|
4094d28c07 | ||
|
|
3b56cdaaa3 | ||
|
|
079806f11c | ||
|
|
69052d7670 | ||
|
|
2afd715f77 | ||
|
|
8d78104be8 | ||
|
|
076c6764a0 | ||
|
|
8ff48ed88d | ||
|
|
00501f0913 | ||
|
|
4b05f125a0 | ||
|
|
df05a80201 | ||
|
|
6b2912b0e2 | ||
|
|
4ea2345eda | ||
|
|
a7477e0184 | ||
|
|
6492ab66b0 | ||
|
|
78972b1d40 | ||
|
|
51ae782f02 | ||
|
|
a87541c354 | ||
|
|
4fbb8f1164 | ||
|
|
32b2c1e2e7 | ||
|
|
242e552f4d | ||
|
|
d7e6d51cc2 | ||
|
|
708c12ddbe | ||
|
|
21d16c8ba0 | ||
|
|
51b0df5c1f | ||
|
|
f07305ae4f | ||
|
|
b352078917 | ||
|
|
79f379a868 | ||
|
|
520c856c57 | ||
|
|
7a4bb8b94e | ||
|
|
4b7300c2e8 | ||
|
|
a7b7f26da5 | ||
|
|
26ebfe3e1f | ||
|
|
8212f28b90 | ||
|
|
2421824535 | ||
|
|
8e500b78aa | ||
|
|
70b2325de0 | ||
|
|
58cbad1828 | ||
|
|
aef0322617 | ||
|
|
d4bb75a2ee | ||
|
|
43cd85b8e4 | ||
|
|
f574267746 | ||
|
|
b2d715f041 | ||
|
|
2831ab0727 | ||
|
|
1f3160571c | ||
|
|
4c1fc14ac5 | ||
|
|
6d703d236a | ||
|
|
de635ae25f | ||
|
|
8dff6d6750 | ||
|
|
1e1e72c9c2 | ||
|
|
f51f4ad5cd | ||
|
|
711d18d9ad | ||
|
|
3cadbbeb85 | ||
|
|
d7fe15d635 | ||
|
|
d6b172c744 | ||
|
|
40650f1bde | ||
|
|
87edcc4966 | ||
|
|
09fa9bc28d | ||
|
|
280d8e8405 | ||
|
|
0eeca11838 | ||
|
|
281ad0f046 |
No files matched your search
@@ -4,9 +4,20 @@
|
|||||||
*.pyc
|
*.pyc
|
||||||
*.zip
|
*.zip
|
||||||
*.exe
|
*.exe
|
||||||
|
*.gcode
|
||||||
|
*.swp
|
||||||
|
darwin-Cura-*
|
||||||
|
win32-Cura-*
|
||||||
|
linux-Cura-*
|
||||||
*.iml
|
*.iml
|
||||||
|
Printrun
|
||||||
|
=======
|
||||||
.idea
|
.idea
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
Cura/current_profile.ini
|
||||||
|
Cura/preferences.ini
|
||||||
build
|
build
|
||||||
dist
|
dist
|
||||||
|
pypy
|
||||||
OctoPrint.egg-info
|
OctoPrint.egg-info
|
||||||
|
*.orig
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
Bug Reports
|
||||||
|
-----------
|
||||||
|
|
||||||
|
**READ [How to file a bug report](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)!**.
|
||||||
|
|
||||||
|
Pull Requests
|
||||||
|
-------------
|
||||||
|
|
||||||
|
1. Please create all pull requests against the `devel` branch.
|
||||||
|
2. Create **one pull request per feature/bug fix**.
|
||||||
|
3. Create a custom branch for your feature/bug fix and use that as base for your pull request. Pull requests directly against your version of `devel` will be closed.
|
||||||
|
4. In your pull request's description, state what your pull request is doing, as in, what feature does it implement, what bug does it fix.
|
||||||
|
|
||||||
@@ -1,2 +1,2 @@
|
|||||||
recursive-include octoprint/static *
|
recursive-include src/octoprint/static *
|
||||||
recursive-include octoprint/templates *
|
recursive-include src/octoprint/templates *
|
||||||
@@ -21,6 +21,14 @@ Please create all pull requests against the [devel branch](https://github.com/fo
|
|||||||
features and then merged against master when those features are deemed mature enough for general consumption. In case
|
features and then merged against master when those features are deemed mature enough for general consumption. In case
|
||||||
of bug fixes I'll take care to cherry pick them against master if the bugs they are fixing are critical.
|
of bug fixes I'll take care to cherry pick them against master if the bugs they are fixing are critical.
|
||||||
|
|
||||||
|
Installation
|
||||||
|
------------
|
||||||
|
|
||||||
|
Installation instructions for installing from source for different operating systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
|
||||||
|
|
||||||
|
If you want to run OctoPrint on a Raspberry Pi you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
|
||||||
|
which is a custom SD card image that includes OctoPrint plus dependencies.
|
||||||
|
|
||||||
Dependencies
|
Dependencies
|
||||||
------------
|
------------
|
||||||
|
|
||||||
|
|||||||
@@ -1,49 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
#
|
|
||||||
# Copy this script to /etc/init.d/octoprint and adjust the variables
|
|
||||||
# at the top to match your installation (should be okay for a Raspian
|
|
||||||
# setup). Then link it to the correct run levels. On Debian/Rasbian
|
|
||||||
# just call 'sudo update-rc.d octoprint defaults'
|
|
||||||
|
|
||||||
### BEGIN INIT INFO
|
|
||||||
# Provides: octoprint
|
|
||||||
# Required-Start: $local_fs networking
|
|
||||||
# Required-Stop:
|
|
||||||
# Should-Start:
|
|
||||||
# Default-Start: 2 3 4 5
|
|
||||||
# Default-Stop: 0 1 6
|
|
||||||
# Short-Description: Run octoprint
|
|
||||||
# Description: Octoprint provides a responsive web interface for
|
|
||||||
# controlling a 3D printer
|
|
||||||
### END INIT INFO
|
|
||||||
|
|
||||||
|
|
||||||
# OctoPrint's run script
|
|
||||||
DAEMON=/home/pi/OctoPrint/run
|
|
||||||
|
|
||||||
# Port to use
|
|
||||||
PORT=5000
|
|
||||||
|
|
||||||
# Run as this user
|
|
||||||
RUNAS=pi
|
|
||||||
|
|
||||||
# Exit if the run script is not found
|
|
||||||
[ -x "$DAEMON" ] || exit 0
|
|
||||||
|
|
||||||
|
|
||||||
case "$1" in
|
|
||||||
start)
|
|
||||||
su $RUNAS -c "$DAEMON --port=$PORT --daemon start"
|
|
||||||
;;
|
|
||||||
stop)
|
|
||||||
su $RUNAS -c "$DAEMON --port=$PORT --daemon stop"
|
|
||||||
;;
|
|
||||||
restart)
|
|
||||||
su $RUNAS -c "$DAEMON --port=$PORT --daemon restart"
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
echo "Usage: $0 {start|stop|restart}" >&2
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
:
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
|
|
||||||
@@ -6,3 +6,5 @@ PyYAML==3.10
|
|||||||
Flask-Login==0.2.2
|
Flask-Login==0.2.2
|
||||||
Flask-Principal==0.3.5
|
Flask-Principal==0.3.5
|
||||||
netaddr>=0.7.10
|
netaddr>=0.7.10
|
||||||
|
mock>=1.0.1
|
||||||
|
nose>=1.3.0
|
||||||
@@ -5,6 +5,7 @@ sockjs-tornado>=1.0.0
|
|||||||
PyYAML==3.10
|
PyYAML==3.10
|
||||||
Flask-Login==0.2.2
|
Flask-Login==0.2.2
|
||||||
Flask-Principal==0.3.5
|
Flask-Principal==0.3.5
|
||||||
numpy>=1.6.2
|
|
||||||
pyserial>=2.6
|
pyserial>=2.6
|
||||||
netaddr>=0.7.10
|
netaddr>=0.7.10
|
||||||
|
mock>=1.0.1
|
||||||
|
nose>=1.3.0
|
||||||
@@ -1,65 +1,22 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
import os
|
||||||
import sys
|
import sys
|
||||||
from octoprint.daemon import Daemon
|
|
||||||
from octoprint.server import Server
|
|
||||||
|
|
||||||
class Main(Daemon):
|
basedir = os.path.dirname(os.path.realpath(__file__))
|
||||||
def __init__(self, pidfile, configfile, basedir, host, port, debug):
|
|
||||||
Daemon.__init__(self, pidfile)
|
|
||||||
|
|
||||||
self._configfile = configfile
|
old = os.path.join(basedir, "octoprint")
|
||||||
self._basedir = basedir
|
if os.path.exists(old):
|
||||||
self._host = host
|
# rename left-overs from old file structure
|
||||||
self._port = port
|
print """
|
||||||
self._debug = debug
|
Found left-overs from old file structure, renaming to
|
||||||
|
"octoprint.backup". Please remove this manually (I don't
|
||||||
|
dare to do so myself since you might have changes in there
|
||||||
|
I don't know anything about).
|
||||||
|
"""
|
||||||
|
os.rename(old, os.path.join(basedir, "octoprint.backup"))
|
||||||
|
|
||||||
def run(self):
|
sys.path.insert(0, os.path.join(basedir, "src"))
|
||||||
octoprint = Server(self._configfile, self._basedir, self._host, self._port, self._debug)
|
|
||||||
octoprint.run()
|
|
||||||
|
|
||||||
def main():
|
import octoprint
|
||||||
import argparse
|
octoprint.main()
|
||||||
|
|
||||||
parser = argparse.ArgumentParser(prog="run")
|
|
||||||
|
|
||||||
parser.add_argument("-d", "--debug", action="store_true", dest="debug",
|
|
||||||
help="Enable debug mode")
|
|
||||||
|
|
||||||
parser.add_argument("--host", action="store", type=str, dest="host",
|
|
||||||
help="Specify the host on which to bind the server")
|
|
||||||
parser.add_argument("--port", action="store", type=int, dest="port",
|
|
||||||
help="Specify the port on which to bind the server")
|
|
||||||
|
|
||||||
parser.add_argument("-c", "--config", action="store", dest="config",
|
|
||||||
help="Specify the config file to use. OctoPrint needs to have write access for the settings dialog to work. Defaults to ~/.octoprint/config.yaml")
|
|
||||||
parser.add_argument("-b", "--basedir", action="store", dest="basedir",
|
|
||||||
help="Specify the basedir to use for uploads, timelapses etc. OctoPrint needs to have write access. Defaults to ~/.octoprint")
|
|
||||||
|
|
||||||
parser.add_argument("--daemon", action="store", type=str, choices=["start", "stop", "restart"],
|
|
||||||
help="Daemonize/control daemonized OctoPrint instance (only supported under Linux right now)")
|
|
||||||
parser.add_argument("--pid", action="store", type=str, dest="pidfile", default="/tmp/octoprint.pid",
|
|
||||||
help="Pidfile to use for daemonizing, defaults to /tmp/octoprint.pid")
|
|
||||||
|
|
||||||
parser.add_argument("--iknowwhatimdoing", action="store_true", dest="allowRoot",
|
|
||||||
help="Allow OctoPrint to run as user root")
|
|
||||||
|
|
||||||
args = parser.parse_args()
|
|
||||||
|
|
||||||
if args.daemon:
|
|
||||||
if sys.platform == "darwin" or sys.platform == "win32":
|
|
||||||
print >> sys.stderr, "Sorry, daemon mode is only supported under Linux right now"
|
|
||||||
sys.exit(2)
|
|
||||||
|
|
||||||
daemon = Main(args.pidfile, args.config, args.basedir, args.host, args.port, args.debug)
|
|
||||||
if "start" == args.daemon:
|
|
||||||
daemon.start()
|
|
||||||
elif "stop" == args.daemon:
|
|
||||||
daemon.stop()
|
|
||||||
elif "restart" == args.daemon:
|
|
||||||
daemon.restart()
|
|
||||||
else:
|
|
||||||
octoprint = Server(args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot)
|
|
||||||
octoprint.run()
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# Configuration for /etc/init.d/octoprint
|
||||||
|
|
||||||
|
# The init.d script will only run if this variable non-empty.
|
||||||
|
OCTOPRINT_USER=pi
|
||||||
|
|
||||||
|
# On what port to run daemon, default is 5000
|
||||||
|
PORT=5000
|
||||||
|
|
||||||
|
# Path to the OctoPrint executable, use this to override the default setting "/usr/bin/octoprint"
|
||||||
|
#DAEMON=/path/to/octoprint/executable
|
||||||
|
|
||||||
|
# What arguments to pass to octoprint, usually no need to touch this
|
||||||
|
DAEMON_ARGS="--port=$PORT"
|
||||||
|
|
||||||
|
# Umask of files octoprint generates, Change this to 000 if running octoprint as its own, separate user
|
||||||
|
UMASK=022
|
||||||
|
|
||||||
|
# Should we run at startup?
|
||||||
|
START=yes
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
### BEGIN INIT INFO
|
||||||
|
# Provides: octoprint
|
||||||
|
# Required-Start: $local_fs networking
|
||||||
|
# Required-Stop:
|
||||||
|
# Should-Start:
|
||||||
|
# Should-Stop:
|
||||||
|
# Default-Start: 2 3 4 5
|
||||||
|
# Default-Stop: 0 1 6
|
||||||
|
# Short-Description: OctoPrint daemon
|
||||||
|
# Description: Starts the OctoPrint daemon with the user specified in
|
||||||
|
# /etc/default/octoprint.
|
||||||
|
### END INIT INFO
|
||||||
|
|
||||||
|
# Author: Sami Olmari
|
||||||
|
|
||||||
|
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
|
||||||
|
DESC="Octoprint Daemon"
|
||||||
|
NAME="Octoprint"
|
||||||
|
DAEMON=/usr/bin/octoprint
|
||||||
|
PIDFILE=/var/run/$NAME.pid
|
||||||
|
PKGNAME=octoprint
|
||||||
|
SCRIPTNAME=/etc/init.d/$PKGNAME
|
||||||
|
|
||||||
|
# Read configuration variable file if it is present
|
||||||
|
[ -r /etc/default/$PKGNAME ] && . /etc/default/$PKGNAME
|
||||||
|
|
||||||
|
# Exit if the octoprint is not installed
|
||||||
|
[ -x "$DAEMON" ] || exit 0
|
||||||
|
|
||||||
|
# Load the VERBOSE setting and other rcS variables
|
||||||
|
[ -f /etc/default/rcS ] && . /etc/default/rcS
|
||||||
|
|
||||||
|
# Define LSB log_* functions.
|
||||||
|
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
|
||||||
|
. /lib/lsb/init-functions
|
||||||
|
|
||||||
|
if [ -z "$START" -o "$START" != "yes" ]
|
||||||
|
then
|
||||||
|
log_warning_msg "Not starting $PKGNAME, edit /etc/default/$PKGNAME to start it."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -z "$OCTOPRINT_USER" ]
|
||||||
|
then
|
||||||
|
log_warning_msg "Not starting $PKGNAME, OCTOPRINT_USER not set in /etc/default/$PKGNAME."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
#
|
||||||
|
# Function to verify if a pid is alive
|
||||||
|
#
|
||||||
|
is_alive()
|
||||||
|
{
|
||||||
|
pid=`cat $1` > /dev/null 2>&1
|
||||||
|
kill -0 $pid > /dev/null 2>&1
|
||||||
|
return $?
|
||||||
|
}
|
||||||
|
|
||||||
|
#
|
||||||
|
# Function that starts the daemon/service
|
||||||
|
#
|
||||||
|
do_start()
|
||||||
|
{
|
||||||
|
# Return
|
||||||
|
# 0 if daemon has been started
|
||||||
|
# 1 if daemon was already running
|
||||||
|
# 2 if daemon could not be started
|
||||||
|
|
||||||
|
is_alive $PIDFILE
|
||||||
|
RETVAL="$?"
|
||||||
|
|
||||||
|
if [ $RETVAL != 0 ]; then
|
||||||
|
start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile \
|
||||||
|
--exec $DAEMON --chuid $OCTOPRINT_USER --user $OCTOPRINT_USER --umask $UMASK -- $DAEMON_ARGS
|
||||||
|
RETVAL="$?"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
#
|
||||||
|
# Function that stops the daemon/service
|
||||||
|
#
|
||||||
|
do_stop()
|
||||||
|
{
|
||||||
|
# Return
|
||||||
|
# 0 if daemon has been stopped
|
||||||
|
# 1 if daemon was already stopped
|
||||||
|
# 2 if daemon could not be stopped
|
||||||
|
# other if a failure occurred
|
||||||
|
|
||||||
|
start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --user $OCTOPRINT_USER --pidfile $PIDFILE
|
||||||
|
RETVAL="$?"
|
||||||
|
[ "$RETVAL" = "2" ] && return 2
|
||||||
|
|
||||||
|
rm -f $PIDFILE
|
||||||
|
|
||||||
|
[ "$RETVAL" = "0" ] && return 0 || return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
case "$1" in
|
||||||
|
start)
|
||||||
|
[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
|
||||||
|
do_start
|
||||||
|
case "$?" in
|
||||||
|
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
|
||||||
|
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
stop)
|
||||||
|
[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
|
||||||
|
do_stop
|
||||||
|
case "$?" in
|
||||||
|
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
|
||||||
|
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
restart)
|
||||||
|
log_daemon_msg "Restarting $DESC" "$NAME"
|
||||||
|
do_stop
|
||||||
|
case "$?" in
|
||||||
|
0|1)
|
||||||
|
do_start
|
||||||
|
case "$?" in
|
||||||
|
0) log_end_msg 0 ;;
|
||||||
|
1) log_end_msg 1 ;; # Old process is still running
|
||||||
|
*) log_end_msg 1 ;; # Failed to start
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
# Failed to stop
|
||||||
|
log_end_msg 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2
|
||||||
|
exit 3
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
from setuptools import setup, find_packages
|
from setuptools import setup, find_packages
|
||||||
|
|
||||||
VERSION = "1.0.0-rc1"
|
VERSION = "1.0.0"
|
||||||
|
|
||||||
def params():
|
def params():
|
||||||
name = "OctoPrint"
|
name = "OctoPrint"
|
||||||
@@ -34,11 +34,23 @@ def params():
|
|||||||
url = "http://octoprint.org"
|
url = "http://octoprint.org"
|
||||||
license = "AGPLv3"
|
license = "AGPLv3"
|
||||||
|
|
||||||
packages = find_packages()
|
packages = find_packages(where="src")
|
||||||
|
package_dir = {"octoprint": "src/octoprint"}
|
||||||
|
|
||||||
include_package_data = True
|
include_package_data = True
|
||||||
zip_safe = False
|
zip_safe = False
|
||||||
install_requires = open("requirements.txt").read().split("\n")
|
install_requires = open("requirements.txt").read().split("\n")
|
||||||
|
|
||||||
|
entry_points = {
|
||||||
|
"console_scripts": [
|
||||||
|
"octoprint = octoprint:main"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#scripts = {
|
||||||
|
# "scripts/octoprint.init": "/etc/init.d/octoprint"
|
||||||
|
#}
|
||||||
|
|
||||||
return locals()
|
return locals()
|
||||||
|
|
||||||
setup(**params())
|
setup(**params())
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
import sys
|
||||||
|
from octoprint.daemon import Daemon
|
||||||
|
from octoprint.server import Server
|
||||||
|
|
||||||
|
|
||||||
|
class Main(Daemon):
|
||||||
|
def __init__(self, pidfile, configfile, basedir, host, port, debug, allowRoot):
|
||||||
|
Daemon.__init__(self, pidfile)
|
||||||
|
|
||||||
|
self._configfile = configfile
|
||||||
|
self._basedir = basedir
|
||||||
|
self._host = host
|
||||||
|
self._port = port
|
||||||
|
self._debug = debug
|
||||||
|
self._allowRoot = allowRoot
|
||||||
|
|
||||||
|
def run(self):
|
||||||
|
octoprint = Server(self._configfile, self._basedir, self._host, self._port, self._debug, self._allowRoot)
|
||||||
|
octoprint.run()
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(prog="run")
|
||||||
|
|
||||||
|
parser.add_argument("-d", "--debug", action="store_true", dest="debug",
|
||||||
|
help="Enable debug mode")
|
||||||
|
|
||||||
|
parser.add_argument("--host", action="store", type=str, dest="host",
|
||||||
|
help="Specify the host on which to bind the server")
|
||||||
|
parser.add_argument("--port", action="store", type=int, dest="port",
|
||||||
|
help="Specify the port on which to bind the server")
|
||||||
|
|
||||||
|
parser.add_argument("-c", "--config", action="store", dest="config",
|
||||||
|
help="Specify the config file to use. OctoPrint needs to have write access for the settings dialog to work. Defaults to ~/.octoprint/config.yaml")
|
||||||
|
parser.add_argument("-b", "--basedir", action="store", dest="basedir",
|
||||||
|
help="Specify the basedir to use for uploads, timelapses etc. OctoPrint needs to have write access. Defaults to ~/.octoprint")
|
||||||
|
|
||||||
|
parser.add_argument("--daemon", action="store", type=str, choices=["start", "stop", "restart"],
|
||||||
|
help="Daemonize/control daemonized OctoPrint instance (only supported under Linux right now)")
|
||||||
|
parser.add_argument("--pid", action="store", type=str, dest="pidfile", default="/tmp/octoprint.pid",
|
||||||
|
help="Pidfile to use for daemonizing, defaults to /tmp/octoprint.pid")
|
||||||
|
|
||||||
|
parser.add_argument("--iknowwhatimdoing", action="store_true", dest="allowRoot",
|
||||||
|
help="Allow OctoPrint to run as user root")
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
if args.daemon:
|
||||||
|
if sys.platform == "darwin" or sys.platform == "win32":
|
||||||
|
print >> sys.stderr, "Sorry, daemon mode is only supported under Linux right now"
|
||||||
|
sys.exit(2)
|
||||||
|
|
||||||
|
daemon = Main(args.pidfile, args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot)
|
||||||
|
if "start" == args.daemon:
|
||||||
|
daemon.start()
|
||||||
|
elif "stop" == args.daemon:
|
||||||
|
daemon.stop()
|
||||||
|
elif "restart" == args.daemon:
|
||||||
|
daemon.restart()
|
||||||
|
else:
|
||||||
|
octoprint = Server(args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot)
|
||||||
|
octoprint.run()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ class Daemon:
|
|||||||
# decouple from parent environment
|
# decouple from parent environment
|
||||||
os.chdir('/')
|
os.chdir('/')
|
||||||
os.setsid()
|
os.setsid()
|
||||||
os.umask(0)
|
os.umask(002)
|
||||||
|
|
||||||
# do second fork
|
# do second fork
|
||||||
try:
|
try:
|
||||||
@@ -7,6 +7,8 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
|||||||
import datetime
|
import datetime
|
||||||
import logging
|
import logging
|
||||||
import subprocess
|
import subprocess
|
||||||
|
import Queue
|
||||||
|
import threading
|
||||||
|
|
||||||
from octoprint.settings import settings
|
from octoprint.settings import settings
|
||||||
|
|
||||||
@@ -28,6 +30,27 @@ class EventManager(object):
|
|||||||
self._registeredListeners = {}
|
self._registeredListeners = {}
|
||||||
self._logger = logging.getLogger(__name__)
|
self._logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
self._queue = Queue.PriorityQueue()
|
||||||
|
self._worker = threading.Thread(target=self._work)
|
||||||
|
self._worker.daemon = True
|
||||||
|
self._worker.start()
|
||||||
|
|
||||||
|
def _work(self):
|
||||||
|
while True:
|
||||||
|
(event, payload) = self._queue.get(True)
|
||||||
|
|
||||||
|
eventListeners = self._registeredListeners.get(event, None)
|
||||||
|
if eventListeners is None:
|
||||||
|
return
|
||||||
|
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
|
||||||
|
|
||||||
|
for listener in eventListeners:
|
||||||
|
self._logger.debug("Sending action to %r" % listener)
|
||||||
|
try:
|
||||||
|
listener(event, payload)
|
||||||
|
except:
|
||||||
|
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
|
||||||
|
|
||||||
def fire(self, event, payload=None):
|
def fire(self, event, payload=None):
|
||||||
"""
|
"""
|
||||||
Fire an event to anyone subscribed to it
|
Fire an event to anyone subscribed to it
|
||||||
@@ -41,16 +64,7 @@ class EventManager(object):
|
|||||||
|
|
||||||
if not event in self._registeredListeners.keys():
|
if not event in self._registeredListeners.keys():
|
||||||
return
|
return
|
||||||
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
|
self._queue.put((event, payload), 0)
|
||||||
|
|
||||||
eventListeners = self._registeredListeners[event]
|
|
||||||
for listener in eventListeners:
|
|
||||||
self._logger.debug("Sending action to %r" % listener)
|
|
||||||
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):
|
def subscribe(self, event, callback):
|
||||||
"""
|
"""
|
||||||
@@ -68,6 +82,10 @@ class EventManager(object):
|
|||||||
self._logger.debug("Subscribed listener %r for event %s" % (callback, event))
|
self._logger.debug("Subscribed listener %r for event %s" % (callback, event))
|
||||||
|
|
||||||
def unsubscribe (self, event, callback):
|
def unsubscribe (self, event, callback):
|
||||||
|
"""
|
||||||
|
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
|
||||||
|
"""
|
||||||
|
|
||||||
if not event in self._registeredListeners:
|
if not event in self._registeredListeners:
|
||||||
# no callback registered for callback, just return
|
# no callback registered for callback, just return
|
||||||
return
|
return
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
class FileDestinations(object):
|
||||||
|
|
||||||
|
SDCARD = "sdcard"
|
||||||
|
LOCAL = "local"
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
|
||||||
|
|
||||||
|
class FileTypes(object):
|
||||||
|
|
||||||
|
STL = "stl"
|
||||||
|
GCODE = "gcode"
|
||||||
@@ -11,23 +11,67 @@ import time
|
|||||||
import logging
|
import logging
|
||||||
import octoprint.util as util
|
import octoprint.util as util
|
||||||
import octoprint.util.gcodeInterpreter as gcodeInterpreter
|
import octoprint.util.gcodeInterpreter as gcodeInterpreter
|
||||||
|
|
||||||
from octoprint.settings import settings
|
from octoprint.settings import settings
|
||||||
|
from octoprint.events import eventManager
|
||||||
|
from octoprint.filemanager.destinations import FileDestinations
|
||||||
|
|
||||||
from werkzeug.utils import secure_filename
|
from werkzeug.utils import secure_filename
|
||||||
|
|
||||||
SUPPORTED_EXTENSIONS=["gcode", "gco"]
|
GCODE_EXTENSIONS = ["gcode", "gco", "g"]
|
||||||
|
STL_EXTENSIONS = ["stl"]
|
||||||
|
SUPPORTED_EXTENSIONS = GCODE_EXTENSIONS + STL_EXTENSIONS
|
||||||
|
|
||||||
|
def isGcodeFileName(filename):
|
||||||
|
"""Simple helper to determine if a filename has the .gcode extension.
|
||||||
|
|
||||||
|
:param filename: :class: `str`
|
||||||
|
|
||||||
|
:returns boolean:
|
||||||
|
"""
|
||||||
|
return "." in filename and filename.rsplit(".", 1)[1].lower() in GCODE_EXTENSIONS
|
||||||
|
|
||||||
|
|
||||||
|
def isSTLFileName(filename):
|
||||||
|
"""Simple helper to determine if a filename has the .stl extension.
|
||||||
|
|
||||||
|
:param filename: :class: `str`
|
||||||
|
|
||||||
|
:returns boolean:
|
||||||
|
"""
|
||||||
|
return "." in filename and filename.rsplit(".", 1)[1].lower() in STL_EXTENSIONS
|
||||||
|
|
||||||
|
|
||||||
|
def genGcodeFileName(filename):
|
||||||
|
if not filename:
|
||||||
|
return None
|
||||||
|
|
||||||
|
name, ext = filename.rsplit(".", 1)
|
||||||
|
return name + ".gcode"
|
||||||
|
|
||||||
|
|
||||||
|
def genStlFileName(filename):
|
||||||
|
if not filename:
|
||||||
|
return None
|
||||||
|
|
||||||
|
name, ext = filename.rsplit(".", 1)
|
||||||
|
return name + ".stl"
|
||||||
|
|
||||||
|
|
||||||
class GcodeManager:
|
class GcodeManager:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._logger = logging.getLogger(__name__)
|
self._logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
self._uploadFolder = settings().getBaseFolder("uploads")
|
self._settings = settings()
|
||||||
|
|
||||||
|
self._uploadFolder = self._settings.getBaseFolder("uploads")
|
||||||
|
|
||||||
self._callbacks = []
|
self._callbacks = []
|
||||||
|
|
||||||
self._metadata = {}
|
self._metadata = {}
|
||||||
self._metadataDirty = False
|
self._metadataDirty = False
|
||||||
self._metadataFile = os.path.join(self._uploadFolder, "metadata.yaml")
|
self._metadataFile = os.path.join(self._uploadFolder, "metadata.yaml")
|
||||||
|
self._metadataTempFile = os.path.join(self._uploadFolder, "metadata.yaml.tmp")
|
||||||
self._metadataFileAccessMutex = threading.Lock()
|
self._metadataFileAccessMutex = threading.Lock()
|
||||||
|
|
||||||
self._metadataAnalyzer = MetadataAnalyzer(getPathCallback=self.getAbsolutePath, loadedCallback=self._onMetadataAnalysisFinished)
|
self._metadataAnalyzer = MetadataAnalyzer(getPathCallback=self.getAbsolutePath, loadedCallback=self._onMetadataAnalysisFinished)
|
||||||
@@ -38,6 +82,9 @@ class GcodeManager:
|
|||||||
def _processAnalysisBacklog(self):
|
def _processAnalysisBacklog(self):
|
||||||
for osFile in os.listdir(self._uploadFolder):
|
for osFile in os.listdir(self._uploadFolder):
|
||||||
filename = self._getBasicFilename(osFile)
|
filename = self._getBasicFilename(osFile)
|
||||||
|
if not isGcodeFileName(filename):
|
||||||
|
continue
|
||||||
|
|
||||||
absolutePath = self.getAbsolutePath(filename)
|
absolutePath = self.getAbsolutePath(filename)
|
||||||
if absolutePath is None:
|
if absolutePath is None:
|
||||||
continue
|
continue
|
||||||
@@ -66,7 +113,7 @@ class GcodeManager:
|
|||||||
if gcode.extrusionAmount:
|
if gcode.extrusionAmount:
|
||||||
analysisResult["filament"] = "%.2fm" % (gcode.extrusionAmount / 1000)
|
analysisResult["filament"] = "%.2fm" % (gcode.extrusionAmount / 1000)
|
||||||
if gcode.calculateVolumeCm3():
|
if gcode.calculateVolumeCm3():
|
||||||
analysisResult["filament"] += " / %.2fcm³" % gcode.calculateVolumeCm3()
|
analysisResult["filament"] += " / %.2fcm³" % gcode.calculateVolumeCm3()
|
||||||
dirty = True
|
dirty = True
|
||||||
|
|
||||||
if dirty:
|
if dirty:
|
||||||
@@ -89,9 +136,11 @@ class GcodeManager:
|
|||||||
return
|
return
|
||||||
|
|
||||||
with self._metadataFileAccessMutex:
|
with self._metadataFileAccessMutex:
|
||||||
with open(self._metadataFile, "wb") as f:
|
with open(self._metadataTempFile, "wb") as f:
|
||||||
yaml.safe_dump(self._metadata, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
yaml.safe_dump(self._metadata, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||||
self._metadataDirty = False
|
self._metadataDirty = False
|
||||||
|
util.safeRename(self._metadataTempFile, self._metadataFile)
|
||||||
|
|
||||||
self._loadMetadata()
|
self._loadMetadata()
|
||||||
self._sendUpdateTrigger("gcodeFiles")
|
self._sendUpdateTrigger("gcodeFiles")
|
||||||
|
|
||||||
@@ -117,7 +166,38 @@ class GcodeManager:
|
|||||||
|
|
||||||
#~~ file handling
|
#~~ file handling
|
||||||
|
|
||||||
def addFile(self, file):
|
def addFile(self, file, destination, uploadCallback=None):
|
||||||
|
"""
|
||||||
|
Adds the given file for the given destination to the systems. Takes care of slicing if enabled and
|
||||||
|
necessary.
|
||||||
|
|
||||||
|
If the file's processing won't be finished directly with the return from this method but happen
|
||||||
|
asynchronously in the background (e.g. due to slicing), returns a tuple containing the just added file's
|
||||||
|
filename and False. Otherwise returns a tuple (filename, True).
|
||||||
|
"""
|
||||||
|
if not file or not destination:
|
||||||
|
return None, True
|
||||||
|
|
||||||
|
curaEnabled = self._settings.getBoolean(["cura", "enabled"])
|
||||||
|
filename = file.filename
|
||||||
|
|
||||||
|
absolutePath = self.getAbsolutePath(filename, mustExist=False)
|
||||||
|
gcode = isGcodeFileName(filename)
|
||||||
|
|
||||||
|
if absolutePath is None or (not curaEnabled and not gcode):
|
||||||
|
return None, True
|
||||||
|
|
||||||
|
file.save(absolutePath)
|
||||||
|
|
||||||
|
if gcode:
|
||||||
|
return self.processGcode(absolutePath, destination, uploadCallback), True
|
||||||
|
else:
|
||||||
|
if curaEnabled and isSTLFileName(filename):
|
||||||
|
self.processStl(absolutePath, destination, uploadCallback)
|
||||||
|
return filename, False
|
||||||
|
|
||||||
|
|
||||||
|
def getFutureFileName(self, file):
|
||||||
if not file:
|
if not file:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -125,15 +205,49 @@ class GcodeManager:
|
|||||||
if absolutePath is None:
|
if absolutePath is None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
basename = self._getBasicFilename(absolutePath)
|
return self._getBasicFilename(absolutePath)
|
||||||
if basename in self._metadata.keys():
|
|
||||||
|
|
||||||
|
def processStl(self, absolutePath, destination, uploadCallback=None):
|
||||||
|
from octoprint.slicers.cura import CuraFactory
|
||||||
|
|
||||||
|
cura = CuraFactory.create_slicer()
|
||||||
|
gcodePath = genGcodeFileName(absolutePath)
|
||||||
|
config = self._settings.get(["cura", "config"])
|
||||||
|
|
||||||
|
slicingStart = time.time()
|
||||||
|
|
||||||
|
def stlProcessed(stlPath, gcodePath, error=None):
|
||||||
|
if error:
|
||||||
|
eventManager().fire("SlicingFailed", {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "reason": error})
|
||||||
|
if os.path.exists(stlPath):
|
||||||
|
os.remove(stlPath)
|
||||||
|
else:
|
||||||
|
slicingStop = time.time()
|
||||||
|
eventManager().fire("SlicingDone", {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "time": "%.2f" % (slicingStop - slicingStart)})
|
||||||
|
self.processGcode(gcodePath, destination, uploadCallback)
|
||||||
|
|
||||||
|
eventManager().fire("SlicingStarted", {"stl": self._getBasicFilename(absolutePath), "gcode": self._getBasicFilename(gcodePath)})
|
||||||
|
cura.process_file(config, gcodePath, absolutePath, stlProcessed, [absolutePath, gcodePath])
|
||||||
|
|
||||||
|
|
||||||
|
def processGcode(self, absolutePath, destination, uploadCallback=None):
|
||||||
|
if absolutePath is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
filename = self._getBasicFilename(absolutePath)
|
||||||
|
|
||||||
|
if filename in self._metadata.keys():
|
||||||
# delete existing metadata entry, since the file is going to get overwritten
|
# delete existing metadata entry, since the file is going to get overwritten
|
||||||
del self._metadata[basename]
|
del self._metadata[filename]
|
||||||
self._metadataDirty = True
|
self._metadataDirty = True
|
||||||
self._saveMetadata()
|
self._saveMetadata()
|
||||||
file.save(absolutePath)
|
|
||||||
self._metadataAnalyzer.addFileToQueue(basename)
|
self._metadataAnalyzer.addFileToQueue(os.path.basename(absolutePath))
|
||||||
return basename
|
|
||||||
|
if uploadCallback is not None:
|
||||||
|
uploadCallback(filename, absolutePath, destination)
|
||||||
|
return filename
|
||||||
|
|
||||||
def getFutureFilename(self, file):
|
def getFutureFilename(self, file):
|
||||||
if not file:
|
if not file:
|
||||||
@@ -148,10 +262,15 @@ class GcodeManager:
|
|||||||
def removeFile(self, filename):
|
def removeFile(self, filename):
|
||||||
filename = self._getBasicFilename(filename)
|
filename = self._getBasicFilename(filename)
|
||||||
absolutePath = self.getAbsolutePath(filename)
|
absolutePath = self.getAbsolutePath(filename)
|
||||||
|
stlPath = genStlFileName(absolutePath)
|
||||||
|
|
||||||
if absolutePath is None:
|
if absolutePath is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
os.remove(absolutePath)
|
os.remove(absolutePath)
|
||||||
|
if os.path.exists(stlPath):
|
||||||
|
os.remove(stlPath)
|
||||||
|
|
||||||
if filename in self._metadata.keys():
|
if filename in self._metadata.keys():
|
||||||
del self._metadata[filename]
|
del self._metadata[filename]
|
||||||
self._metadataDirty = True
|
self._metadataDirty = True
|
||||||
@@ -159,11 +278,11 @@ class GcodeManager:
|
|||||||
|
|
||||||
def getAbsolutePath(self, filename, mustExist=True):
|
def getAbsolutePath(self, filename, mustExist=True):
|
||||||
"""
|
"""
|
||||||
Returns the absolute path of the given filename in the gcode upload folder.
|
Returns the absolute path of the given filename in the correct upload folder.
|
||||||
|
|
||||||
Ensures that the file
|
Ensures that the file
|
||||||
<ul>
|
<ul>
|
||||||
<li>has the extension ".gcode"</li>
|
<li>has any of the extensions listed in SUPPORTED_EXTENSIONS</li>
|
||||||
<li>exists and is a file (not a directory) if "mustExist" is set to True</li>
|
<li>exists and is a file (not a directory) if "mustExist" is set to True</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
@@ -176,6 +295,7 @@ class GcodeManager:
|
|||||||
if not util.isAllowedFile(filename.lower(), set(SUPPORTED_EXTENSIONS)):
|
if not util.isAllowedFile(filename.lower(), set(SUPPORTED_EXTENSIONS)):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
# TODO: detect which type of file and add in the extra folder portion
|
||||||
secure = os.path.join(self._uploadFolder, secure_filename(self._getBasicFilename(filename)))
|
secure = os.path.join(self._uploadFolder, secure_filename(self._getBasicFilename(filename)))
|
||||||
if mustExist and (not os.path.exists(secure) or not os.path.isfile(secure)):
|
if mustExist and (not os.path.exists(secure) or not os.path.isfile(secure)):
|
||||||
return None
|
return None
|
||||||
@@ -191,7 +311,15 @@ class GcodeManager:
|
|||||||
return files
|
return files
|
||||||
|
|
||||||
def getFileData(self, filename):
|
def getFileData(self, filename):
|
||||||
|
if not filename:
|
||||||
|
return
|
||||||
|
|
||||||
filename = self._getBasicFilename(filename)
|
filename = self._getBasicFilename(filename)
|
||||||
|
|
||||||
|
# TODO: Make this more robust when STLs will be viewable from the client
|
||||||
|
if isSTLFileName(filename):
|
||||||
|
return
|
||||||
|
|
||||||
absolutePath = self.getAbsolutePath(filename)
|
absolutePath = self.getAbsolutePath(filename)
|
||||||
if absolutePath is None:
|
if absolutePath is None:
|
||||||
return None
|
return None
|
||||||
@@ -210,7 +338,7 @@ class GcodeManager:
|
|||||||
if key == "prints":
|
if key == "prints":
|
||||||
val = self._metadata[filename][key]
|
val = self._metadata[filename][key]
|
||||||
formattedLast = None
|
formattedLast = None
|
||||||
if val["last"] is not None:
|
if "last" in val and val["last"] is not None:
|
||||||
formattedLast = {
|
formattedLast = {
|
||||||
"date": util.getFormattedDateTime(datetime.datetime.fromtimestamp(val["last"]["date"])),
|
"date": util.getFormattedDateTime(datetime.datetime.fromtimestamp(val["last"]["date"])),
|
||||||
"success": val["last"]["success"]
|
"success": val["last"]["success"]
|
||||||
@@ -358,8 +486,6 @@ class MetadataAnalyzer:
|
|||||||
def _work(self):
|
def _work(self):
|
||||||
aborted = None
|
aborted = None
|
||||||
while True:
|
while True:
|
||||||
self._active.wait()
|
|
||||||
|
|
||||||
if aborted is not None:
|
if aborted is not None:
|
||||||
filename = aborted
|
filename = aborted
|
||||||
aborted = None
|
aborted = None
|
||||||
@@ -368,6 +494,8 @@ class MetadataAnalyzer:
|
|||||||
(priority, filename) = self._queue.get()
|
(priority, filename) = self._queue.get()
|
||||||
self._logger.debug("Processing file %s from queue (priority %d)" % (filename, priority))
|
self._logger.debug("Processing file %s from queue (priority %d)" % (filename, priority))
|
||||||
|
|
||||||
|
self._active.wait()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self._analyzeGcode(filename)
|
self._analyzeGcode(filename)
|
||||||
self._queue.task_done()
|
self._queue.task_done()
|
||||||
@@ -377,7 +505,7 @@ class MetadataAnalyzer:
|
|||||||
|
|
||||||
def _analyzeGcode(self, filename):
|
def _analyzeGcode(self, filename):
|
||||||
path = self._getPathCallback(filename)
|
path = self._getPathCallback(filename)
|
||||||
if path is None:
|
if path is None or not os.path.exists(path):
|
||||||
return
|
return
|
||||||
|
|
||||||
self._currentFile = filename
|
self._currentFile = filename
|
||||||
@@ -7,6 +7,7 @@ import datetime
|
|||||||
import threading
|
import threading
|
||||||
import copy
|
import copy
|
||||||
import os
|
import os
|
||||||
|
import logging
|
||||||
|
|
||||||
#import logging, logging.config
|
#import logging, logging.config
|
||||||
|
|
||||||
@@ -16,6 +17,8 @@ import octoprint.util as util
|
|||||||
from octoprint.settings import settings
|
from octoprint.settings import settings
|
||||||
from octoprint.events import eventManager
|
from octoprint.events import eventManager
|
||||||
|
|
||||||
|
from octoprint.filemanager.destinations import FileDestinations
|
||||||
|
|
||||||
def getConnectionOptions():
|
def getConnectionOptions():
|
||||||
"""
|
"""
|
||||||
Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer.
|
Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer.
|
||||||
@@ -70,6 +73,8 @@ class Printer():
|
|||||||
self._sdPrinting = False
|
self._sdPrinting = False
|
||||||
self._sdStreaming = False
|
self._sdStreaming = False
|
||||||
self._sdFilelistAvailable = threading.Event()
|
self._sdFilelistAvailable = threading.Event()
|
||||||
|
self._sdRemoteName = None
|
||||||
|
self._streamingFinishedCallback = None
|
||||||
|
|
||||||
self._selectedFile = None
|
self._selectedFile = None
|
||||||
|
|
||||||
@@ -187,6 +192,7 @@ class Printer():
|
|||||||
|
|
||||||
def selectFile(self, filename, sd, printAfterSelect=False):
|
def selectFile(self, filename, sd, printAfterSelect=False):
|
||||||
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
|
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
|
||||||
|
logging.info("Cannot load file: printer not connected or currently busy")
|
||||||
return
|
return
|
||||||
|
|
||||||
self._printAfterSelect = printAfterSelect
|
self._printAfterSelect = printAfterSelect
|
||||||
@@ -456,6 +462,10 @@ class Printer():
|
|||||||
def mcFileTransferDone(self):
|
def mcFileTransferDone(self):
|
||||||
self._sdStreaming = False
|
self._sdStreaming = False
|
||||||
|
|
||||||
|
if self._streamingFinishedCallback is not None:
|
||||||
|
self._streamingFinishedCallback(self._sdRemoteName, FileDestinations.SDCARD)
|
||||||
|
|
||||||
|
self._sdRemoteName = None
|
||||||
self._setCurrentZ(None)
|
self._setCurrentZ(None)
|
||||||
self._setJobData(None, None, None)
|
self._setJobData(None, None, None)
|
||||||
self._setProgressData(None, None, None, None)
|
self._setProgressData(None, None, None, None)
|
||||||
@@ -471,15 +481,18 @@ class Printer():
|
|||||||
return []
|
return []
|
||||||
return self._comm.getSdFiles()
|
return self._comm.getSdFiles()
|
||||||
|
|
||||||
def addSdFile(self, filename, path):
|
def addSdFile(self, filename, absolutePath, streamingFinishedCallback):
|
||||||
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
|
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
|
||||||
|
logging.error("No connection to printer or printer is busy")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
self._streamingFinishedCallback = streamingFinishedCallback
|
||||||
|
|
||||||
self.refreshSdFiles(blocking=True)
|
self.refreshSdFiles(blocking=True)
|
||||||
existingSdFiles = self._comm.getSdFiles()
|
existingSdFiles = self._comm.getSdFiles()
|
||||||
|
|
||||||
sdFilename = util.getDosFilename(filename, existingSdFiles)
|
self._sdRemoteName = util.getDosFilename(filename, existingSdFiles)
|
||||||
self._comm.startFileTransfer(path, sdFilename)
|
self._comm.startFileTransfer(absolutePath, self._sdRemoteName)
|
||||||
|
|
||||||
def deleteSdFile(self, filename):
|
def deleteSdFile(self, filename):
|
||||||
if not self._comm or not self._comm.isSdReady():
|
if not self._comm or not self._comm.isSdReady():
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||||
|
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||||
|
|
||||||
|
from sockjs.tornado import SockJSRouter
|
||||||
|
from flask import Flask, render_template, send_from_directory
|
||||||
|
from flask.ext.login import LoginManager
|
||||||
|
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
|
||||||
|
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
import logging.config
|
||||||
|
|
||||||
|
SUCCESS = {}
|
||||||
|
|
||||||
|
app = Flask("octoprint")
|
||||||
|
debug = False
|
||||||
|
|
||||||
|
printer = None
|
||||||
|
gcodeManager = None
|
||||||
|
userManager = None
|
||||||
|
eventManager = None
|
||||||
|
loginManager = None
|
||||||
|
|
||||||
|
principals = Principal(app)
|
||||||
|
admin_permission = Permission(RoleNeed("admin"))
|
||||||
|
user_permission = Permission(RoleNeed("user"))
|
||||||
|
|
||||||
|
|
||||||
|
from octoprint.server.util import LargeResponseHandler, ReverseProxied, restricted_access, PrinterStateConnection
|
||||||
|
from octoprint.printer import Printer, getConnectionOptions
|
||||||
|
from octoprint.settings import settings
|
||||||
|
import octoprint.gcodefiles as gcodefiles
|
||||||
|
import octoprint.util as util
|
||||||
|
import octoprint.users as users
|
||||||
|
import octoprint.events as events
|
||||||
|
import octoprint.timelapse
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/")
|
||||||
|
def index():
|
||||||
|
branch = None
|
||||||
|
commit = None
|
||||||
|
try:
|
||||||
|
branch, commit = util.getGitInfo()
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return render_template(
|
||||||
|
"index.jinja2",
|
||||||
|
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
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/robots.txt")
|
||||||
|
def robotsTxt():
|
||||||
|
return send_from_directory(app.static_folder, "robots.txt")
|
||||||
|
|
||||||
|
|
||||||
|
@identity_loaded.connect_via(app)
|
||||||
|
def on_identity_loaded(sender, identity):
|
||||||
|
user = load_user(identity.id)
|
||||||
|
if user is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
identity.provides.add(UserNeed(user.get_name()))
|
||||||
|
if user.is_user():
|
||||||
|
identity.provides.add(RoleNeed("user"))
|
||||||
|
if user.is_admin():
|
||||||
|
identity.provides.add(RoleNeed("admin"))
|
||||||
|
|
||||||
|
|
||||||
|
def load_user(id):
|
||||||
|
if userManager is not None:
|
||||||
|
return userManager.findUser(id)
|
||||||
|
return users.DummyUser()
|
||||||
|
|
||||||
|
|
||||||
|
#~~ startup code
|
||||||
|
|
||||||
|
|
||||||
|
class Server():
|
||||||
|
def __init__(self, configfile=None, basedir=None, host="0.0.0.0", port=5000, debug=False, allowRoot=False):
|
||||||
|
self._configfile = configfile
|
||||||
|
self._basedir = basedir
|
||||||
|
self._host = host
|
||||||
|
self._port = port
|
||||||
|
self._debug = debug
|
||||||
|
self._allowRoot = allowRoot
|
||||||
|
|
||||||
|
|
||||||
|
def run(self):
|
||||||
|
if not self._allowRoot:
|
||||||
|
self._checkForRoot()
|
||||||
|
|
||||||
|
global printer
|
||||||
|
global gcodeManager
|
||||||
|
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
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
# then initialize logging
|
||||||
|
self._initLogging(self._debug)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
eventManager = events.eventManager()
|
||||||
|
gcodeManager = gcodefiles.GcodeManager()
|
||||||
|
printer = Printer(gcodeManager)
|
||||||
|
|
||||||
|
# configure timelapse
|
||||||
|
octoprint.timelapse.configureTimelapse()
|
||||||
|
|
||||||
|
# setup system and gcode command triggers
|
||||||
|
events.SystemCommandTrigger(printer)
|
||||||
|
events.GcodeCommandTrigger(printer)
|
||||||
|
if self._debug:
|
||||||
|
events.DebugEventListener()
|
||||||
|
|
||||||
|
if settings().getBoolean(["accessControl", "enabled"]):
|
||||||
|
userManagerName = settings().get(["accessControl", "userManager"])
|
||||||
|
try:
|
||||||
|
clazz = util.getClass(userManagerName)
|
||||||
|
userManager = clazz()
|
||||||
|
except AttributeError, e:
|
||||||
|
logger.exception("Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName)
|
||||||
|
|
||||||
|
app.wsgi_app = ReverseProxied(app.wsgi_app)
|
||||||
|
|
||||||
|
app.secret_key = "k3PuVYgtxNm8DXKKTw2nWmFQQun9qceV"
|
||||||
|
loginManager = LoginManager()
|
||||||
|
loginManager.session_protection = "strong"
|
||||||
|
loginManager.user_callback = load_user
|
||||||
|
if userManager is None:
|
||||||
|
loginManager.anonymous_user = users.DummyUser
|
||||||
|
principals.identity_loaders.appendleft(users.dummy_identity_loader)
|
||||||
|
loginManager.init_app(app)
|
||||||
|
|
||||||
|
if self._host is None:
|
||||||
|
self._host = settings().get(["server", "host"])
|
||||||
|
if self._port is None:
|
||||||
|
self._port = settings().getInt(["server", "port"])
|
||||||
|
|
||||||
|
logger.info("Listening on http://%s:%d" % (self._host, self._port))
|
||||||
|
app.debug = self._debug
|
||||||
|
|
||||||
|
from octoprint.server.ajax import ajax
|
||||||
|
from octoprint.server.api import api
|
||||||
|
|
||||||
|
app.register_blueprint(ajax, url_prefix="/ajax")
|
||||||
|
app.register_blueprint(api, url_prefix="/api")
|
||||||
|
|
||||||
|
self._router = SockJSRouter(self._createSocketConnection, "/sockjs")
|
||||||
|
|
||||||
|
self._tornado_app = Application(self._router.urls + [
|
||||||
|
(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.wsgi_app)})
|
||||||
|
])
|
||||||
|
self._server = HTTPServer(self._tornado_app)
|
||||||
|
self._server.listen(self._port, address=self._host)
|
||||||
|
|
||||||
|
eventManager.fire("Startup")
|
||||||
|
if settings().getBoolean(["serial", "autoconnect"]):
|
||||||
|
(port, baudrate) = settings().get(["serial", "port"]), settings().getInt(["serial", "baudrate"])
|
||||||
|
connectionOptions = getConnectionOptions()
|
||||||
|
if port in connectionOptions["ports"]:
|
||||||
|
printer.connect(port, baudrate)
|
||||||
|
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):
|
||||||
|
global printer, gcodeManager, userManager, eventManager
|
||||||
|
return PrinterStateConnection(printer, gcodeManager, userManager, eventManager, session)
|
||||||
|
|
||||||
|
def _checkForRoot(self):
|
||||||
|
if "geteuid" in dir(os) and os.geteuid() == 0:
|
||||||
|
exit("You should not run OctoPrint as root!")
|
||||||
|
|
||||||
|
def _initSettings(self, configfile, basedir):
|
||||||
|
settings(init=True, basedir=basedir, configfile=configfile)
|
||||||
|
|
||||||
|
def _initLogging(self, debug):
|
||||||
|
config = {
|
||||||
|
"version": 1,
|
||||||
|
"formatters": {
|
||||||
|
"simple": {
|
||||||
|
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"handlers": {
|
||||||
|
"console": {
|
||||||
|
"class": "logging.StreamHandler",
|
||||||
|
"level": "DEBUG",
|
||||||
|
"formatter": "simple",
|
||||||
|
"stream": "ext://sys.stdout"
|
||||||
|
},
|
||||||
|
"file": {
|
||||||
|
"class": "logging.handlers.TimedRotatingFileHandler",
|
||||||
|
"level": "DEBUG",
|
||||||
|
"formatter": "simple",
|
||||||
|
"when": "D",
|
||||||
|
"backupCount": "1",
|
||||||
|
"filename": os.path.join(settings().getBaseFolder("logs"), "octoprint.log")
|
||||||
|
},
|
||||||
|
"serialFile": {
|
||||||
|
"class": "logging.handlers.RotatingFileHandler",
|
||||||
|
"level": "DEBUG",
|
||||||
|
"formatter": "simple",
|
||||||
|
"maxBytes": 2 * 1024 * 1024, # let's limit the serial log to 2MB in size
|
||||||
|
"filename": os.path.join(settings().getBaseFolder("logs"), "serial.log")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"loggers": {
|
||||||
|
#"octoprint.timelapse": {
|
||||||
|
# "level": "DEBUG"
|
||||||
|
#},
|
||||||
|
#"octoprint.events": {
|
||||||
|
# "level": "DEBUG"
|
||||||
|
#},
|
||||||
|
"SERIAL": {
|
||||||
|
"level": "CRITICAL",
|
||||||
|
"handlers": ["serialFile"],
|
||||||
|
"propagate": False
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"level": "INFO",
|
||||||
|
"handlers": ["console", "file"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if debug:
|
||||||
|
config["root"]["level"] = "DEBUG"
|
||||||
|
|
||||||
|
logging.config.dictConfig(config)
|
||||||
|
|
||||||
|
if settings().getBoolean(["serial", "log"]):
|
||||||
|
# enable debug logging to serial.log
|
||||||
|
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
|
||||||
|
logging.getLogger("SERIAL").debug("Enabling serial logging")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
octoprint = Server()
|
||||||
|
octoprint.run()
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||||
|
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import subprocess
|
||||||
|
import netaddr
|
||||||
|
|
||||||
|
from flask import Blueprint, request, jsonify, abort, current_app, session, make_response
|
||||||
|
from flask.ext.login import login_user, logout_user, current_user
|
||||||
|
from flask.ext.principal import Identity, identity_changed, AnonymousIdentity
|
||||||
|
|
||||||
|
import octoprint.util as util
|
||||||
|
import octoprint.users
|
||||||
|
from octoprint.server import restricted_access, SUCCESS, admin_permission, loginManager, principals
|
||||||
|
from octoprint.settings import settings as s, valid_boolean_trues
|
||||||
|
|
||||||
|
#~~ init ajax blueprint, including sub modules
|
||||||
|
|
||||||
|
ajax = Blueprint("ajax", __name__)
|
||||||
|
|
||||||
|
from . import control as ajax_control
|
||||||
|
from . import gcodefiles as ajax_gcodefiles
|
||||||
|
from . import settings as ajax_settings
|
||||||
|
from . import timelapse as ajax_timelapse
|
||||||
|
from . import users as ajax_users
|
||||||
|
|
||||||
|
|
||||||
|
#~~ first run setup
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/setup", methods=["POST"])
|
||||||
|
def firstRunSetup():
|
||||||
|
if not s().getBoolean(["server", "firstRun"]):
|
||||||
|
abort(403)
|
||||||
|
|
||||||
|
if "ac" in request.values.keys() and request.values["ac"] in valid_boolean_trues and \
|
||||||
|
"user" in request.values.keys() and "pass1" in request.values.keys() and \
|
||||||
|
"pass2" in request.values.keys() and request.values["pass1"] == request.values["pass2"]:
|
||||||
|
# configure access control
|
||||||
|
s().setBoolean(["accessControl", "enabled"], True)
|
||||||
|
octoprint.server.userManager.addUser(request.values["user"], request.values["pass1"], True, ["user", "admin"])
|
||||||
|
s().setBoolean(["server", "firstRun"], False)
|
||||||
|
elif "ac" in request.values.keys() and not request.values["ac"] in valid_boolean_trues:
|
||||||
|
# disable access control
|
||||||
|
s().setBoolean(["accessControl", "enabled"], False)
|
||||||
|
s().setBoolean(["server", "firstRun"], False)
|
||||||
|
|
||||||
|
loginManager.anonymous_user = octoprint.users.DummyUser
|
||||||
|
principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
|
||||||
|
|
||||||
|
s().save()
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
|
||||||
|
#~~ system control
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/system", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
@admin_permission.require(403)
|
||||||
|
def performSystemAction():
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
if request.values.has_key("action"):
|
||||||
|
action = request.values["action"]
|
||||||
|
availableActions = s().get(["system", "actions"])
|
||||||
|
for availableAction in availableActions:
|
||||||
|
if availableAction["action"] == action:
|
||||||
|
logger.info("Performing command: %s" % availableAction["command"])
|
||||||
|
try:
|
||||||
|
subprocess.check_output(availableAction["command"], shell=True)
|
||||||
|
except subprocess.CalledProcessError, e:
|
||||||
|
logger.warn("Command failed with return code %i: %s" % (e.returncode, e.message))
|
||||||
|
return make_response(("Command failed with return code %i: %s" % (e.returncode, e.message), 500, []))
|
||||||
|
except Exception, ex:
|
||||||
|
logger.exception("Command failed")
|
||||||
|
return make_response(("Command failed: %r" % ex, 500, []))
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
|
||||||
|
#~~ Login/user handling
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/login", methods=["POST"])
|
||||||
|
def login():
|
||||||
|
if octoprint.server.userManager is not None and "user" in request.values.keys() and "pass" in request.values.keys():
|
||||||
|
username = request.values["user"]
|
||||||
|
password = request.values["pass"]
|
||||||
|
|
||||||
|
if "remember" in request.values.keys() and request.values["remember"] == "true":
|
||||||
|
remember = True
|
||||||
|
else:
|
||||||
|
remember = False
|
||||||
|
|
||||||
|
user = octoprint.server.userManager.findUser(username)
|
||||||
|
if user is not None:
|
||||||
|
if user.check_password(octoprint.users.UserManager.createPasswordHash(password)):
|
||||||
|
login_user(user, remember=remember)
|
||||||
|
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||||
|
return jsonify(user.asDict())
|
||||||
|
return make_response(("User unknown or password incorrect", 401, []))
|
||||||
|
elif "passive" in request.values.keys():
|
||||||
|
user = current_user
|
||||||
|
if user is not None and not user.is_anonymous():
|
||||||
|
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||||
|
return jsonify(user.asDict())
|
||||||
|
elif s().getBoolean(["accessControl", "autologinLocal"]) \
|
||||||
|
and s().get(["accessControl", "autologinAs"]) is not None \
|
||||||
|
and s().get(["accessControl", "localNetworks"]) is not None:
|
||||||
|
|
||||||
|
autologinAs = s().get(["accessControl", "autologinAs"])
|
||||||
|
localNetworks = netaddr.IPSet([])
|
||||||
|
for ip in s().get(["accessControl", "localNetworks"]):
|
||||||
|
localNetworks.add(ip)
|
||||||
|
|
||||||
|
try:
|
||||||
|
remoteAddr = util.getRemoteAddress(request)
|
||||||
|
if netaddr.IPAddress(remoteAddr) in localNetworks:
|
||||||
|
user = octoprint.server.userManager.findUser(autologinAs)
|
||||||
|
if user is not None:
|
||||||
|
login_user(user)
|
||||||
|
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||||
|
return jsonify(user.asDict())
|
||||||
|
except:
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/logout", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
def logout():
|
||||||
|
# Remove session keys set by Flask-Principal
|
||||||
|
for key in ('identity.id', 'identity.auth_type'):
|
||||||
|
del session[key]
|
||||||
|
identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
|
||||||
|
|
||||||
|
logout_user()
|
||||||
|
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||||
|
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||||
|
|
||||||
|
from flask import request, jsonify
|
||||||
|
|
||||||
|
from octoprint.settings import settings
|
||||||
|
from octoprint.printer import getConnectionOptions
|
||||||
|
from octoprint.server import printer, restricted_access, SUCCESS
|
||||||
|
from octoprint.server.ajax import ajax
|
||||||
|
|
||||||
|
|
||||||
|
#~~ Printer control
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/control/connection/options", methods=["GET"])
|
||||||
|
def connectionOptions():
|
||||||
|
return jsonify(getConnectionOptions())
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/control/connection", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
def connect():
|
||||||
|
if "command" in request.values.keys() and request.values["command"] == "connect":
|
||||||
|
port = None
|
||||||
|
baudrate = None
|
||||||
|
if "port" in request.values.keys():
|
||||||
|
port = request.values["port"]
|
||||||
|
if "baudrate" in request.values.keys():
|
||||||
|
baudrate = request.values["baudrate"]
|
||||||
|
if "save" in request.values.keys():
|
||||||
|
settings().set(["serial", "port"], port)
|
||||||
|
settings().setInt(["serial", "baudrate"], baudrate)
|
||||||
|
settings().save()
|
||||||
|
if "autoconnect" in request.values.keys():
|
||||||
|
settings().setBoolean(["serial", "autoconnect"], True)
|
||||||
|
settings().save()
|
||||||
|
printer.connect(port=port, baudrate=baudrate)
|
||||||
|
elif "command" in request.values.keys() and request.values["command"] == "disconnect":
|
||||||
|
printer.disconnect()
|
||||||
|
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/control/command", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
def printerCommand():
|
||||||
|
if "application/json" in request.headers["Content-Type"]:
|
||||||
|
data = request.json
|
||||||
|
|
||||||
|
parameters = {}
|
||||||
|
if "parameters" in data.keys(): parameters = data["parameters"]
|
||||||
|
|
||||||
|
commands = []
|
||||||
|
if "command" in data.keys(): commands = [data["command"]]
|
||||||
|
elif "commands" in data.keys(): commands = data["commands"]
|
||||||
|
|
||||||
|
commandsToSend = []
|
||||||
|
for command in commands:
|
||||||
|
commandToSend = command
|
||||||
|
if len(parameters) > 0:
|
||||||
|
commandToSend = command % parameters
|
||||||
|
commandsToSend.append(commandToSend)
|
||||||
|
|
||||||
|
printer.commands(commandsToSend)
|
||||||
|
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/control/job", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
def printJobControl():
|
||||||
|
if "command" in request.values.keys():
|
||||||
|
if request.values["command"] == "start":
|
||||||
|
printer.startPrint()
|
||||||
|
elif request.values["command"] == "pause":
|
||||||
|
printer.togglePausePrint()
|
||||||
|
elif request.values["command"] == "cancel":
|
||||||
|
printer.cancelPrint()
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/control/temperature", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
def setTargetTemperature():
|
||||||
|
if "temp" in request.values.keys():
|
||||||
|
# set target temperature
|
||||||
|
temp = request.values["temp"]
|
||||||
|
printer.command("M104 S" + temp)
|
||||||
|
|
||||||
|
if "bedTemp" in request.values.keys():
|
||||||
|
# set target bed temperature
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/control/jog", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
def jog():
|
||||||
|
if not printer.isOperational() or printer.isPrinting():
|
||||||
|
# do not jog when a print job is running or we don't have a connection
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
(movementSpeedX, movementSpeedY, movementSpeedZ, movementSpeedE) = settings().get(["printerParameters", "movementSpeed", ["x", "y", "z", "e"]])
|
||||||
|
if "x" in request.values.keys():
|
||||||
|
# jog x
|
||||||
|
x = request.values["x"]
|
||||||
|
printer.commands(["G91", "G1 X%s F%d" % (x, movementSpeedX), "G90"])
|
||||||
|
if "y" in request.values.keys():
|
||||||
|
# jog y
|
||||||
|
y = request.values["y"]
|
||||||
|
printer.commands(["G91", "G1 Y%s F%d" % (y, movementSpeedY), "G90"])
|
||||||
|
if "z" in request.values.keys():
|
||||||
|
# jog z
|
||||||
|
z = request.values["z"]
|
||||||
|
printer.commands(["G91", "G1 Z%s F%d" % (z, movementSpeedZ), "G90"])
|
||||||
|
if "homeXY" in request.values.keys():
|
||||||
|
# home x/y
|
||||||
|
printer.command("G28 X0 Y0")
|
||||||
|
if "homeZ" in request.values.keys():
|
||||||
|
# home z
|
||||||
|
printer.command("G28 Z0")
|
||||||
|
if "extrude" in request.values.keys():
|
||||||
|
# extrude/retract
|
||||||
|
length = request.values["extrude"]
|
||||||
|
printer.commands(["G91", "G1 E%s F%d" % (length, movementSpeedE), "G90"])
|
||||||
|
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/control/custom", methods=["GET"])
|
||||||
|
def getCustomControls():
|
||||||
|
customControls = settings().get(["controls"])
|
||||||
|
return jsonify(controls=customControls)
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/control/sd", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
def sdCommand():
|
||||||
|
if not settings().getBoolean(["feature", "sdSupport"]) or not printer.isOperational() or printer.isPrinting():
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
if "command" in request.values.keys():
|
||||||
|
command = request.values["command"]
|
||||||
|
if command == "init":
|
||||||
|
printer.initSdCard()
|
||||||
|
elif command == "refresh":
|
||||||
|
printer.refreshSdFiles()
|
||||||
|
elif command == "release":
|
||||||
|
printer.releaseSdCard()
|
||||||
|
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||||
|
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||||
|
|
||||||
|
from flask import request, jsonify, make_response, url_for
|
||||||
|
|
||||||
|
import octoprint.gcodefiles as gcodefiles
|
||||||
|
import octoprint.util as util
|
||||||
|
from octoprint.filemanager.destinations import FileDestinations
|
||||||
|
from octoprint.settings import settings, valid_boolean_trues
|
||||||
|
from octoprint.server import printer, gcodeManager, eventManager, restricted_access, SUCCESS
|
||||||
|
from octoprint.server.util import redirectToTornado
|
||||||
|
from octoprint.server.ajax import ajax
|
||||||
|
|
||||||
|
|
||||||
|
#~~ GCODE file handling
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/gcodefiles", methods=["GET"])
|
||||||
|
def readGcodeFiles():
|
||||||
|
files = gcodeManager.getAllFileData()
|
||||||
|
|
||||||
|
sdFileList = printer.getSdFiles()
|
||||||
|
if sdFileList is not None:
|
||||||
|
for sdFile in sdFileList:
|
||||||
|
files.append({
|
||||||
|
"name": sdFile,
|
||||||
|
"size": "n/a",
|
||||||
|
"bytes": 0,
|
||||||
|
"date": "n/a",
|
||||||
|
"origin": "sd"
|
||||||
|
})
|
||||||
|
return jsonify(files=files, free=util.getFormattedSize(util.getFreeBytes(settings().getBaseFolder("uploads"))))
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/gcodefiles/<string:target>", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
def uploadGcodeFile(target):
|
||||||
|
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||||
|
return make_response("Invalid target: %s" % target, 400)
|
||||||
|
|
||||||
|
if "gcode_file" in request.files.keys():
|
||||||
|
file = request.files["gcode_file"]
|
||||||
|
sd = target == FileDestinations.SDCARD
|
||||||
|
selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues
|
||||||
|
printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues
|
||||||
|
|
||||||
|
# determine current job
|
||||||
|
currentFilename = None
|
||||||
|
currentSd = None
|
||||||
|
currentJob = printer.getCurrentJob()
|
||||||
|
if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys():
|
||||||
|
currentFilename = currentJob["filename"]
|
||||||
|
currentSd = currentJob["sd"]
|
||||||
|
|
||||||
|
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||||
|
futureFilename = gcodeManager.getFutureFilename(file)
|
||||||
|
if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)):
|
||||||
|
return make_response("Can not upload file %s, wrong format?" % file.filename, 400)
|
||||||
|
|
||||||
|
# prohibit overwriting currently selected file while it's being printed
|
||||||
|
if futureFilename == currentFilename and sd == currentSd and printer.isPrinting() or printer.isPaused():
|
||||||
|
return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 403)
|
||||||
|
|
||||||
|
filename = None
|
||||||
|
|
||||||
|
def fileProcessingFinished(filename, absFilename, destination):
|
||||||
|
"""
|
||||||
|
Callback for when the file processing (upload, optional slicing, addition to analysis queue) has
|
||||||
|
finished.
|
||||||
|
|
||||||
|
Depending on the file's destination triggers either streaming to SD card or directly calls selectOrPrint.
|
||||||
|
"""
|
||||||
|
sd = destination == FileDestinations.SDCARD
|
||||||
|
if sd:
|
||||||
|
printer.addSdFile(filename, absFilename, selectAndOrPrint)
|
||||||
|
else:
|
||||||
|
selectAndOrPrint(absFilename, destination)
|
||||||
|
|
||||||
|
def selectAndOrPrint(nameToSelect, destination):
|
||||||
|
"""
|
||||||
|
Callback for when the file is ready to be selected and optionally printed. For SD file uploads this only
|
||||||
|
the case after they have finished streaming to the printer, which is why this callback is also used
|
||||||
|
for the corresponding call to addSdFile.
|
||||||
|
|
||||||
|
Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the
|
||||||
|
exact file is already selected, such reloading it.
|
||||||
|
"""
|
||||||
|
sd = destination == FileDestinations.SDCARD
|
||||||
|
if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentSd == sd):
|
||||||
|
printer.selectFile(nameToSelect, sd, printAfterSelect)
|
||||||
|
|
||||||
|
destination = FileDestinations.SDCARD if sd else FileDestinations.LOCAL
|
||||||
|
filename, done = gcodeManager.addFile(file, destination, fileProcessingFinished)
|
||||||
|
if filename is None:
|
||||||
|
return make_response("Could not upload the file %s" % file.filename, 500)
|
||||||
|
|
||||||
|
eventManager.fire("Upload", filename)
|
||||||
|
return jsonify(files=gcodeManager.getAllFileData(), filename=filename, done=done)
|
||||||
|
else:
|
||||||
|
return make_response("No gcode_file included", 400)
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/gcodefiles/load", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
def loadGcodeFile():
|
||||||
|
if "filename" in request.values.keys():
|
||||||
|
printAfterLoading = False
|
||||||
|
if "print" in request.values.keys() and request.values["print"] in valid_boolean_trues:
|
||||||
|
printAfterLoading = True
|
||||||
|
|
||||||
|
sd = False
|
||||||
|
if "target" in request.values.keys() and request.values["target"] == "sd":
|
||||||
|
filename = request.values["filename"]
|
||||||
|
sd = True
|
||||||
|
else:
|
||||||
|
filename = gcodeManager.getAbsolutePath(request.values["filename"])
|
||||||
|
printer.selectFile(filename, sd, printAfterLoading)
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/gcodefiles/delete", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
def deleteGcodeFile():
|
||||||
|
if "filename" in request.values.keys():
|
||||||
|
filename = request.values["filename"]
|
||||||
|
sd = "target" in request.values.keys() and request.values["target"] == "sd"
|
||||||
|
|
||||||
|
currentJob = printer.getCurrentJob()
|
||||||
|
currentFilename = None
|
||||||
|
currentSd = None
|
||||||
|
if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys():
|
||||||
|
currentFilename = currentJob["filename"]
|
||||||
|
currentSd = currentJob["sd"]
|
||||||
|
|
||||||
|
if currentFilename is not None and filename == currentFilename and not (printer.isPrinting() or printer.isPaused()):
|
||||||
|
printer.unselectFile()
|
||||||
|
|
||||||
|
if not (currentFilename == filename and currentSd == sd and (printer.isPrinting() or printer.isPaused())):
|
||||||
|
if sd:
|
||||||
|
printer.deleteSdFile(filename)
|
||||||
|
else:
|
||||||
|
gcodeManager.removeFile(filename)
|
||||||
|
return readGcodeFiles()
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/gcodefiles/refresh", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
def refreshFiles():
|
||||||
|
printer.updateSdFiles()
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||||
|
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from flask import request, jsonify
|
||||||
|
|
||||||
|
from octoprint.settings import settings
|
||||||
|
from octoprint.printer import getConnectionOptions
|
||||||
|
|
||||||
|
from octoprint.server import restricted_access, admin_permission
|
||||||
|
from octoprint.server.ajax import ajax
|
||||||
|
|
||||||
|
|
||||||
|
#~~ settings
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/settings", methods=["GET"])
|
||||||
|
def getSettings():
|
||||||
|
s = settings()
|
||||||
|
|
||||||
|
[movementSpeedX, movementSpeedY, movementSpeedZ, movementSpeedE] \
|
||||||
|
= s.get(["printerParameters", "movementSpeed", ["x", "y", "z", "e"]])
|
||||||
|
|
||||||
|
connectionOptions = getConnectionOptions()
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
"api": {
|
||||||
|
"enabled": s.getBoolean(["api", "enabled"]),
|
||||||
|
"key": s.get(["api", "key"])
|
||||||
|
},
|
||||||
|
"appearance": {
|
||||||
|
"name": s.get(["appearance", "name"]),
|
||||||
|
"color": s.get(["appearance", "color"])
|
||||||
|
},
|
||||||
|
"printer": {
|
||||||
|
"movementSpeedX": movementSpeedX,
|
||||||
|
"movementSpeedY": movementSpeedY,
|
||||||
|
"movementSpeedZ": movementSpeedZ,
|
||||||
|
"movementSpeedE": movementSpeedE,
|
||||||
|
"invertAxes": s.get(["printerParameters", "invertAxes"])
|
||||||
|
},
|
||||||
|
"webcam": {
|
||||||
|
"streamUrl": s.get(["webcam", "stream"]),
|
||||||
|
"snapshotUrl": s.get(["webcam", "snapshot"]),
|
||||||
|
"ffmpegPath": s.get(["webcam", "ffmpeg"]),
|
||||||
|
"bitrate": s.get(["webcam", "bitrate"]),
|
||||||
|
"watermark": s.getBoolean(["webcam", "watermark"]),
|
||||||
|
"flipH": s.getBoolean(["webcam", "flipH"]),
|
||||||
|
"flipV": s.getBoolean(["webcam", "flipV"])
|
||||||
|
},
|
||||||
|
"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"]),
|
||||||
|
"sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]),
|
||||||
|
"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"])
|
||||||
|
},
|
||||||
|
"serial": {
|
||||||
|
"port": connectionOptions["portPreference"],
|
||||||
|
"baudrate": connectionOptions["baudratePreference"],
|
||||||
|
"portOptions": connectionOptions["ports"],
|
||||||
|
"baudrateOptions": connectionOptions["baudrates"],
|
||||||
|
"autoconnect": s.getBoolean(["serial", "autoconnect"]),
|
||||||
|
"timeoutConnection": s.getFloat(["serial", "timeout", "connection"]),
|
||||||
|
"timeoutDetection": s.getFloat(["serial", "timeout", "detection"]),
|
||||||
|
"timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]),
|
||||||
|
"log": s.getBoolean(["serial", "log"])
|
||||||
|
},
|
||||||
|
"folder": {
|
||||||
|
"uploads": s.getBaseFolder("uploads"),
|
||||||
|
"timelapse": s.getBaseFolder("timelapse"),
|
||||||
|
"timelapseTmp": s.getBaseFolder("timelapse_tmp"),
|
||||||
|
"logs": s.getBaseFolder("logs")
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"profiles": s.get(["temperature", "profiles"])
|
||||||
|
},
|
||||||
|
"system": {
|
||||||
|
"actions": s.get(["system", "actions"]),
|
||||||
|
"events": s.get(["system", "events"])
|
||||||
|
},
|
||||||
|
"terminalFilters": s.get(["terminalFilters"]),
|
||||||
|
"cura": {
|
||||||
|
"enabled": s.getBoolean(["cura", "enabled"]),
|
||||||
|
"path": s.get(["cura", "path"]),
|
||||||
|
"config": s.get(["cura", "config"])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/settings", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
@admin_permission.require(403)
|
||||||
|
def setSettings():
|
||||||
|
if "application/json" in request.headers["Content-Type"]:
|
||||||
|
data = request.json
|
||||||
|
s = settings()
|
||||||
|
|
||||||
|
if "api" in data.keys():
|
||||||
|
if "enabled" in data["api"].keys(): s.set(["api", "enabled"], data["api"]["enabled"])
|
||||||
|
if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True)
|
||||||
|
|
||||||
|
if "appearance" in data.keys():
|
||||||
|
if "name" in data["appearance"].keys(): s.set(["appearance", "name"], data["appearance"]["name"])
|
||||||
|
if "color" in data["appearance"].keys(): s.set(["appearance", "color"], data["appearance"]["color"])
|
||||||
|
|
||||||
|
if "printer" in data.keys():
|
||||||
|
if "movementSpeedX" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "x"], data["printer"]["movementSpeedX"])
|
||||||
|
if "movementSpeedY" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "y"], data["printer"]["movementSpeedY"])
|
||||||
|
if "movementSpeedZ" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "z"], data["printer"]["movementSpeedZ"])
|
||||||
|
if "movementSpeedE" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "e"], data["printer"]["movementSpeedE"])
|
||||||
|
if "invertAxes" in data["printer"].keys(): s.set(["printerParameters", "invertAxes"], data["printer"]["invertAxes"])
|
||||||
|
|
||||||
|
if "webcam" in data.keys():
|
||||||
|
if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
|
||||||
|
if "snapshotUrl" in data["webcam"].keys(): s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
|
||||||
|
if "ffmpegPath" in data["webcam"].keys(): s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
|
||||||
|
if "bitrate" in data["webcam"].keys(): s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
|
||||||
|
if "watermark" in data["webcam"].keys(): s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
|
||||||
|
if "flipH" in data["webcam"].keys(): s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
|
||||||
|
if "flipV" in data["webcam"].keys(): s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
|
||||||
|
|
||||||
|
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 "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
|
||||||
|
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"])
|
||||||
|
if "port" in data["serial"].keys(): s.set(["serial", "port"], data["serial"]["port"])
|
||||||
|
if "baudrate" in data["serial"].keys(): s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
|
||||||
|
if "timeoutConnection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
|
||||||
|
if "timeoutDetection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
|
||||||
|
if "timeoutCommunication" in data["serial"].keys(): s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
|
||||||
|
|
||||||
|
oldLog = s.getBoolean(["serial", "log"])
|
||||||
|
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
|
||||||
|
if oldLog and not s.getBoolean(["serial", "log"]):
|
||||||
|
# disable debug logging to serial.log
|
||||||
|
logging.getLogger("SERIAL").debug("Disabling serial logging")
|
||||||
|
logging.getLogger("SERIAL").setLevel(logging.CRITICAL)
|
||||||
|
elif not oldLog and s.getBoolean(["serial", "log"]):
|
||||||
|
# enable debug logging to serial.log
|
||||||
|
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
|
||||||
|
logging.getLogger("SERIAL").debug("Enabling serial logging")
|
||||||
|
|
||||||
|
if "folder" in data.keys():
|
||||||
|
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
|
||||||
|
if "timelapse" in data["folder"].keys(): s.setBaseFolder("timelapse", data["folder"]["timelapse"])
|
||||||
|
if "timelapseTmp" in data["folder"].keys(): s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
|
||||||
|
if "logs" in data["folder"].keys(): s.setBaseFolder("logs", data["folder"]["logs"])
|
||||||
|
|
||||||
|
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"])
|
||||||
|
|
||||||
|
cura = data.get("cura", None)
|
||||||
|
if cura:
|
||||||
|
path = cura.get("path")
|
||||||
|
if path:
|
||||||
|
s.set(["cura", "path"], path)
|
||||||
|
|
||||||
|
config = cura.get("config")
|
||||||
|
if config:
|
||||||
|
s.set(["cura", "config"], config)
|
||||||
|
|
||||||
|
# Enabled is a boolean so we cannot check that we have a result
|
||||||
|
enabled = cura.get("enabled")
|
||||||
|
s.setBoolean(["cura", "enabled"], enabled)
|
||||||
|
|
||||||
|
s.save()
|
||||||
|
|
||||||
|
return getSettings()
|
||||||
|
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||||
|
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
from flask import request, jsonify, url_for
|
||||||
|
from werkzeug.utils import secure_filename
|
||||||
|
|
||||||
|
import octoprint.timelapse
|
||||||
|
import octoprint.util as util
|
||||||
|
from octoprint.settings import settings, valid_boolean_trues
|
||||||
|
|
||||||
|
from octoprint.server import restricted_access, admin_permission
|
||||||
|
from octoprint.server.util import redirectToTornado
|
||||||
|
from octoprint.server.ajax import ajax
|
||||||
|
|
||||||
|
|
||||||
|
#~~ timelapse handling
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/timelapse", methods=["GET"])
|
||||||
|
def getTimelapseData():
|
||||||
|
timelapse = octoprint.timelapse.current
|
||||||
|
|
||||||
|
type = "off"
|
||||||
|
additionalConfig = {}
|
||||||
|
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
||||||
|
type = "zchange"
|
||||||
|
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
||||||
|
type = "timed"
|
||||||
|
additionalConfig = {
|
||||||
|
"interval": timelapse.interval()
|
||||||
|
}
|
||||||
|
|
||||||
|
files = octoprint.timelapse.getFinishedTimelapses()
|
||||||
|
for file in files:
|
||||||
|
file["url"] = url_for("index") + "downloads/timelapse/" + file["name"]
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
"type": type,
|
||||||
|
"config": additionalConfig,
|
||||||
|
"files": files
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/timelapse/<filename>", methods=["GET"])
|
||||||
|
def downloadTimelapse(filename):
|
||||||
|
return redirectToTornado(request, url_for("index") + "downloads/timelapse/" + filename)
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/timelapse/<filename>", methods=["DELETE"])
|
||||||
|
@restricted_access
|
||||||
|
def deleteTimelapse(filename):
|
||||||
|
if util.isAllowedFile(filename, {"mpg"}):
|
||||||
|
secure = os.path.join(settings().getBaseFolder("timelapse"), secure_filename(filename))
|
||||||
|
if os.path.exists(secure):
|
||||||
|
os.remove(secure)
|
||||||
|
return getTimelapseData()
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/timelapse", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
def setTimelapseConfig():
|
||||||
|
if "type" in request.values:
|
||||||
|
config = {
|
||||||
|
"type": request.values["type"],
|
||||||
|
"options": {}
|
||||||
|
}
|
||||||
|
|
||||||
|
if "interval" in request.values:
|
||||||
|
interval = 10
|
||||||
|
try:
|
||||||
|
interval = int(request.values["interval"])
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
config["options"] = {
|
||||||
|
"interval": interval
|
||||||
|
}
|
||||||
|
|
||||||
|
if admin_permission.can() and "save" in request.values and request.values["save"] in valid_boolean_trues:
|
||||||
|
octoprint.timelapse.configureTimelapse(config, True)
|
||||||
|
else:
|
||||||
|
octoprint.timelapse.configureTimelapse(config)
|
||||||
|
|
||||||
|
return getTimelapseData()
|
||||||
|
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||||
|
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||||
|
|
||||||
|
from flask import request, jsonify, abort, make_response
|
||||||
|
from flask.ext.login import current_user
|
||||||
|
|
||||||
|
import octoprint.users as users
|
||||||
|
|
||||||
|
from octoprint.server import restricted_access, SUCCESS, admin_permission, userManager
|
||||||
|
from octoprint.server.ajax import ajax
|
||||||
|
|
||||||
|
|
||||||
|
#~~ user settings
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/users", methods=["GET"])
|
||||||
|
@restricted_access
|
||||||
|
@admin_permission.require(403)
|
||||||
|
def getUsers():
|
||||||
|
if userManager is None:
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
return jsonify({"users": userManager.getAllUsers()})
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/users", methods=["POST"])
|
||||||
|
@restricted_access
|
||||||
|
@admin_permission.require(403)
|
||||||
|
def addUser():
|
||||||
|
if userManager is None:
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
if "application/json" in request.headers["Content-Type"]:
|
||||||
|
data = request.json
|
||||||
|
|
||||||
|
name = data["name"]
|
||||||
|
password = data["password"]
|
||||||
|
active = data["active"]
|
||||||
|
|
||||||
|
roles = ["user"]
|
||||||
|
if "admin" in data.keys() and data["admin"]:
|
||||||
|
roles.append("admin")
|
||||||
|
|
||||||
|
try:
|
||||||
|
userManager.addUser(name, password, active, roles)
|
||||||
|
except users.UserAlreadyExists:
|
||||||
|
abort(409)
|
||||||
|
return getUsers()
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/users/<username>", methods=["GET"])
|
||||||
|
@restricted_access
|
||||||
|
def getUser(username):
|
||||||
|
if userManager is None:
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||||
|
user = userManager.findUser(username)
|
||||||
|
if user is not None:
|
||||||
|
return jsonify(user.asDict())
|
||||||
|
else:
|
||||||
|
abort(404)
|
||||||
|
else:
|
||||||
|
abort(403)
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/users/<username>", methods=["PUT"])
|
||||||
|
@restricted_access
|
||||||
|
@admin_permission.require(403)
|
||||||
|
def updateUser(username):
|
||||||
|
if userManager is None:
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
user = userManager.findUser(username)
|
||||||
|
if user is not None:
|
||||||
|
if "application/json" in request.headers["Content-Type"]:
|
||||||
|
data = request.json
|
||||||
|
|
||||||
|
# change roles
|
||||||
|
roles = ["user"]
|
||||||
|
if "admin" in data.keys() and data["admin"]:
|
||||||
|
roles.append("admin")
|
||||||
|
userManager.changeUserRoles(username, roles)
|
||||||
|
|
||||||
|
# change activation
|
||||||
|
if "active" in data.keys():
|
||||||
|
userManager.changeUserActivation(username, data["active"])
|
||||||
|
return getUsers()
|
||||||
|
else:
|
||||||
|
abort(404)
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/users/<username>", methods=["DELETE"])
|
||||||
|
@restricted_access
|
||||||
|
@admin_permission.require(http_exception=403)
|
||||||
|
def removeUser(username):
|
||||||
|
if userManager is None:
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
try:
|
||||||
|
userManager.removeUser(username)
|
||||||
|
return getUsers()
|
||||||
|
except users.UnknownUser:
|
||||||
|
abort(404)
|
||||||
|
|
||||||
|
|
||||||
|
@ajax.route("/users/<username>/password", methods=["PUT"])
|
||||||
|
@restricted_access
|
||||||
|
def changePasswordForUser(username):
|
||||||
|
if userManager is None:
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||||
|
if "application/json" in request.headers["Content-Type"]:
|
||||||
|
data = request.json
|
||||||
|
if "password" in data.keys() and data["password"]:
|
||||||
|
try:
|
||||||
|
userManager.changeUserPassword(username, data["password"])
|
||||||
|
except users.UnknownUser:
|
||||||
|
return make_response(("Unknown user: %s" % username, 404, []))
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
else:
|
||||||
|
return make_response(("Forbidden", 403, []))
|
||||||
|
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||||
|
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from flask import Blueprint, request, jsonify, abort
|
||||||
|
|
||||||
|
from octoprint.server import printer, gcodeManager, SUCCESS
|
||||||
|
from octoprint.settings import settings, valid_boolean_trues
|
||||||
|
from octoprint.filemanager.destinations import FileDestinations
|
||||||
|
import octoprint.gcodefiles as gcodefiles
|
||||||
|
|
||||||
|
api = Blueprint("api", __name__)
|
||||||
|
|
||||||
|
#-- very simple api routines
|
||||||
|
@api.route("/load", methods=["POST"])
|
||||||
|
def apiLoad():
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
if not settings().get(["api", "enabled"]):
|
||||||
|
abort(401)
|
||||||
|
|
||||||
|
if not "apikey" in request.values.keys():
|
||||||
|
abort(401)
|
||||||
|
|
||||||
|
if request.values["apikey"] != settings().get(["api", "key"]):
|
||||||
|
abort(403)
|
||||||
|
|
||||||
|
if not "file" in request.files.keys():
|
||||||
|
abort(400)
|
||||||
|
|
||||||
|
# Perform an upload
|
||||||
|
file = request.files["file"]
|
||||||
|
if not gcodefiles.isGcodeFileName(file.filename):
|
||||||
|
abort(400)
|
||||||
|
|
||||||
|
destination = FileDestinations.LOCAL
|
||||||
|
filename, done = gcodeManager.addFile(file, destination)
|
||||||
|
if filename is None:
|
||||||
|
logger.warn("Upload via API failed")
|
||||||
|
abort(500)
|
||||||
|
|
||||||
|
# Immediately perform a file select and possibly print too
|
||||||
|
printAfterSelect = False
|
||||||
|
if "print" in request.values.keys() and request.values["print"] in valid_boolean_trues:
|
||||||
|
printAfterSelect = True
|
||||||
|
filepath = gcodeManager.getAbsolutePath(filename)
|
||||||
|
if filepath is not None:
|
||||||
|
printer.selectFile(filepath, False, printAfterSelect)
|
||||||
|
return jsonify(SUCCESS)
|
||||||
|
|
||||||
|
@api.route("/state", methods=["GET"])
|
||||||
|
def apiPrinterState():
|
||||||
|
if not settings().get(["api", "enabled"]):
|
||||||
|
abort(401)
|
||||||
|
|
||||||
|
if not "apikey" in request.values.keys():
|
||||||
|
abort(401)
|
||||||
|
|
||||||
|
if request.values["apikey"] != settings().get(["api", "key"]):
|
||||||
|
abort(403)
|
||||||
|
|
||||||
|
currentData = printer.getCurrentData()
|
||||||
|
currentData.update({
|
||||||
|
"temperatures": printer.getCurrentTemperatures()
|
||||||
|
})
|
||||||
|
return jsonify(currentData)
|
||||||
|
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
|
||||||
|
from tornado.web import StaticFileHandler, HTTPError
|
||||||
|
from flask import url_for, make_response
|
||||||
|
from flask.ext.login import login_required
|
||||||
|
from werkzeug.utils import redirect
|
||||||
|
from sockjs.tornado import SockJSConnection
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
import stat
|
||||||
|
import mimetypes
|
||||||
|
import email
|
||||||
|
import time
|
||||||
|
import os
|
||||||
|
import threading
|
||||||
|
import logging
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
|
from octoprint.server import userManager
|
||||||
|
from octoprint.settings import settings
|
||||||
|
import octoprint.timelapse
|
||||||
|
|
||||||
|
|
||||||
|
def restricted_access(func):
|
||||||
|
"""
|
||||||
|
If you decorate a view with this, it will ensure that first setup has been
|
||||||
|
done for OctoPrint's Access Control plus that any conditions of the
|
||||||
|
login_required decorator are met.
|
||||||
|
|
||||||
|
If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun"
|
||||||
|
flag from the settings being set to True and the userManager not indicating
|
||||||
|
that it's user database has been customized from default), the decorator
|
||||||
|
will cause a HTTP 403 status code to be returned by the decorated resource.
|
||||||
|
|
||||||
|
Otherwise the result of calling login_required will be returned.
|
||||||
|
"""
|
||||||
|
@wraps(func)
|
||||||
|
def decorated_view(*args, **kwargs):
|
||||||
|
if settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized()):
|
||||||
|
return make_response("OctoPrint isn't setup yet", 403)
|
||||||
|
return login_required(func)(*args, **kwargs)
|
||||||
|
return decorated_view
|
||||||
|
|
||||||
|
|
||||||
|
#~~ Printer state
|
||||||
|
|
||||||
|
|
||||||
|
class PrinterStateConnection(SockJSConnection):
|
||||||
|
def __init__(self, printer, gcodeManager, userManager, eventManager, session):
|
||||||
|
SockJSConnection.__init__(self, session)
|
||||||
|
|
||||||
|
self._logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
self._temperatureBacklog = []
|
||||||
|
self._temperatureBacklogMutex = threading.Lock()
|
||||||
|
self._logBacklog = []
|
||||||
|
self._logBacklogMutex = threading.Lock()
|
||||||
|
self._messageBacklog = []
|
||||||
|
self._messageBacklogMutex = threading.Lock()
|
||||||
|
|
||||||
|
self._printer = printer
|
||||||
|
self._gcodeManager = gcodeManager
|
||||||
|
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: %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)
|
||||||
|
self._eventManager.subscribe("SlicingStarted", self._onSlicingStarted)
|
||||||
|
self._eventManager.subscribe("SlicingDone", self._onSlicingDone)
|
||||||
|
self._eventManager.subscribe("SlicingFailed", self._onSlicingFailed)
|
||||||
|
|
||||||
|
octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current)
|
||||||
|
|
||||||
|
def on_close(self):
|
||||||
|
self._logger.info("Closed client connection")
|
||||||
|
self._printer.unregisterCallback(self)
|
||||||
|
self._gcodeManager.unregisterCallback(self)
|
||||||
|
octoprint.timelapse.unregisterCallback(self)
|
||||||
|
|
||||||
|
self._eventManager.fire("ClientClosed")
|
||||||
|
self._eventManager.unsubscribe("MovieDone", self._onMovieDone)
|
||||||
|
self._eventManager.unsubscribe("SlicingStarted", self._onSlicingStarted)
|
||||||
|
self._eventManager.unsubscribe("SlicingDone", self._onSlicingDone)
|
||||||
|
self._eventManager.unsubscribe("SlicingFailed", self._onSlicingFailed)
|
||||||
|
|
||||||
|
def on_message(self, message):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def sendCurrentData(self, data):
|
||||||
|
# add current temperature, log and message backlogs to sent data
|
||||||
|
with self._temperatureBacklogMutex:
|
||||||
|
temperatures = self._temperatureBacklog
|
||||||
|
self._temperatureBacklog = []
|
||||||
|
|
||||||
|
with self._logBacklogMutex:
|
||||||
|
logs = self._logBacklog
|
||||||
|
self._logBacklog = []
|
||||||
|
|
||||||
|
with self._messageBacklogMutex:
|
||||||
|
messages = self._messageBacklog
|
||||||
|
self._messageBacklog = []
|
||||||
|
|
||||||
|
data.update({
|
||||||
|
"temperatures": temperatures,
|
||||||
|
"logs": logs,
|
||||||
|
"messages": messages
|
||||||
|
})
|
||||||
|
self._emit("current", data)
|
||||||
|
|
||||||
|
def sendHistoryData(self, data):
|
||||||
|
self._emit("history", data)
|
||||||
|
|
||||||
|
def sendUpdateTrigger(self, type, payload=None):
|
||||||
|
self._emit("updateTrigger", {"type": type, "payload": payload})
|
||||||
|
|
||||||
|
def sendFeedbackCommandOutput(self, name, output):
|
||||||
|
self._emit("feedbackCommandOutput", {"name": name, "output": output})
|
||||||
|
|
||||||
|
def sendTimelapseConfig(self, timelapseConfig):
|
||||||
|
self._emit("timelapse", timelapseConfig)
|
||||||
|
|
||||||
|
def addLog(self, data):
|
||||||
|
with self._logBacklogMutex:
|
||||||
|
self._logBacklog.append(data)
|
||||||
|
|
||||||
|
def addMessage(self, data):
|
||||||
|
with self._messageBacklogMutex:
|
||||||
|
self._messageBacklog.append(data)
|
||||||
|
|
||||||
|
def addTemperature(self, data):
|
||||||
|
with self._temperatureBacklogMutex:
|
||||||
|
self._temperatureBacklog.append(data)
|
||||||
|
|
||||||
|
def _onMovieDone(self, event, payload):
|
||||||
|
self.sendUpdateTrigger("timelapseFiles")
|
||||||
|
|
||||||
|
def _onSlicingStarted(self, event, payload):
|
||||||
|
self.sendUpdateTrigger("slicingStarted", payload)
|
||||||
|
|
||||||
|
def _onSlicingDone(self, event, payload):
|
||||||
|
self.sendUpdateTrigger("slicingDone", payload)
|
||||||
|
|
||||||
|
def _onSlicingFailed(self, event, payload):
|
||||||
|
self.sendUpdateTrigger("slicingFailed", payload)
|
||||||
|
|
||||||
|
def _emit(self, type, payload):
|
||||||
|
self.send({type: payload})
|
||||||
|
|
||||||
|
|
||||||
|
#~~ customized large response handler
|
||||||
|
|
||||||
|
|
||||||
|
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")
|
||||||
|
|
||||||
|
|
||||||
|
#~~ reverse proxy compatible wsgi middleware
|
||||||
|
|
||||||
|
|
||||||
|
class ReverseProxied(object):
|
||||||
|
"""
|
||||||
|
Wrap the application in this middleware and configure the
|
||||||
|
front-end server to add these headers, to let you quietly bind
|
||||||
|
this to a URL other than / and to an HTTP scheme that is
|
||||||
|
different than what is used locally.
|
||||||
|
|
||||||
|
In nginx:
|
||||||
|
location /myprefix {
|
||||||
|
proxy_pass http://192.168.0.1:5001;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Scheme $scheme;
|
||||||
|
proxy_set_header X-Script-Name /myprefix;
|
||||||
|
}
|
||||||
|
|
||||||
|
Alternatively define prefix and scheme via config.yaml:
|
||||||
|
server:
|
||||||
|
baseUrl: /myprefix
|
||||||
|
scheme: http
|
||||||
|
|
||||||
|
:param app: the WSGI application
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, app):
|
||||||
|
self.app = app
|
||||||
|
|
||||||
|
def __call__(self, environ, start_response):
|
||||||
|
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
|
||||||
|
if not script_name:
|
||||||
|
script_name = settings().get(["server", "baseUrl"])
|
||||||
|
|
||||||
|
if script_name:
|
||||||
|
environ['SCRIPT_NAME'] = script_name
|
||||||
|
path_info = environ['PATH_INFO']
|
||||||
|
if path_info.startswith(script_name):
|
||||||
|
environ['PATH_INFO'] = path_info[len(script_name):]
|
||||||
|
|
||||||
|
scheme = environ.get('HTTP_X_SCHEME', '')
|
||||||
|
if not scheme:
|
||||||
|
scheme = settings().get(["server", "scheme"])
|
||||||
|
|
||||||
|
if scheme:
|
||||||
|
environ['wsgi.url_scheme'] = scheme
|
||||||
|
return self.app(environ, start_response)
|
||||||
|
|
||||||
|
|
||||||
|
def redirectToTornado(request, target):
|
||||||
|
requestUrl = request.url
|
||||||
|
appBaseUrl = requestUrl[:requestUrl.find(url_for("ajax.base"))]
|
||||||
|
|
||||||
|
redirectUrl = appBaseUrl + target
|
||||||
|
if "?" in requestUrl:
|
||||||
|
fragment = requestUrl[requestUrl.rfind("?"):]
|
||||||
|
redirectUrl += fragment
|
||||||
|
return redirect(redirectUrl)
|
||||||
|
|
||||||
@@ -38,7 +38,9 @@ default_settings = {
|
|||||||
"server": {
|
"server": {
|
||||||
"host": "0.0.0.0",
|
"host": "0.0.0.0",
|
||||||
"port": 5000,
|
"port": 5000,
|
||||||
"firstRun": True
|
"firstRun": True,
|
||||||
|
"baseUrl": "",
|
||||||
|
"scheme": ""
|
||||||
},
|
},
|
||||||
"webcam": {
|
"webcam": {
|
||||||
"stream": None,
|
"stream": None,
|
||||||
@@ -59,6 +61,7 @@ default_settings = {
|
|||||||
"waitForStartOnConnect": False,
|
"waitForStartOnConnect": False,
|
||||||
"alwaysSendChecksum": False,
|
"alwaysSendChecksum": False,
|
||||||
"sdSupport": True,
|
"sdSupport": True,
|
||||||
|
"sdAlwaysAvailable": False,
|
||||||
"swallowOkAfterResend": True
|
"swallowOkAfterResend": True
|
||||||
},
|
},
|
||||||
"folder": {
|
"folder": {
|
||||||
@@ -82,7 +85,8 @@ default_settings = {
|
|||||||
"z": 200,
|
"z": 200,
|
||||||
"e": 300
|
"e": 300
|
||||||
},
|
},
|
||||||
"pauseTriggers": []
|
"pauseTriggers": [],
|
||||||
|
"invertAxes": []
|
||||||
},
|
},
|
||||||
"appearance": {
|
"appearance": {
|
||||||
"name": "",
|
"name": "",
|
||||||
@@ -100,6 +104,11 @@ default_settings = {
|
|||||||
"localNetworks": ["127.0.0.0/8"],
|
"localNetworks": ["127.0.0.0/8"],
|
||||||
"autologinAs": None
|
"autologinAs": None
|
||||||
},
|
},
|
||||||
|
"cura": {
|
||||||
|
"enabled": False,
|
||||||
|
"path": "/default/path/to/cura",
|
||||||
|
"config": "/default/path/to/your/cura/config.ini"
|
||||||
|
},
|
||||||
"events": {
|
"events": {
|
||||||
"systemCommandTrigger": {
|
"systemCommandTrigger": {
|
||||||
"enabled": False
|
"enabled": False
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
__author__ = "Ross Hendrickson savorywatt"
|
||||||
|
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
|
||||||
|
from octoprint.settings import settings
|
||||||
|
|
||||||
|
class CuraFactory(object):
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def create_slicer(path=None):
|
||||||
|
"""Utilizes the factory pattern to setup a CuraEngine object
|
||||||
|
|
||||||
|
:param path: :class: `str`
|
||||||
|
"""
|
||||||
|
if path:
|
||||||
|
return Cura(path)
|
||||||
|
|
||||||
|
current_settings = settings(init=True)
|
||||||
|
path = current_settings.get(["cura", "path"])
|
||||||
|
|
||||||
|
return Cura(path)
|
||||||
|
|
||||||
|
|
||||||
|
class Cura(object):
|
||||||
|
|
||||||
|
def __init__(self, cura_path):
|
||||||
|
|
||||||
|
if not cura_path:
|
||||||
|
raise Exception("Unable to create CuraEngine - no path specified")
|
||||||
|
|
||||||
|
self.cura_path = cura_path
|
||||||
|
self._logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def process_file(
|
||||||
|
self, config, gcode, file_path, call_back=None,
|
||||||
|
call_back_args=None):
|
||||||
|
|
||||||
|
"""Wraps around the main.cpp processFile method.
|
||||||
|
|
||||||
|
:param config: :class: `string` :path to a cura config file:
|
||||||
|
:param gcode: :class: `string :path to write out the gcode generated:
|
||||||
|
:param file_path: :class: `string :path to the STL to be sliced:
|
||||||
|
:note: This will spawn a thread to handle the subprocess call and allow
|
||||||
|
us to be able to have a call back
|
||||||
|
"""
|
||||||
|
import threading
|
||||||
|
|
||||||
|
def start_thread(call_back, call_back_args, call_args, cwd):
|
||||||
|
import subprocess
|
||||||
|
self._logger.info("Running %r in %s" % (call_args, cwd))
|
||||||
|
try:
|
||||||
|
subprocess.check_call(call_args, cwd=cwd)
|
||||||
|
call_back(*call_back_args)
|
||||||
|
except subprocess.CalledProcessError as (e):
|
||||||
|
self._logger.warn("Could not slice via Cura, got return code %r" % e.returncode)
|
||||||
|
call_back_args.append("Got returncode %r" % e.returncode)
|
||||||
|
call_back(*call_back_args)
|
||||||
|
|
||||||
|
executable = self.cura_path
|
||||||
|
(workingDir, ignored) = os.path.split(executable)
|
||||||
|
args = [executable, '-i', config, '-s', file_path, '-o', gcode]
|
||||||
|
|
||||||
|
thread = threading.Thread(target=start_thread, args=(call_back,
|
||||||
|
call_back_args, args, workingDir))
|
||||||
|
|
||||||
|
thread.start()
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
|
||||||
|
|
||||||
|
import unittest
|
||||||
|
from mock import patch
|
||||||
|
|
||||||
|
from octoprint.slicers.cura import CuraFactory
|
||||||
|
from octoprint.slicers.cura import Cura
|
||||||
|
|
||||||
|
class CuraFactoryTestCase(unittest.TestCase):
|
||||||
|
|
||||||
|
|
||||||
|
def test_cura_factory(self):
|
||||||
|
|
||||||
|
fake_path = 'my/temp/path'
|
||||||
|
result = CuraFactory.create_slicer(fake_path)
|
||||||
|
|
||||||
|
self.assertEqual(fake_path, result.cura_path)
|
||||||
|
|
||||||
|
|
||||||
|
@patch('threading.Thread')
|
||||||
|
def test_cura_engine_process_file(self, thread):
|
||||||
|
path = 'rosshendrickson/workspaces/opensource/CuraEngine/'
|
||||||
|
|
||||||
|
cura = CuraFactory.create_slicer(path)
|
||||||
|
file_path = './cura/tests/test.stl'
|
||||||
|
config_path = './cura/tests/config'
|
||||||
|
gcode_filename = './cura/tests/output.gcode'
|
||||||
|
|
||||||
|
cura.process_file(config_path, gcode_filename, file_path)
|
||||||
|
self.assertTrue(thread.called)
|
||||||
|
|
||||||
@@ -295,7 +295,7 @@ table {
|
|||||||
#temperature-graph {
|
#temperature-graph {
|
||||||
height: 350px;
|
height: 350px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
background-image: url("/static/img/graph-background.png");
|
background-image: url("../img/graph-background.png");
|
||||||
background-position: center;
|
background-position: center;
|
||||||
background-repeat: no-repeat;
|
background-repeat: no-repeat;
|
||||||
}
|
}
|
||||||
|
Before Width: | Height: | Size: 135 KiB After Width: | Height: | Size: 135 KiB |
|
Before Width: | Height: | Size: 890 B After Width: | Height: | Size: 890 B |
|
Before Width: | Height: | Size: 251 B After Width: | Height: | Size: 251 B |
|
Before Width: | Height: | Size: 212 B After Width: | Height: | Size: 212 B |
|
Before Width: | Height: | Size: 119 B After Width: | Height: | Size: 119 B |
|
Before Width: | Height: | Size: 131 B After Width: | Height: | Size: 131 B |
|
Before Width: | Height: | Size: 124 B After Width: | Height: | Size: 124 B |
|
Before Width: | Height: | Size: 103 B After Width: | Height: | Size: 103 B |
|
Before Width: | Height: | Size: 118 B After Width: | Height: | Size: 118 B |
|
Before Width: | Height: | Size: 104 B After Width: | Height: | Size: 104 B |
|
Before Width: | Height: | Size: 119 B After Width: | Height: | Size: 119 B |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 112 B After Width: | Height: | Size: 112 B |
|
Before Width: | Height: | Size: 8.8 KiB After Width: | Height: | Size: 8.8 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 8.6 KiB After Width: | Height: | Size: 8.6 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 28 KiB |
|
Before Width: | Height: | Size: 197 B After Width: | Height: | Size: 197 B |
|
Before Width: | Height: | Size: 45 KiB After Width: | Height: | Size: 45 KiB |
|
Before Width: | Height: | Size: 780 B After Width: | Height: | Size: 780 B |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 721 B After Width: | Height: | Size: 721 B |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 815 B After Width: | Height: | Size: 815 B |
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 6.7 KiB After Width: | Height: | Size: 6.7 KiB |
@@ -40,9 +40,12 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
|
|||||||
if ($("#offline_overlay").is(":visible")) {
|
if ($("#offline_overlay").is(":visible")) {
|
||||||
$("#offline_overlay").hide();
|
$("#offline_overlay").hide();
|
||||||
self.timelapseViewModel.requestData();
|
self.timelapseViewModel.requestData();
|
||||||
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
|
|
||||||
self.loginStateViewModel.requestData();
|
self.loginStateViewModel.requestData();
|
||||||
self.gcodeFilesViewModel.requestData();
|
self.gcodeFilesViewModel.requestData();
|
||||||
|
|
||||||
|
if ($('#tabs li[class="active"] a').attr("href") == "#control") {
|
||||||
|
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,45 +77,62 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM
|
|||||||
|
|
||||||
self._onmessage = function(e) {
|
self._onmessage = function(e) {
|
||||||
for (var prop in e.data) {
|
for (var prop in e.data) {
|
||||||
var payload = e.data[prop];
|
var data = e.data[prop];
|
||||||
|
|
||||||
switch (prop) {
|
switch (prop) {
|
||||||
case "history": {
|
case "history": {
|
||||||
self.connectionViewModel.fromHistoryData(payload);
|
self.connectionViewModel.fromHistoryData(data);
|
||||||
self.printerStateViewModel.fromHistoryData(payload);
|
self.printerStateViewModel.fromHistoryData(data);
|
||||||
self.temperatureViewModel.fromHistoryData(payload);
|
self.temperatureViewModel.fromHistoryData(data);
|
||||||
self.controlViewModel.fromHistoryData(payload);
|
self.controlViewModel.fromHistoryData(data);
|
||||||
self.terminalViewModel.fromHistoryData(payload);
|
self.terminalViewModel.fromHistoryData(data);
|
||||||
self.timelapseViewModel.fromHistoryData(payload);
|
self.timelapseViewModel.fromHistoryData(data);
|
||||||
self.gcodeViewModel.fromHistoryData(payload);
|
self.gcodeViewModel.fromHistoryData(data);
|
||||||
self.gcodeFilesViewModel.fromCurrentData(payload);
|
self.gcodeFilesViewModel.fromCurrentData(data);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "current": {
|
case "current": {
|
||||||
self.connectionViewModel.fromCurrentData(payload);
|
self.connectionViewModel.fromCurrentData(data);
|
||||||
self.printerStateViewModel.fromCurrentData(payload);
|
self.printerStateViewModel.fromCurrentData(data);
|
||||||
self.temperatureViewModel.fromCurrentData(payload);
|
self.temperatureViewModel.fromCurrentData(data);
|
||||||
self.controlViewModel.fromCurrentData(payload);
|
self.controlViewModel.fromCurrentData(data);
|
||||||
self.terminalViewModel.fromCurrentData(payload);
|
self.terminalViewModel.fromCurrentData(data);
|
||||||
self.timelapseViewModel.fromCurrentData(payload);
|
self.timelapseViewModel.fromCurrentData(data);
|
||||||
self.gcodeViewModel.fromCurrentData(payload);
|
self.gcodeViewModel.fromCurrentData(data);
|
||||||
self.gcodeFilesViewModel.fromCurrentData(payload);
|
self.gcodeFilesViewModel.fromCurrentData(data);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "updateTrigger": {
|
case "updateTrigger": {
|
||||||
if (payload == "gcodeFiles") {
|
var type = data["type"];
|
||||||
|
var payload = data["payload"];
|
||||||
|
if (type == "gcodeFiles") {
|
||||||
gcodeFilesViewModel.requestData();
|
gcodeFilesViewModel.requestData();
|
||||||
} else if (payload == "timelapseFiles") {
|
} else if (type == "timelapseFiles") {
|
||||||
timelapseViewModel.requestData();
|
timelapseViewModel.requestData();
|
||||||
|
} else if (type == "slicingStarted") {
|
||||||
|
$("#gcode_upload_progress .bar").css("width", "100%");
|
||||||
|
$("#gcode_upload_progress").addClass("progress-striped").addClass("active");
|
||||||
|
$("#gcode_upload_progress .bar").text("Slicing ...");
|
||||||
|
} else if (type == "slicingDone") {
|
||||||
|
$("#gcode_upload_progress .bar").css("width", "0%");
|
||||||
|
$("#gcode_upload_progress").removeClass("progress-striped").removeClass("active");
|
||||||
|
$("#gcode_upload_progress .bar").text("");
|
||||||
|
$.pnotify({title: "Slicing done", text: "Sliced " + payload.stl + " to " + payload.gcode + ", took " + payload.time + " seconds"});
|
||||||
|
gcodeFilesViewModel.requestData(payload.gcode);
|
||||||
|
} else if (type == "slicingFailed") {
|
||||||
|
$("#gcode_upload_progress .bar").css("width", "0%");
|
||||||
|
$("#gcode_upload_progress").removeClass("progress-striped").removeClass("active");
|
||||||
|
$("#gcode_upload_progress .bar").text("");
|
||||||
|
$.pnotify({title: "Slicing failed", text: "Could not slice " + payload.stl + " to " + payload.gcode + ": " + payload.reason, type: "error"});
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "feedbackCommandOutput": {
|
case "feedbackCommandOutput": {
|
||||||
self.controlViewModel.fromFeedbackCommandData(payload);
|
self.controlViewModel.fromFeedbackCommandData(data);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "timelapse": {
|
case "timelapse": {
|
||||||
self.printerStateViewModel.fromTimelapseData(payload);
|
self.printerStateViewModel.fromTimelapseData(data);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -51,19 +51,42 @@ $(function() {
|
|||||||
terminalViewModel.updateOutput();
|
terminalViewModel.updateOutput();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
var webcamDisableTimeout;
|
||||||
|
$('#tabs a[data-toggle="tab"]').on('show', function (e) {
|
||||||
|
var current = e.target;
|
||||||
|
var previous = e.relatedTarget;
|
||||||
|
|
||||||
|
if (current.hash == "#control") {
|
||||||
|
clearTimeout(webcamDisableTimeout);
|
||||||
|
var webcamImage = $("#webcam_image");
|
||||||
|
var currentSrc = webcamImage.attr("src");
|
||||||
|
if (currentSrc === undefined || currentSrc.trim() == "") {
|
||||||
|
webcamImage.attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
|
||||||
|
}
|
||||||
|
} else if (previous.hash == "#control") {
|
||||||
|
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
|
||||||
|
// more load by the constant connection creation than by the actual webcam stream
|
||||||
|
webcamDisableTimeout = setTimeout(function() {
|
||||||
|
$("#webcam_image").attr("src", "");
|
||||||
|
}, 5000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
//~~ Gcode upload
|
//~~ Gcode upload
|
||||||
|
|
||||||
function gcode_upload_done(e, data) {
|
function gcode_upload_done(e, data) {
|
||||||
gcodeFilesViewModel.fromResponse(data.result);
|
gcodeFilesViewModel.fromResponse(data.result);
|
||||||
$("#gcode_upload_progress .bar").css("width", "0%");
|
if (data.result.done) {
|
||||||
$("#gcode_upload_progress").removeClass("progress-striped").removeClass("active");
|
$("#gcode_upload_progress .bar").css("width", "0%");
|
||||||
$("#gcode_upload_progress .bar").text("");
|
$("#gcode_upload_progress").removeClass("progress-striped").removeClass("active");
|
||||||
|
$("#gcode_upload_progress .bar").text("");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function gcode_upload_fail(e, data) {
|
function gcode_upload_fail(e, data) {
|
||||||
$.pnotify({
|
$.pnotify({
|
||||||
title: "Upload failed",
|
title: "Upload failed",
|
||||||
text: "<p>Could not upload the file. Make sure it is a GCODE file and has one of the following extensions: .gcode, .gco</p><p>Server reported: <pre>" + data.jqXHR.responseText + "</pre></p>",
|
text: "<p>Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and Cura support is enabled and configured.</p><p>Server reported: <pre>" + data.jqXHR.responseText + "</pre></p>",
|
||||||
type: "error",
|
type: "error",
|
||||||
hide: false
|
hide: false
|
||||||
});
|
});
|
||||||
@@ -84,9 +107,9 @@ $(function() {
|
|||||||
|
|
||||||
function enable_local_dropzone() {
|
function enable_local_dropzone() {
|
||||||
$("#gcode_upload").fileupload({
|
$("#gcode_upload").fileupload({
|
||||||
|
url: AJAX_BASEURL + "gcodefiles/local",
|
||||||
dataType: "json",
|
dataType: "json",
|
||||||
dropZone: localTarget,
|
dropZone: localTarget,
|
||||||
formData: {target: "local"},
|
|
||||||
done: gcode_upload_done,
|
done: gcode_upload_done,
|
||||||
fail: gcode_upload_fail,
|
fail: gcode_upload_fail,
|
||||||
progressall: gcode_upload_progress
|
progressall: gcode_upload_progress
|
||||||
@@ -95,9 +118,9 @@ $(function() {
|
|||||||
|
|
||||||
function disable_local_dropzone() {
|
function disable_local_dropzone() {
|
||||||
$("#gcode_upload").fileupload({
|
$("#gcode_upload").fileupload({
|
||||||
|
url: AJAX_BASEURL + "gcodefiles/local",
|
||||||
dataType: "json",
|
dataType: "json",
|
||||||
dropZone: null,
|
dropZone: null,
|
||||||
formData: {target: "local"},
|
|
||||||
done: gcode_upload_done,
|
done: gcode_upload_done,
|
||||||
fail: gcode_upload_fail,
|
fail: gcode_upload_fail,
|
||||||
progressall: gcode_upload_progress
|
progressall: gcode_upload_progress
|
||||||
@@ -106,9 +129,9 @@ $(function() {
|
|||||||
|
|
||||||
function enable_sd_dropzone() {
|
function enable_sd_dropzone() {
|
||||||
$("#gcode_upload_sd").fileupload({
|
$("#gcode_upload_sd").fileupload({
|
||||||
|
url: AJAX_BASEURL + "gcodefiles/sdcard",
|
||||||
dataType: "json",
|
dataType: "json",
|
||||||
dropZone: $("#drop_sd"),
|
dropZone: $("#drop_sd"),
|
||||||
formData: {target: "sd"},
|
|
||||||
done: gcode_upload_done,
|
done: gcode_upload_done,
|
||||||
fail: gcode_upload_fail,
|
fail: gcode_upload_fail,
|
||||||
progressall: gcode_upload_progress
|
progressall: gcode_upload_progress
|
||||||
@@ -117,6 +140,7 @@ $(function() {
|
|||||||
|
|
||||||
function disable_sd_dropzone() {
|
function disable_sd_dropzone() {
|
||||||
$("#gcode_upload_sd").fileupload({
|
$("#gcode_upload_sd").fileupload({
|
||||||
|
url: AJAX_BASEURL + "gcodefiles/sdcard",
|
||||||
dataType: "json",
|
dataType: "json",
|
||||||
dropZone: null,
|
dropZone: null,
|
||||||
formData: {target: "sd"},
|
formData: {target: "sd"},
|
||||||
@@ -80,6 +80,11 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
|
|||||||
self.sendJogCommand = function(axis, multiplier, distance) {
|
self.sendJogCommand = function(axis, multiplier, distance) {
|
||||||
if (typeof distance === "undefined")
|
if (typeof distance === "undefined")
|
||||||
distance = $('#jog_distance button.active').data('distance');
|
distance = $('#jog_distance button.active').data('distance');
|
||||||
|
|
||||||
|
if (self.settings.getPrinterInvertAxis(axis)) {
|
||||||
|
multiplier *= -1;
|
||||||
|
}
|
||||||
|
|
||||||
$.ajax({
|
$.ajax({
|
||||||
url: AJAX_BASEURL + "control/jog",
|
url: AJAX_BASEURL + "control/jog",
|
||||||
type: "POST",
|
type: "POST",
|
||||||