Automatic Klipper connect on powerup with OctoPrint

How to get Klipper ready to run when you power up your board!

  1. Connect to the raspberry using your favourite utility. I’m using Putty.
  2. Log in (user= pi, password= raspberry)
  3. Turn on the 3D printer connected to your Raspberry
  4. Input the following shell commands:

Become a superuser:
sudo su

Install the at utility (needed later)
apt update
apt install at

Get the idVendor and idProduct values of your 3D printer motherboard, use the lsusb command to list all usb devices connected to the Raspberry and inspect the output.
lsusb

root@raspberrypi:/# lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 033: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter
Bus 001 Device 002: ID 2109:3431 VIA Labs, Inc. Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

In my case, idVendoris 1a86 and idProductis 7523.
These values identify my 3d printer motherboard, write them dows as we’ll need them later.

Create a new udev rule, which will run a custom script when the board will be plugged into the raspberry:
nano /etc/udev/rules.d/40-usb-attach.rules

Inside nano, write this line, customize it with your idVendor, idProduct values.
SUBSYSTEM=="usb", ATTR{idVendor}=="1a86", ATTR{idProduct}=="7523", ACTION=="add", RUN+="/usr/bin/at -M -f /home/pi/onUsbConnected.sh now"

Basically, this rule runs the script /home/pi/onUsbConnected.sh each time the motherboard is connected to the raspberry (i.e. powered up). The at utility is used to run the script as a background task.
Once finished editing, exit nano with Ctrl-X and save the file when prompted.

Reload the list of udev rules to enable the new one:
udevadm control --reload-rules

Let’s create our script.
nano /home/pi/onUsbConnected.sh

To allow klipper connecting to the board, edit the onUsbConnected.sh script as follows:
#!/bin/sh
logger PRINTER BOARD CONNECTED
#if needed, allow more than 3 seconds to allow for your MCU to boot

sleep 3
/bin/echo FIRMWARE_RESTART > /dev/pts/0

You can add more lines with the GCODE you wish
For example, home your printer:
sleep 5
/bin/echo G28 > /dev/pts/0