denkyem / home-assistant-moonraker

Integration between Moonraker and Home Assistant
121 stars 20 forks source link

Nested Files #12

Open jeffeb3 opened 1 year ago

jeffeb3 commented 1 year ago

Thank you so much for collecting this info together.

I usually use a folder structure for my gcode files. For whatever reason, the files and thumbnails get stacked like this:

.
├── desk
│   ├── 2020 foot_0.2mm_PLA_MK3S_58m.gcode
│   ├── 2020 hand_0.2mm_PLA_MK3S_31m.gcode
│   └── .thumbs
│       ├── 2020 foot_0.2mm_PLA_MK3S_58m-32x32.png
│       ├── 2020 foot_0.2mm_PLA_MK3S_58m-400x300.png
│       ├── 2020 hand_0.2mm_PLA_MK3S_31m-32x32.png
│       └── 2020 hand_0.2mm_PLA_MK3S_31m-400x300.png
├── games
│   ├── Game_tray_thick_tapered_0.2mm_PLA_MK3S_1h22m.gcode
│   └── .thumbs
│       ├── Game_tray_thick_tapered_0.2mm_PLA_MK3S_1h22m-32x32.png
│       └── Game_tray_thick_tapered_0.2mm_PLA_MK3S_1h22m-400x300.png

That causes 3d_printer_object_thumbnails to not be relative to the top level server file. It ends up as .thumbs/Game_tray_thick_tapered_0.2mm_PLA_MK3S_1h22m-400x300.png. It should be games/.thumbs/Game_tray_thick_tapered_0.2mm_PLA_MK3S_1h22m-400x300.png.

That breaks the 3D Printer Thumbnail.

The solution I found, which I think works for nested and unnested files, is to find the path from start until the last '/' in the filename, and prepend that to the 3d_printer_object_thumbnails:

state: '{{ states(("sensor.3d_printer_current_print"))[0:states(("sensor.3d_printer_current_print")).rfind("/")+1]}}{{ states.sensor.3d_printer_file_metadata.attributes["thumbnails"][1]["relative_path"] }}'

It is easier to read in a multiline template, which I used in the templates section of the developer tools:

{% set path = "foobar/games.gcode" %}
{{ path[0:path.rfind('/')+1] }}

The +1 on the slice is a little tricky/clever/unintuitive. On a path with a slash, that ends up catching the slash as well. On a path without any slash, the rfind returns -1. A slice of path[0:-1] is an empty string. So the result is either concatenating nothing, or concatenating the folders and the following slash.