SimulationControl Sample
This sample demonstrates how to use the SimulationControl service to start a simulation and monitor its status using SignalR events.
import time
from restmapi.services import MAPIServices
def on_status_changed(new_status):
print(f"Received StatusChanged event: {new_status}")
# Ensure MAPIServices is initialized (usually done automatically if MAPI is running)
if MAPIServices.instance is None:
print("MAPI Services not available.")
exit(1)
# Use the 'with' statement to ensure proper resource cleanup
with MAPIServices.instance.get_service("SimulationControl") as sc:
print("Connected to SimulationControl service.")
# Initialize SignalR connection to receive events
sc.init_signalr()
# Register the callback for status changes
sc.register_status_changed_callback(on_status_changed)
simulation_name = "DC_Motor"
print(f"Starting simulation '{simulation_name}'...")
try:
# Start the simulation
sc.start_simulation(simulation_name)
# Keep the script running to listen for events
# In a real application, you might wait for a specific state (e.g., "Stopped")
print("Press Ctrl+C to stop the simulation and exit.")
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\nInterrupted by user.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
# Attempt to stop the simulation before exiting
print("Stopping simulation...")
try:
sc.stop_simulation()
except:
pass