34 Commits
Author SHA1 Message Date
Arksine 46de7c48c8 moonraker: bump env version to 0.2.6
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 19:06:53 -05:00
Arksine 063ef7194a update_manager: fix bug in env dist package update
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 18:33:37 -05:00
Arksine 313357061e moonraker: bump env version to 0.2.5
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 18:29:03 -05:00
Arksine 0f62b283bd update_manager: rebuild the enviroment if a new env version is detected
This should be done even if new dependencies are not required.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 18:10:58 -05:00
Arksine 9f9a05cabb update_manager: symlink dist packages on virtualenv rebuild
This allows for the installation of python "dist-packages" without enabling "system-site-packages" in the virtualenv.  As of the moment moonraker only requires the gpiod dist package.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 17:59:22 -05:00
Arksine 40fbe1abf1 scripts: don't install system site packages in virtualenv
This can create issues of the system includes conflicting packages.  Create a symlink for the system "gpiod" instead.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 15:41:42 -05:00
Arksine 9a309ffd59 file_manager: allow directories in "/etc/moonraker" to be registered
This may be useful for system packaging options that do not wish to put configuration in the home directory.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-20 08:37:45 -05:00
Arksine 684ff07ba2 update_manager: check local git version after an update
Before the service is restarted, check the local version.  This should make sure that the local repo state is reported correctly after an update, regardless of the timing of a status request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-20 06:46:52 -05:00
Arksine 0a7eed2767 update_manager: fix bug in "check_initialized" methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-19 14:05:11 -05:00
Arksine 6898ff8ab6 update_manager: make sure than all updaters are intialized before updating status
It is possible that a status request can occur while an updater is checking intial state.  Use an event to wait on initializing before returning the status request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-19 07:40:23 -05:00
Arksine 653c9190c4 docs: document "complete" field for "notifiy_update_response"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-17 17:58:04 -05:00
Arksine cdbaaedc8a test client: log when an update is complete
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-17 17:45:51 -05:00
Arksine fa20d106cf update_manager: add "complete" field to update_repsonse notification
This signals to connected clients that the current update in progress has compelted.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-17 17:45:51 -05:00
Arksine 40b74cefb5 update_manager: refresh the local git repo state when a status refresh is requested
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-17 17:45:51 -05:00
Arksine 20d27b0be6 docs: Add KlipperScreen to list of available clients
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-16 12:39:46 -05:00
Arksine 44bdf708e6 update_manager: correctly handle origins that do not contain a ".git" extension
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-16 11:50:52 -05:00
Arksine 2ddd1966fe file_manager: handle gcode files with special characters
Files with quotation marks and spaces are now acceptable and properly handled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-14 10:21:38 -05:00
Arksine 8bb7139468 websockets: remove refrenced to undefined attribute in websocket handler
This resolves an issue where an unhandled exception is rasied when a websocket attempts to write to a closed websocket.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-13 17:05:44 -05:00
Arksine ba4d771d10 paneldue: implement queues for command handling
This implements two queues, one for commands that execute locally and a second
for gcode commands that execute on the Klippy host.  While it is valid for a local
command to execute concurrently with a remote command, commands of the same type
(local or remote) should execute sequentially.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>

Update paneldue.py
2020-12-12 08:35:04 -05:00
Arksine eea2abd60e paneldue: execute commands synchronously
This prevents gcode requests from blocking temperature updates, accessing the file list, etc.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-11 07:28:39 -05:00
Arksine 70501772c1 paneldue: re-initalize if the paneldue disconnects
If 10 seconds passes without an update request, re-initialize the PanelDue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-10 11:31:40 -05:00
Arksine 119b0bf60c paneldue: attempt reconnect if disconnected due to error
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-10 06:29:49 -05:00
Arksine 59e58226ff paneldue: prevent reentry when processing incoming commands
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-10 06:29:49 -05:00
Arksine ec5be560d5 paneldue: update macros on first connection
Report that the PanelDue is "idle" until it is first initialized.  This allows for the Macros to be set upon first connection

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2020-12-10 06:29:28 -05:00
KwadFan d19e9e2d28 scripts: add update support to sudo_fix.sh
Signed-off-by: Stephan Wendel <me@stephanwe.de>
2020-12-06 07:39:50 -05:00
Arksine abbd02aa73 scripts: minor fixes
Run the legacy install cleanup after Klipper is detected in install-moonraker.sh

Fix whitespace errros in uninstall-moonraker.sh

Signed-ff-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-06 07:28:11 -05:00
Arksine 1b997b7457 docs: Note changes to install script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-06 07:05:21 -05:00
Arksine 6dfd3ca915 scripts: install Moonraker as a systemd service
This allows users to view the log using the journalctl command.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-06 06:54:48 -05:00
Arksine aaa6ec8eb2 utils: add support for logging to stdout
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-06 06:54:48 -05:00
Arksine aba5bdf339 docs: add clarification
This clarifies the installation and configuration instructions, updating some outdated info.  Also added is a sample moonraker.conf file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-05 19:19:13 -05:00
Eric Callahan 43e2893e01 docs: Note supported version of PanelDue Firmware
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-02 07:46:26 -05:00
KwadFan e025a5ce01 make executable by default
Signed-off-by: Stephan Wendel <me@stephanwe.de>
2020-11-30 14:07:14 -05:00
Arksine 2e44766e1e shell_command: check the return code of the proc for success
Add a "get_return_code" method that allows users to fetch the return code after the shell command has executed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-29 12:12:58 -05:00
KwadFan 77f79fcc20 scripts: add sudo_fix.sh
This script may be used to fix sudo permissions on "custompios" based distributions.

Signed-off-by: Stephan Wendel <me@stephanwe.de>
2020-11-29 07:46:02 -05:00
18 changed files with 636 additions and 195 deletions

No files matched your search

+3 -2
View File
@@ -6,9 +6,10 @@ the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
is used to provide Moonraker's server functionality.
Note that Moonraker does not come bundled with a client, you will need to
install one. The following web clients are currently available:
install one. The following clients are currently available:
- [Mainsail](https://github.com/meteyou/mainsail) by Meteyou
- [Fluidd](https://github.com/cadriel/fluidd) by Cadriel
- [KlipperScreen](https://github.com/jordanruthe/KlipperScreen) by jordanruthe
### Changes
@@ -17,7 +18,7 @@ to see if any action is necessary on their part. The date of the most
recent change is included.
Users:\
[user_changes.md](/docs/user_changes.md) - November 19th 2020
[user_changes.md](/docs/user_changes.md) - December 6th 2020
Developers:\
[api_changes.md](/docs/api_changes.md) - November 28th 2020
+36 -7
View File
@@ -1,9 +1,14 @@
This document describes Moonraker's full configuration.
This document describes Moonraker's full configuration. As this file
references configuration for both Klipper (printer.cfg) and Moonraker
(moonraker.conf), each example contains a commment indicating which
configuration file is being refrenenced.
# Primary Configuration
The sections outlined here are required for Moonraker to function. A
minimal functional configuration might look like the following:
```
# moonraker.conf
[server]
host: 0.0.0.0
port: 7125
@@ -19,6 +24,8 @@ trusted_clients:
## server
```
# moonraker.conf
[server]
host: 0.0.0.0
# The host address in which to bind the HTTP server. Default is to bind
@@ -34,15 +41,22 @@ enable_debug_logging: True
# When set to True Moonraker will log in verbose mode. During this stage
# of development the default is True. In the future this will change.
config_path:
# An optional path where configuration files are located. If specified,
# Moonraker will serve this path allowing file and directory manipulation
# within it. This path must be located within the user's HOME directory,
# by may not be the home directory itself. The default is no path, which
# results in no configuration files being served.
# The path to a directory where configuration files are located. This
# directory may contain Klipper config files (printer.cfg) or Moonraker
# config files (moonraker.conf). Clients may also write their own config
# files to this directory. There are restrictions on the location of
# this path, it must be located within the users HOME directory or within
# "/etc/moonraker". The path may not be the HOME directory itself. It is
# valid for the path to be "/etc/moonraker", however this is not recommended.
# Something like "/etc/moonraker/config" would be a more appropriate option.
# If you choose to locate files in "/etc/moonraker" be sure that Moonraker
# has read/write permissions in this directory.
```
## authorization
```
# moonraker.conf
[authorization]
enabled: True
# Enables authorization. When set to true, requests must either contain
@@ -75,9 +89,12 @@ functionality in moonraker.
## paneldue
Enables PanelDue display support. The PanelDue should be connected to the
host machine, either via the machine's UART GPIOs or through a USB-TTL
converter.
converter. Currently PanelDue Firmware Version 1.24 is supported. Other
releases may not behave correctly.
```
# moonraker.conf
[paneldue]
serial:
# The serial port in which the PanelDue is connected. This parameter
@@ -110,6 +127,8 @@ in the PanelDue's "macro" menu.
Note that buzzing the piezo requires the following gcode_macro in `printer.cfg`:
```
# printer.cfg
[gcode_macro PANELDUE_BEEP]
# Beep frequency
default_parameter_FREQUENCY: 300
@@ -126,6 +145,8 @@ Enables device power control. Currently GPIO (relays), TPLink Smartplug,
and Tasmota (via http) devices are supported.
```
# moonraker.conf
[power device_name]
type: gpio
# The type of device. Can be either gpio, tplink_smartplug or tasmota.
@@ -160,6 +181,8 @@ output_id:
```
Below are some potential examples:
```
# moonraker.conf
[power printer]
type: gpio
pin: gpio26
@@ -181,6 +204,8 @@ password: password1
It is possible to toggle device power from the Klippy host, this can be done
with a gcode_macro, such as:
```
# printer.cfg
[gcode_macro POWER_OFF_PRINTER]
gcode:
{action_call_remote_method("set_device_power",
@@ -191,6 +216,8 @@ The `POWER_OFF_PRINTER` gcode can be run to turn off the "printer" device.
This could be used in conjunction with Klipper's idle timeout to turn the
printer off when idle with a configuration similar to that of below:
```
# printer.cfg
[delayed_gcode delayed_printer_off]
initial_duration: 0.
gcode:
@@ -211,6 +238,8 @@ performed on pristine git repos. Repos that have been modified on
disk or cloned from unofficial sources are not supported.
```
# moonraker.conf
[update_manager]
client_repo:
# This is the GitHub repo of the client, in the format of user/client.
+49 -15
View File
@@ -8,7 +8,8 @@ Python 3 packages meet this requirement.
Klipper should be installed prior to installing Moonraker. Please see
[Klipper's Documention](https://github.com/KevinOConnor/klipper/blob/master/docs/Installation.md)
for instructions on how to do this.
for instructions on how to do this. After installation you should make
sure that the [prerequistes](#prerequisites-klipper-configuration) are configured.
After Klipper is installed, you need to modify its "default" file. This file
contains klipper's command line arguments, and you must add an argument that
@@ -38,8 +39,27 @@ KLIPPY_EXEC=/home/pi/klippy-env/bin/python
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds"
```
You may also want to take this opportunity to change the location of
printer.cfg if you enable Moonraker's "config_path" option (see the
[configuration section](#moonraker-configuration-moonrakerconf) for more information).
printer.cfg to match Moonraker's "config_path" option (see the
[configuration document](configuration.md#primary-configuration)
for more information on the config_path). For example, if the `config_path`
option is set to `~/printer_config`, your klipper defaults file might look
like the following:
```
# Configuration for /etc/init.d/klipper
KLIPPY_USER=pi
KLIPPY_EXEC=/home/pi/klippy-env/bin/python
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer_config/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds"
```
If necessary, create the config directory and move printer.cfg to it:
```
cd ~
mkdir printer_config
mv printer.cfg printer_config
```
You can now install the Moonraker application:
```
@@ -47,12 +67,24 @@ cd ~
git clone https://github.com/Arksine/moonraker.git
```
Finally, run moonraker's install script:
Prior to installation it is a good idea to create
[moonraker.conf](configuration.md). If you are using the `config_path`,
create it in the specified directory otherwise create it in the HOME
directory. A sample `moonraker.conf` may be found in the `docs` folder
of this repo.
For a default installation run the following commands:
```
cd ~/moonraker/scripts
./install-moonraker.sh
```
Or to install with `moonraker.conf` in the `config_path`:
```
cd ~/moonraker/scripts
./install-moonraker.sh -f -c /home/pi/printer_config/moonraker.conf
```
The install script has a few command line options that may be useful,
particularly for those upgrading:
- -r\
@@ -64,18 +96,15 @@ particularly for those upgrading:
detected as present.
- -c /path/to/moonraker.conf\
This allows the user to specify the path to Moonraker's config file.
The default location is "/home/<user>/moonraker.conf".
The default location is `/home/<user>/moonraker.conf`.
When the script completes it should start both Moonraker and Klipper. In
`klippy.log` you should find the following entry:\
`webhooks: New connection established`
`webhooks client <uid>: Client info {'program': 'Moonraker', 'version': '<version>'}`\
Now you may install a client, such as [Mainsail](
https://github.com/meteyou/mainsail).
- Note that as of the time of this writing (August 11 2020) the current version
of Mainsail (0.1.2) is not compatible with this repo. Please give the
developer some time to bring up Mainsail in line with the latest release
of Moonraker.
Now you may install a client, such as
[Mainsail](https://github.com/meteyou/mainsail) or
[Fluidd](https://github.com/cadriel/fluidd)
## Command line Usage
The configuration and log file paths may be specified via the command
@@ -121,9 +150,14 @@ path: ~/gcode_files
```
NOTES:
- While Klipper does not set any hard limits on the location of the
`path` option for the `virtual_sdcard`, Moonraker requires that the path
be located within the HOME directory, it cannot however be the HOME
directory. If you wish to host your files elsewhere, use a symlink.
`path` option for the `virtual_sdcard`, Moonraker does have specific
requirements for the location of this folder:
- It must be directory located in the HOME path or in `/etc/moonraker`
- It may not be the HOME directory itself. It is ok for this folder
to be `/etc/moonraker`, however that is not recommended. Something
like `/etc/moonraker/gcode_files` would be more appropriate.
- If you choose to place files in `/etc/moonraker` you must be sure that
Moonraker has permission to read/write to the directory.
- Upon first starting Moonraker is not aware of the gcode file path, thus
it cannot serve gcode files, add directories, etc. After Klippy enters
the "ready" state it sends Moonraker the gcode file path.
+15
View File
@@ -0,0 +1,15 @@
# Sample Moonraker Configuration File
[server]
# Bind server defaults of 0.0.0.0, port 7125
enable_debug_logging: True
config_path: ~/printer_config
[authorization]
enabled: True
trusted_clients:
# Enter your client IP here or range here
192.168.1.0/24
cors_domains:
# Allow CORS requests for Fluidd
http://app.fluidd.xyz
+12
View File
@@ -1,6 +1,18 @@
This file will track changes that require user intervention,
such as a configuration change or a reinstallation.
### December 6th 2020
- Moonraker is now installed as a systemd service. This allows logging
to stdout which can be viewed with the `journalctl -u moonraker` command.
This changes requires the user to rerun the install script. If
`moonraker.conf` is not located in the home directory, the command
will looks something like the following:
```
cd ~/moonraker
./scripts/install-moonraker.sh -f -c /home/pi/klipper_config/moonraker.conf
```
Otherwise you can run the install script with no arguments.
### November 19th 2020
- The install script (`install-moonraker.sh`) now has command-line
options:\
+5 -1
View File
@@ -1159,7 +1159,8 @@ Where `response` is an object int he following format:
{
application: <string>,
proc_id: <int>,
message: <string>
message: <string>,
complete: <boolean>
}
```
- The `application` field contains the name of application currently being
@@ -1169,6 +1170,9 @@ Where `response` is an object int he following format:
process. This id is generated for each update request.
- The `message` field contains an asyncronous message sent during the update
process.
- The `complete` field is set to true on the final message sent during an
update, indicating that the update completed successfully. Otherwise it
will be false.
# Appendix
+8 -5
View File
@@ -15,6 +15,7 @@ from tornado.locks import Event
VALID_GCODE_EXTS = ['.gcode', '.g', '.gco']
FULL_ACCESS_ROOTS = ["gcodes", "config"]
ETC_DIR = "/etc/moonraker"
METADATA_SCRIPT = os.path.normpath(os.path.join(
os.path.dirname(__file__), "../../scripts/extract_metadata.py"))
@@ -85,8 +86,8 @@ class FileManager:
return False
home = os.path.expanduser('~')
path = os.path.normpath(os.path.expanduser(path))
if not os.path.isdir(path) or not path.startswith(home) or \
path == home:
if not os.path.isdir(path) or path == home or \
not (path.startswith(home) or path.startswith(ETC_DIR)):
logging.info(
f"\nSupplied path ({path}) for ({root}) not valid. Please\n"
"check that the path exists and is a subfolder in the HOME\n"
@@ -373,8 +374,7 @@ class FileManager:
full_path = root_path
dir_path = ""
else:
parts = os.path.split(upload['filename'].strip().lstrip("/"))
filename = os.path.join(parts[0], "_".join(parts[1].split()))
filename = upload['filename'].strip().lstrip("/")
if dir_path:
filename = os.path.join(dir_path, filename)
full_path = os.path.normpath(os.path.join(root_path, filename))
@@ -653,8 +653,11 @@ class MetadataStorage:
self.busy = False
async def _run_extract_metadata(self, filename, notify):
# Escape single quotes in the file name so that it may be
# properly loaded
filename = filename.replace("\"", "\\\"")
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
self.gc_path, "-f", "'" + filename + "'"])
self.gc_path, "-f", f"\"{filename}\""])
shell_command = self.server.lookup_plugin('shell_command')
scmd = shell_command.build_shell_command(
cmd, self._handle_script_response)
+2
View File
@@ -80,6 +80,8 @@ class KlippyAPI:
# XXX - validate that file is on disk
if filename[0] == '/':
filename = filename[1:]
# Escape existing double quotes in the file name
filename = filename.replace("\"", "\\\"")
script = f'SDCARD_PRINT_FILE FILENAME="{filename}"'
return await self.run_gcode(script)
+139 -88
View File
@@ -9,13 +9,14 @@ import time
import json
import errno
import logging
import asyncio
from collections import deque
from utils import ServerError
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.locks import Lock
MIN_EST_TIME = 10.
INITIALIZE_TIMEOUT = 10.
class PanelDueError(ServerError):
pass
@@ -29,13 +30,15 @@ class SerialConnection:
self.paneldue = paneldue
self.port = config.get('serial')
self.baud = config.getint('baud', 57600)
self.sendlock = Lock()
self.partial_input = b""
self.ser = self.fd = None
self.connected = False
self.send_busy = False
self.send_buffer = b""
self.attempting_connect = True
self.ioloop.spawn_callback(self._connect)
def disconnect(self):
def disconnect(self, reconnect=False):
if self.connected:
if self.fd is not None:
self.ioloop.remove_handler(self.fd)
@@ -43,7 +46,13 @@ class SerialConnection:
self.connected = False
self.ser.close()
self.ser = None
self.partial_input = b""
self.send_buffer = b""
self.paneldue.initialized = False
logging.info("PanelDue Disconnected")
if reconnect and not self.attempting_connect:
self.attempting_connect = True
self.ioloop.call_later(1., self._connect)
async def _connect(self):
start_time = connect_time = time.time()
@@ -69,11 +78,12 @@ class SerialConnection:
self.fd, self._handle_incoming, IOLoop.READ | IOLoop.ERROR)
self.connected = True
logging.info("PanelDue Connected")
self.attempting_connect = False
def _handle_incoming(self, fd, events):
if events & IOLoop.ERROR:
logging.info("PanelDue Connection Error")
self.disconnect()
self.disconnect(reconnect=True)
return
# Process incoming data using same method as gcode.py
try:
@@ -83,49 +93,51 @@ class SerialConnection:
if not data:
# possibly an error, disconnect
self.disconnect()
self.disconnect(reconnect=True)
logging.info("serial_display: No data received, disconnecting")
return
self.ioloop.spawn_callback(self._process_data, data)
async def _process_data(self, data):
# Remove null bytes, separate into lines
data = data.strip(b'\x00')
lines = data.split(b'\n')
lines[0] = self.partial_input + lines[0]
self.partial_input = lines.pop()
for line in lines:
line = line.strip().decode()
try:
await self.paneldue.process_line(line)
line = line.strip().decode('utf-8', 'ignore')
self.paneldue.process_line(line)
except ServerError:
logging.exception(
"GCode Processing Error: " + line)
f"GCode Processing Error: {line}")
self.paneldue.handle_gcode_response(
"!! GCode Processing Error: " + line)
f"!! GCode Processing Error: {line}")
except Exception:
logging.exception("Error during gcode processing")
async def send(self, data):
if self.connected:
async with self.sendlock:
while data:
try:
sent = os.write(self.fd, data)
except os.error as e:
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
sent = 0
else:
await gen.sleep(.001)
continue
if sent:
data = data[sent:]
else:
logging.exception(
"Error writing data, closing serial connection")
self.disconnect()
return
def send(self, data):
self.send_buffer += data
if not self.send_busy:
self.send_busy = True
self.ioloop.spawn_callback(self._do_send)
async def _do_send(self):
while self.send_buffer:
try:
sent = os.write(self.fd, self.send_buffer)
except os.error as e:
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
sent = 0
else:
await gen.sleep(.001)
continue
if sent:
self.send_buffer = self.send_buffer[sent:]
else:
logging.exception(
"Error writing data, closing serial connection")
self.disconnect(reconnect=True)
return
self.send_busy = False
class PanelDue:
def __init__(self, config):
@@ -153,7 +165,12 @@ class PanelDue:
self.heaters = []
self.is_ready = False
self.is_shutdown = False
self.last_printer_state = 'C'
self.initialized = False
self.cq_busy = self.gq_busy = False
self.command_queue = []
self.gc_queue = []
self.last_printer_state = 'O'
self.last_update_time = 0.
# Set up macros
self.confirmed_gcode = ""
@@ -277,31 +294,32 @@ class PanelDue:
self.is_shutdown = False
self.is_ready = True
async def _process_klippy_shutdown(self):
def _process_klippy_shutdown(self):
self.is_shutdown = True
async def _process_klippy_disconnect(self):
# Tell the PD that we are shutting down
await self.write_response({'status': 'S'})
self.is_ready = False
def _process_klippy_disconnect(self):
# Tell the PD that the printer is "off"
self.write_response({'status': 'O'})
self.last_printer_state = 'O'
self.is_shutdown = self.is_shutdown = False
async def handle_status_update(self, status):
def handle_status_update(self, status):
for obj, items in status.items():
if obj in self.printer_state:
self.printer_state[obj].update(items)
else:
self.printer_state[obj] = items
async def paneldue_beep(self, frequency, duration):
def paneldue_beep(self, frequency, duration):
duration = int(duration * 1000.)
await self.write_response(
self.write_response(
{'beep_freq': frequency, 'beep_length': duration})
async def process_line(self, line):
def process_line(self, line):
self.debug_queue.append(line)
# If we find M112 in the line then skip verification
if "M112" in line.upper():
await self.klippy_apis.emergency_stop()
self.ioloop.spawn_callback(self.klippy_apis.emergency_stop)
return
if self.enable_checksum:
@@ -337,11 +355,9 @@ class PanelDue:
logging.info("PanelDue: " + msg)
raise PanelDueError(msg)
await self._run_gcode(line[line_index+1:cs_index])
script = line[line_index+1:cs_index]
else:
await self._run_gcode(line)
async def _run_gcode(self, script):
script = line
# Execute the gcode. Check for special RRF gcodes that
# require special handling
parts = script.split()
@@ -353,7 +369,8 @@ class PanelDue:
for p in parts[1:]:
arg = p[0].lower() if p[0].lower() in "psr" else "p"
try:
val = int(p[1:].strip()) if arg in "sr" else p[1:].strip()
val = int(p[1:].strip()) if arg in "sr" \
else p[1:].strip(" \"\t\n")
except Exception:
msg = f"paneldue: Error parsing direct gcode {script}"
self.handle_gcode_response("!! " + msg)
@@ -361,7 +378,7 @@ class PanelDue:
return
params["arg_" + arg] = val
func = self.direct_gcodes[cmd]
await func(**params)
self.queue_command(func, **params)
return
# Prepare GCodes that require special handling
@@ -371,18 +388,48 @@ class PanelDue:
if not script:
return
elif script in RESTART_GCODES:
await self.klippy_apis.do_restart(script)
return
self.queue_gcode(script)
try:
await self.klippy_apis.run_gcode(script)
except self.server.error:
msg = f"Error executing script {script}"
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
def queue_gcode(self, script):
self.gc_queue.append(script)
if not self.gq_busy:
self.gq_busy = True
self.ioloop.spawn_callback(self._process_gcode_queue)
async def _process_gcode_queue(self):
while self.gc_queue:
script = self.gc_queue.pop(0)
try:
if script in RESTART_GCODES:
await self.klippy_apis.do_restart(script)
else:
await self.klippy_apis.run_gcode(script)
except self.server.error:
msg = f"Error executing script {script}"
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
self.gq_busy = False
def queue_command(self, cmd, *args, **kwargs):
self.command_queue.append((cmd, args, kwargs))
if not self.cq_busy:
self.cq_busy = True
self.ioloop.spawn_callback(self._process_command_queue)
async def _process_command_queue(self):
while self.command_queue:
cmd, args, kwargs = self.command_queue.pop(0)
try:
ret = cmd(*args, **kwargs)
if asyncio.iscoroutine(ret):
await ret
except Exception:
logging.exception("Error processing command")
self.cq_busy = False
def _clean_filename(self, filename):
# Remove quotes and whitespace
filename.strip(" \"\t\n")
# Remove drive number
if filename.startswith("0:/"):
filename = filename[3:]
@@ -399,15 +446,17 @@ class PanelDue:
return filename
def _prepare_M23(self, args):
filename = self._clean_filename(args[0].strip())
return "M23 " + filename
filename = self._clean_filename(args[0])
return f"M23 {filename}"
def _prepare_M32(self, args):
filename = self._clean_filename(args[0].strip())
return "SDCARD_PRINT_FILE FILENAME=" + filename
filename = self._clean_filename(args[0])
# Escape existing double quotes in the file name
filename = filename.replace("\"", "\\\"")
return f"SDCARD_PRINT_FILE FILENAME=\"{filename}\""
def _prepare_M98(self, args):
macro = args[0][1:].strip()
macro = args[0][1:].strip(" \"\t\n")
name_start = macro.rfind('/') + 1
macro = macro[name_start:]
cmd = self.available_macros.get(macro)
@@ -444,7 +493,8 @@ class PanelDue:
mbox['msgBox.title'] = title
mbox['msgBox.controls'] = 0
mbox['msgBox.timeout'] = 0
self.ioloop.spawn_callback(self.write_response, mbox)
logging.debug(f"Creating PanelDue Confirmation: {mbox}")
self.write_response(mbox)
def handle_gcode_response(self, response):
# Only queue up "non-trivial" gcode responses. At the
@@ -458,9 +508,9 @@ class PanelDue:
self.last_gcode_response = response
return
async def write_response(self, response):
def write_response(self, response):
byte_resp = json.dumps(response) + "\r\n"
await self.ser_conn.send(byte_resp.encode())
self.ser_conn.send(byte_resp.encode())
def _get_printer_status(self):
# PanelDue States applicable to Klipper:
@@ -471,8 +521,6 @@ class PanelDue:
return 'S'
printer_state = self.printer_state
p_busy = printer_state['idle_timeout'].get(
'state', 'Idle') == "Printing"
sd_state = printer_state['print_stats'].get('state', "standby")
if sd_state == "printing":
if self.last_printer_state == 'A':
@@ -481,37 +529,41 @@ class PanelDue:
# Printing
return 'P'
elif sd_state == "paused":
if p_busy and self.last_printer_state != 'A':
p_active = printer_state['idle_timeout'].get(
'state', 'Idle') == "Printing"
if p_active and self.last_printer_state != 'A':
# Pausing
return 'D'
else:
# Paused
return 'A'
if p_busy:
# Printer is "busy"
return 'B'
return 'I'
async def _run_paneldue_M408(self, arg_r=None, arg_s=1):
def _run_paneldue_M408(self, arg_r=None, arg_s=1):
response = {}
sequence = arg_r
response_type = arg_s
if not self.is_ready:
# Klipper is still starting up, do not query status
self.last_printer_state = 'S' if self.is_shutdown else 'C'
response['status'] = self.last_printer_state
await self.write_response(response)
return
curtime = self.ioloop.time()
if curtime - self.last_update_time > INITIALIZE_TIMEOUT:
self.initialized = False
self.last_update_time = curtime
# Send gcode responses
if not self.initialized:
response['dir'] = "/macros"
response['files'] = list(self.available_macros.keys())
self.initialized = True
if not self.is_ready:
self.last_printer_state = 'O'
response['status'] = self.last_printer_state
self.write_response(response)
return
if sequence is not None and self.last_gcode_response:
# Send gcode responses
response['seq'] = sequence + 1
response['resp'] = self.last_gcode_response
self.last_gcode_response = None
if response_type == 1:
# Extended response Request
response['myName'] = self.machine_name
@@ -611,9 +663,9 @@ class PanelDue:
# is strange about this, and displays it as a full screen
# notification
self.last_message = msg
await self.write_response(response)
self.write_response(response)
async def _run_paneldue_M20(self, arg_p, arg_s=0):
def _run_paneldue_M20(self, arg_p, arg_s=0):
response_type = arg_s
if response_type != 2:
logging.info(
@@ -651,7 +703,7 @@ class PanelDue:
flist = self.file_manager.list_dir(path, simple_format=True)
if flist:
response['files'] = flist
await self.write_response(response)
self.write_response(response)
async def _run_paneldue_M30(self, arg_p=None):
# Delete a file. Clean up the file name and make sure
@@ -667,7 +719,7 @@ class PanelDue:
path = "gcodes/" + path
await self.file_manager.delete_file(path)
async def _run_paneldue_M36(self, arg_p=None):
def _run_paneldue_M36(self, arg_p=None):
response = {}
filename = arg_p
sd_status = self.printer_state.get('virtual_sdcard', {})
@@ -682,12 +734,11 @@ class PanelDue:
if not filename or not active:
# Either no file printing or no virtual_sdcard
response['err'] = 1
await self.write_response(response)
self.write_response(response)
return
else:
response['fileName'] = filename.split("/")[-1]
# For consistency make sure that the filename begins with the
# "gcodes/" root. The M20 HACK should add this in some cases.
# Ideally we would add support to the PanelDue firmware that
@@ -718,9 +769,9 @@ class PanelDue:
response['printTime'] = int(est_time + .5)
else:
response['err'] = 1
await self.write_response(response)
self.write_response(response)
async def close(self):
def close(self):
self.ser_conn.disconnect()
msg = "\nPanelDue GCode Dump:"
for i, gc in enumerate(self.debug_queue):
+7 -2
View File
@@ -20,6 +20,7 @@ class ShellCommand:
self.command = shlex.split(cmd)
self.partial_output = b""
self.cancelled = False
self.return_code = None
def _process_output(self, fd, events):
if events & IOLoop.ERROR:
@@ -40,8 +41,11 @@ class ShellCommand:
def cancel(self):
self.cancelled = True
def get_return_code(self):
return self.return_code
async def run(self, timeout=2., verbose=True):
fd = None
self.return_code = fd = None
if timeout is None:
# Never timeout
timeout = 9999999999999999.
@@ -87,7 +91,8 @@ class ShellCommand:
msg = f"Command ({self.name}) timed out"
logging.info(msg)
self.io_loop.remove_handler(fd)
return complete
self.return_code = proc.returncode
return self.return_code == 0 and complete
async def run_with_response(self, timeout=2.):
result = []
+111 -47
View File
@@ -11,9 +11,11 @@ import sys
import shutil
import zipfile
import io
import asyncio
import tornado.gen
from tornado.ioloop import IOLoop
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from tornado.locks import Event
MOONRAKER_PATH = os.path.normpath(os.path.join(
os.path.dirname(__file__), "../.."))
@@ -25,17 +27,23 @@ REPO_PREFIX = "https://api.github.com/repos"
REPO_DATA = {
'moonraker': {
'repo_url': f"{REPO_PREFIX}/arksine/moonraker/branches/master",
'origin': "https://github.com/Arksine/moonraker.git",
'origin': "https://github.com/arksine/moonraker.git",
'install_script': "scripts/install-moonraker.sh",
'requirements': "scripts/moonraker-requirements.txt",
'venv_args': "-p python3 --system-site-packages"
'venv_args': "-p python3",
'dist_packages': ["gpiod"],
'dist_dir': "/usr/lib/python3/dist-packages",
'site_pkg_path': "lib/python3.7/site-packages",
},
'klipper': {
'repo_url': f"{REPO_PREFIX}/kevinoconnor/klipper/branches/master",
'origin': "https://github.com/KevinOConnor/klipper.git",
'origin': "https://github.com/kevinoconnor/klipper.git",
'install_script': "scripts/install-octopi.sh",
'requirements': "scripts/klippy-requirements.txt",
'venv_args': "-p python2"
'venv_args': "-p python2",
'dist_packages': [],
'dist_dir': "",
'site_pkg_path': "",
}
}
@@ -44,11 +52,10 @@ class UpdateManager:
self.server = config.get_server()
AsyncHTTPClient.configure(None, defaults=dict(user_agent="Moonraker"))
self.http_client = AsyncHTTPClient()
sw_version = config['system_args'].get('software_version')
env = sys.executable
self.updaters = {
"system": PackageUpdater(self),
"moonraker": GitUpdater(self, "moonraker", MOONRAKER_PATH,
sw_version, sys.executable)
"moonraker": GitUpdater(self, "moonraker", MOONRAKER_PATH, env)
}
self.current_update = None
client_repo = config.get("client_repo", None)
@@ -86,14 +93,8 @@ class UpdateManager:
logging.info("No valid klippy info received")
return
kpath = kinfo['klipper_path']
kversion = kinfo['software_version']
env = kinfo['python_path']
self.updaters['klipper'] = GitUpdater(
self, "klipper", kpath, kversion, env)
async def _check_versions(self):
for updater in self.updaters.values():
await updater.check_remote_version()
self.updaters['klipper'] = GitUpdater(self, "klipper", kpath, env)
async def _handle_update_request(self, web_request):
app = web_request.get_endpoint().split("/")[-1]
@@ -113,10 +114,14 @@ class UpdateManager:
return "ok"
async def _handle_status_request(self, web_request):
if web_request.get_boolean('refresh', False):
await self._check_versions()
refresh = web_request.get_boolean('refresh', False)
vinfo = {}
for name, updater in self.updaters.items():
await updater.check_initialized(10.)
if refresh:
ret = updater.refresh()
if asyncio.iscoroutine(ret):
await ret
if hasattr(updater, "get_update_status"):
vinfo[name] = updater.get_update_status()
return {
@@ -165,14 +170,15 @@ class UpdateManager:
decoded = json.loads(resp.body)
return decoded
def notify_update_response(self, resp):
def notify_update_response(self, resp, is_complete=False):
resp = resp.strip()
if isinstance(resp, bytes):
resp = resp.decode()
notification = {
'message': resp,
'application': None,
'proc_id': None}
'proc_id': None,
'complete': is_complete}
if self.current_update is not None:
notification['application'] = self.current_update[0]
notification['proc_id'] = self.current_update[1]
@@ -184,7 +190,7 @@ class UpdateManager:
class GitUpdater:
def __init__(self, umgr, name, path, ver, env):
def __init__(self, umgr, name, path, env):
self.server = umgr.server
self.execute_cmd = umgr.execute_cmd
self.execute_cmd_with_response = umgr.execute_cmd_with_response
@@ -194,14 +200,9 @@ class GitUpdater:
self.repo_path = path
self.env = env
self.version = self.cur_hash = self.remote_hash = "?"
self.is_valid = False
self.is_dirty = ver.endswith("dirty")
tag_version = "?"
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", ver)
if ver_match:
tag_version = ver_match.group()
self.version = tag_version
IOLoop.current().spawn_callback(self._init_repo)
self.init_evt = Event()
self.is_valid = self.is_dirty = False
IOLoop.current().spawn_callback(self.refresh)
def _get_version_info(self):
ver_path = os.path.join(self.repo_path, "scripts/version.txt")
@@ -234,12 +235,24 @@ class GitUpdater:
log_msg = f"Repo {self.name}: {msg}"
logging.info(log_msg)
def _notify_status(self, msg):
def _notify_status(self, msg, is_complete=False):
log_msg = f"Repo {self.name}: {msg}"
logging.debug(log_msg)
self.notify_update_response(log_msg)
self.notify_update_response(log_msg, is_complete)
async def _init_repo(self):
async def check_initialized(self, timeout=None):
if self.init_evt.is_set():
return
if timeout is not None:
to = IOLoop.current().time() + timeout
await self.init_evt.wait(to)
async def refresh(self):
await self._check_local_version()
await self._check_remote_version()
self.init_evt.set()
async def _check_local_version(self):
self.is_valid = False
self.cur_hash = "?"
try:
@@ -249,28 +262,37 @@ class GitUpdater:
f"git -C {self.repo_path} remote get-url origin")
hash = await self.execute_cmd_with_response(
f"git -C {self.repo_path} rev-parse HEAD")
repo_version = await self.execute_cmd_with_response(
f"git -C {self.repo_path} describe --always "
"--tags --long --dirty")
except Exception:
self._log_exc("Error retreiving git info")
return
self.is_dirty = repo_version.endswith("dirty")
tag_version = "?"
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", repo_version)
if ver_match:
tag_version = ver_match.group()
self.version = tag_version
if not branch.startswith("fatal:"):
self.cur_hash = hash
if branch == "master":
origin = origin.lower()
if origin[-4:] != ".git":
origin += ".git"
if origin == REPO_DATA[self.name]['origin']:
self.is_valid = True
self._log_info("Validity check for git repo passed")
else:
self._log_info(f"Invalid git origin '{origin}''")
self._log_info(f"Invalid git origin '{origin}'")
else:
self._log_info("Git repo not on master branch")
else:
self._log_info(f"Invalid git repo at path '{self.repo_path}''")
try:
await self.check_remote_version()
except Exception:
pass
self._log_info(f"Invalid git repo at path '{self.repo_path}'")
async def check_remote_version(self):
async def _check_remote_version(self):
repo_url = REPO_DATA[self.name]['repo_url']
try:
branch_info = await self.github_request(repo_url)
@@ -291,7 +313,7 @@ class GitUpdater:
raise self._log_exc(
"Update aborted, repo is has been modified", False)
if self.remote_hash == "?":
await self.check_remote_version()
await self._check_remote_version()
if self.remote_hash == self.cur_hash:
# No need to update
return
@@ -308,12 +330,19 @@ class GitUpdater:
if update_deps:
await self._install_packages()
await self._update_virtualenv(need_env_rebuild)
elif need_env_rebuild:
await self._update_virtualenv(True)
# Refresh local repo state
await self._check_local_version()
if self.name == "moonraker":
# Launch restart async so the request can return
# before the server restarts
IOLoop.current().spawn_callback(self.restart_service)
self._notify_status("Update Finished...",
is_complete=True)
IOLoop.current().call_later(.1, self.restart_service)
else:
await self.restart_service()
self._notify_status("Update Finished...", is_complete=True)
async def _install_packages(self):
# Open install file file and read
@@ -361,6 +390,17 @@ class GitUpdater:
return
if not os.path.expanduser(self.env):
raise self._log_exc("Failed to create new virtualenv", False)
dist_pkgs = REPO_DATA[self.name]['dist_packages']
dist_dir = REPO_DATA[self.name]['dist_dir']
site_path = REPO_DATA[self.name]['site_pkg_path']
for pkg in dist_pkgs:
for f in os.listdir(dist_dir):
if f.startswith(pkg):
src = os.path.join(dist_dir, f)
dest = os.path.join(env_path, site_path, f)
self._notify_status(f"Linking to dist package: {pkg}")
os.symlink(src, dest)
break
reqs = os.path.join(
self.repo_path, REPO_DATA[self.name]['requirements'])
if not os.path.isfile(reqs):
@@ -397,7 +437,12 @@ class PackageUpdater:
self.execute_cmd = umgr.execute_cmd
self.notify_update_response = umgr.notify_update_response
async def check_remote_version(self):
def refresh(self):
# TODO: We should be able to determine if packages need to be
# updated here
pass
async def check_initialized(self, timeout=None):
pass
async def update(self, *args):
@@ -409,6 +454,8 @@ class PackageUpdater:
f"{APT_CMD} upgrade --yes", timeout=3600., notify=True)
except Exception:
raise self.server.error("Error updating system packages")
self.notify_update_response("Package update finished...",
is_complete=True)
class ClientUpdater:
def __init__(self, umgr, repo, path):
@@ -419,17 +466,32 @@ class ClientUpdater:
self.name = self.repo.split("/")[-1]
self.path = path
self.version = self.remote_version = self.dl_url = "?"
self.init_evt = Event()
self._get_local_version()
logging.info(f"\nInitializing Client Updater: '{self.name}',"
f"\nversion: {self.version}"
f"\npath: {self.path}")
IOLoop.current().spawn_callback(self.refresh)
def _get_local_version(self):
version_path = os.path.join(self.path, ".version")
if os.path.isfile(os.path.join(self.path, ".version")):
with open(version_path, "r") as f:
v = f.read()
self.version = v.strip()
logging.info(f"\nInitializing repo '{self.name}',"
f"\nversion: {self.version}"
f"\npath: {self.path}")
IOLoop.current().spawn_callback(self.check_remote_version)
async def check_remote_version(self):
async def check_initialized(self, timeout=None):
if self.init_evt.is_set():
return
if timeout is not None:
to = IOLoop.current().time() + timeout
await self.init_evt.wait(to)
async def refresh(self):
# Local state
self._get_local_version()
# Remote state
url = f"https://api.github.com/repos/{self.repo}/releases/latest"
try:
result = await self.github_request(url)
@@ -443,10 +505,11 @@ class ClientUpdater:
f"Github client Info Received: {self.name}, "
f"version: {self.remote_version} "
f"url: {self.dl_url}")
self.init_evt.set()
async def update(self, *args):
if self.remote_version == "?":
await self.check_remote_version()
await self.refresh()
if self.remote_version == "?":
raise self.server.error(
f"Client {self.repo}: Unable to locate update")
@@ -468,7 +531,8 @@ class ClientUpdater:
if not os.path.exists(version_path):
with open(version_path, "w") as f:
f.write(self.version)
self.notify_update_response(f"Client Updated: {self.name}")
self.notify_update_response(f"Client Updated Finished: {self.name}",
is_complete=True)
def get_update_status(self):
return {
+7 -1
View File
@@ -6,6 +6,7 @@
import logging
import logging.handlers
import os
import sys
import subprocess
import asyncio
from queue import SimpleQueue as Queue
@@ -75,9 +76,14 @@ def setup_logging(log_file, software_version):
root_logger.setLevel(logging.INFO)
file_hdlr = MoonrakerLoggingHandler(
software_version, log_file, when='midnight', backupCount=2)
stdout_hdlr = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
file_hdlr.setFormatter(formatter)
listener = logging.handlers.QueueListener(queue, file_hdlr)
stdout_fmt = logging.Formatter(
'[%(filename)s:%(funcName)s()] - %(message)s')
stdout_hdlr.setFormatter(stdout_fmt)
listener = logging.handlers.QueueListener(
queue, file_hdlr, stdout_hdlr)
listener.start()
return listener
+2 -2
View File
@@ -309,8 +309,8 @@ class WebSocket(WebSocketHandler):
'method': "notify_status_update",
'params': [status]})
except WebSocketClosedError:
self.websockets.pop(self.uid, None)
logging.info(f"Websocket Removed: {self.uid}")
logging.info(
f"Websocket Closed During Status Update: {self.uid}")
except Exception:
logging.exception(
f"Error sending data over websocket: {self.uid}")
+42 -24
View File
@@ -3,6 +3,7 @@
# Raspbian/Raspberry Pi OS based distributions.
PYTHONDIR="${HOME}/moonraker-env"
SYSTEMDDIR="/etc/systemd/system"
REBUILD_ENV="n"
FORCE_DEFAULTS="n"
CONFIG_PATH="${HOME}/moonraker.conf"
@@ -19,7 +20,19 @@ check_klipper()
}
# Step 2: Install packages
# Step 2: Clean up legacy installation
cleanup_legacy() {
if [ -f "/etc/init.d/moonraker" ]; then
# Stop Moonraker Service
echo "#### Cleanup legacy install script"
sudo systemctl stop moonraker
sudo update-rc.d -f moonraker remove
sudo rm -f /etc/init.d/moonraker
sudo rm -f /etc/default/moonraker
fi
}
# Step 3: Install packages
install_packages()
{
PKGLIST="python3-virtualenv python3-dev nginx libopenjp2-7 python3-libgpiod"
@@ -33,7 +46,7 @@ install_packages()
sudo apt-get install --yes ${PKGLIST}
}
# Step 3: Create python virtual environment
# Step 4: Create python virtual environment
create_virtualenv()
{
report_status "Installing python virtual environment..."
@@ -44,45 +57,50 @@ create_virtualenv()
rm -rf ${PYTHONDIR}
fi
[ ! -d ${PYTHONDIR} ] && virtualenv -p /usr/bin/python3 --system-site-packages ${PYTHONDIR}
if [ ! -d ${PYTHONDIR} ]; then
virtualenv -p /usr/bin/python3 ${PYTHONDIR}
ln -s /usr/lib/python3/dist-packages/gpiod* ${PYTHONDIR}/lib/python*/site-packages
fi
# Install/update dependencies
${PYTHONDIR}/bin/pip install -r ${SRCDIR}/scripts/moonraker-requirements.txt
}
# Step 4: Install startup script
# Step 5: Install startup script
install_script()
{
# Create systemd service file
SERVICE_FILE="${SYSTEMDDIR}/moonraker.service"
[ -f $SERVICE_FILE ] && [ $FORCE_DEFAULTS = "n" ] && return
report_status "Installing system start script..."
sudo cp "${SRCDIR}/scripts/moonraker-start.sh" /etc/init.d/moonraker
sudo update-rc.d moonraker defaults
}
sudo /bin/sh -c "cat > ${SERVICE_FILE}" << EOF
#Systemd service file for moonraker
[Unit]
Description=Starts Moonraker on startup
After=network.target
# Step 5: Install startup script config
install_config()
{
DEFAULTS_FILE=/etc/default/moonraker
[ -f $DEFAULTS_FILE ] && [ $FORCE_DEFAULTS = "n" ] && return
report_status "Installing system start configuration..."
sudo /bin/sh -c "cat > $DEFAULTS_FILE" <<EOF
# Configuration for /etc/init.d/moonraker
MOONRAKER_USER=$USER
MOONRAKER_EXEC=${PYTHONDIR}/bin/python
MOONRAKER_ARGS="${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}"
[Install]
WantedBy=multi-user.target
[Service]
Type=simple
User=$USER
RemainAfterExit=yes
ExecStart=${PYTHONDIR}/bin/python ${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}
Restart=always
RestartSec=10
EOF
# Use systemctl to enable the klipper systemd service script
sudo systemctl enable moonraker.service
}
# Step 6: Start server
start_software()
{
report_status "Launching Moonraker API Server..."
sudo systemctl stop klipper
sudo /etc/init.d/moonraker restart
sudo systemctl restart moonraker
sudo systemctl start klipper
}
@@ -118,8 +136,8 @@ done
# Run installation steps defined above
verify_ready
check_klipper
cleanup_legacy
install_packages
create_virtualenv
install_script
install_config
start_software
+184
View File
@@ -0,0 +1,184 @@
#!/bin/bash
# moonraker-sudo (mnrkrsudo)
# Provides a specified Group that is intended to elevate user privileges
# to help moonraker with sudo actions, if in CustomPIOS Images with
# Module "password-for-sudo".
#
# Partially used functions from Arcsine
#
# Copyright (C) 2020 Stephan Wendel <me@stephanwe.de>
#
# This file may be distributed under the terms of the GNU GPLv3 license
### Exit on Errors
set -e
### Configuration
SUDOERS_DIR='/etc/sudoers.d'
SUDOERS_FILE='020-sudo-for-moonraker'
NEW_GROUP='mnrkrsudo'
### Functions
verify_ready()
{
if [ "$EUID" -eq 0 ]; then
echo "This script must not run as root"
exit -1
fi
}
create_sudoers_file()
{
SCRIPT_TEMP_PATH=/tmp
report_status "Creating ${SUDOERS_FILE} ..."
sudo rm -f $SCRIPT_TEMP_PATH/$SUDOERS_FILE
sudo sed "s/GROUPNAME/$NEW_GROUP/g" > $SCRIPT_TEMP_PATH/$SUDOERS_FILE << '#EOF'
### Elevate moonraker API rights
### Do NOT allow Command Parts only Full Commands
### for example
###
### /sbin/systemctl "reboot", /sbin/apt "update", .....
Defaults!/usr/bin/apt-get env_keep +="DEBIAN_FRONTEND"
Cmnd_Alias REBOOT = /sbin/shutdown -r now, /bin/systemctl "reboot"
Cmnd_Alias SHUTDOWN = /sbin/shutdown now, /sbin/shutdown -h now, /bin/systemctl "poweroff"
Cmnd_Alias APT = /usr/bin/apt-get
Cmnd_Alias SYSTEMCTL = /bin/systemctl
%GROUPNAME ALL=(ALL) NOPASSWD: REBOOT, SHUTDOWN, APT, SYSTEMCTL
#EOF
report_status "\e[1;32m...done\e[0m"
}
update_env()
{
report_status "Export System Variable: DEBIAN_FRONTEND=noninteractive"
sudo /bin/sh -c 'echo "DEBIAN_FRONTEND=noninteractive" >> /etc/environment'
}
verify_syntax()
{
report_status "\e[1;33mVerifying Syntax of ${SUDOERS_FILE}\e[0m\n"
if [ $(LANG=C visudo -cf $SCRIPT_TEMP_PATH/$SUDOERS_FILE | grep -c "OK" ) -eq 1 ];
then
VERIFY_STATUS=0
report_status "\e[1;32m$(LANG=C visudo -cf $SCRIPT_TEMP_PATH/$SUDOERS_FILE)\e[0m"
else
report_status "\e[1;31mSyntax Error:\e[0m Check File: $SCRIPT_TEMP_PATH/$SUDOERS_FILE"
exit 1
fi
}
install_sudoers_file()
{
verify_syntax
if [ $VERIFY_STATUS -eq 0 ];
then
report_status "Copying $SCRIPT_TEMP_PATH/$SUDOERS_FILE to $SUDOERS_DIR/$SUDOERS_FILE"
sudo chmod 0440 $SCRIPT_TEMP_PATH/$SUDOERS_FILE
sudo cp --preserve=mode $SCRIPT_TEMP_PATH/$SUDOERS_FILE $SUDOERS_DIR/$SUDOERS_FILE
else
exit 1
fi
}
check_update_sudoers_file()
{
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ];
then
create_sudoers_file
if [ -z $(sudo diff $SCRIPT_TEMP_PATH/$SUDOERS_FILE $SUDOERS_DIR/$SUDOERS_FILE) ]
then
report_status "No need to update $SUDOERS_DIR/$SUDOERS_FILE"
else
report_status "$SUDOERS_DIR/$SUDOERS_FILE needs to be updated."
install_sudoers_file
fi
fi
}
add_new_group()
{
sudo addgroup --system $NEW_GROUP &> /dev/null
report_status "\e[1;32m...done\e[0m"
}
add_user_to_group()
{
sudo usermod -aG $NEW_GROUP $USER &> /dev/null
report_status "\e[1;32m...done\e[0m"
}
adduser_hint()
{
report_status "\e[1;31mYou have to REBOOT to take changes effect!\e[0m"
}
# Helper functions
report_status()
{
echo -e "\n\n###### $1"
}
clean_temp()
{
sudo rm -f $SCRIPT_TEMP_PATH/$SUDOERS_FILE
}
### Main
verify_ready
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ] && [ $(sudo cat /etc/gshadow | grep -c "${NEW_GROUP}") -eq 1 ] && [ $(groups | grep -c "$NEW_GROUP") -eq 1 ];
then
check_update_sudoers_file
report_status "\e[1;32mEverything is setup, nothing to do...\e[0m\n"
exit 0
else
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ];
then
report_status "\e[1;32mFile exists:\e[0m ${SUDOERS_FILE}"
check_update_sudoers_file
else
report_status "\e[1;31mFile not found:\e[0m ${SUDOERS_FILE}\n"
create_sudoers_file
install_sudoers_file
fi
if [ $(sudo cat /etc/gshadow | grep -c "${NEW_GROUP}") -eq 1 ];
then
report_status "Group ${NEW_GROUP} already exists..."
else
report_status "Group ${NEW_GROUP} will be added..."
add_new_group
fi
if [ $(groups | grep -c "$NEW_GROUP") -eq 1 ];
then
report_status "User ${USER} is already in $NEW_GROUP..."
else
report_status "Adding User ${USER} to Group $NEW_GROUP..."
add_user_to_group
adduser_hint
fi
fi
update_env
clean_temp
exit 0
+9
View File
@@ -20,6 +20,14 @@ remove_service() {
}
remove_sudo_fix() {
echo
echo "#### Removing sudo_fix"
sudo gpasswd -d $USER mnrkrsudo
sudo delgroup --only-if-empty mnrkrsudo
sudo rm -f /etc/sudoers.d/020-sudo-for-moonraker
}
remove_files() {
# Remove API Key file from older versions
if [ -e ~/.klippy_api_key ]; then
@@ -61,3 +69,4 @@ verify_ready
stop_service
remove_service
remove_files
remove_sudo_fix
+1 -1
View File
@@ -1,2 +1,2 @@
env_version=0.2.2
env_version=0.2.6
deps_version=0.2.2
+4
View File
@@ -738,6 +738,10 @@ function handle_power_changed(power_status) {
json_rpc.register_method("notify_power_changed", handle_power_changed);
function handle_update_response(response) {
if (response.complete === true) {
console.log("Update complete");
console.log(response);
}
update_term(response.message)
}
json_rpc.register_method("notify_update_response", handle_update_response);