Refresh connections and react to changes¶
MultiConn separates port discovery from metadata loading. In a normal script,
metadata access can wait. In a GUI, use ui_mode=True and react to events as data
arrives.
What a refresh does¶
conn.refresh.all_ports() probes ports in parallel. The calling thread
waits for the probes, then applies additions, removals, and refreshed connections.
HTTP metadata fetching continues in background threads.
A refresh preserves an existing primary where possible. If there is no primary,
it chooses the lowest known open port. If no connections remain, primary becomes
None. Other refresh actions target open_ports(), closed_ports(), specific
ports with from_ports(...), or specific headers with from_headers(...).
This means UI mode does not make every method non-blocking. Call connection management methods on the application thread; allow for the short probe wait.
Deliver callbacks on the UI thread¶
Without a dispatcher, callbacks execute on the thread that publishes them. For a GUI using an asyncio event loop, this helper creates a manager with a thread-safe callback bridge:
import asyncio
from multiconn_archicad import MultiConn
def create_connections() -> MultiConn:
loop = asyncio.get_running_loop()
return MultiConn(ui_mode=True, dispatcher=loop.call_soon_threadsafe)
Call this after the GUI event loop has started. Other frameworks need their own equivalent of posting a callback onto the UI thread. The relevant programming concepts are an event loop and thread dispatching.
Subscribe to selection and metadata¶
This small state holder shows the callbacks without depending on a GUI framework:
from multiconn_archicad import MultiConn
class ProjectState:
def __init__(self, conn: MultiConn):
self.selected = None
self.cache = {}
self._stop_primary = conn.events.subscribe_primary_changed(self.on_primary)
self._stop_metadata = conn.events.subscribe_metadata_resolved(self.on_metadata)
def on_primary(self, previous, current):
self.selected = current
self.cache.clear()
def on_metadata(self, header):
if header is self.selected:
print(f"Metadata resolved for port {header.port}; check readiness before enabling work.")
def close(self):
self._stop_primary()
self._stop_metadata()
Subscriptions replay the current selection and completed metadata for managed headers. Each returns an idempotent unsubscribe function. Register subscriptions on the application thread and dispose of them when the owning view closes.
In a real shell, update the project label and run-button state in these callbacks. Do not assume metadata resolution means success: check readiness. Clear project-specific caches on selection changes and refresh. If background work finishes after the user changes projects, discard that old result rather than displaying it for the new selection.
See GUI application patterns for the relationship between connection events and long-running script work.