Setup on a Raspberry Pi running Raspbian

Gina Häußge edited this page Jan 16, 2017 · 107 revisions

If you want to get OctoPrint up and running as fast as possible, it is highly recommended to take a look at OctoPi, which is an SD card image based on Raspbian already prepared with OctoPrint, Webcamsupport, HAProxy and SSL. Just download it, flash it to an SD card and you are good to go -- you can follow this excellent video guide by Thomas Sanladerer who explains all needed steps in detail.

If on the other hand you want to run the latest versions of Raspbian, OctoPrint and all the other packages, and get a sense of how it all fits together, do follow the instructions below (warning: not for the faint of heart).


Important: This guide expects you to have a more than basic grasp of the Linux command line. In order to follow it you'll need to know:

  • how to issue commands on the shell,
  • how to edit a text file from the command line,
  • what the difference is between your user account (e.g. pi) and the superuser account root,
  • how to SSH into your Pi (so you don't need to also attach keyboard and monitor),
  • how to use Git and
  • how to use the Internet to help you if you run into problems.

This is not a "Linux for Beginners guide", those can be found for example here and here. For some Git basics please take a look here.


OctoPrint support for 250000 baudrate on a Raspberry Pi running Raspbian

In this guide, it is assumed you are going to be using the latest version of Raspbian available from the Raspberry Foundation. In any case, please check this OctoPrint wiki page for a detailed discussion about this issue.

Before installing OctoPrint on a virgin copy of Raspbian, first run "sudo apt-get update" to ensure that you are installing to the latest updates as there are a few routines that are not current that OctoPrint will need.

Basic setup

For the basic package you'll need Python 2.7 (should be installed by default) and pip. OctoPrint's dependencies will be installed by the setup.py script:

cd ~
sudo apt-get install python-pip python-dev python-setuptools python-virtualenv git libyaml-dev build-essential
git clone https://github.com/foosel/OctoPrint.git
cd OctoPrint
virtualenv venv
./venv/bin/pip install pip --upgrade
./venv/bin/python setup.py install
mkdir ~/.octoprint

You may need to add the pi user to the dialout group and tty so that the user can access the serial ports:

sudo usermod -a -G tty pi
sudo usermod -a -G dialout pi

You should then be able to start the OctoPrint server:

pi@raspberrypi ~ $ ~/OctoPrint/venv/bin/octoprint
 * Running on http://0.0.0.0:5000/

Updating & Switching Branches


Note: These instructions do not apply to OctoPi! Please take a look at the FAQ on how to update/switch branches on OctoPi.


In order to update your installation to the current status from the repository, perform the following commands:

cd ~/OctoPrint/
git pull
./venv/bin/python setup.py clean
./venv/bin/python setup.py install

Note: If you followed an older version of this guide which did not yet use a virtualenv, substitute the last two lines with python setup.py clean and sudo python setup.py install.


If you want to switch to a different branch, e.g. devel or a feature branch, perform the following commands instead:

cd ~/OctoPrint/
git pull
git checkout <branch>
./venv/bin/python setup.py clean
./venv/bin/python setup.py install

Note: If you followed an older version of this guide which did not yet use a virtualenv, substitute the last two lines with python setup.py clean and sudo python setup.py install.


If you want to switch back to an older stable release on the master branch, e.g. 1.2.13, perform the following commands:

cd ~/OctoPrint/
git checkout master
git pull
git reset --hard <old_version>
./venv/bin/python setup.py clean
./venv/bin/python setup.py install

Same goes for arbitrary commits or tags on any branch (just leave out the git checkout master line in that case and substitute <old_version> with the commit or tag).


Note: If you followed an older version of this guide which did not yet use a virtualenv, substitute the last two lines with python setup.py clean and sudo python setup.py install.


The stable branch is master, the development branch is devel, feature branches vary depending on the current development focus.

Webcam

If you also want webcam and timelapse support, you'll need to download and compile MJPG-Streamer:

cd ~
sudo apt-get install subversion libjpeg8-dev imagemagick libav-tools cmake
git clone https://github.com/jacksonliam/mjpg-streamer.git
cd mjpg-streamer/mjpg-streamer-experimental
export LD_LIBRARY_PATH=.
make

This should hopefully run through without any compilation errors. You should then be able to start the webcam server using:

./mjpg_streamer -i "./input_uvc.so" -o "./output_http.so"

This should give the following output:

MJPG Streamer Version: svn rev:
 i: Using V4L2 device.: /dev/video0
 i: Desired Resolution: 640 x 480
 i: Frames Per Second.: 5
 i: Format............: MJPEG
[...]
 o: www-folder-path...: disabled
 o: HTTP TCP port.....: 8080
 o: username:password.: disabled
 o: commands..........: enabled

For some webcams (including the PS3 Eye) you'll need to force the YUV mode by using the following start command:

./mjpg_streamer -i "./input_uvc.so -y" -o "./output_http.so" 

Please be aware that YUV mode will put additional strain on your Raspi's CPU which will then lower its performance, possibly up to the point of causing printing issues. If your camera requires the -y parameter to function, consider replacing it with one that doesn't.


Note: If your webcam requires switching to YUV mode in order to work at all, it is strongly recommended to instead use a webcam that natively supports MJPG. For YUV cameras mjpg_streamer will need to transcode all data from the camera to MJPG on your Raspberry Pi, which will put a lot of strain on its CPU (YUV mode at around 30-40% vs MJPG mode at around 1-2%). This MIGHT negatively influence print quality, so better get yourself a cheap MJPG compatible webcam. See this wiki page for a compatibility list and steer clear of cams that require -y to work.


Note: If you want to use the official RaspberryPi Camera Module you need to run

./mjpg_streamer -i "./input_raspicam.so -fps 5" -o "./output_http.so" 

If you now point your browser to http://<your Raspi's IP>:8080/?action=stream, you should see a moving picture at 5fps. (If you get an error message about missing files or directories calling the output plugin with -o "./output_http.so -w ./www" should help.)

Open ~/.octoprint/config.yaml (just create it if it doesn't exist yet) and add the following lines to it:

webcam:
  stream: http://<your Raspi's IP>:8080/?action=stream
  snapshot: http://127.0.0.1:8080/?action=snapshot
  ffmpeg: /usr/bin/avconv

Restart the OctoPrint server, clear the cache on your browser and reload the OctoPrint page. You should now see the stream from the webcam in the "Control" tab, and a "Timelapse" tab with options.


If you want to be able to start and stop mjpeg-streamer from within OctoPrint, put the following in /home/pi/scripts/webcam:

#!/bin/bash
# Start / stop streamer daemon

case "$1" in
    start)
        /home/pi/scripts/webcamDaemon >/dev/null 2>&1 &
        echo "$0: started"
        ;;
    stop)
        pkill -x webcamDaemon
        pkill -x mjpg_streamer
        echo "$0: stopped"
        ;;
    *)
        echo "Usage: $0 {start|stop}" >&2
        ;;
esac

Put this in /home/pi/scripts/webcamDaemon:

#!/bin/bash

MJPGSTREAMER_HOME=/home/pi/mjpg-streamer/mjpg-streamer-experimental
MJPGSTREAMER_INPUT_USB="input_uvc.so"
MJPGSTREAMER_INPUT_RASPICAM="input_raspicam.so"

# init configuration
camera="auto"
camera_usb_options="-r 640x480 -f 10"
camera_raspi_options="-fps 10"

if [ -e "/boot/octopi.txt" ]; then
    source "/boot/octopi.txt"
fi

# runs MJPG Streamer, using the provided input plugin + configuration
function runMjpgStreamer {
    input=$1
    pushd $MJPGSTREAMER_HOME
    echo Running ./mjpg_streamer -o "output_http.so -w ./www" -i "$input"
    LD_LIBRARY_PATH=. ./mjpg_streamer -o "output_http.so -w ./www" -i "$input"
    popd
}

# starts up the RasPiCam
function startRaspi {
    logger "Starting Raspberry Pi camera"
    runMjpgStreamer "$MJPGSTREAMER_INPUT_RASPICAM $camera_raspi_options"
}

# starts up the USB webcam
function startUsb {
    logger "Starting USB webcam"
    runMjpgStreamer "$MJPGSTREAMER_INPUT_USB $camera_usb_options"
}

# we need this to prevent the later calls to vcgencmd from blocking
# I have no idea why, but that's how it is...
vcgencmd version

# echo configuration
echo camera: $camera
echo usb options: $camera_usb_options
echo raspi options: $camera_raspi_options

# keep mjpg streamer running if some camera is attached
while true; do
    if [ -e "/dev/video0" ] && { [ "$camera" = "auto" ] || [ "$camera" = "usb" ] ; }; then
        startUsb
    elif [ "`vcgencmd get_camera`" = "supported=1 detected=1" ] && { [ "$camera" = "auto" ] || [ "$camera" = "raspi" ] ; }; then
        startRaspi
    fi

    sleep 120
done

Make sure both files are executable:

chmod +x /home/pi/scripts/webcam
chmod +x /home/pi/scripts/webcamDaemon

If you want different camera options put them in /boot/octopi.txt.

Then, in the system: actions: section of /home/pi/.octoprint/config.yaml put the following:

   - action: streamon
     command: /home/pi/scripts/webcam start
     confirm: false
     name: Start video stream
   - action: streamoff
     command: /home/pi/scripts/webcam stop
     confirm: false
     name: Stop video stream

Note: If you want to view the stream directly on your Pi, please be aware that Midori will not allow you to see the webcam picture. Chromium works although it is a bit slow, but it still might be useful for testing or aiming the camera:

sudo apt-get install chromium-browser

In any case this is only recommended for debugging purposes during setup, running a graphical user interface on the Pi will put a lot of unnecessary load on the CPU which might negatively influence print results.


Note: mjpegstreamer does not allow to bind to a specific interface to limit the accessibility to localhost only. If you want your octoprint instance to be reachable from the internet you need to block access to port 8080 from all sources except localhost if you don't want the whole world to see your webcam image.

To do this simply add iptables rules like this:

sudo /sbin/iptables -A INPUT -p tcp -i wlan0 ! -s 127.0.0.1 --dport 8080 -j DROP    # for ipv4
sudo /sbin/ip6tables -A INPUT -p tcp -i wlan0 ! -s ::1 --dport 8080 -j DROP         # for ipv6

Replace the interface with eth0, if you happen to use ethernet.

To make them persistenst, they need to be saved. In order to be restored at boot time, the easiest way is to install iptables-persist:

sudo apt-get install iptables-persist

The only thing left to do now, is save the rules you have added:

sudo /sbin/ip6tables-save > /etc/iptables/rules.v6
sudo /sbin/iptables-save > /etc/iptables/rules.v4

Touch UI

Touch UI is a plugin that provides an interface for touch screens, e.G. mobile phones or the small 3,5 inch LCDs you can connect to the pi's GPIO pins.

Install the plugin using the plugin manager in the octoprint settings. If you want to use is for a local LCD, you need to setup epiphany to start automatically. To do so, first install xautomation to send the keypress for fullscreen later and the epiphany browser if it is not already installed:

sudo apt-get install epiphany-browser xautomation

Next, create a file startTouchUI.sh in ~/ and add:

epiphany-browser http://127.0.0.1:5000 --display=:0 &
sleep 10s;
xte "key F11" -x:0

Make it executable: chmod +x startTouchUI.sh and add the following to ~/.config/lxsession/LXDE-pi/autostart

@/home/pi/startTouchUI.sh

This will launch the mobile webinterface on startup and put it into fullscreen mode.

Automatic start up

Adjust the paths to your octoprint binary in both ~/OctoPrint/scripts/octoprint.init and ~/OctoPrint/scripts/octoprint.default. If you set it up in a virtualenv as described above make sure your /etc/default/octoprint is modified like this:

DAEMON=/home/pi/OctoPrint/venv/bin/octoprint

Copy the script files to their respective folders and make the init script executable:

sudo cp ~/OctoPrint/scripts/octoprint.init /etc/init.d/octoprint
sudo chmod +x /etc/init.d/octoprint
sudo cp ~/OctoPrint/scripts/octoprint.default /etc/default/octoprint

Then add the script to autostart using sudo update-rc.d octoprint defaults.

This will also allow you to start/stop/restart the OctoPrint daemon via

sudo service octoprint {start|stop|restart}

System commands

Add the following lines to your ~/.octoprint/config.yaml (if it doesn't exist yet just create it). NB: spaces are significant in this file -- a misplaced space here will stop Octoprint from running:

system:
  actions:
  - name: Shutdown
    command: sudo shutdown -h now
    action: shutdown
    confirm: You are about to shutdown the system.
  - name: Reboot
    command: sudo shutdown -r now
    action: reboot
    confirm: You are about to reboot the system

After restarting and reloading OctoPrint, this should add a System menu to the top right where you'll find the two commands. Both are configured to show you a confirmation message before being executed (the confirm part) so that you'll hopefully not shutdown or reboot your Pi accidentally.


Note: If you disabled Raspbian's default behaviour of allowing the pi user passwordless sudo for every command, you'll need to explicitly allow the pi user passwordless sudo access to the /sbin/shutdown program for the above to work. You'll have to add a sudo rule by creating a file /etc/sudoers.d/octoprint-shutdown (as root) with the following contents:

pi ALL=NOPASSWD: /sbin/shutdown

Make everything accessible on port 80

If you want to have nicer URLs or simply need OctoPrint to run on port 80 (http's default port) due to some network restrictions, I recommend using HAProxy as a reverse proxy instead of configuring OctoPrint to run on port 80. This has the following advantages:

  • OctoPrint does not need to run with root privileges, which it would need to to be able to bind to port 80 thanks to Linux privileged port restrictions
  • You can make mjpg-streamer accessible on port 80 as well
  • You can add authentication to OctoPrint
  • Depending on the HAProxy version you can also use SSL to access OctoPrint

Setup on Raspbian is as follows:

pi@raspberrypi ~ $ sudo apt-get install haproxy

I'm using the following configuration in /etc/haproxy/haproxy.cfg, for further examples take a look here:

global
        maxconn 4096
        user haproxy
        group haproxy
        daemon
        log 127.0.0.1 local0 debug

defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        retries 3
        option redispatch
        option http-server-close
        option forwardfor
        maxconn 2000
        timeout connect 5s
        timeout client  15min
        timeout server  15min

frontend public
        bind :::80 v4v6
        use_backend webcam if { path_beg /webcam/ }
        default_backend octoprint

backend octoprint
        reqrep ^([^\ :]*)\ /(.*)     \1\ /\2
        option forwardfor
        server octoprint1 127.0.0.1:5000

backend webcam
        reqrep ^([^\ :]*)\ /webcam/(.*)     \1\ /\2
        server webcam1  127.0.0.1:8080

This will make OctoPrint accessible under http://<your Raspi's IP>/ and make mjpg-streamer accessible under http://<your Raspi's IP>/webcam/. You'll also need to modify /etc/default/haproxy and enable HAProxy by setting ENABLED to 1. After that you can start HAProxy by issuing the following command

sudo service haproxy start

Pointing your browser to http://<your Raspi's IP> should greet you with OctoPrint's UI. Now open the settings and switch to the webcam tab or alternatively open ~/.octoprint/config.yaml. Set the webcam's stream URL from http://<your Raspi's IP>:8080/?action=stream to /webcam/?action=stream (leave the snapshotUrl at http://127.0.0.1:8080/?action=snapshot!) and reload the page.

If everything works you can add the following lines to ~/.octoprint/config.yaml (just create it if it doesn't exist yet) to make the server bind only to the loopback interface:

server:
    host: 127.0.0.1

Restart the server. OctoPrint should still be available on port 80, including the webcam feed (if enabled).

User authentication

In order to protect OctoPrint from unauthorized access, you have two options. For OctoPrint's built-in access control, please see this guide.

If you only need password protection for your OctoPrint instance, not the full-fledged user management that the access control feature gives you, you can also make HAProxy do the work for you. Just change the your /etc/haproxy/haproxy.cfg to look something like this (take note of the new backend octoprint_socket and additional acl line in the backend octoprint):

frontend public
    bind *:80
    use_backend webcam if { path_beg /webcam/ }
    use_backend octoprint_socket if { path_beg /sockjs/ }
    default_backend octoprint

backend octoprint
    reqrep ^([^\ :]*)\ /(.*)     \1\ /\2
    server octoprint1 127.0.0.1:5000
    acl AuthOkay http_auth(L1)
    http-request auth realm octoprint if !AuthOkay

backend octoprint_socket
    reqrep ^([^\ :]*)\ /(.*)     \1\ /\2
    server octoprint1 127.0.0.1:5000

backend webcam
    reqrep ^([^\ :]*)\ /webcam/(.*)     \1\ /\2
    server webcam1  127.0.0.1:8080

userlist L1
    group G1

    user <your username> insecure-password <your password> groups G1

This will require you to first authenticate with username your username and password your password to access OctoPrint.

Additional Resources:

Reach your printer by typing its name in address bar of your browser - Avahi/zeroconf/bonjour-based

If you want to reach your printer by typing its name (the hostname of the RasPi running OctoPrint) instead of its IP into your browser's address bar, then you can use the Raspberry Pi Avahi setup (See only section "The flexible way: set up avahi / zeroconf"). Note: "Avahi" is called "Zeroconf", "Rendezvous" or "Bonjour", too.

Installation is simple, on your RasPi just type:

sudo apt-get update && sudo apt-get install avahi-daemon

For a network of Linux computers you are done here with the avahi setup. Jump to the paragraph relating the change of the hostname. If you want to enable Avahi support on Windows computers too you'll have to install Bonjour, allow traffic on UDP port 5353 within your firewall and grant internet access to the mDNSresponder.exe on these machines. Have a look here (search for "Get Bonjour for Windows") for a detailed description of the Windows setup.

The next step is to change the hostname of your RasPi into something more printer specific (e.g. <yourprinter>) via editing the files etc/hostname and the etc/hosts on your RasPi. Change the default name into <yourprinter> in the hostname-file via

sudo nano /etc/hostname

and do the same (here change the name behind the 127.0.1.1 into <yourprinter>) in the hosts-file via

sudo nano /etc/hosts

Now restart your RasPi via

sudo reboot.

You can now reach your RasPi running OctoPrint within your network by pointing your browser to

<yourprinter>.local .

Note you can use this too, when you want to ssh into your RasPi:

ssh <username>@<yourprinter>.local.

Additional Resources: