1{
2 lib,
3 writeShellApplication,
4 klipper,
5 klipper-firmware,
6 avrdude,
7 dfu-util,
8 stm32flash,
9 mcu ? "mcu",
10 flashDevice ? "/dev/null",
11 firmwareConfig ? ./simulator.cfg,
12}:
13let
14 getConfigField =
15 field:
16 with builtins;
17 let
18 matches = match ''^.*${field}="([a-zA-Z0-9_]+)".*$'' (readFile firmwareConfig);
19 in
20 if matches != null then head matches else null;
21 matchPlatform = getConfigField "CONFIG_BOARD_DIRECTORY";
22 matchBoard = getConfigField "CONFIG_MCU";
23in
24writeShellApplication {
25 name = "klipper-flash-${mcu}";
26 runtimeInputs =
27 [ ]
28 ++ lib.optionals (matchPlatform == "avr") [ avrdude ]
29 ++ lib.optionals (matchPlatform == "stm32") [
30 stm32flash
31 dfu-util
32 ]
33 ++ lib.optionals (matchPlatform == "lpc176x") [ dfu-util ]
34 # bossac, hid-flash and RP2040 flash binaries are built by klipper-firmware
35 ;
36 text =
37 # generic USB script for most things with serial and bootloader (see MCU_TYPES in scripts/flash_usb.py)
38 if matchBoard != null && matchPlatform != null then
39 ''
40 pushd ${klipper-firmware}
41 ${klipper}/lib/scripts/flash_usb.py -t ${matchBoard} -d ${flashDevice} ${klipper-firmware}/klipper.bin $@
42 popd
43 ''
44 else
45 ''
46 cat <<EOF
47 Board pair ${toString matchBoard}/${toString matchPlatform} (config ${firmwareConfig}) is not supported in NixOS auto flashing script.
48 Please manually flash the firmware using the appropriate tool for your board.
49 Built firmware is located here:
50 ${klipper-firmware}
51 EOF
52 '';
53}