Update Websocket + README.md

This commit is contained in:
Stefan Dej committed 2020-04-27 01:55:01 +02:00
1 parent efc70ca5aa
commit 706515bc84
10 files changed
+188 -311

No files matched your search

+162 -147
View File
@@ -1,30 +1,171 @@
# Klipper Web Control
KWC is a responsive web interface for [Klipper](https://github.com/KevinOConnor/klipper) 3D printer firmware. It communicates with the klipper-api from [Arksine](https://github.com/arksine).
# Mainsail
Mainsail is a responsive web interface for [Klipper](https://github.com/KevinOConnor/klipper) 3D printer firmware. It communicates with the klipper-api from [Arksine](https://github.com/arksine).
## Installation
At first install Arksine klipper-api fork/branch -> [install manual](https://github.com/Arksine/klipper/tree/work-web_server-20200131/klippy/extras/web_server)
## Requirement
You need a full working Klipper-instance. Install Klipper with the official Installation documentaion and check the Logfile if klipper (/tmp/klippy.log) works.
## Installtion of Mainsail
The installation is split into several sections
- [Change branch for Klipper-API](#change-brunch-for-klipper-api)
- [configure Klipper-API](#configure-klipper-api)
- [install webserver & reverse proxy (nginx)](#install-webserver--reverse-proxy-nginx)
- [install & configure Mainsail](#install--configure-mainsail)
### Change brunch for Klipper-API
The Klipper-API isn't merged in Klipper at the moment, so you have to change the Repository to [Arksine's Fork](https://github.com/Arksine/klipper/tree/work-web_server-20200131/klippy/extras/remote_api) with the Klipper-API.
Download and install KWC:
```bash
mkdir -p ~/sdcard
mkdir -p ~/kwc
cd ~/kwc
wget -q -O kwc.zip https://github.com/meteyou/kwc/releases/download/v0.0.8/kwc-alpha-0.0.8.zip && unzip kwc.zip && rm kwc.zip
cd ~/klipper
git fetch arksine
git checkout arksine/work-web_server-20200131
```
and install the python package "tornado"
```bash
~/klippy-env/bin/pip install tornado
```
Configure web_server in printer.cfg:
### configure Klipper-API
edit your `printer.cfg` with `nano ~/printer.cfg` and add following lines:
```
[web_server]
port: 8080
enable_cors: true
trusted_clients:
192.168.1.0/24
127.0.0.1
allow_file_ops_when_printing: true
[virtual_sdcard]
path: /home/pi/sdcard
[remote_api]
trusted_clients:
192.168.0.0/24
127.0.0.0/24
```
edit the first line of trusted_clients (192.168.0.0/24) to your network. The second line (127.0.0.0/24) is for reverse proxy later.
at last, we create the virtual_sdcard directory:
```
mkdir ~/sdcard
```
now restart klipper (`sudo service klipper restart`) and check your klippy-log if klipper is starting correct again.
when klipper is running, open the url `http://<printer-ip>:7125/printer/info` in your browser. if you see a content like this
```
{"result": {"hostname": "voron250", "error_detected": false, "version": "v0.8.0-479-gd586fb06", "is_ready": true, "message": "Printer is ready", "cpu": "4 core ARMv7 Processor rev 4 (v7l)"}}
```
your API is working!
### install webserver & reverse proxy (nginx)
nginx is important to mount all components on port 80 and host the static files from Mainsail.
If you have installed lighttpd & haproxy before you have to stop & disable it:
```bash
sudo service haproxy stop
sudo update-rc.d -f haproxy remove
sudo service lighttpd stop
sudo update-rc.d -f lighttpd remove
```
After disable all other webserver you can install nginx now:
```bash
sudo apt install nginx
```
now we create the config file with
```bash
sudo nano /etc/nginx/sites-available/mainsail
```
and fill it with the following content:
```
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream apiserver {
#edit your api port here
ip_hash;
server 127.0.0.1:7125;
}
server {
listen 80 default_server;
listen [::]:80 default_server;
access_log /var/log/nginx/kwc-access.log;
error_log /var/log/nginx/kwc-error.log;
#web_path from mainsail static files
root /home/pi/mainsail;
index index.html;
server_name _;
#max upload size for gcodes
client_max_body_size 200M;
location / {
try_files $uri $uri/ /index.html;
}
location /printer {
proxy_pass http://apiserver/printer;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
}
location /api {
proxy_pass http://apiserver/api;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
}
location /access {
proxy_pass http://apiserver/access;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
}
location /websocket {
proxy_pass http://apiserver/websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 86400;
}
location /machine {
proxy_pass http://apiserver/machine;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Scheme $scheme;
}
}
```
create directory for static files and active nginx config:
```bash
mkdir ~/mainsail
sudo rm /etc/nginx/sites-enabled/default
sudo ln -s /etc/nginx/sites-available/mainsail /etc/nginx/sites-enabled/
sudo service nginx restart
```
now you can check again the API if it works with the reverse proxy. Open the url `http://<printer-ip>/printer/info` in your browser. if you see a content like this:
```
{"result": {"hostname": "voron250", "error_detected": false, "version": "v0.8.0-479-gd586fb06", "is_ready": true, "message": "Printer is ready", "cpu": "4 core ARMv7 Processor rev 4 (v7l)"}}
```
now we can install Mainsail.
### install & configure Mainsail
now you can download the current mainsail static data
```bash
cd ~/mainsail
wget -q -O mainsail.zip https://github.com/meteyou/mainsail/releases/download/v0.0.9/mailsail-alpha-0.0.9.zip && unzip mainsail.zip && rm mainsail.zip
```
Example Klipper macros:
```
@@ -71,136 +212,10 @@ gcode:
BASE_RESUME
```
## Installation lighttpd & haproxy (out-dated)
```bash
sudo apt install lighttpd haproxy
## Update Mainsail to V0.0.9
```
edit configfile `/etc/lighttpd/lighttpd.conf` and edit following lines:
```
server.document-root = "/home/pi/kwc"
server.bind = "127.0.0.1"
server.port = 81
```
```bash
sudo usermod -a -G www-data pi
```
add following lines at the end of `/etc/haproxy/haproxy.cfg`:
```
frontend public
bind :::80 v4v6
default_backend lighttpd
use_backend printer if { path_beg /printer/ }
# use_backend webcam if { path_beg /webcam1/ }
acl is_websocket path_beg /websocket
acl is_websocket hdr(Upgrade) -i WebSocket
acl is_websocket hdr_beg(Host) -i ws
use_backend websocket if is_websocket
backend lighttpd
reqrep ^([^\ :]*)\ /(.*) \1\ /\2
option forwardfor
server lighttpd1 127.0.0.1:81
backend printer
reqrep ^([^\ :]*)\ /(.*) \1\ /\2
option forwardfor
server printer1 127.0.0.1:8080
backend websocket
reqrep ^([^\ :]*)\ /(.*) \1\ /\2
option forwardfor
server websocket1 127.0.0.1:8080
#backend webcam
# reqrep ^([^\ :]*)\ /webcam1/(.*) \1\ /\2
# server webcam1 127.0.0.1:8081
```
all comments are for webcam support. You can install MJPEG-Streamer with this [tutorial](https://github.com/cncjs/cncjs/wiki/Setup-Guide:-Raspberry-Pi-%7C-MJPEG-Streamer-Install-&-Setup-&-FFMpeg-Recording).
## Installation nginx
If you have installed lighttpd & haproxy before:
```bash
sudo service haproxy stop
sudo update-rc.d -f haproxy remove
sudo service lighttpd stop
sudo update-rc.d -f lighttpd remove
```
and now install nginx:
```bash
sudo apt install nginx
```
create configfile `/etc/nginx/sites-available/kwc`:
```
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream apiserver {
#edit your api port here
server 127.0.0.1:8080;
}
server {
listen 80 default_server;
listen [::]:80 default_server;
access_log /var/log/nginx/kwc-access.log;
error_log /var/log/nginx/kwc-error.log;
#web_path from kwc static files
root /home/pi/kwc;
index index.html;
server_name _;
#max upload size for gcodes
client_max_body_size 128M;
location / {
try_files $uri $uri/ /index.html;
}
location /printer {
proxy_pass http://apiserver/printer;
}
location /api {
proxy_pass http://apiserver/api;
}
location /access {
proxy_pass http://apiserver/access;
}
location /websocket {
proxy_pass http://apiserver/websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
}
}
```
change api port & root path.
```bash
sudo rm /etc/nginx/sites-enabled/default
sudo ln -s /etc/nginx/sites-available/kwc /etc/nginx/sites-enabled/
sudo service nginx restart
```
## Update KWC to V0.0.8
```
rm -R ~/kwc/*
cd ~/kwc
rm -R ~/mainsail/*
cd ~/mainsail
wget -q -O kwc.zip https://github.com/meteyou/kwc/releases/download/v0.0.8/kwc-alpha-0.0.8.zip && unzip kwc.zip && rm kwc.zip
```
and update your macros & nginx config.
+1 -2
View File
@@ -89,8 +89,7 @@ export default {
}),
created () {
this.$vuetify.theme.dark = true;
window.console.log('app created');
this.$webSocketsConnect();
//this.$webSocketsConnect();
},
computed: {
currentPage: function() {
+1 -1
View File
@@ -118,7 +118,7 @@
this.doSend(gcode);
},
doSend(gcode) {
Vue.prototype.$webSocketsSendObj('post_printer_gcode', { script: gcode }, "sendGcode");
Vue.prototype.$socket.sendObj('post_printer_gcode', { script: gcode }, "sendGcode");
},
},
watch: {
+1 -1
View File
@@ -43,7 +43,7 @@
<v-flex grow class="equal-width">
<v-layout column>
<v-flex tag="strong">Filament used</v-flex>
<v-flex tag="span">{{ filament_total.toFixed(2) }}mm</v-flex>
<v-flex tag="span">{{ filament_used.toFixed(2) }}mm</v-flex>
</v-layout>
</v-flex>
<v-flex grow class="equal-width">
+10 -15
View File
@@ -1,6 +1,5 @@
import Vue from 'vue'
//import WebSocketClient from './plugins/wsClient'
import webSocketService from './services/websocket'
import WebSocketClient from './plugins/wsClient'
import App from './App.vue'
import vuetify from './plugins/vuetify'
import VueResource from 'vue-resource'
@@ -20,22 +19,18 @@ Vue.http.headers.common['Access-Control-Allow-Methods'] = 'POST, GET, PUT, OPTIO
Vue.component('vue-headful', vueHeadful);
fetch('/config.json').then(res => res.json())
.then(file => {
fetch('/config.json')
.then(res => res.json())
.then(file => {
store.commit('setSettings', file);
/*const socketClient = new WebSocketClient('ws://' + store.state.socket.hostname + ':' + store.state.socket.port + '/websocket', {
const socketClient = new WebSocketClient('ws://' + store.state.socket.hostname + ':' + store.state.socket.port + '/websocket', {
store: store,
reconnectEnabled: true,
reconnectInterval: store.state.socket.reconnectInterval,
});
socketClient.connect()
Vue.prototype.$socket = socketClient*/
Vue.use(webSocketService, {
store,
url: 'ws://' + store.state.socket.hostname + ':' + store.state.socket.port + '/websocket'
})
socketClient.connect();
Vue.prototype.$socket = socketClient;
new Vue({
vuetify,
@@ -43,11 +38,11 @@ fetch('/config.json').then(res => res.json())
store,
render: h => h(App)
}).$mount('#app')
})
.catch((error) => {
})
.catch((error) => {
let p = document.createElement("p");
let content = document.createTextNode("config.json not found or cannot be decoded!");
p.appendChild(content);
document.getElementById('app').append(p);
window.console.error('Error:', error);
});
});
+1 -2
View File
@@ -132,9 +132,8 @@
},
methods: {
doSend() {
window.console.log('send gcode: '+this.gcode);
this.loadingSendGcode = true;
Vue.prototype.$webSocketsSendObj('post_printer_gcode', { script: this.gcode }, "sendGcode");
Vue.prototype.$socket.sendObj('post_printer_gcode', { script: this.gcode }, "sendGcode");
this.lastCommands.push(this.gcode);
this.gcode = "";
this.lastCommandNumber = null;
+1 -18
View File
@@ -27,7 +27,7 @@ export default class WebSocketClient {
let method = 'dispatch'
let target = eventName
let msg = event
if (event.data) {
if (event && event.data) {
msg = JSON.parse(event.data)
}
this.store[method](target, msg)
@@ -38,13 +38,11 @@ export default class WebSocketClient {
this.instance.onopen = () => {
if (this.store) this.passToStore('socket_on_open', event);
this.keepAlive();
};
this.instance.onclose = (e) => {
window.console.log("Websocket Closed, reconnecting in "+this.reconnectInterval+"ms: ", e.reason);
this.passToStore('socket_on_close', e);
this.cancelKeepAlive();
setTimeout(() => {
this.connect();
@@ -70,21 +68,6 @@ export default class WebSocketClient {
};
}
keepAlive() {
window.console.log('keepAlive start');
window.console.log(this.instance);
if (this.instance.readyState === this.instance.OPEN) {
window.console.log('keepAlive send');
this.sendObj('get_printer_info', {}, 'getKlipperInfo');
}
this.timerId = setTimeout(this.keepAlive, this.keepAliveTimeout);
}
cancelKeepAlive() {
if (this.timerId) clearTimeout(this.timerId);
}
sendObj (method, params, action = '') {
let id = Math.floor(Math.random() * 10000) + 1
this.wsData.push({
-107
View File
@@ -1,107 +0,0 @@
let webSocketsService = {}
webSocketsService.install = function (Vue, options) {
let ws = new WebSocket(options.url)
let reconnectInterval = options.reconnectInterval || 1000
let wsData = [];
let timerId = 0;
Vue.prototype.$webSocketsConnect = () => {
window.console.log('webSocketConnect');
ws = new WebSocket(options.url);
ws.onopen = () => {
window.console.log('onopen');
// Restart reconnect interval
reconnectInterval = options.reconnectInterval || 1000
options.store.dispatch('socket_on_open');
keepAlive();
}
ws.onmessage = (event) => {
// New message from the backend - use JSON.parse(event.data)
handleNotification(event)
}
ws.onclose = (event) => {
cancelKeepAlive();
if (event) {
// Event.code 1000 is our normal close event
if (event.code !== 1000) {
let maxReconnectInterval = options.maxReconnectInterval || 3000
setTimeout(() => {
if (reconnectInterval < maxReconnectInterval) {
// Reconnect interval can't be > x seconds
reconnectInterval += 1000
}
Vue.prototype.$webSocketsConnect()
}, reconnectInterval)
}
}
}
ws.onerror = (error) => {
window.console.log(error);
ws.close()
}
}
Vue.prototype.$webSocketsDisconnect = () => {
window.console.log('disconnect');
// Our custom disconnect event
ws.close()
}
Vue.prototype.$webSocketsSend = (data) => {
ws.send(JSON.stringify(data))
}
Vue.prototype.$webSocketsSendObj = (method, params, action = '') => {
let id = Math.floor(Math.random() * 10000) + 1
wsData.push({
id: id,
action: action
});
ws.send(JSON.stringify({
jsonrpc: '2.0', method: method, params: params, id: id
}))
}
function keepAlive() {
var timeout = 5000;
if (ws.readyState === ws.OPEN) {
Vue.prototype.$webSocketsSendObj('get_printer_info', {}, 'getKlipperInfo');
}
timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
if (timerId) {
clearTimeout(timerId);
}
}
function passToStore (eventName, event) {
if (!eventName.startsWith('socket_')) { return }
let target = eventName
let msg = event
if (event.data) {
msg = JSON.parse(event.data)
}
options.store.dispatch(target, msg)
}
function handleNotification (params) {
let data = JSON.parse(params.data);
if (wsData.filter(item => item.id === data.id).length > 0 &&
wsData.filter(item => item.id === data.id)[0].action !== "") {
options.store.dispatch(
wsData.filter(item => item.id === data.id)[0].action,
data.result
)
} else passToStore('socket_on_message', data)
}
}
export default webSocketsService
+9 -16
View File
@@ -7,7 +7,7 @@ import axios from "axios";
export default {
socket_on_open ({ commit }) {
commit('setConnected');
Vue.prototype.$webSocketsSendObj('get_printer_status', { }, 'getHelpData');
Vue.prototype.$socket.sendObj('get_printer_status', { }, 'getHelpData');
fetch('http://'+store.state.socket.hostname+':'+store.state.socket.port+'/printer/files/gui.json')
.then(res => res.json()).then(file => {
@@ -16,11 +16,11 @@ export default {
window.console.warn('No kwc config file found.');
});
Vue.prototype.$webSocketsSendObj('get_printer_info', {}, 'getKlipperInfo');
Vue.prototype.$webSocketsSendObj('get_printer_objects', {}, 'getObjectInfo');
Vue.prototype.$webSocketsSendObj('get_printer_status', { heater: [] }, 'getObjectInfo');
Vue.prototype.$webSocketsSendObj('get_printer_status', { configfile: ['config'] }, 'getPrinterConfig');
Vue.prototype.$webSocketsSendObj('post_printer_subscriptions', {
Vue.prototype.$socket.sendObj('get_printer_info', {}, 'getKlipperInfo');
Vue.prototype.$socket.sendObj('get_printer_objects', {}, 'getObjectInfo');
Vue.prototype.$socket.sendObj('get_printer_status', { heater: [] }, 'getObjectInfo');
Vue.prototype.$socket.sendObj('get_printer_status', { configfile: ['config'] }, 'getPrinterConfig');
Vue.prototype.$socket.sendObj('post_printer_subscriptions', {
gcode: [],
toolhead: [],
virtual_sdcard: [],
@@ -32,8 +32,8 @@ export default {
idle_timeout: [],
});
Vue.prototype.$webSocketsSendObj('get_printer_files', {}, 'getFileList');
Vue.prototype.$webSocketsSendObj('get_printer_gcode_help', {}, 'getHelpList');
Vue.prototype.$socket.sendObj('get_printer_files', {}, 'getFileList');
Vue.prototype.$socket.sendObj('get_printer_gcode_help', {}, 'getHelpList');
},
socket_on_close ({ commit }, event) {
@@ -115,11 +115,6 @@ export default {
commit('setPrinterConfig', data);
},
addSubscription(state, data) {
window.console.log(state);
window.console.log(data);
},
getFileList({ commit }, data) {
commit('setFileList', data);
commit('setLoadingGcodeRefresh', false);
@@ -150,11 +145,9 @@ export default {
},
sendGcode({commit}, data) {
window.console.log('finish');
window.console.log(data);
commit('setLoadingSendGcode', false);
commit('sendGcode', data);
commit('addGcodeResponse', data);
},
responseHome({commit}) {
+2 -2
View File
@@ -102,11 +102,11 @@ export default {
let nameSplit = key.split(" ");
if (nameSplit[0] === "temperature_fan") {
Vue.prototype.$webSocketsSendObj('post_printer_subscriptions', { [key]: [] });
Vue.prototype.$socket.sendObj('post_printer_subscriptions', { [key]: [] });
}
if (nameSplit[0] === "filament_switch_sensor") {
Vue.prototype.$webSocketsSendObj('post_printer_subscriptions', { [key]: [] });
Vue.prototype.$socket.sendObj('post_printer_subscriptions', { [key]: [] });
}
}
},