From 706515bc84ed7d658a1da38c3bbb43231bafaaee Mon Sep 17 00:00:00 2001 From: Stefan Dej Date: Mon, 27 Apr 2020 01:55:01 +0200 Subject: [PATCH] Update Websocket + README.md --- README.md | 309 +++++++++++++------------ src/App.vue | 3 +- src/components/panels/ControlPanel.vue | 2 +- src/components/panels/StatusPanel.vue | 2 +- src/main.js | 25 +- src/pages/Console.vue | 3 +- src/plugins/wsClient.js | 19 +- src/services/websocket.js | 107 --------- src/store/actions.js | 25 +- src/store/mutations.js | 4 +- 10 files changed, 188 insertions(+), 311 deletions(-) delete mode 100644 src/services/websocket.js diff --git a/README.md b/README.md index cfe99eda..5485e55c 100644 --- a/README.md +++ b/README.md @@ -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://: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/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. \ No newline at end of file diff --git a/src/App.vue b/src/App.vue index 317c7c57..031ac037 100644 --- a/src/App.vue +++ b/src/App.vue @@ -89,8 +89,7 @@ export default { }), created () { this.$vuetify.theme.dark = true; - window.console.log('app created'); - this.$webSocketsConnect(); + //this.$webSocketsConnect(); }, computed: { currentPage: function() { diff --git a/src/components/panels/ControlPanel.vue b/src/components/panels/ControlPanel.vue index 892a8114..6eb852e7 100644 --- a/src/components/panels/ControlPanel.vue +++ b/src/components/panels/ControlPanel.vue @@ -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: { diff --git a/src/components/panels/StatusPanel.vue b/src/components/panels/StatusPanel.vue index b1bcf007..a5aba195 100644 --- a/src/components/panels/StatusPanel.vue +++ b/src/components/panels/StatusPanel.vue @@ -43,7 +43,7 @@ Filament used - {{ filament_total.toFixed(2) }}mm + {{ filament_used.toFixed(2) }}mm diff --git a/src/main.js b/src/main.js index 599b03a6..c194e2cc 100644 --- a/src/main.js +++ b/src/main.js @@ -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); - }); \ No newline at end of file +}); \ No newline at end of file diff --git a/src/pages/Console.vue b/src/pages/Console.vue index 3ccb1fa7..5aa45f23 100644 --- a/src/pages/Console.vue +++ b/src/pages/Console.vue @@ -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; diff --git a/src/plugins/wsClient.js b/src/plugins/wsClient.js index 765444d8..2d766c0d 100644 --- a/src/plugins/wsClient.js +++ b/src/plugins/wsClient.js @@ -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({ diff --git a/src/services/websocket.js b/src/services/websocket.js deleted file mode 100644 index eca50b53..00000000 --- a/src/services/websocket.js +++ /dev/null @@ -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 \ No newline at end of file diff --git a/src/store/actions.js b/src/store/actions.js index ed10200b..4b97e5f1 100644 --- a/src/store/actions.js +++ b/src/store/actions.js @@ -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}) { diff --git a/src/store/mutations.js b/src/store/mutations.js index 5a25577f..763e3afb 100644 --- a/src/store/mutations.js +++ b/src/store/mutations.js @@ -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]: [] }); } } },