Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ Klipper printers by a closed tester group.
- Heaters: `extruder`, `extruder1`, `heater_bed`, and a chamber as `heater_generic chamber` (settable) or
`temperature_sensor chamber` (read only) (`MoonrakerHeaters`).
- Power devices have no documented change notification, so they are read every 2 s while there are any.
- Klipper has no temperature presets. They are Mainsail's (`mainsail` / `presets`) and Fluidd's (`fluidd` /
`uiSettings.dashboard.tempPresets`) from Moonraker's database, read with the settings (`MoonrakerPresets`).

**Actions.**

Expand Down
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Printer Control talks to the software that runs your printer. Supported today:
| Printer software | Notes |
| --- | --- |
| [OctoPrint](https://octoprint.org) | Everything below. Lights need the GPIO Control plugin. |
| [Moonraker](https://moonraker.readthedocs.io) (Klipper with Mainsail or Fluidd) | Everything below except connecting and disconnecting the printer, which Klipper does not do. Temperature presets are not read. Lights are Moonraker's power devices. *Start* and *Restart* print the last loaded file again, and *Print a file* can only start a print, not just load the file. |
| [Moonraker](https://moonraker.readthedocs.io) (Klipper with Mainsail or Fluidd) | Everything below except connecting and disconnecting the printer, which Klipper does not do. Temperature presets are the ones saved in Mainsail or Fluidd. Lights are Moonraker's power devices. *Start* and *Restart* print the last loaded file again, and *Print a file* can only start a print, not just load the file. |

The plugin is built so more printer software can be added; see
[Adding printer software](#adding-printer-software). This is an unofficial community plugin, not made or
Expand Down Expand Up @@ -64,7 +64,7 @@ Every action starts with the printer to use; with only one printer set up, leave
| Control print job | Pause or resume, pause, resume, cancel, start the selected file, restart. Waits until the printer confirms. |
| Print a file | Picks a file stored on the printer's server (or on the SD card) and starts it. |
| Set temperature | Sets the hotend, bed or chamber target. 0 turns it off. |
| Preheat | Uses one of the printer's temperature presets (PLA, PETG, ...) or cools everything down. |
| Preheat | Uses one of the printer's temperature presets (PLA, PETG, ...) or cools everything down. The presets are the ones set up in OctoPrint (Settings, Printer, Temperatures) or in Mainsail or Fluidd. A change in OctoPrint shows up right away, one in Mainsail or Fluidd when the plugin connects again. Only the hotend, bed and chamber targets are used, not a preset's own G-code. |
| Home axes | Homes X, Y and/or Z. |
| Move print head | Moves one axis by a distance. |
| Extrude or retract | Moves filament. |
Expand Down Expand Up @@ -142,8 +142,9 @@ without credentials. For OctoPrint:
For Moonraker:

- `/server/info` and `/printer/info` while you add the printer,
- Moonraker's websocket (`/websocket`) for everything else: live state, files, webcams, your commands, and
its power devices every 2 seconds while it has any.
- Moonraker's websocket (`/websocket`) for everything else: live state, files, webcams, the temperature
presets Mainsail and Fluidd keep in Moonraker's database, your commands, and its power devices every 2
seconds while it has any.

The webcam is loaded by Macro Deck itself from the webcam address and relayed to your deck devices; it
does not pass through the plugin. The API key is stored in Macro Deck's encrypted secret store. The plugin
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ private async Task RefreshSettingsAsync(MoonrakerRpc rpc, CancellationToken canc
PublishSettings(new PrinterSettings(
hostname,
await ReadWebcamAsync(rpc, cancellationToken),
[],
await MoonrakerPresets.ReadAsync(rpc, cancellationToken),
await ReadOutputsQuietlyAsync(rpc, cancellationToken)));
}

Expand Down
91 changes: 91 additions & 0 deletions src/PrinterControl/Backends/Moonraker/MoonrakerPresets.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
using System.Text.Json;
using PrinterControl.Core;

namespace PrinterControl.Backends.Moonraker;

// Klipper has no temperature presets; Mainsail and Fluidd keep their own in Moonraker's database:
// Mainsail under "mainsail" "presets.presets.<id>", Fluidd under "fluidd" "uiSettings.dashboard.tempPresets".
internal static class MoonrakerPresets
{
public static async Task<IReadOnlyList<TemperatureProfile>> ReadAsync(MoonrakerRpc rpc, CancellationToken cancellationToken)
{
var mainsail = await ReadItemAsync(rpc, "mainsail", "presets", cancellationToken);
var fluidd = await ReadItemAsync(rpc, "fluidd", "uiSettings", cancellationToken);
return Parse(mainsail, fluidd);
}

internal static IReadOnlyList<TemperatureProfile> Parse(JsonElement? mainsail, JsonElement? fluidd)
{
var presets = new List<JsonElement>();
if (mainsail?.Obj("presets") is { } byId)
{
presets.AddRange(byId.EnumerateObject()
.Select(p => p.Value)
.OrderBy(p => p.Str("name"), StringComparer.OrdinalIgnoreCase));
}

if (fluidd?.Obj("dashboard")?.Arr("tempPresets") is { } list)
{
presets.AddRange(list.EnumerateArray());
}

var profiles = new List<TemperatureProfile>();
foreach (var preset in presets)
{
if (preset.Str("name")?.Trim() is not { Length: > 0 } name
|| profiles.Any(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase))
|| ToProfile(name, preset.Obj("values")) is not { } profile)
{
continue;
}

profiles.Add(profile);
}

return profiles;
}

private static TemperatureProfile? ToProfile(string name, JsonElement? values)
{
double? extruder = null, bed = null, chamber = null;
foreach (var entry in values?.EnumerateObject() ?? default)
{
// Mainsail marks a heater the preset sets with "bool", Fluidd with "active"; Fluidd also writes -1 for unset.
var target = entry.Value;
if ((target.Bool("bool") ?? target.Bool("active")) != true
|| target.Str("type") is { } type && type != "heater"
|| target.Num("value") is not (>= 0 and var value))
{
continue;
}

switch (entry.Name)
{
case "extruder":
extruder = value;
break;
case "heater_bed":
bed = value;
break;
case "heater_generic chamber" or "chamber":
chamber = value;
break;
}
}

return extruder is null && bed is null && chamber is null ? null : new TemperatureProfile(name, extruder, bed, chamber);
}

private static async Task<JsonElement?> ReadItemAsync(MoonrakerRpc rpc, string space, string key, CancellationToken cancellationToken)
{
try
{
var item = await rpc.CallAsync("server.database.get_item", new { @namespace = space, key }, cancellationToken);
return item.Obj("value");
}
catch (PrinterException)
{
return null;
}
}
}
56 changes: 56 additions & 0 deletions tests/PrinterControl.Tests/Backends/MoonrakerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,62 @@ public async Task Temperatures_are_set_with_klippers_heater_names()
]));
}

[Test]
public async Task Temperature_presets_come_from_mainsail_and_fluidd()
{
_server.Database[("mainsail", "presets")] = new
{
presets = new Dictionary<string, object>
{
["b2"] = new { id = "b2", name = "PLA", gcode = "", values = new Dictionary<string, object>
{
["extruder"] = new { @bool = true, type = "heater", value = 210 },
["heater_bed"] = new { @bool = true, type = "heater", value = 60 },
} },
["a1"] = new { id = "a1", name = "ABS", gcode = "", values = new Dictionary<string, object>
{
["extruder"] = new { @bool = true, type = "heater", value = 245 },
["heater_bed"] = new { @bool = false, type = "heater", value = 100 },
["heater_generic chamber"] = new { @bool = true, type = "heater", value = 45 },
} },
},
cooldownGcode = "TURN_OFF_HEATERS",
};
_server.Database[("fluidd", "uiSettings")] = new
{
dashboard = new
{
tempPresets = new object[]
{
new { id = 1, name = "pla", values = new Dictionary<string, object> { ["extruder"] = new { value = 200, type = "heater", active = true } } },
new { id = 2, name = "PETG", values = new Dictionary<string, object>
{
["extruder"] = new { value = 240, type = "heater", active = true },
["heater_bed"] = new { value = -1, type = "heater", active = true },
["chamber"] = new { value = 50, type = "fan", active = true },
} },
new { id = 3, name = "Only G-code", values = new Dictionary<string, object>(), gcode = "M117 hi" },
},
},
};

var printer = await OnlineAsync();

Assert.That(printer.Settings.TemperatureProfiles, Is.EqualTo((TemperatureProfile[])[
new("ABS", 245, null, 45),
new("PLA", 210, 60, null),
new("PETG", 240, null, null),
]));
}

[Test]
public async Task A_printer_without_web_interface_presets_has_none()
{
var printer = await OnlineAsync();

Assert.That(printer.Settings.TemperatureProfiles, Is.Empty);
}

[Test]
public async Task A_chamber_without_a_heater_cannot_be_set()
{
Expand Down
11 changes: 11 additions & 0 deletions tests/PrinterControl.Tests/Support/FakeMoonraker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ private FakeMoonraker(WebApplication app, Uri baseUri)

public int WebcamRotation { get; set; } = 90;

// Moonraker's database by namespace and top-level key, as the web interfaces store into it.
public Dictionary<(string Namespace, string Key), object> Database { get; } = new();

public static async Task<FakeMoonraker> StartAsync()
{
FakeMoonraker? fake = null;
Expand Down Expand Up @@ -236,6 +239,7 @@ private string Answer(JsonElement request)
"server.files.list" => new[] { new { path = "benchy.gcode", modified = 1700000000.5, size = 1024, permissions = "rw" } },
"machine.device_power.devices" => new { devices = PowerDevices.Select(d => new { device = d.Key, status = d.Value, locked_while_printing = false, type = "gpio" }).ToArray() },
"machine.device_power.post_device" => SetPower(parameters),
"server.database.get_item" => DatabaseItem(parameters),
"printer.print.start" or "printer.print.pause" or "printer.print.resume" or "printer.print.cancel"
or "printer.gcode.script" or "printer.firmware_restart" or "printer.restart"
or "machine.reboot" or "machine.shutdown" or "machine.services.restart" => "ok",
Expand Down Expand Up @@ -274,6 +278,13 @@ private object Subscription()
}
}

private object? DatabaseItem(JsonElement parameters)
{
var space = parameters.GetProperty("namespace").GetString()!;
var key = parameters.GetProperty("key").GetString()!;
return Database.TryGetValue((space, key), out var value) ? new { @namespace = space, key, value } : null;
}

private Dictionary<string, string> SetPower(JsonElement parameters)
{
var device = parameters.GetProperty("device").GetString()!;
Expand Down
Loading