forked from moggieuk/Happy-Hare
-
Notifications
You must be signed in to change notification settings - Fork 0
/
install.sh
executable file
·2089 lines (1921 loc) · 80.3 KB
/
install.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# Happy Hare MMU Software
#
# Installer / Updater script
#
# Copyright (C) 2022 moggieuk#6538 (discord) [email protected]
#
# Creality K1 Support
# 2024 hamyy <[email protected]>
# 2024 Unsweeticetea <[email protected]>
# 2024 Dmitry Kychanov <[email protected]>
#
VERSION=3.01 # Important: Keep synced with mmy.py
F_VERSION=$(echo "$VERSION" | sed 's/\([0-9]\+\)\.\([0-9]\)\([0-9]\)/\1.\2.\3/')
SCRIPT="$(readlink -f "$0")"
SCRIPTFILE="$(basename "$SCRIPT")"
SCRIPTPATH="$(dirname "$SCRIPT")"
SCRIPTNAME="$0"
ARGS=( "$@" )
# Creality K1 series printers run on MIPS, with a limited instruction set and different default klipper directories
# Checking for machine type is the easiest way so far to spot them (will be set to 1 if on MIPS):
IS_MIPS=0
if [ $(uname -m) = "mips" ]; then
IS_MIPS=1
fi
KLIPPER_HOME="${HOME}/klipper"
MOONRAKER_HOME="${HOME}/moonraker"
KLIPPER_CONFIG_HOME="${HOME}/printer_data/config"
OCTOPRINT_KLIPPER_CONFIG_HOME="${HOME}"
KLIPPER_LOGS_HOME="${HOME}/printer_data/logs"
OLD_KLIPPER_CONFIG_HOME="${HOME}/klipper_config"
if [ "$IS_MIPS" -eq 1 ]; then
KLIPPER_HOME="/usr/share/klipper"
MOONRAKER_HOME="/usr/data/moonraker/moonraker"
KLIPPER_CONFIG_HOME="/usr/data/printer_data/config"
unset OCTOPRINT_KLIPPER_CONFIG_HOME
unset OLD_KLIPPER_CONFIG_HOME
fi
clear
set -e # Exit immediately on error
declare -A PIN 2>/dev/null || {
echo "Please run this script with bash $0"
exit 1
}
# Source pin defs for common MCU's
source ${SCRIPTPATH}/pin_defs
# These pins will usually be on main mcu for wiring simplification
#
_hw_toolhead_sensor_pin=""
_hw_extruder_sensor_pin=""
_hw_gantry_servo_pin=""
_hw_sync_feedback_tension_pin=""
_hw_sync_feedback_compression_pin=""
# Screen Colors
OFF='\033[0m' # Text Reset
BLACK='\033[0;30m' # Black
RED='\033[0;31m' # Red
GREEN='\033[0;32m' # Green
YELLOW='\033[0;33m' # Yellow
BLUE='\033[0;34m' # Blue
PURPLE='\033[0;35m' # Purple
CYAN='\033[0;36m' # Cyan
WHITE='\033[0;37m' # White
B_RED='\033[1;31m' # Bold Red
B_GREEN='\033[1;32m' # Bold Green
B_YELLOW='\033[1;33m' # Bold Yellow
B_CYAN='\033[1;36m' # Bold Cyan
B_WHITE='\033[1;37m' # Bold White
TITLE="${B_WHITE}"
DETAIL="${BLUE}"
INFO="${CYAN}"
EMPHASIZE="${B_CYAN}"
ERROR="${B_RED}"
WARNING="${B_YELLOW}"
PROMPT="${CYAN}"
DIM="${PURPLE}"
INPUT="${OFF}"
SECTION="----------------\n"
get_logo() {
caption=$1
logo=$(cat <<EOF
${INFO}
(\_/)
( *,*)
(")_(") ${caption}
${OFF}
EOF
)
echo -e "$logo"
}
sad_logo=$(cat <<EOF
${INFO}
(\_/)
( v,v)
(")^(") Very Unhappy Hare
${OFF}
EOF
)
self_update() {
[ "$UPDATE_GUARD" ] && return
export UPDATE_GUARD=YES
clear
cd "$SCRIPTPATH"
set +e
# timeout is unavailable on MIPS
if [ "$IS_MIPS" -ne 1 ]; then
BRANCH=$(timeout 3s git branch --show-current)
else
BRANCH=$(git branch --show-current)
fi
if [ $? -ne 0 ]; then
echo -e "${ERROR}Error updating from github"
echo -e "${ERROR}You might have an old version of git"
echo -e "${ERROR}Skipping automatic update..."
set -e
return
fi
set -e
[ -z "${BRANCH}" ] && {
echo -e "${ERROR}Timeout talking to github. Skipping upgrade check"
return
}
echo -e "${B_GREEN}Running on '${BRANCH}' branch"
# Both check for updates but also help me not loose changes accidently
echo -e "${B_GREEN}Checking for updates..."
git fetch --quiet
set +e
git diff --quiet --exit-code "origin/$BRANCH"
if [ $? -eq 1 ]; then
echo -e "${B_GREEN}Found a new version of Happy Hare on github, updating..."
[ -n "$(git status --porcelain)" ] && {
git stash push -m 'local changes stashed before self update' --quiet
}
RESTART=1
fi
set -e
if [ -n "${N_BRANCH}" -a "${BRANCH}" != "${N_BRANCH}" ]; then
BRANCH=${N_BRANCH}
echo -e "${B_GREEN}Switching to '${BRANCH}' branch"
RESTART=1
fi
if [ -n "${RESTART}" ]; then
git checkout $BRANCH --quiet
if git symbolic-ref -q HEAD > /dev/null; then
# On a branch (if using tags we will be detached)
git pull --quiet --force
fi
GIT_VER=$(git describe --tags)
echo -e "${B_GREEN}Now on git version ${GIT_VER}"
echo -e "${B_GREEN}Running the new install script..."
cd - >/dev/null
exec "$SCRIPTNAME" "${ARGS[@]}"
exit 0 # Exit this old instance
fi
GIT_VER=$(git describe --tags)
echo -e "${B_GREEN}Already the latest version: ${GIT_VER}"
}
function nextfilename {
local name="$1"
if [ -d "${name}" ]; then
printf "%s-%s" ${name} $(date '+%Y%m%d_%H%M%S')
else
printf "%s-%s.%s-old" ${name%.*} $(date '+%Y%m%d_%H%M%S') ${name##*.}
fi
}
function nextsuffix {
local name="$1"
local -i num=0
while [ -e "$name.0$num" ]; do
num+=1
done
printf "%s.0%d" "$name" "$num"
}
verify_not_root() {
if [ "$IS_MIPS" -ne 1 ]; then
if [ "$EUID" -eq 0 ]; then
echo -e "${ERROR}This script must not run as root"
exit -1
fi
else
echo -e "${WARNING}This script is running on a MIPS system, so we expect it to be run as root"
fi
}
check_klipper() {
if [ "$NOSERVICE" -ne 1 ]; then
if [ "$IS_MIPS" -ne 1 ]; then
if [ "$(systemctl list-units --full -all -t service --no-legend | grep -F "${KLIPPER_SERVICE}")" ]; then
echo -e "${DIM}Klipper ${KLIPPER_SERVICE} systemd service found"
else
echo -e "${ERROR}Klipper ${KLIPPER_SERVICE} systemd service not found! Please install Klipper first"
exit -1
fi
else
# There is no systemd on MIPS, we can only check the running processes
running_klipper_pid=$(ps -o pid,comm,args | grep [^]]/klipper/klippy/klippy.py | awk '{print $1}')
KLIPPER_PID_FILE=/var/run/klippy.pid
if [ $(cat $KLIPPER_PID_FILE) = $running_klipper_pid ]; then
echo -e "${DIM}Klipper service found"
else
echo -e "${ERROR}Klipper service not found! Please install Klipper first"
exit -1
fi
fi
fi
}
check_octoprint() {
if [ "$IS_MIPS" -eq 1 ]; then
OCTOPRINT=0 # Octoprint can not be set up on MIPS
elif [ "$NOSERVICE" -ne 1 ]; then
if [ "$(sudo systemctl list-units --full -all -t service --no-legend | grep -F "octoprint.service")" ]; then
echo -e "${DIM}OctoPrint service found"
OCTOPRINT=1
else
OCTOPRINT=0
fi
fi
}
verify_home_dirs() {
if [ ! -d "${KLIPPER_HOME}" ]; then
echo -e "${ERROR}Klipper home directory (${KLIPPER_HOME}) not found. Use '-k <dir>' option to override"
exit -1
fi
if [ ! -d "${KLIPPER_CONFIG_HOME}" ]; then
if [ ! -d "${OLD_KLIPPER_CONFIG_HOME}" ]; then
if [ ! -f "${OCTOPRINT_KLIPPER_CONFIG_HOME}/${PRINTER_CONFIG}" ]; then
echo -e "${ERROR}Klipper config directory (${KLIPPER_CONFIG_HOME} or ${OLD_KLIPPER_CONFIG_HOME}) not found. Use '-c <dir>' option to override"
exit -1
fi
KLIPPER_CONFIG_HOME="${OCTOPRINT_KLIPPER_CONFIG_HOME}"
else
KLIPPER_CONFIG_HOME="${OLD_KLIPPER_CONFIG_HOME}"
fi
fi
echo -e "${DIM}Klipper config directory (${KLIPPER_CONFIG_HOME}) found"
if [ ! -d "${MOONRAKER_HOME}" ]; then
if [ "${OCTOPRINT}" -eq 0 ]; then
echo -e "${ERROR}Moonraker home directory (${MOONRAKER_HOME}) not found. Use '-m <dir>' option to override"
exit -1
fi
echo -e "${WARNING}Moonraker home directory (${MOONRAKER_HOME}) not found. OctoPrint detected, skipping."
fi
}
# Silently cleanup any potentially old klippy modules
cleanup_old_klippy_modules() {
if [ -d "${KLIPPER_HOME}/klippy/extras" ]; then
for file in mmu.py mmu_toolhead.py mmu_config_setup.py; do
rm -f "${KLIPPER_HOME}/klippy/extras/${file}"
done
fi
}
link_mmu_plugins() {
echo -e "${INFO}Linking mmu extensions to Klipper..."
if [ -d "${KLIPPER_HOME}/klippy/extras" ]; then
mkdir -p "${KLIPPER_HOME}/klippy/extras/mmu"
for dir in extras extras/mmu; do
for file in ${SRCDIR}/${dir}/*.py; do
ln -sf "$file" "${KLIPPER_HOME}/klippy/${dir}/$(basename "$file")"
done
done
else
echo -e "${WARNING}Klipper extensions not installed because Klipper 'extras' directory not found!"
fi
echo -e "${INFO}Linking mmu extension to Moonraker..."
if [ -d "${MOONRAKER_HOME}/moonraker/components" ]; then
for file in `cd ${SRCDIR}/components ; ls *.py`; do
ln -sf "${SRCDIR}/components/${file}" "${MOONRAKER_HOME}/moonraker/components/${file}"
done
else
echo -e "${WARNING}Moonraker extensions not installed because Moonraker 'components' directory not found!"
fi
}
unlink_mmu_plugins() {
echo -e "${INFO}Unlinking mmu extensions from Klipper..."
if [ -d "${KLIPPER_HOME}/klippy/extras" ]; then
for dir in extras extras/mmu; do
for file in ${SRCDIR}/${dir}/*.py; do
rm -f "${KLIPPER_HOME}/klippy/${dir}/$(basename "$file")"
done
done
rm -rf "${KLIPPER_HOME}/klippy/extras/mmu"
else
echo -e "${WARNING}MMU modules not uninstalled because Klipper 'extras' directory not found!"
fi
echo -e "${INFO}Unlinking mmu extension from Moonraker..."
if [ -d "${MOONRAKER_HOME}/moonraker/components" ]; then
for file in `cd ${SRCDIR}/components ; ls *.py`; do
rm -f "${MOONRAKER_HOME}/moonraker/components/${file}"
done
else
echo -e "${WARNING}MMU modules not uninstalled because Moonraker 'components' directory not found!"
fi
}
# Parse file config settings into memory
parse_file() {
file="$1"
prefix_filter="$2"
namespace="$3"
checkdup="$4"
checkdup=""
if [ ! -f "${file}" ]; then
return
fi
# Read old config files
while IFS= read -r line
do
# Remove leading spaces, comments and config sections
line="${line#"${line%%[![:space:]]*}"}"
line="${line%%#*}"
line="${line%%[*}"
line="${line%%;*}"
# Check if line is not empty and contains variable or parameter
if [ ! -z "$line" ] && { [ -z "$prefix_filter" ] || [[ "$line" =~ ^($prefix_filter) ]]; }; then
# Split the line into parameter and value
IFS=":=" read -r parameter value <<< "$line"
# Remove leading and trailing whitespace
parameter=$(echo "$parameter" | xargs)
# Need to be more careful with value because it can be quoted
value=$(echo "$value" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
# If parameter is one of interest and it has a value remember it
if echo "$parameter" | grep -E -q "${prefix_filter}"; then
if [ "${value}" != "" ]; then
combined="${namespace}${parameter}"
if [ -n "${checkdup}" ] && [ ! -z "${!combined+x}" ]; then
echo -e "${ERROR}${parameter} defined multiple times!"
fi
if echo "$value" | grep -q '^{.*}$'; then
eval "${combined}=\$${value}"
elif [ "${value%"${value#?}"}" = "'" ]; then
eval "${combined}=\'${value}\'"
else
eval "${combined}='${value}'"
fi
fi
fi
fi
done < "${file}"
}
# Copy config file substituting in memory values from past config or initial interview
update_copy_file() {
src="$1"
dest="$2"
prefix_filter="$3"
namespace="$4"
# Read the file line by line
while IFS="" read -r line || [ -n "$line" ]
do
if echo "$line" | grep -E -q '^[[:space:]]*#'; then
# Just copy simple comments
echo "$line"
elif [ ! -z "$line" ] && { [ -z "$prefix_filter" ] || [[ "$line" =~ ^($prefix_filter) ]]; }; then
# Line of interest
# Split the line into the part before # and the part after #
parameterAndValueAndSpace=$(echo "$line" | sed 's/^[[:space:]]*//' | sed 's/;/# /' | cut -d'#' -f1)
comment=""
if echo "$line" | grep -q "#"; then
commentChar="#"
comment=$(echo "$line" | sed 's/[^#]*#//')
elif echo "$line" | grep -q ";"; then
commentChar=";"
comment=$(echo "$line" | sed 's/[^;]*;//')
fi
space=`printf "%s" "$parameterAndValueAndSpace" | sed 's/.*[^[:space:]]\(.*\)$/\1/'`
if echo "$parameterAndValueAndSpace" | grep -E -q "${prefix_filter}"; then
# If parameter and value exist, substitute the value with the in memory variable of the same name
if echo "$parameterAndValueAndSpace" | grep -E -q '^\['; then
echo "$line"
elif [ -n "$parameterAndValueAndSpace" ]; then
parameter=$(echo "$parameterAndValueAndSpace" | cut -d':' -f1)
value=$(echo "$parameterAndValueAndSpace" | cut -d':' -f2)
if [ -n "${namespace}${parameter}" ]; then
# If 'parameter' is set and not empty, evaluate its value
new_value=$(eval echo "\$${namespace}${parameter}")
if [ -n "${namespace}" ]; then
# Namespaced, use once
eval unset ${namespace}${parameter}
fi
elif [ -n "${parameter}" ]; then
# Try non-namespaced name, multi-use
new_value=$(eval echo "\$${parameter}")
else
# If 'parameter' is unset or empty leave as token
new_value="{$parameter}"
fi
if [ -z "$new_value" ]; then
new_value="''"
fi
if [ -n "$comment" ]; then
echo "${parameter}: ${new_value}${space}${commentChar}${comment}"
else
echo "${parameter}: ${new_value}"
fi
else
echo "$line"
fi
else
echo "$line"
fi
else
# Just copy simple comments
echo "$line"
fi
done < "$src" >"$dest"
}
# Get MMU type info first
read_previous_mmu_type() {
HAS_SELECTOR="yes"
dest_cfg="${KLIPPER_CONFIG_HOME}/mmu/base/mmu_hardware.cfg"
if [ -f "${dest_cfg}" ]; then
if ! grep -q "^\[stepper_mmu_selector\]" "${dest_cfg}"; then
HAS_SELECTOR="no"
fi
fi
HAS_SERVO="yes"
dest_cfg="${KLIPPER_CONFIG_HOME}/mmu/base/mmu_hardware.cfg"
if [ -f "${dest_cfg}" ]; then
if ! grep -q "^\[mmu_servo selector_servo\]" "${dest_cfg}" && ! grep -q "^\[mmu_servo mmu_servo\]" "${dest_cfg}"; then
HAS_SERVO="no"
fi
fi
}
# Set default parameters from the distribution (reference) config files
read_default_config() {
echo -e "${INFO}Reading default configuration parameters..."
if [ "$HAS_SELECTOR" == "no" ]; then
# Virtual Selector
parse_file "${SRCDIR}/config/base/mmu_parameters.cfg.vs" "" "_param_" "checkdup"
else
parse_file "${SRCDIR}/config/base/mmu_parameters.cfg" "" "_param_" "checkdup"
fi
parse_file "${SRCDIR}/config/base/mmu_macro_vars.cfg" "variable_|filename" "" "checkdup"
for file in `cd ${SRCDIR}/config/addons ; ls *.cfg | grep -v "_hw" | grep -v "my_"`; do
parse_file "${SRCDIR}/config/addons/${file}" "variable_" "" "checkdup"
done
}
# Pull parameters from previous installation
read_previous_config() {
# Get a few vital bits of information stored in mmu_hardware.cfg if available
cfg="mmu_hardware.cfg"
dest_cfg=${KLIPPER_CONFIG_HOME}/mmu/base/${cfg}
if [ -f "${dest_cfg}" ]; then
_hw_num_gates=$(sed -n 's/^[[:space:]]*num_gates:[[:space:]]*\([0-9]\{1,\}\)[[:space:]]*.*$/\1/p' "${dest_cfg}")
fi
cfg="mmu_parameters.cfg"
dest_cfg=${KLIPPER_CONFIG_HOME}/mmu/base/${cfg}
if [ -f "${dest_cfg}" -a "$_hw_num_gates" == "" ]; then
_hw_num_gates=$(sed -n 's/^[[:space:]]*mmu_num_gates[:=][[:space:]]*\([0-9]\{1,\}\)[[:space:]]*.*$/\1/p' "${dest_cfg}")
fi
if [ ! -f "${dest_cfg}" ]; then
echo -e "${WARNING}No previous ${cfg} found. Will install default"
else
echo -e "${INFO}Reading ${cfg} configuration from previous installation..."
parse_file "${dest_cfg}" "" "_param_"
fi
for cfg in mmu_macro_vars.cfg; do
dest_cfg=${KLIPPER_CONFIG_HOME}/mmu/base/${cfg}
if [ ! -f "${dest_cfg}" ]; then
echo -e "${WARNING}No previous ${cfg} found. Will install default"
else
echo -e "${INFO}Reading ${cfg} configuration from previous installation..."
if [ "${cfg}" == "mmu_macro_vars.cfg" ]; then
parse_file "${dest_cfg}" "variable_|filename"
else
parse_file "${dest_cfg}" "variable_"
fi
fi
done
# TODO namespace config in third-party addons separately
if [ -d "${KLIPPER_CONFIG_HOME}/mmu/addons" ]; then
for cfg in `cd ${KLIPPER_CONFIG_HOME}/mmu/addons ; ls *.cfg | grep -v "_hw"`; do
dest_cfg=${KLIPPER_CONFIG_HOME}/mmu/addons/${cfg}
if [ ! -f "${dest_cfg}" ]; then
echo -e "${WARNING}No previous ${cfg} found. Will install default"
else
echo -e "${INFO}Reading ${cfg} configuration from previous installation..."
parse_file "${dest_cfg}" "variable_"
fi
done
fi
# Upgrade / map / force old parameters...
# v2.7.1
if [ ! "${variable_pin_park_x_dist}" == "" ]; then
variable_pin_park_dist="${variable_pin_park_x_dist}"
fi
if [ ! "${variable_pin_loc_x_compressed}" == "" ]; then
variable_pin_loc_compressed="${variable_pin_loc_x_compressed}"
fi
if [ ! "${variable_park_xy}" == "" ]; then
variable_park_toolchange="${variable_park_xy}, ${_param_z_hop_height_toolchange:-0}, 0, 2"
variable_park_error="${variable_park_xy}, ${_param_z_hop_height_error:-0}, 0, 2"
fi
if [ ! "${variable_lift_speed}" == "" ]; then
variable_park_lift_speed="${variable_lift_speed}"
fi
if [ "${variable_enable_park}" == "False" ]; then
variable_enable_park_printing="'pause,cancel'"
if [ "${variable_enable_park_runout}" == "True" ]; then
variable_enable_park_printing="'toolchange,load,unload,runout,pause,cancel'"
fi
else
variable_enable_park_printing="'toolchange,load,unload,pause,cancel'"
fi
if [ "${variable_enable_park_standalone}" == "False" ]; then
variable_enable_park_standalone="'pause,cancel'"
else
variable_enable_park_standalone="'toolchange,load,unload,pause,cancel'"
fi
# v2.7.2
if [ "${_param_toolhead_residual_filament}" == "0" -a ! "${_param_toolhead_ooze_reduction}" == "0" ]; then
_param_toolhead_residual_filament=$_param_toolhead_ooze_reduction
_param_toolhead_ooze_reduction=0
fi
# v2.7.3 - Blobifer update - Oct 13th 20204
if [ ! "${variable_iteration_z_raise}" == "" ]; then
echo -e "${INFO}Setting Blobifier variable_z_raise and variable_purge_length_maximum from previous settings"
variable_z_raise=$(awk -v iter_z_raise="$variable_iteration_z_raise" -v max_iter="$variable_max_iterations_per_blob" -v z_change="$variable_iteration_z_change" 'BEGIN {
triangular_value = (max_iter - 1) * max_iter / 2;
print iter_z_raise * max_iter - triangular_value * z_change;
}')
variable_purge_length_maximum=$(awk -v max_len="$variable_max_iteration_length" -v max_iter="$variable_max_iterations_per_blob" 'BEGIN { print max_len * max_iter }')
fi
# v3.0.0
if [ "${_param_auto_calibrate_gates}" != "" ]; then
_param_autotune_rotation_distance=${_param_auto_calibrate_gates}
fi
if [ "${_param_auto_calibrate_bowden}" != "" ]; then
_param_autotune_bowden_length=${_param_auto_calibrate_bowden}
fi
if [ "${_param_endless_spool_final_eject}" != "" ]; then
_param_gate_final_eject_distance=${_param_endless_spool_final_eject}
fi
if [ "${_variable_eject_tool}" != "" ]; then
_variable_unload_tool=${_variable_eject_tool}
fi
if [ "${_variable_eject_tool_on_cancel}" != "" ]; then
_variable_unload_tool_on_cancel=${_variable_eject_tool_on_cancel}
fi
# Temp for alpha testers..
if [ "${_param_respooler_start_macro}" != "" ]; then
_param_espooler_start_macro=${_param_respooler_start_macro}
fi
if [ "${_param_respooler_stop_macro}" != "" ]; then
_param_espooler_stop_macro=${_param_respooler_stop_macro}
fi
}
# Helper for upgrade logic
convert_to_boolean_string() {
if [ "$1" -eq 1 ] 2>/dev/null; then
echo "True"
elif [ "$1" -eq 0 ] 2>/dev/null; then
echo "False"
else
echo "$1"
fi
}
# I'd prefer not to attempt to upgrade mmu_hardware.cfg but these will ease pain
# and are relatively safe
upgrade_mmu_hardware() {
hardware_cfg="${KLIPPER_CONFIG_HOME}/mmu/base/mmu_hardware.cfg"
# v3.0.0: Upgrade mmu_servo to mmu_selector_servo
found_mmu_servo=$(grep -E -c "^\[mmu_servo mmu_servo\]" ${hardware_cfg} || true)
if [ "${found_mmu_servo}" -eq 1 ]; then
sed "s/\[mmu_servo mmu_servo\]/\[mmu_servo selector_servo\]/g" "${hardware_cfg}" > "${hardware_cfg}.tmp" && mv "${hardware_cfg}.tmp" ${hardware_cfg}
echo -e "${INFO}Updated [mmu_servo mmu_servo] in mmu_hardware.cfg..."
fi
found_mmu_machine=$(grep -E -c "^\[mmu_machine\]" ${hardware_cfg} || true)
# v3.0.0: Remove num_gates in led section
found_num_gates=$(grep -E -c "^(#?num_gates)" ${hardware_cfg} || true)
if [ "${found_num_gates}" -gt 0 -a "${found_mmu_machine}" -eq 0 ]; then
sed "/^\(#\?num_gates\)/d" "${hardware_cfg}" > "${hardware_cfg}.tmp" && mv "${hardware_cfg}.tmp" ${hardware_cfg}
echo -e "${INFO}Removed 'num_gates' from [mmu_leds] section in mmu_hardware.cfg..."
fi
# v3.0.0: Add minimal [mmu_machine] section as first section
if [ "${found_mmu_machine}" -eq 0 ]; then
# Note params will be comming from mmu_parameters
new_section=$(cat <<EOF
# MMU MACHINE / TYPE ---------------------------------------------------------------------------------------------------
# ███╗ ███╗███╗ ███╗██╗ ██╗ ███╗ ███╗ █████╗ ██████╗██╗ ██╗██╗███╗ ██╗███████╗
# ████╗ ████║████╗ ████║██║ ██║ ████╗ ████║██╔══██╗██╔════╝██║ ██║██║████╗ ██║██╔════╝
# ██╔████╔██║██╔████╔██║██║ ██║ ██╔████╔██║███████║██║ ███████║██║██╔██╗ ██║█████╗
# ██║╚██╔╝██║██║╚██╔╝██║██║ ██║ ██║╚██╔╝██║██╔══██║██║ ██╔══██║██║██║╚██╗██║██╔══╝
# ██║ ╚═╝ ██║██║ ╚═╝ ██║╚██████╔╝ ██║ ╚═╝ ██║██║ ██║╚██████╗██║ ██║██║██║ ╚████║███████╗
# ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝╚══════╝
[mmu_machine]
num_gates: ${_param_mmu_num_gates} # Number of selectable gates on MMU
mmu_vendor: ${_param_mmu_vendor} # MMU family
mmu_version: ${_param_mmu_version} # MMU hardware version number (add mod suffix documented above)
EOF
)
temp_file=$(mktemp)
echo "$new_section" > "$temp_file"
awk '
BEGIN { found = 0 }
/^[[:space:]]*$/ && !found {
print
while ((getline line < "'"$temp_file"'") > 0) print line
close("'"$temp_file"'")
found = 1
next
}
{ print }
' "${hardware_cfg}" > "${hardware_cfg}.tmp" && mv "${hardware_cfg}.tmp" "${hardware_cfg}"
rm "$temp_file"
echo -e "${INFO}Added new [mmu_machine] section to mmu_hardware.cfg..."
fi
}
copy_config_files() {
mmu_dir="${KLIPPER_CONFIG_HOME}/mmu"
next_mmu_dir="$(nextfilename "${mmu_dir}")"
echo -e "${INFO}Copying configuration files into ${mmu_dir} directory..."
if [ ! -d "${mmu_dir}" ]; then
mkdir ${mmu_dir}
mkdir ${mmu_dir}/base
mkdir ${mmu_dir}/optional
mkdir ${mmu_dir}/addons
else
echo -e "${DETAIL}Config directory ${mmu_dir} already exists"
echo -e "${DETAIL}Backing up old config files to ${next_mmu_dir}"
mkdir ${next_mmu_dir}
(cd "${mmu_dir}"; cp -r * "${next_mmu_dir}")
# Ensure all new directories exist
mkdir -p ${mmu_dir}/base
mkdir -p ${mmu_dir}/optional
mkdir -p ${mmu_dir}/addons
fi
_hw_additional_pins=
if [ ${ADDONS_DC_ESPOOLER} -eq 1 ]; then
for i in $(seq 0 $(expr $_hw_num_gates - 1)); do
espooler_pins=" MMU_DC_MOT_$(expr $i + 1)_EN={spooler_en_${i}_pin},\n"
espooler_pins="${espooler_pins} MMU_DC_MOT_$(expr $i + 1)_A={spooler_rwd_${i}_pin},\n"
espooler_pins="${espooler_pins} MMU_DC_MOT_$(expr $i + 1)_B={spooler_fwd_${i}_pin},\n"
_hw_additional_pins="${_hw_additional_pins}\n${espooler_pins}"
done
fi
# Now substitute tokens using given brd_type and "questionaire" starting values
_hw_num_leds=$(expr $_hw_num_gates \* 2 + 1)
_hw_num_leds_minus1=$(expr $_hw_num_leds - 1)
_hw_num_gates_plus1=$(expr $_hw_num_gates + 1)
# Find all variables that start with _hw_
for var in $(compgen -v | grep '^_hw_'); do
value=${!var}
pattern="{${var#_hw_}}"
sed_expr="${sed_expr}s|${pattern}|${value}|g; "
done
# Find all variables in the form of PIN[$_hw_brd_type,*]
if [ "$HAS_SELECTOR" == "yes" ]; then
key_match="$_hw_brd_type"
else
# Type-B MMU has alternative pin allocation
key_match="B,$_hw_brd_type"
fi
for key in "${!PIN[@]}"; do
if [[ $key == "$key_match"* ]]; then
value="${PIN[$key]}"
pin_var=$(echo "$key" | sed "s/^$key_match,//")
pattern="{${pin_var}}"
sed_expr="${sed_expr}s|${pattern}|${value}|g; "
fi
done
for file in `cd ${SRCDIR}/config/base ; ls *.cfg`; do
src=${SRCDIR}/config/base/${file}
dest=${mmu_dir}/base/${file}
next_dest=${next_mmu_dir}/base/${file}
if [ -f "${dest}" ]; then
if [ "${file}" == "mmu_hardware.cfg" -a "${INSTALL}" -eq 0 ] || [ "${file}" == "mmu.cfg" -a "${INSTALL}" -eq 0 ]; then
echo -e "${WARNING}Skipping copy of hardware config file ${file} because already exists"
continue
else
if [ "${file}" == "mmu_parameters.cfg" ] || [ "${file}" == "mmu_macro_vars.cfg" ]; then
echo -e "${INFO}Upgrading configuration file ${file}"
else
echo -e "${INFO}Installing configuration file ${file}"
fi
mv ${dest} ${next_dest} # Backup old config file
fi
fi
# Hardware files: Special token substitution -----------------------------------------
if [ "${file}" == "mmu.cfg" -o "${file}" == "mmu_hardware.cfg" ]; then
cp ${src} ${dest}
# Correct shared uart_address for EASY-BRD
if [ "${_hw_brd_type}" == "EASY-BRD" ]; then
# Share uart_pin to avoid duplicate alias problem
cat ${dest} | sed -e "\
s/^uart_pin: mmu:MMU_SEL_UART/uart_pin: mmu:MMU_GEAR_UART/; \
" > ${dest}.tmp && mv ${dest}.tmp ${dest}
else
# Remove uart_address lines
cat ${dest} | sed -e "\
/^uart_address:/ d; \
" > ${dest}.tmp && mv ${dest}.tmp ${dest}
fi
if [ "${SETUP_SELECTOR_TOUCH}" == "yes" ]; then
cat ${dest} | sed -e "\
s/^#\(diag_pin: \^mmu:MMU_SEL_DIAG\)/\1/; \
s/^#\(driver_SGTHRS: 75\)/\1/; \
s/^#\(extra_endstop_pins: tmc2209_stepper_mmu_selector:virtual_endstop\)/\1/; \
s/^#\(extra_endstop_names: mmu_sel_touch\)/\1/; \
s/^uart_address:/${uart_comment}uart_address:/; \
" > ${dest}.tmp && mv ${dest}.tmp ${dest}
elif [ "${SETUP_SELECTOR_STALLGUARD_HOMING}" == "yes" ]; then
cat ${dest} | sed -e "\
s/^#\(diag_pin: \^mmu:MMU_SEL_DIAG\)/\1/; \
s/^#\(driver_SGTHRS: 75\)/\1/; \
s/^endstop_pin: ^mmu:MMU_SEL_ENDSTOP.*$/endstop_pin: tmc2209_stepper_mmu_selector:virtual_endstop/; \
s/^#\(homing_retract_dist\)/\1/; \
" > ${dest}.tmp && mv ${dest}.tmp ${dest}
fi
# Do all the token substitution
cat ${dest} | sed -e "$sed_expr" "${dest}" > "${dest}.tmp" > ${dest}.tmp && mv ${dest}.tmp ${dest}
# Handle LED option - Comment out if disabled (section is last, go comment to end of file)
if [ "${file}" == "mmu_hardware.cfg" -a "$SETUP_LED" == "no" ]; then
sed "/^# MMU OPTIONAL NEOPIXEL/,$ {/^[^#]/ s/^/#/}" ${dest} > ${dest}.tmp && mv ${dest}.tmp ${dest}
fi
# Handle Encoder option - Delete if not required (section is 25 lines long)
if [ "${file}" == "mmu_hardware.cfg" -a "$HAS_ENCODER" == "no" ]; then
sed "/^# ENCODER/,+24 d" ${dest} > ${dest}.tmp && mv ${dest}.tmp ${dest}
fi
# Handle Selector options - Delete if not required (sections are 8 and 38 lines respectively)
if [ "${file}" == "mmu_hardware.cfg" ]; then
if [ "$HAS_SELECTOR" == "no" ]; then
sed "/^# SELECTOR SERVO/,+7 d" ${dest} > ${dest}.tmp && mv ${dest}.tmp ${dest}
sed "/^# SELECTOR STEPPER/,+37 d" ${dest} > ${dest}.tmp && mv ${dest}.tmp ${dest}
# Expand out the additional filament drive for each gate
additional_gear_section=$(sed -n "/^# ADDITIONAL FILAMENT DRIVE/,+10 p" ${dest} | sed "1,3d")
awk '{ print } /^# ADDITIONAL FILAMENT DRIVE/ { for (i=1; i<=11; i++) { getline; print }; exit }' ${dest} > ${dest}.tmp
for (( i=2; i<=$(expr $_hw_num_gates - 1); i++ ))
do
echo "$(echo "${additional_gear_section}" | sed "s/_1/_$i/g")" >> ${dest}.tmp
echo >> ${dest}.tmp
done
awk '/^# ADDITIONAL FILAMENT DRIVE/ {flag=1; count=0} flag && count++ >= 12 {print}' ${dest} >> ${dest}.tmp && mv ${dest}.tmp ${dest}
else
if [ "$HAS_SERVO" == "no" ]; then
sed "/^# SELECTOR SERVO/,+7 d" ${dest} > ${dest}.tmp && mv ${dest}.tmp ${dest}
fi
# Delete additional gear drivers template section
sed "/^# ADDITIONAL FILAMENT DRIVE/,+10 d" ${dest} > ${dest}.tmp && mv ${dest}.tmp ${dest}
fi
fi
# Configuration parameters -----------------------------------------------------------
elif [ "${file}" == "mmu_parameters.cfg" ]; then
if [ "${HAS_SELECTOR}" == "no" ]; then
# Use truncated VirtualSelector parameter file
update_copy_file "${src}.vs" "$dest" "" "_param_"
else
update_copy_file "$src" "$dest" "" "_param_"
if [ "$HAS_SERVO" == "no" ]; then
# Remove selector servo section
sed "/^# Servo configuration/,+27 d" ${dest} > ${dest}.tmp && mv ${dest}.tmp ${dest}
fi
fi
# Ensure that supplemental user added params are retained. These are those that are
# by default set internally in Happy Hare based on vendor and version settings but
# can be overridden. This set also includes a couple of hidden test parameters.
echo "" >> $dest
echo "# SUPPLEMENTAL USER CONFIG retained after upgrade --------------------------------------------------------------------" >> $dest
echo "#" >> $dest
supplemental_params="cad_gate0_pos cad_gate_width cad_bypass_offset cad_last_gate_offset cad_block_width cad_bypass_block_width cad_bypass_block_delta cad_selector_tolerance gate_material gate_color gate_spool_id gate_status gate_filament_name gate_temperature gate_speed_override endless_spool_groups tool_to_gate_map"
hidden_params="test_random_failures test_random_failures test_disable_encoder test_force_in_print serious"
for var in $(set | grep '^_param_' | cut -d'=' -f1 | sort); do
param=${var#_param_}
for item in ${supplemental_params} ${hidden_params}; do
if [ "$item" = "$param" ]; then
value=$(eval echo "\$${var}")
echo "${param}: ${value}"
eval unset ${var}
fi
done
done >> $dest
# If any params are still left warn the user because they will be lost (should have been upgraded)
for var in $(set | grep '^_param_' | cut -d= -f1); do
param=${var#_param_}
value=$(eval echo \$$var)
echo "Parameter: '$param: $value' is deprecated and has been removed"
done
# Variables macro ---------------------------------------------------------------------
elif [ "${file}" == "mmu_macro_vars.cfg" ]; then
tx_macros=""
if [ "$_hw_num_gates" == "" -o "$_hw_num_gates" == "{num_gates}" ]; then
_hw_num_gates=12
fi
for (( i=0; i<=$(expr $_hw_num_gates - 1); i++ ))
do
tx_macros+="[gcode_macro T${i}]\n"
tx_macros+="gcode: MMU_CHANGE_TOOL TOOL=${i}\n"
done
if [ "${INSTALL}" -eq 1 ]; then
cat ${src} | sed -e "\
s%{tx_macros}%${tx_macros}%g; \
" > ${dest}
else
cat ${src} | sed -e "\
s%{tx_macros}%${tx_macros}%g; \
" > ${dest}.tmp
update_copy_file "${dest}.tmp" "${dest}" "variable_|filename" && rm ${dest}.tmp
fi
# Everything else is read-only symlink ------------------------------------------------
else
ln -sf ${src} ${dest}
fi
done
# Optional config are read-only symlinks --------------------------------------------------
for file in `cd ${SRCDIR}/config/optional ; ls *.cfg`; do
src=${SRCDIR}/config/optional/${file}
dest=${mmu_dir}/optional/${file}
ln -sf ${src} ${dest}
done
# Don't stomp on existing persisted state ------------------------------------------------
src=${SRCDIR}/config/mmu_vars.cfg
dest=${mmu_dir}/mmu_vars.cfg
if [ -f "${dest}" ]; then
echo -e "${WARNING}Skipping copy of mmu_vars.cfg file because already exists"
else
cp ${src} ${dest}
fi
# Addon config files are always copied (and updated) so they can be edited ----------------
# Skipping files with 'my_' prefix for development
for file in `cd ${SRCDIR}/config/addons ; ls *.cfg | grep -v "my_"`; do
src=${SRCDIR}/config/addons/${file}
dest=${mmu_dir}/addons/${file}
if [ -f "${dest}" ]; then
if ! echo "$file" | grep -E -q ".*_hw\.cfg.*"; then
echo -e "${INFO}Upgrading configuration file ${file}"
update_copy_file ${src} ${dest} "variable_"
else
echo -e "${WARNING}Skipping copy of ${file} file because already exists"
fi
else
echo -e "${INFO}Installing configuration file ${file}"
cp ${src} ${dest}
fi
done
}
uninstall_config_files() {
if [ -d "${KLIPPER_CONFIG_HOME}/mmu" ]; then
echo -e "${INFO}Removing MMU configuration files from ${KLIPPER_CONFIG_HOME}"
mv "${KLIPPER_CONFIG_HOME}/mmu" /tmp/mmu.uninstalled
fi
}
install_printer_includes() {
# Link in all includes if not already present
dest=${KLIPPER_CONFIG_HOME}/${PRINTER_CONFIG}
if test -f $dest; then
klippain_included=$(grep -c "\[include config/hardware/mmu.cfg\]" ${dest} || true)
if [ "${klippain_included}" -eq 1 ]; then
echo -e "${WARNING}This looks like a Klippain config installation - skipping automatic config install. Please add config includes by hand"
else
next_dest="$(nextfilename "$dest")"
echo -e "${INFO}Copying original ${PRINTER_CONFIG} file to ${next_dest}"
cp ${dest} ${next_dest}
if [ ${ADDONS_EREC} -eq 1 ]; then
i='\[include mmu/addons/mmu_erec_cutter.cfg\]'
already_included=$(grep -c "${i}" ${dest} || true)
if [ "${already_included}" -eq 0 ]; then
sed -i "1i ${i}" ${dest}
fi
fi
if [ ${ADDONS_BLOBIFIER} -eq 1 ]; then
i='\[include mmu/addons/blobifier.cfg\]'
already_included=$(grep -c "${i}" ${dest} || true)
if [ "${already_included}" -eq 0 ]; then
sed -i "1i ${i}" ${dest}
fi
fi
if [ ${ADDONS_DC_ESPOOLER} -eq 1 ]; then
i='\[include mmu/addons/dc_espooler.cfg\]'
already_included=$(grep -c "${i}" ${dest} || true)
if [ "${already_included}" -eq 0 ]; then
sed -i "1i ${i}" ${dest}
fi
fi
if [ ${MENU_12864} -eq 1 ]; then
i='\[include mmu/optional/mmu_menu.cfg\]'
already_included=$(grep -c "${i}" ${dest} || true)
if [ "${already_included}" -eq 0 ]; then
sed -i "1i ${i}" ${dest}
fi
fi
if [ ${CLIENT_MACROS} -eq 1 ]; then
i='\[include mmu/optional/client_macros.cfg\]'
already_included=$(grep -c "${i}" ${dest} || true)
if [ "${already_included}" -eq 0 ]; then
sed -i "1i ${i}" ${dest}
fi
fi
for i in '\[include mmu/base/\*.cfg\]' ; do
already_included=$(grep -c "${i}" ${dest} || true)
if [ "${already_included}" -eq 0 ]; then
sed -i "1i ${i}" ${dest}
fi
done
fi
else
echo -e "${WARNING}File ${PRINTER_CONFIG} file not found! Cannot include MMU configuration files"
fi
}
uninstall_printer_includes() {
echo -e "${INFO}Cleaning MMU references from ${PRINTER_CONFIG}"
dest=${KLIPPER_CONFIG_HOME}/${PRINTER_CONFIG}
if test -f $dest; then
next_dest="$(nextfilename "$dest")"