### Python Module Example Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/pyconnector.md Example Python module with functions that can be called from FlexSim. Ensure this module is in the model directory or Python path. ```Python # Located in the model directory or Python path def process_entity(entity_type, priority): """Process an entity with given type and priority.""" if priority > 5: return 10.0 else: return entity_type * 2.0 def calculate_service_time(queue_length): """Calculate service time based on queue length.""" base_time = 5.0 return base_time + (queue_length * 0.5) ``` -------------------------------- ### Use Evaluation License in FlexSimPy Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md This Python example demonstrates how to launch FlexSimPy with an evaluation license enabled. This is useful for testing and prototyping without requiring a permanent FlexSim license installation. ```python # Use evaluation license for testing controller = FlexSimPy.launch( evaluationLicense=True, showGUI=False ) ``` -------------------------------- ### FlexSimPy Full Configuration Example Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md Launches FlexSimPy with asynchronous concurrency, auto-detected program directory, disabled GUI, evaluation license, and custom arguments. Use the controller for subsequent simulation operations. ```python import FlexSimPy as fp # Full configuration example controller = fp.launch( # Run in separate thread, allowing concurrent Python operations concurrency=fp.Controller.LAUNCH_ASYNCHRONOUS, # Use standard FlexSim installation location (auto-detected) programDir="", # Run without GUI for faster headless simulation showGUI=False, # Use evaluation license (no permanent license needed) evaluationLicense=True, # Pass custom arguments if needed args="" ) # Now use controller for simulation controller.open("C:\\Models\\MyModel.fsm") controller.reset() controller.run() ``` -------------------------------- ### Launch FlexSim with Evaluation License Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md Launches FlexSim using an evaluation license, which is time-limited and does not require a permanent license installation. This is useful for testing purposes. ```python # Use evaluation license (no permanent license required) controller = FlexSimPy.launch(evaluationLicense=True, showGUI=False) ``` -------------------------------- ### Launch FlexSim with Default Settings Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Launches a FlexSim instance using default asynchronous execution and specifies the program directory. Ensure the FlexSim installation path is correctly provided. ```python import FlexSimPy as fp # Launch FlexSim with default settings (no GUI, asynchronous) controller = fp.launch(programDir="C:\\Program Files\\FlexSim") ``` -------------------------------- ### Run FlexSim Simulation Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Starts the simulation execution. Can be run at default speed or a specified multiplier. ```python # Run at default speed controller.run() # Run at 2x speed controller.run(2.0) ``` -------------------------------- ### Controller.run Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Starts the simulation execution. Optionally, a run speed can be specified to control the simulation's step rate. ```APIDOC ## Controller.run(runSpeed=-1) ### Description Starts the simulation. If runSpeed is specified and greater than 0, sets the simulation step rate. ### Method Controller.run ### Parameters #### Path Parameters - **runSpeed** (float) - No - Simulation speed multiplier. Use -1 for default speed. Must be > 0 if specified. (Default: -1) ### Request Example ```python # Run at default speed controller.run() # Run at 2x speed controller.run(2.0) ``` ``` -------------------------------- ### Handle FlexSim Launch and Model Open Errors Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/README.md This example shows how to use a try-except block to catch potential runtime errors when launching FlexSim or opening a model. Refer to errors.md for specific error handling details. ```python try: controller = fp.launch() controller.open("model.fsm") except RuntimeError as e: print(f"Error: {e}") # See errors.md for specific error handling ``` -------------------------------- ### Specify FlexSim Program Directory Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md Explicitly sets the path to the FlexSim installation directory. If an empty string is provided, FlexSimPy will attempt to auto-detect the installation. ```python controller = FlexSimPy.launch(programDir="C:\\Program Files\\FlexSim") ``` -------------------------------- ### Python Console Redirection Example Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/pyconnector.md Demonstrates how Python's print and raise statements are redirected to FlexSim's console output (stdout and stderr). ```python print("This goes to FlexSim console stdout") raise Exception("This goes to FlexSim console stderr") ``` -------------------------------- ### Verify FlexSimPy Installation Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md A Python script to confirm that the FlexSimPy module is loaded correctly and that a simulation controller can be launched. Checks Python version and controller status. ```python import sys print(f"Python version: {sys.version}") import FlexSimPy print("FlexSimPy module loaded successfully") controller = FlexSimPy.launch(showGUI=False) print(f"Simulation time: {controller.time()}") ``` -------------------------------- ### PyXDecRefPtr Usage Example Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/types.md Demonstrates how to use the PyXDecRefPtr smart pointer to manage Python objects, ensuring their reference counts are automatically handled upon scope exit. ```cpp { PyXDecRefPtr tuple(PyTuple_New(n)); PyXDecRefPtr result(PyObject_Call(func, tuple, nullptr)); // Automatically decremented on scope exit } ``` -------------------------------- ### Launching FlexSimPy Controller Outside of Callbacks Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/errors.md Shows the correct pattern for launching a FlexSimPy controller at the application start and using an existing controller within callbacks. Prevents the 'Cannot launch FlexSim from a nested call' error. ```python # Wrong - launching from callback import FlexSimPy as fp def on_simulation_event(): controller = fp.launch() # ❌ Cannot launch from nested call # Correct - launch once at application start controller = fp.launch() def on_simulation_event(): # Use existing controller controller.setParameter("SomeParam", 100) on_simulation_event() ``` -------------------------------- ### Override FlexSim Installation Directory Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md Set the FLEXSIMDIR environment variable to manually specify the FlexSim installation directory, overriding the auto-detection mechanism. This is useful if FlexSim is installed in a non-standard location. ```bash set FLEXSIMDIR=D:\\Software\\FlexSim ``` -------------------------------- ### FlexSim Model Configuration (FlexScript) Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/pyconnector.md Example of configuring a FlexSim node to execute a Python function using FlexScript. This method allows direct invocation of Python functions within the FlexSim environment. ```flexscript node.value->type = 4; // Python code type node->evaluatepythonexpression("myprocessors.process_entity"); ``` -------------------------------- ### Launch FlexSim, Open Model, and Run Simulation Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/README.md This snippet demonstrates the basic workflow of launching FlexSim, opening a model, setting a parameter, running the simulation, and monitoring performance measures. ```python import FlexSimPy as fp # Launch FlexSim controller = fp.launch(showGUI=False) # Open model controller.open("C:\\Models\\MyModel.fsm") controller.reset() # Set parameters controller.setParameter("InterarrivalTime", 5.0) # Run simulation controller.run() # Monitor results while controller.time() < 100: measure = controller.getPerformanceMeasure("Throughput") print(f"Time: {controller.time()}, Throughput: {measure}") controller.stop() ``` -------------------------------- ### Launching FlexSim Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/INDEX.md Demonstrates how to launch the FlexSim simulation environment using the FlexSimPy library, with options for basic and fully configured launches. ```APIDOC ## Launching FlexSim ### Description Launches the FlexSim simulation environment. Can be done asynchronously with default settings or with a full configuration. ### Method `fp.launch()` ### Parameters - `concurrency` (int, optional): Launch mode. `fp.Controller.LAUNCH_ASYNCHRONOUS` (0) for async, `fp.Controller.LAUNCH_SYNCHRONOUS` (1) for sync. - `programDir` (str, optional): Path to the FlexSim executable directory. Auto-detected if empty. - `args` (str, optional): Additional command-line arguments for FlexSim. - `showGUI` (bool, optional): Whether to display the FlexSim GUI. Defaults to `False`. - `evaluationLicense` (bool, optional): Whether to use an evaluation license. Defaults to `False`. ### Request Example ```python import FlexSimPy as fp # Basic launch (asynchronous, no GUI, auto-detect FlexSim) controller = fp.launch() # Full configuration controller = fp.launch( concurrency=fp.Controller.LAUNCH_ASYNCHRONOUS, programDir="", # Auto-detect args="", showGUI=False, evaluationLicense=False ) ``` ### Returns A `Controller` object for interacting with the FlexSim instance. ``` -------------------------------- ### Basic FlexSimPy Workflow Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Launches FlexSim asynchronously, opens a specified model, resets it, sets a simulation parameter, runs the simulation, monitors progress, and retrieves final results. ```python import FlexSimPy as fp # Launch FlexSim controller = fp.launch( concurrency=fp.Controller.LAUNCH_ASYNCHRONOUS, showGUI=False ) # Open and reset model controller.open("C:\\Models\\TestModel.fsm") controller.reset() # Set parameters controller.setParameter("InterarrivalTime", 5.0) # Run simulation controller.run() # Monitor while running while controller.time() < 100: time = controller.time() measure = controller.getPerformanceMeasure("Output") print(f"Time: {time}, Output: {measure}") controller.stop() # Get final results output = controller.getPerformanceMeasure("Output") print(f"Final Output: {output}") ``` -------------------------------- ### Launch FlexSim with All Options Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Launches a FlexSim instance with explicit configuration for concurrency, program directory, command-line arguments, GUI display, and license type. This provides fine-grained control over the simulation launch. ```python import FlexSimPy as fp # Or with all options controller = fp.launch( concurrency=fp.Controller.LAUNCH_ASYNCHRONOUS, programDir="C:\\Program Files\\FlexSim", args="", showGUI=True, evaluationLicense=False ) ``` -------------------------------- ### Launch FlexSim Headless (No GUI) Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md Launches FlexSim without displaying the graphical user interface. This is recommended for automated or batch simulations to reduce resource usage and speed up startup. ```python # Headless simulation (typical) controller = FlexSimPy.launch(showGUI=False) ``` -------------------------------- ### Get Current Simulation Time Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Returns the current simulation time in FlexSim. Useful for time-based logic within the simulation. ```python current_time = controller.time() print(f"Simulation time: {current_time}") ``` -------------------------------- ### Get FlexSim Model Parameter Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Retrieves the value of a model parameter. Can be used for simple parameters or expressions requiring evaluation arguments. ```python # Get a simple parameter interarrival_time = controller.getParameter("InterarrivalTime") # Get a parameter with evaluation arguments value = controller.getParameter("ParameterName", arg1, arg2) ``` -------------------------------- ### Get FlexSim Performance Measures Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Retrieves the current value of a specified performance measure from FlexSim. Ensure the performance measure name is correct. ```python throughput = controller.getPerformanceMeasure("Throughput") avg_wait_time = controller.getPerformanceMeasure("AvgWaitTime") ``` -------------------------------- ### Correctly Launching a Single FlexSimPy Controller Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/errors.md Illustrates the correct way to launch a FlexSimPy controller once and how to properly release it before launching another. Avoids the 'multiple in-process controllers' error. ```python import FlexSimPy as fp # Wrong - launching twice try: controller1 = fp.launch() controller2 = fp.launch() # ❌ RuntimeError except RuntimeError as e: print(f"Error: {e}") # Correct - launch once, or clean up before launching again controller = fp.launch() # ... use controller ... # Before launching another: del controller # Release the controller # Or if needed, can re-use the same controller: controller.reset() controller.run() ``` -------------------------------- ### FlexSimPy.launch Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Launches a new instance of FlexSim and returns a Controller object to manage it. This function allows for various configurations such as execution mode, FlexSim program directory, additional arguments, GUI display, and license type. ```APIDOC ## FlexSimPy.launch ### Description Launches a new instance of FlexSim and returns a Controller object to manage it. Only one in-process controller can exist at a time. ### Method `launch(concurrency=None, programDir='', args='', showGUI=False, evaluationLicense=False)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **concurrency** (int) - Optional - Default: 0 (LAUNCH_ASYNCHRONOUS) - Execution mode: 0 = asynchronous (separate thread), 1 = synchronous (main thread) - **programDir** (str) - Optional - Default: '' (auto-detect) - Path to FlexSim program directory. If empty, auto-locates FlexSim installation - **args** (str) - Optional - Default: '' - Additional command-line arguments to pass to FlexSim - **showGUI** (bool) - Optional - Default: False - Whether to display the FlexSim GUI - **evaluationLicense** (bool) - Optional - Default: False - Whether to use evaluation license mode ### Request Example ```python import FlexSimPy as fp # Launch FlexSim with default settings (no GUI, asynchronous) controller = fp.launch(programDir="C:\\Program Files\\FlexSim") # Or with all options controller = fp.launch( concurrency=fp.Controller.LAUNCH_ASYNCHRONOUS, programDir="C:\\Program Files\\FlexSim", args="", showGUI=True, evaluationLicense=False ) ``` ### Response #### Success Response (200) - **Controller** object: An object to manage the running FlexSim simulation. #### Response Example None provided in source. ERROR HANDLING: - `RuntimeError`: Raised if a controller is already running or if FlexSim cannot be located/initialized. ``` -------------------------------- ### FlexSimPy Module Class Definition Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/types.md Defines the main C++ class for the FlexSimPy module, responsible for managing the FlexSim application instance and Python module setup. ```cpp class FlexSimPy { private: FlexSimApplication* flexSimApp = nullptr; Controller* inProcessController = nullptr; public: static FlexSimPy inst; ~FlexSimPy(); void checkBindToLoadedApp(); PyObject* launch(PyObject* self, PyObject* args, PyObject* kwargs); PyObject* sendToController(PyObject* self, PyObject* args); PyObject* receiveFromController(PyObject* self, PyObject* args); static PyMethodDef methods[]; static PyModuleDef flexSimPyModule; static PyTypeObject Controller_Type; }; ``` -------------------------------- ### FlexSimPy Deployment Files Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md Lists the essential files required to run FlexSimPy-based applications. Ensure these files are present in the correct locations. ```text MyApp.py # Your Python application FlexSimPy310.pyd # FlexSimPy module (version-specific) FlexSim\program\* # FlexSim program files FlexSim\program\python\* # PyConnector DLLs ``` -------------------------------- ### Launch FlexSim with GUI Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md Launches FlexSim with the graphical user interface displayed. This is useful for testing, debugging, and visual inspection of the model. ```python # With GUI for visual inspection controller = FlexSimPy.launch(showGUI=True) ``` -------------------------------- ### Handle Python Function Execution Errors Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/errors.md Define Python functions that include error handling for specific conditions. This example shows how to raise a ValueError if an input is invalid, which will be caught and reported by PyConnector. ```Python def myfunction(x): if x < 0: raise ValueError("x must be positive") return x * 2 ``` -------------------------------- ### Launch FlexSim Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/INDEX.md Launches the FlexSim application. Use the basic launch for asynchronous operation without a GUI, or configure advanced settings like program directory and command-line arguments. ```python import FlexSimPy as fp # Basic launch (asynchronous, no GUI, auto-detect FlexSim) controller = fp.launch() # Full configuration controller = fp.launch( concurrency=fp.Controller.LAUNCH_ASYNCHRONOUS, programDir="", # Auto-detect args="", showGUI=False, evaluationLicense=False ) ``` -------------------------------- ### Build FlexSimPy Release Configuration for Python 3.10 Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md Use this command to build the FlexSimPy solution with a specific release configuration for Python 3.10 and a 64-bit platform. ```batch msbuild FlexSimPy.sln /p:Configuration=Rel_3_10 /p:Platform=x64 ``` -------------------------------- ### Controller.open Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Opens a FlexSim model file specified by its path. This method is essential for loading a simulation environment before execution. ```APIDOC ## Controller.open(model_path) ### Description Opens a FlexSim model file. ### Method Controller.open ### Parameters #### Path Parameters - **model_path** (str) - Yes - Full path to .fsm model file ### Request Example ```python controller.open("C:\\Models\\MyModel.fsm") ``` ``` -------------------------------- ### Configuration Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/README.md Information regarding the configuration options for FlexSimPy, including launch parameters and supported Python versions. ```APIDOC ## Configuration ### Description This section covers the configuration aspects of FlexSimPy, including the parameters for launching the Controller, supported Python versions, build configurations, and deployment details. ### Options - **launch() parameters** — Details all available configuration options with their default values. - **Python versions** — Lists supported Python versions: 3.9, 3.10, 3.11, 3.12. - **Build configurations** — Supports both Debug and Release builds. - **Deployment** — Information on file locations and installation structure. ``` -------------------------------- ### FlexSimPy Directory Structure Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md Illustrates the expected directory layout for FlexSim and its Python integration components. This structure is crucial for correct operation. ```text C:\Program Files\FlexSim\ ├── program\ │ ├── FlexSim.exe │ ├── FlexSimPy39.pyd │ ├── FlexSimPy310.pyd │ ├── FlexSimPy311.pyd │ ├── FlexSimPy312.pyd │ └── python\ │ ├── PyConnector39.dll │ ├── PyConnector310.dll │ ├── PyConnector311.dll │ └── PyConnector312.dll ``` -------------------------------- ### Pattern 1: Check File Existence Before Loading Model Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/errors.md Implement a 'check before use' pattern by verifying if a model file exists before attempting to open it. This prevents `FileNotFoundError` and provides a clearer error message. ```python import os def safe_load_model(controller, path): if not os.path.exists(path): raise FileNotFoundError(f"Model file not found: {path}") try: controller.open(path) except RuntimeError as e: print(f"Failed to open model: {e}") raise ``` -------------------------------- ### Open FlexSim Model Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Opens a specified FlexSim model file. Ensure the model path is correct. ```python controller.open("C:\\Models\\MyModel.fsm") ``` -------------------------------- ### FlexSimPy Launch Function Signature Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md The function signature for FlexSimPy.launch() shows all available parameters for configuring FlexSim execution. ```python controller = FlexSimPy.launch( concurrency=None, programDir='', args='', showGUI=False, evaluationLicense=False ) ``` -------------------------------- ### Controller Methods Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/types.md Lists the Python method definitions available for the Controller type. These methods allow users to open, reset, run, stop, get/set parameters, and interact with a FlexSim model. ```APIDOC ## Controller Methods ### open ### Description Open a FlexSim model. ### Method `s_open` ### Parameters (VARARGS) ### open ### Description Reset the currently open FlexSim model. ### Method `s_reset` ### Parameters (VARARGS) ### run ### Description Set the currently open FlexSim model to be running. ### Method `s_run` ### Parameters (VARARGS) ### runToTime ### Description Run to a defined time. ### Method `s_runToTime` ### Parameters (VARARGS) ### stop ### Description Stop the model. ### Method `s_stop` ### Parameters (VARARGS) ### getParameter ### Description Get a model parameter. ### Method `s_getParameter` ### Parameters (VARARGS) ### setParameter ### Description Set a model parameter. ### Method `s_setParameter` ### Parameters (VARARGS) ### getPerformanceMeasure ### Description Get a model performance measure. ### Method `s_getPerformanceMeasure` ### Parameters (VARARGS) ### time ### Description Get the model time. ### Method `s_time` ### Parameters (VARARGS) ### evaluate ### Description Evaluate a FlexScript node. ### Method `s_evaluate` ### Parameters (VARARGS) ### send ### Description Send a value to the running model. ### Method `s_send` ### Parameters (VARARGS) ### receive ### Description Receive a response from the model. ### Method `s_receive` ### Parameters (VARARGS) ``` -------------------------------- ### Build Command-Line Arguments in C++ Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md This C++ code snippet constructs command-line arguments for FlexSimPy. It conditionally adds a prefix based on 'maintenance', 'showGUI', and 'evaluationLicense' parameters. ```cpp // From FlexSimPy.cpp lines 134-138 string prefix = ""; if (!strstr(userArgs, "maintenance ") && (!showGUI || evaluationLicense)) prefix.assign("/maintenance ") .append(showGUI ? "" : "nogui_") .append(evaluationLicense ? "evaluationlicense" : "") .append(" "); string argStr = prefix + userArgs; ``` -------------------------------- ### Controller Class Methods Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/MANIFEST.txt Methods for controlling and querying a FlexSim simulation instance via the Controller class. ```APIDOC ## Controller.__new__(), __init__() ### Description Constructor for the Controller class. ### Method `Controller()` ### Parameters None ### Request Example ```python controller = Controller() ``` ### Response #### Success Response (200) An initialized Controller object. ## Controller.open() ### Description Opens a connection to a FlexSim simulation controller. ### Method `controller.open()` ### Parameters None ### Request Example ```python controller.open() ``` ### Response #### Success Response (200) Confirmation of successful connection. ## Controller.reset() ### Description Resets the simulation to its initial state. ### Method `controller.reset()` ### Parameters None ### Request Example ```python controller.reset() ``` ### Response #### Success Response (200) Confirmation of reset. ## Controller.run() ### Description Runs the simulation until completion or a stop condition is met. ### Method `controller.run()` ### Parameters None ### Request Example ```python controller.run() ``` ### Response #### Success Response (200) Confirmation of simulation run completion. ## Controller.runToTime(time) ### Description Runs the simulation up to a specified time. ### Method `controller.runToTime(time)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **time** (float) - Required - The target simulation time. ### Request Example ```python controller.runToTime(100.0) ``` ### Response #### Success Response (200) Confirmation of reaching the target time. ## Controller.stop() ### Description Stops the simulation execution. ### Method `controller.stop()` ### Parameters None ### Request Example ```python controller.stop() ``` ### Response #### Success Response (200) Confirmation of simulation stop. ## Controller.getParameter(name) ### Description Retrieves the value of a simulation parameter. ### Method `controller.getParameter(name)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the parameter. ### Request Example ```python param_value = controller.getParameter('model_version') ``` ### Response #### Success Response (200) - **value** (any) - The value of the parameter. #### Response Example ```json { "value": "1.0" } ``` ## Controller.setParameter(name, value) ### Description Sets the value of a simulation parameter. ### Method `controller.setParameter(name, value)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the parameter. - **value** (any) - Required - The new value for the parameter. ### Request Example ```python controller.setParameter('model_version', '1.1') ``` ### Response #### Success Response (200) Confirmation of parameter update. ## Controller.getPerformanceMeasure(name) ### Description Retrieves the value of a simulation performance measure. ### Method `controller.getPerformanceMeasure(name)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the performance measure. ### Request Example ```python measure_value = controller.getPerformanceMeasure('throughput') ``` ### Response #### Success Response (200) - **value** (float) - The value of the performance measure. #### Response Example ```json { "value": 150.5 } ``` ## Controller.time() ### Description Gets the current simulation time. ### Method `controller.time()` ### Parameters None ### Request Example ```python current_sim_time = controller.time() ``` ### Response #### Success Response (200) - **time** (float) - The current simulation time. #### Response Example ```json { "time": 75.2 } ``` ## Controller.evaluate(expression) ### Description Evaluates a FlexScript expression within the simulation context. ### Method `controller.evaluate(expression)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **expression** (string) - Required - The FlexScript expression to evaluate. ### Request Example ```python result = controller.evaluate("model.find(\"Source1\").output(1)") ``` ### Response #### Success Response (200) - **result** (any) - The result of the evaluated expression. #### Response Example ```json { "result": 10 } ``` ## Controller.send(data) ### Description Sends data to the FlexSim controller (similar to `sendToController` but specific to the Controller object). ### Method `controller.send(data)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (any) - Required - The data to send. ### Request Example ```python controller.send({'command': 'set_parameter', 'name': 'speed', 'value': 5}) ``` ### Response #### Success Response (200) Confirmation of data reception. ## Controller.receive() ### Description Receives data from the FlexSim controller (similar to `receiveFromController` but specific to the Controller object). ### Method `controller.receive()` ### Parameters None ### Request Example ```python received_data = controller.receive() ``` ### Response #### Success Response (200) - **data** (any) - The data received from the controller. #### Response Example ```json { "status": "parameter_updated", "name": "speed" } ``` ``` -------------------------------- ### PyConnector::initialize Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/pyconnector.md Initializes the Python interpreter. This method is called automatically on first use by findProc(). It sets up the Python environment, including the sys.path and console redirection. ```APIDOC ## initialize() ### Description Initializes the Python interpreter. Called automatically by `findProc()` on first use. It sets up the Python environment, including the sys.path and console redirection. ### Method ```cpp bool initialize() ``` ### Behavior 1. Checks if already initialized; returns true if so 2. Records the current model directory 3. Detects if FlexSimPy module is loaded (handles GIL differently if present) 4. Appends "consoleredirection" to importable modules 5. Initializes Python via `Py_Initialize()` 6. Sets up Python path to include model directory 7. Redirects stdout/stderr to FlexSim console via a custom module 8. Returns true on success ### Setup code ```python import consoleredirection import sys class StdOutRedirect: def write(self, stuff): consoleredirection.redirectStdOut(stuff) def flush(self): pass class StdErrRedirect: def write(self, stuff): consoleredirection.redirectStdErr(stuff) def flush(self): pass sys.stdout = StdOutRedirect() sys.stderr = StdErrRedirect() ``` ``` -------------------------------- ### FlexSimPy Module Functions Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/MANIFEST.txt Core functions for launching and interacting with FlexSim simulations from Python. ```APIDOC ## FlexSimPy.launch() ### Description Launches a FlexSim simulation instance. ### Method `FlexSimPy.launch()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python FlexSimPy.launch(concurrency=4, programDir='/path/to/flexsim', args=['-silent'], showGUI=False, evaluationLicense=True) ``` ### Response #### Success Response (200) Details about the launched simulation instance. #### Response Example ```json { "status": "launched", "instance_id": "sim_123" } ``` ## FlexSimPy.sendToController() ### Description Sends data or commands to a running FlexSim controller. ### Method `FlexSimPy.sendToController()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (any) - Required - The data or command to send. ### Request Example ```python FlexSimPy.sendToController({'command': 'run_to_time', 'time': 100}) ``` ### Response #### Success Response (200) Confirmation of data reception. #### Response Example ```json { "status": "received" } ``` ## FlexSimPy.receiveFromController() ### Description Receives data or status updates from a running FlexSim controller. ### Method `FlexSimPy.receiveFromController()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python result = FlexSimPy.receiveFromController() ``` ### Response #### Success Response (200) - **data** (any) - The data received from the controller. #### Response Example ```json { "status": "simulation_running", "current_time": 50.5 } ``` ``` -------------------------------- ### onBuildFlexScript() Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/pyconnector.md Handles model rebuild events in FlexSim, responsible for reloading Python modules to ensure the latest code is used. ```APIDOC ## onBuildFlexScript() ### Description Called by FlexSim when the model is rebuilt (e.g., on model reset or after editing a node). Handles Python module reloading to pick up changes. ### Method ```c extern "C" int onBuildFlexScript() ``` ### Parameters None ### Returns int — 1 on success, 0 on failure ### Behavior 1. Checks if the model directory has changed 2. If changed, clears all imported modules via `clearModules()` 3. If same, reloads all modules via `reloadModules()` to pick up code changes 4. Updates the Python path environment ### Purpose Enables live-editing of Python modules during model development without restarting FlexSim ### Example flow: ``` Model opened in directory "C:\Models\MyModel\" → PyConnector imports "mymodule" → Developer edits C:\Models\MyModel\mymodule.py → User presses F9 (rebuild) in FlexSim → onBuildFlexScript() called → PyConnector reloads the modified mymodule → Node evaluations use updated function code ``` **Source:** `PyConnector/PyConnector.cpp` lines 247-265 ``` -------------------------------- ### Fix: Use Asynchronous Mode for Controller.send() Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/errors.md The `controller.send()` method requires the FlexSim simulation to be running in asynchronous launch mode. Calling `send()` in synchronous mode will result in an error due to the lack of inter-thread communication. ```python # Wrong - using send() in synchronous mode controller = FlexSimPy.launch( concurrency=FlexSimPy.Controller.LAUNCH_SYNCHRONOUS ) controller.send(42) # ❌ Not allowed in sync mode # Correct - use asynchronous mode controller = FlexSimPy.launch( concurrency=FlexSimPy.Controller.LAUNCH_ASYNCHRONOUS # or default ) controller.send(42) # ✓ Allowed ``` -------------------------------- ### Launch FlexSim in Synchronous Mode Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Launches FlexSim in synchronous mode, where FlexSim runs in the main Python thread. Methods like send() and receive() are not available in this mode. ```python controller = fp.launch(concurrency=fp.Controller.LAUNCH_SYNCHRONOUS) controller.open("model.fsm") controller.runToTime(100) # Blocking call # send()/receive() not available in this mode ``` -------------------------------- ### Define FlexSimPy Module Documentation String Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/types.md Declares the documentation string for the FlexSimPy Python module. This string is used by Python's help() function and documentation tools. ```cpp PyDoc_STRVAR(fsPyDoc, "A module for launching and controlling FlexSim."); ``` -------------------------------- ### Launch FlexSim Asynchronously Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md Launches FlexSim in a separate thread, allowing Python and FlexSim to run concurrently. This is the default mode and requires synchronization for communication. ```python # Asynchronous (can interleave Python and FlexSim work) controller = FlexSimPy.launch(concurrency=FlexSimPy.Controller.LAUNCH_ASYNCHRONOUS) ``` -------------------------------- ### redirectStdErr Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/pyconnector.md Writes to the FlexSim console via `EX()` (exception output). This function is part of the console redirection module. ```APIDOC ## redirectStdErr(string) ### Description Writes to FlexSim console via `EX()` (exception output). ### Parameters #### Path Parameters - **string** (const char*) - Required - The string to write to the console. ### Usage from Python ```python raise Exception("This goes to FlexSim console stderr") ``` ``` -------------------------------- ### Catching FlexSimPy RuntimeErrors Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/errors.md Demonstrates how to catch and print FlexSimPy RuntimeError exceptions using standard Python try-except blocks. ```python try: controller = FlexSimPy.launch() except RuntimeError as e: print(f"FlexSimPy error: {e}") ``` -------------------------------- ### Type System Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/README.md Details on the type conversion and management system used by FlexSimPy. ```APIDOC ## Type System ### Description FlexSimPy employs a robust type system for seamless data exchange between Python and FlexSim. This includes bidirectional type conversion, support for variant types, and efficient memory management. ### Components - **PyConverter** — Handles bidirectional type conversion between Python and FlexSim data types. - **Variant types** — Supports String, Number, Array, and Map data structures. - **Reference counting** — Ensures proper Python memory management for FlexSim objects. - **Type tables** — Provides complete mappings for type conversions. ``` -------------------------------- ### PyConnector Class Methods Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/MANIFEST.txt Methods for managing the language binding between Python and FlexSim's DLL interface. ```APIDOC ## PyConnector.findProc(name) ### Description Finds a procedure (function) within the loaded FlexSim modules. ### Method `PyConnector.findProc(name)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the procedure to find. ### Request Example ```python proc_handle = PyConnector.findProc("my_custom_function") ``` ### Response #### Success Response (200) - **handle** (pointer) - A handle to the found procedure. #### Response Example ```json { "handle": "0x12345678" } ``` ## PyConnector.bindToNode(node_path) ### Description Binds the Python connector to a specific FlexSim model node. ### Method `PyConnector.bindToNode(node_path)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **node_path** (string) - Required - The path to the FlexSim node (e.g., '/model/queues/Queue1'). ### Request Example ```python PyConnector.bindToNode("/model/sources/Source1") ``` ### Response #### Success Response (200) Confirmation of successful binding. ## PyConnector.onBuildFlexScript(flexscript_code) ### Description Executes FlexScript code during the FlexSim model build process. ### Method `PyConnector.onBuildFlexScript(flexscript_code)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **flexscript_code** (string) - Required - The FlexScript code to execute. ### Request Example ```python PyConnector.onBuildFlexScript("trace(\"Model built!\")") ``` ### Response #### Success Response (200) Confirmation of FlexScript execution. ## PyConnector.initialize() ### Description Initializes the PyConnector language binding. ### Method `PyConnector.initialize()` ### Parameters None ### Request Example ```python PyConnector.initialize() ``` ### Response #### Success Response (200) Confirmation of initialization. ## PyConnector.clearModules() ### Description Clears all loaded Python modules managed by PyConnector. ### Method `PyConnector.clearModules()` ### Parameters None ### Request Example ```python PyConnector.clearModules() ``` ### Response #### Success Response (200) Confirmation of module clearing. ## PyConnector.reloadModules() ### Description Reloads all Python modules managed by PyConnector. ### Method `PyConnector.reloadModules()` ### Parameters None ### Request Example ```python PyConnector.reloadModules() ``` ### Response #### Success Response (200) Confirmation of module reloading. ## PyConnector.redirectStdOut(file_path) ### Description Redirects the standard output stream from Python scripts to a specified file. ### Method `PyConnector.redirectStdOut(file_path)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file_path** (string) - Required - The path to the file for redirecting stdout. ### Request Example ```python PyConnector.redirectStdOut("/var/log/flexsim_stdout.log") ``` ### Response #### Success Response (200) Confirmation of stdout redirection. ## PyConnector.redirectStdErr(file_path) ### Description Redirects the standard error stream from Python scripts to a specified file. ### Method `PyConnector.redirectStdErr(file_path)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file_path** (string) - Required - The path to the file for redirecting stderr. ### Request Example ```python PyConnector.redirectStdErr("/var/log/flexsim_stderr.log") ``` ### Response #### Success Response (200) Confirmation of stderr redirection. ## PyConnector.printLastPyError() ### Description Prints the last encountered Python error to the FlexSim output console. ### Method `PyConnector.printLastPyError()` ### Parameters None ### Request Example ```python PyConnector.printLastPyError() ``` ### Response #### Success Response (200) Prints error details to the FlexSim console. ``` -------------------------------- ### Launch FlexSim Synchronously Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md Launches FlexSim in the main Python thread, blocking all Python operations during simulation. This mode is simpler but does not allow concurrent execution. ```python # Synchronous (simpler, single-threaded) controller = FlexSimPy.launch(concurrency=FlexSimPy.Controller.LAUNCH_SYNCHRONOUS) ``` -------------------------------- ### FlexSimPy Class Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/types.md The main module class responsible for managing the FlexSim application instance and setting up the Python module. It provides methods for launching controllers and internal communication. ```APIDOC ## FlexSimPy Class ### Description The main module class responsible for managing the FlexSim application instance and setting up the Python module. It provides methods for launching controllers and internal communication between Python and FlexSim. ### Fields: - **inst** (static FlexSimPy) - Global module instance - **flexSimApp** (FlexSimApplication*) - Pointer to FlexSim application instance - **inProcessController** (Controller*) - Current in-process controller (only one allowed) ### Module Methods: - **launch**() — Create and launch a Controller - **sendToController**() — Receive value from FlexSim (internal) - **receiveFromController**() — Send value to FlexSim (internal) ``` -------------------------------- ### Checking Model File Existence Before Opening Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/errors.md Illustrates how to prevent 'Model file not found' errors by checking if a model file exists using Python's `os.path.exists` before attempting to open it with `controller.open()`. ```python import os # Wrong - non-existent file controller.open("C:\\Models\\NonExistent.fsm") # May raise error # Correct - verify file exists first model_path = "C:\\Models\\MyModel.fsm" if os.path.exists(model_path): controller.open(model_path) else: print(f"Model file not found: {model_path}") ``` -------------------------------- ### redirectStdOut Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/pyconnector.md Writes to the FlexSim console via `pt()` (print to output). This function is part of the console redirection module. ```APIDOC ## redirectStdOut(string) ### Description Writes to FlexSim console via `pt()` (print to output). ### Parameters #### Path Parameters - **string** (const char*) - Required - The string to write to the console. ### Usage from Python ```python print("This goes to FlexSim console stdout") ``` ``` -------------------------------- ### Controller.time Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Returns the current simulation time in the FlexSim model. ```APIDOC ## Controller.time() ### Description Returns the current simulation time. ### Parameters None ### Returns - float: The current simulation time. ### Example ```python current_time = controller.time() print(f"Simulation time: {current_time}") ``` ``` -------------------------------- ### PyCode Class Methods Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/MANIFEST.txt Methods for evaluating Python code within the FlexSim environment. ```APIDOC ## PyCode.evaluate(code_string) ### Description Evaluates a string containing Python code within the FlexSim context. ### Method `PyCode.evaluate(code_string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **code_string** (string) - Required - The Python code to evaluate. ### Request Example ```python result = PyCode.evaluate("import math; math.sqrt(16)") ``` ### Response #### Success Response (200) - **result** (any) - The result of the evaluated Python code. #### Response Example ```json { "result": 4.0 } ``` ``` -------------------------------- ### Controller Class Methods Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/INDEX.md Methods available on the Controller instance for simulation management. ```APIDOC ## `open(path)` ### Description Opens a FlexSim model file. ### Method Controller method call ### Parameters - **path** (string) - Required - The file path to the FlexSim model. ### Response None ## `reset()` ### Description Resets the simulation to its initial state. ### Method Controller method call ### Parameters None ### Response None ## `run(speed)` ### Description Starts or resumes the simulation. ### Method Controller method call ### Parameters - **speed** (number) - Optional - The simulation speed multiplier. ### Response None ## `runToTime(time)` ### Description Runs the simulation until a specified time. ### Method Controller method call ### Parameters - **time** (number) - Required - The target simulation time. ### Response None ## `stop()` ### Description Stops the simulation. ### Method Controller method call ### Parameters None ### Response None ## `time()` ### Description Gets the current simulation time. ### Method Controller method call ### Parameters None ### Response - **current_time** (number) - The current simulation time. ## `getParameter(name, *args)` ### Description Gets the value of a simulation parameter. ### Method Controller method call ### Parameters - **name** (string) - Required - The name of the parameter. - **args** (any) - Optional - Additional arguments for the parameter. ### Response - **value** (any) - The value of the parameter. ## `setParameter(name, value)` ### Description Sets the value of a simulation parameter. ### Method Controller method call ### Parameters - **name** (string) - Required - The name of the parameter. - **value** (any) - Required - The new value for the parameter. ### Response None ## `getPerformanceMeasure(name)` ### Description Gets the value of a performance measure. ### Method Controller method call ### Parameters - **name** (string) - Required - The name of the performance measure. ### Response - **measure_value** (any) - The value of the performance measure. ## `evaluate(path, *args)` ### Description Evaluates a tree node in the simulation model. ### Method Controller method call ### Parameters - **path** (string) - Required - The path to the tree node. - **args** (any) - Optional - Arguments for evaluation. ### Response - **result** (any) - The result of the evaluation. ## `send(value)` ### Description Sends data to the FlexSim simulation. ### Method Controller method call ### Parameters - **value** (any) - Required - The data to send. ### Response None ## `receive()` ### Description Receives data from the FlexSim simulation. ### Method Controller method call ### Parameters None ### Response - **data** (any) - The data received from FlexSim. ``` -------------------------------- ### Launch FlexSim in Asynchronous Mode Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/flexsimpy-module.md Launches FlexSim in asynchronous mode, allowing Python threads to send values and receive responses. This mode is the default. ```python controller = fp.launch(concurrency=fp.Controller.LAUNCH_ASYNCHRONOUS) controller.open("model.fsm") controller.run() # Python thread can send values controller.send(100) # And receive responses response = controller.receive() # Blocks until FlexSim responds ``` -------------------------------- ### FlexSim Main Thread Callback Source: https://github.com/flexsim/flexsimpy/blob/main/_autodocs/configuration.md Executes a callback lambda on FlexSim's main thread, with an option to wait for completion. Ensure proper GIL state management within the callback. ```cpp FlexSimApplication::getPlatform().callMainThreadCallback( [args, &result, &callback]() { PyGILState_STATE gstate; gstate = PyGILState_Ensure(); result = callback(args); PyGILState_Release(gstate); }, true // wait for completion ); ```