Files
OrcaSlicer/tests/slic3rutils/test_network_discovery.cpp
HanifKoh dda4a89315 Discover Printers on Every Printer Agent and List Them All in the Printer Picker (#17970)
* Discover Printers on Every Printer Agent at Once

Every printer agent that scans the LAN now discovers in the background, not
only the live one, and each device is recorded under the agent that found it.
A discovery no longer takes over a device another agent owns. The
disabled_discovery_agents setting turns an agent's scan off.

* List Every Printer Agent's Printers in the Printer Picker, Greying Out the Ones the Preset Cannot Use

The picker now lists the printers of every agent under My Device and Other Device, the live agent's first and the others grouped in registration order, without headings. Printers of other agents are greyed out, ignore hover and clicks, and tell the user to select a preset to use them.

* Turn Each Printer Agent's Network Discovery On or Off in Preferences

The Online tab gets a Printer discovery section with a "Find <agent> printers" checkbox for each printer agent that scans the LAN: the Orca agent, the Bambu Lab agent while its network plug-in is loaded, and any agent already created that scans, such as a Python agent once it is in use. Unticking one adds its id to disabled_discovery_agents and restarts discovery at once; the printer list still searches with the live agent while it is open. The setting is also in the preference table, so preferences_get lists it and preferences_set writes it as text.

* Discover on Every Registered Printer Agent From Startup

A printer agent that scans now discovers from startup without a preset having selected it. Discovery used to consider only the agents registered with a scans_on_lan flag (Orca and Bambu Lab) plus the ones already created, so a Python agent that returned True from discovers_on_lan(), or a C++ agent registered without the flag, found nothing until it had been selected once. Every registered agent is now a candidate and discovers_on_lan() alone decides, so the flag is gone and cannot disagree with it. Creating the candidates is cheap: the built-in constructors only store their arguments, and a Python agent's factory returns the capability its plugin already loaded.

* Stop a Python Printer Agent From Calling Into Its Plugin Once It Starts to Unload

When a plugin is unloaded off the UI thread, as a plugin update does, its unload callbacks are deferred to the UI thread while its module is released at once, so the deferred deregistration and any discovery refresh in between could still call the printer agent. A capability is now marked as unloading before its module is released, and every Python printer-agent call made after the mark answers as if no agent were set instead of reaching the plugin. A call takes its reference before checking the mark, so the unload's drain waits for any call that got past it.

* Disconnect Only the Printer Agents That Were Selected

Discovery now creates every registered agent, so the agent cache holds agents that never connected. At shutdown and when a Python plugin is reloaded or unloaded, the cache disconnects only the agents that create_printer_agent_by_id() handed out to be selected, so a plugin is not asked to disconnect a printer it never connected to.

* Disconnect a Re-Registered Python Agent's Old Selected Agent and Find the Live Agent by Its Stored Id

When a Python printer agent registers again under a new id, the agent cached under its old id is taken out through the same helper as the new one, so its "selected" mark goes with it and both are disconnected if they were ever selected; before, the old one could be dropped without a disconnect and its mark could pass to a later agent under that id. Deregistration now finds the live agent by the id NetworkAgent stored when the agent went live, since an unloading agent no longer reports its own. The lifecycle test plugin now answers discovers_on_lan and disconnect_printer, so all three calls after the unload show the guard at work.

* Create Every Printer Agent When Networking Starts Instead of When Discovery Asks

get_discovery_candidates() created any registered agent that was not cached yet, so creating agents was a side effect of asking for the list. The built-in agents are now created by NetworkAgentFactory::create_printer_agents() when on_init_network() builds networking, which also hands the cached agents the new cloud agents when networking is rebuilt, and a Python agent is cached when its plugin registers it. get_discovery_candidates() only reads the cache. Behaviour is the same: every registered agent exists from startup, and discovers_on_lan() decides which ones scan.
2026-11-30 16:26:29 +08:00

400 lines
13 KiB
C++

#include <catch2/catch_test_macros.hpp>
#include <algorithm>
#include <functional>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "libslic3r/AppConfig.hpp"
#include "slic3r/Utils/IPrinterAgent.hpp"
#include "slic3r/Utils/bambu_networking.hpp"
#include "slic3r/Utils/MoonrakerPrinterAgent.hpp"
#include "slic3r/Utils/NetworkAgent.hpp"
#include "slic3r/Utils/NetworkAgentFactory.hpp"
using namespace Slic3r;
namespace {
class DiscoverySource : public MoonrakerPrinterAgent
{
public:
explicit DiscoverySource(std::string id, bool scans = true)
: MoonrakerPrinterAgent(""), scans(scans), m_info{std::move(id), "Discovery source", "1.0", "test agent"}
{
}
AgentInfo get_agent_info() override { return m_info; }
bool discovers_on_lan() const override { return scans; }
bool start_discovery(bool start, bool) override
{
discovering = start;
++(start ? starts : stops);
return true;
}
int set_on_ssdp_msg_fn(OnMsgArrivedFn fn) override
{
discovery_callback = std::move(fn);
return 0;
}
int disconnect_printer() override
{
++disconnects;
return 0;
}
bool scans;
bool discovering{false};
int starts{0};
int stops{0};
int disconnects{0};
OnMsgArrivedFn discovery_callback;
private:
AgentInfo m_info;
};
struct Rig
{
std::vector<std::function<void()>> pending;
std::vector<std::pair<std::string, std::string>> delivered; // agent id, payload
NetworkAgent network{nullptr, nullptr};
Rig()
{
network.set_queue_on_main_fn([this](std::function<void()> fn) { pending.push_back(std::move(fn)); });
network.set_on_discovery_fn(
[this](const std::string& agent_id, std::string payload) { delivered.emplace_back(agent_id, std::move(payload)); });
}
void run_pending()
{
auto queued = std::move(pending);
pending.clear();
for (auto& fn : queued)
fn();
}
};
using Agents = std::vector<std::shared_ptr<IPrinterAgent>>;
} // namespace
TEST_CASE("Every scanning agent discovers at once and reports under its own id", "[NetworkDiscovery]")
{
Rig rig;
auto a = std::make_shared<DiscoverySource>("agent-a");
auto b = std::make_shared<DiscoverySource>("agent-b");
rig.network.sync_discovery(Agents{a, b}, {});
CHECK(a->discovering);
CHECK(b->discovering);
a->discovery_callback("from-a");
b->discovery_callback("from-b");
rig.run_pending();
REQUIRE(rig.delivered.size() == 2);
CHECK(rig.delivered[0] == std::make_pair(std::string("agent-a"), std::string("from-a")));
CHECK(rig.delivered[1] == std::make_pair(std::string("agent-b"), std::string("from-b")));
}
TEST_CASE("A disabled agent does not start discovery", "[NetworkDiscovery]")
{
Rig rig;
auto a = std::make_shared<DiscoverySource>("agent-a");
auto b = std::make_shared<DiscoverySource>("agent-b");
SECTION("Not live")
{
rig.network.sync_discovery(Agents{a, b}, {"agent-b"});
}
SECTION("Live")
{
rig.network.set_printer_agent(b);
rig.network.sync_discovery(Agents{a, b}, {"agent-b"});
}
CHECK(a->discovering);
CHECK_FALSE(b->discovering);
CHECK(b->starts == 0);
CHECK_FALSE(rig.network.is_discovering("agent-b"));
}
TEST_CASE("The disabled agents setting round trips through the app config", "[NetworkDiscovery]")
{
AppConfig config;
CHECK(config.get_disabled_discovery_agents().empty());
config.set_disabled_discovery_agents({"orca", "bbl"});
CHECK(config.get_disabled_discovery_agents() == std::set<std::string>{"bbl", "orca"});
CHECK(config.get("disabled_discovery_agents") == "bbl;orca");
}
TEST_CASE("An agent that does not scan reports only while it is live", "[NetworkDiscovery]")
{
Rig rig;
auto scanner = std::make_shared<DiscoverySource>("scanner");
auto host = std::make_shared<DiscoverySource>("host-reporter", false);
rig.network.sync_discovery(Agents{scanner, host}, {});
CHECK(scanner->discovering);
CHECK_FALSE(host->discovering);
rig.network.set_printer_agent(host);
rig.network.sync_discovery(Agents{scanner, host}, {});
CHECK(host->discovering);
rig.network.set_printer_agent(scanner);
rig.network.sync_discovery(Agents{scanner, host}, {});
CHECK_FALSE(host->discovering);
CHECK(host->stops == 1);
}
TEST_CASE("An agent switch leaves the scanning agents' discovery running", "[NetworkDiscovery]")
{
Rig rig;
auto a = std::make_shared<DiscoverySource>("agent-a");
auto b = std::make_shared<DiscoverySource>("agent-b");
rig.network.set_printer_agent(a);
rig.network.sync_discovery(Agents{a, b}, {});
auto early = a->discovery_callback;
rig.network.set_printer_agent(b);
rig.network.sync_discovery(Agents{a, b}, {});
CHECK(a->discovering);
CHECK(b->discovering);
CHECK(a->starts == 1);
CHECK(a->stops == 0);
CHECK(b->starts == 1);
// The callback registered before the switch is still the live one and still delivers.
early("after-switch");
rig.run_pending();
REQUIRE(rig.delivered.size() == 1);
CHECK(rig.delivered[0].first == "agent-a");
}
TEST_CASE("Events from a torn-down agent are dropped", "[NetworkDiscovery]")
{
Rig rig;
auto a = std::make_shared<DiscoverySource>("agent-a");
auto b = std::make_shared<DiscoverySource>("agent-b");
rig.network.sync_discovery(Agents{a, b}, {});
auto outgoing = a->discovery_callback;
outgoing("queued-before");
REQUIRE(rig.pending.size() == 1);
SECTION("It leaves the discovering set")
{
rig.network.sync_discovery(Agents{b}, {});
}
SECTION("It is disabled")
{
rig.network.sync_discovery(Agents{a, b}, {"agent-a"});
}
SECTION("It stops scanning, as when the plug-in unloads")
{
a->scans = false;
rig.network.sync_discovery(Agents{a, b}, {});
}
SECTION("It is deregistered")
{
rig.network.stop_discovery("agent-a");
}
SECTION("Discovery stops everywhere")
{
rig.network.stop_all_discovery();
CHECK_FALSE(b->discovering);
}
CHECK_FALSE(a->discovering);
CHECK(a->stops == 1);
rig.run_pending();
outgoing("late");
CHECK(rig.pending.empty());
CHECK(rig.delivered.empty());
}
TEST_CASE("Clearing the listener drops queued discovery events", "[NetworkDiscovery]")
{
Rig rig;
auto a = std::make_shared<DiscoverySource>("agent-a");
rig.network.sync_discovery(Agents{a}, {});
auto callback = a->discovery_callback;
callback("queued");
REQUIRE(rig.pending.size() == 1);
rig.network.set_on_discovery_fn(nullptr);
rig.run_pending();
callback("late");
CHECK(rig.pending.empty());
CHECK(rig.delivered.empty());
}
TEST_CASE("Replacing an agent under the same id restarts discovery on the new object", "[NetworkDiscovery]")
{
Rig rig;
auto old_agent = std::make_shared<DiscoverySource>("agent-a");
rig.network.sync_discovery(Agents{old_agent}, {});
auto stale = old_agent->discovery_callback;
auto new_agent = std::make_shared<DiscoverySource>("agent-a");
rig.network.sync_discovery(Agents{new_agent}, {});
CHECK_FALSE(old_agent->discovering);
CHECK(new_agent->discovering);
CHECK(old_agent->discovery_callback == nullptr);
stale("stale");
CHECK(rig.pending.empty());
}
TEST_CASE("Discovery callbacks expire when networking is destroyed", "[NetworkDiscovery]")
{
auto source = std::make_shared<DiscoverySource>("agent-a");
std::vector<std::function<void()>> pending;
unsigned delivered = 0;
{
NetworkAgent network(nullptr, nullptr);
network.set_queue_on_main_fn([&](std::function<void()> fn) { pending.push_back(std::move(fn)); });
network.set_on_discovery_fn([&](const std::string&, std::string) { ++delivered; });
network.sync_discovery(Agents{source}, {});
source->discovery_callback("queued-device");
}
REQUIRE(pending.size() == 1);
pending.front()();
pending.clear();
source->discovery_callback("late-device");
REQUIRE(pending.empty());
REQUIRE(delivered == 0);
}
TEST_CASE("A disabled live agent discovers while a picker requests it", "[NetworkDiscovery]")
{
Rig rig;
auto live = std::make_shared<DiscoverySource>("agent-a");
rig.network.set_printer_agent(live);
rig.network.sync_discovery(Agents{live}, {"agent-a"});
REQUIRE_FALSE(live->discovering);
rig.network.set_live_discovery_requested(true);
rig.network.sync_discovery(Agents{live}, {"agent-a"});
CHECK(live->discovering);
live->discovery_callback("while-open");
rig.run_pending();
CHECK(rig.delivered.size() == 1);
rig.network.set_live_discovery_requested(false);
rig.network.sync_discovery(Agents{live}, {"agent-a"});
CHECK_FALSE(live->discovering);
CHECK_FALSE(rig.network.is_discovering("agent-a"));
}
TEST_CASE("Stopping all discovery can spare one agent", "[NetworkDiscovery]")
{
Rig rig;
auto a = std::make_shared<DiscoverySource>("agent-a");
auto b = std::make_shared<DiscoverySource>("agent-b");
rig.network.sync_discovery(Agents{a, b}, {});
rig.network.stop_all_discovery("agent-b");
CHECK_FALSE(a->discovering);
CHECK(b->discovering);
CHECK(rig.network.is_discovering("agent-b"));
}
namespace {
// Constructions per agent id: the registry outlives each test, so counts are kept per id.
std::map<std::string, int> s_constructed;
void register_counting_agent(const std::string& id, bool scans)
{
NetworkAgentFactory::register_printer_agent(
id, id, [id, scans](std::shared_ptr<ICloudServiceAgent>, const std::string&) -> std::shared_ptr<IPrinterAgent> {
++s_constructed[id];
return std::make_shared<DiscoverySource>(id, scans);
});
}
struct CacheGuard
{
~CacheGuard() { NetworkAgentFactory::clear_printer_agent_cache(); }
};
} // namespace
TEST_CASE("Every registered agent is created up front and discovers_on_lan alone decides", "[NetworkDiscovery]")
{
const CacheGuard guard;
NetworkAgentFactory::clear_printer_agent_cache();
register_counting_agent("candidate-unselected-scanner", true);
register_counting_agent("candidate-unselected-quiet", false);
s_constructed.clear();
const auto none = [](const std::string&) { return std::shared_ptr<ICloudServiceAgent>(); };
const auto find = [](const auto& agents, const std::string& id) {
return std::any_of(agents.begin(), agents.end(), [&](const auto& a) { return a->get_agent_info().id == id; });
};
// The list of candidates creates nothing: only create_printer_agents() does.
CHECK_FALSE(find(NetworkAgentFactory::get_discovery_candidates(), "candidate-unselected-scanner"));
CHECK(s_constructed["candidate-unselected-scanner"] == 0);
// Nothing selected either agent: both are created once and are candidates.
NetworkAgentFactory::create_printer_agents(none, "");
const auto candidates = NetworkAgentFactory::get_discovery_candidates();
CHECK(find(candidates, "candidate-unselected-scanner"));
CHECK(find(candidates, "candidate-unselected-quiet"));
CHECK(s_constructed["candidate-unselected-scanner"] == 1);
CHECK(s_constructed["candidate-unselected-quiet"] == 1);
// Networking rebuilt: the cached objects are kept, not created again.
NetworkAgentFactory::create_printer_agents(none, "");
CHECK(s_constructed["candidate-unselected-scanner"] == 1);
CHECK(s_constructed["candidate-unselected-quiet"] == 1);
// discovers_on_lan() alone decides: the scanner discovers, the other one does not.
NetworkAgent network(nullptr, nullptr);
network.sync_discovery(candidates, {});
CHECK(network.is_discovering("candidate-unselected-scanner"));
CHECK_FALSE(network.is_discovering("candidate-unselected-quiet"));
}
TEST_CASE("Only agents handed out for use are disconnected when the cache lets them go", "[NetworkDiscovery]")
{
const CacheGuard guard;
NetworkAgentFactory::clear_printer_agent_cache();
register_counting_agent("disconnect-discovery-only", true);
register_counting_agent("disconnect-selected", true);
const auto none = [](const std::string&) { return std::shared_ptr<ICloudServiceAgent>(); };
NetworkAgentFactory::create_printer_agents(none, "");
const auto candidates = NetworkAgentFactory::get_discovery_candidates();
const auto of = [&](const std::string& id) {
for (const auto& agent : candidates)
if (agent->get_agent_info().id == id)
return std::dynamic_pointer_cast<DiscoverySource>(agent);
return std::shared_ptr<DiscoverySource>();
};
const auto discovery_only = of("disconnect-discovery-only");
const auto selected = of("disconnect-selected");
REQUIRE(discovery_only != nullptr);
REQUIRE(selected != nullptr);
// Selecting hands out the cached object and marks it as used.
REQUIRE(NetworkAgentFactory::create_printer_agent_by_id("disconnect-selected", nullptr, "") == selected);
NetworkAgentFactory::clear_printer_agent_cache();
CHECK(discovery_only->disconnects == 0);
CHECK(selected->disconnects == 1);
}