### Basic Setup and API Forwarding with Flapi Source: https://context7.com/maddyguthridge/flapi/llms.txt Enables Flapi to forward all FL Studio API calls through MIDI for execution within FL Studio. This setup requires the 'flapi', 'transport', and 'ui' modules. It connects to MIDI ports, starts FL Studio playback, sets a hint message, queries the tempo, and then stops playback and disconnects. ```python import flapi import transport import ui # Connect to MIDI ports and establish FL Studio connection flapi.enable() # All FL Studio API calls are now forwarded to FL Studio transport.start() # FL Studio starts playback ui.setHintMsg("Hello from Flapi!") # Hint message appears in FL Studio # Query FL Studio state bpm = transport.getTempo() print(f"Current BPM: {bpm}") # Stop playback and close connection transport.stop() flapi.disable() ``` -------------------------------- ### Flapi Server Installation Source: https://context7.com/maddyguthridge/flapi/llms.txt Installs the Flapi MIDI controller script into FL Studio's scripts directory. Options include specifying a custom data directory, installing in development mode using symlinks, forcing an overwrite, and uninstalling the server. ```bash # Install with default Image-Line data directory $ flapi install Success! Make sure you restart FL Studio so the server is registered # Install to custom data directory $ flapi install -d "C:\Custom\FL Studio\Data" # Install in development mode (creates symlink instead of copying) $ flapi install --dev # Force overwrite existing installation $ flapi install -y # Uninstall the server $ flapi uninstall ``` -------------------------------- ### Control FL Studio Playback via Flapi REPL Source: https://github.com/maddyguthridge/flapi/blob/main/README.md This example demonstrates controlling FL Studio's transport functions using the Flapi REPL. It imports the 'transport' module and uses 'transport.start()' to begin playback and 'transport.stop()' to halt it. This highlights Flapi's capability to manage playback. ```bash $ flapi >>> import transport >>> transport.start() # FL Studio starts playback >>> transport.stop() # FL Studio stops playback ``` -------------------------------- ### Custom MIDI Port Configuration with Flapi Source: https://context7.com/maddyguthridge/flapi/llms.txt Allows specifying custom MIDI port names for Flapi connections, useful for non-standard setups. If the initial connection fails (e.g., FL Studio not running), it provides a fallback to manually initialize the connection when FL Studio starts. ```python import flapi # Connect to custom-named MIDI ports success = flapi.enable( req_port="Custom Request Port", res_port="Custom Response Port" ) if not success: # Connection failed, FL Studio not running # Manually initialize when FL Studio starts flapi.init(client_id=42) # Now ready to use FL Studio API import ui ui.setHintMsg("Connected via custom ports") flapi.disable() ``` -------------------------------- ### Server-Side REPL Execution with Flapi Source: https://context7.com/maddyguthridge/flapi/llms.txt Starts a server-side REPL where all code executes directly inside FL Studio, with standard output redirected to the client. This allows for direct inspection of FL Studio's Python environment, such as checking the Python version or executing UI functions. ```bash # Start server-side REPL (all code runs inside FL Studio) $ flapi -s server >>> import sys >>> sys.version '3.12.1 (tags/v3.12.1:2305ca5, Dec 7 2023, 22:03:25) [MSC v.1937 64 bit (AMD64)]' >>> print("This prints from inside FL Studio") This prints from inside FL Studio >>> import ui >>> ui.setHintMsg("Direct server execution") >>> exit() ``` -------------------------------- ### Server-Side Python Execution in FL Studio with Flapi Source: https://github.com/maddyguthridge/flapi/blob/main/README.md This snippet illustrates Flapi's server-side REPL mode, indicated by the '-s server' flag. Code executed in this mode runs directly within FL Studio. The example shows retrieving the Python version used by FL Studio and printing to standard output, demonstrating direct execution and redirected stdout. ```bash $ flapi -s server >>> import sys >>> sys.version '3.12.1 (tags/v3.12.1:2305ca5, Dec 7 2023, 22:03:25) [MSC v.1937 64 bit (AMD64)]' # It's running inside FL Studio! >>> print("Hello") Hello # Stdout is redirected back to the client too! ``` -------------------------------- ### Flapi Error Handling - Python Source: https://context7.com/maddyguthridge/flapi/llms.txt Provides a comprehensive example of handling common Flapi errors using specific exception types like FlapiPortError, FlapiConnectionError, FlapiTimeoutError, FlapiVersionError, and FlapiServerExit. This ensures robust interaction with FL Studio. ```python import flapi from flapi.errors import ( FlapiPortError, FlapiConnectionError, FlapiTimeoutError, FlapiVersionError, FlapiServerExit ) try: flapi.enable() except FlapiPortError as e: print(f"MIDI port error: {e}") print("On Windows, install loopMIDI and create ports named:") print(" - Flapi Request") print(" - Flapi Response") exit(1) except FlapiConnectionError: print("Could not connect to FL Studio") print("Is FL Studio running with Flapi server installed?") exit(1) try: import transport transport.start() except FlapiTimeoutError: print("FL Studio not responding (timeout)") except FlapiVersionError as e: print(f"Version mismatch: {e}") print("Run 'flapi install' to update the server") except FlapiServerExit: print("FL Studio closed") finally: try: flapi.disable() except: pass ``` -------------------------------- ### REPL Configuration - Bash Source: https://context7.com/maddyguthridge/flapi/llms.txt Shows various command-line options for configuring the flapi REPL, including setting connection timeouts, custom MIDI ports, forcing a specific shell, and enabling verbose logging for debugging purposes. ```bash # Wait up to 30 seconds for FL Studio connection $ flapi --timeout 30 # Use custom MIDI ports $ flapi --req "My Request Port" --res "My Response Port" # Force specific shell (python or ipython) $ flapi -s ipython # Enable verbose logging for debugging $ flapi -v # Info level $ flapi -vv # Debug level $ flapi -vvv # Trace level ``` -------------------------------- ### High-Level Client with Pickle Serialization - Python Source: https://context7.com/maddyguthridge/flapi/llms.txt Illustrates using the FlapiClient for high-level automation with automatic serialization and deserialization using pickle. This simplifies handling complex data types and executing/evaluating expressions in FL Studio. ```python from flapi.client import FlapiClient # Client uses pickle for automatic serialization client = FlapiClient( req_port="Flapi Request", res_port="Flapi Response" ) # Execute statements client.exec("import mixer") client.exec("mixer.setTrackVolume(0, 0.5)") # Evaluate expressions with automatic unpickling track_count = client.eval("mixer.trackCount()") print(f"Track count: {track_count}") # Complex return types work automatically track_names = client.eval("[mixer.getTrackName(i) for i in range(5)]") print(f"First 5 tracks: {track_names}") # Exceptions are raised on the client side try: client.eval("1 / 0") except ZeroDivisionError as e: print(f"Caught remote exception: {e}") ``` -------------------------------- ### Execute Python Code in FL Studio via Flapi REPL Source: https://github.com/maddyguthridge/flapi/blob/main/README.md This snippet demonstrates using the Flapi command-line interface (CLI) to interact with FL Studio. It imports the 'ui' module and sets a hint message displayed in FL Studio's hint panel. This showcases basic remote execution of Python commands. ```bash $ flapi >>> import ui >>> ui.setHintMsg("Hello from Flapi!") # Hint message "Hello from Flapi!" is displayed in FL Studio's hint panel ``` -------------------------------- ### Low-Level MIDI Communication with FlapiBaseClient Source: https://context7.com/maddyguthridge/flapi/llms.txt Provides access to the low-level Flapi client for advanced message handling and custom protocols. This includes defining custom callbacks for stdout and unknown messages, querying the server version, executing code, and performing a clean disconnect. ```python from flapi.client.base_client import FlapiBaseClient # Create and connect client with custom callbacks def handle_stdout(text: str): print(f"[FL Studio] {text}") def handle_unknown(msg: bytes): print(f"Unknown message: {msg.hex()}") client = FlapiBaseClient( stdout_callback=handle_stdout, unknown_msg_callback=handle_unknown ).open("Flapi Request", "Flapi Response").hello(timeout=5.0) # Query server version major, minor, patch = client.version_query() print(f"Server version: {major}.{minor}.{patch}") # Execute code client.exec("import transport; transport.start()") # Clean disconnect client.goodbye(code=0) ``` -------------------------------- ### Interactive REPL with Flapi Source: https://context7.com/maddyguthridge/flapi/llms.txt Launches an interactive Python shell with FL Studio API access. This command utilizes IPython if available, otherwise falls back to the standard Python shell. Inside the shell, users can import FL Studio modules like 'transport' and 'mixer' to control playback and adjust track volumes. ```bash # Start REPL (uses IPython if available, falls back to standard Python shell) $ flapi Flapi interactive shell Client version: 1.0.1 Python version: 3.12.1 Connected to FL Studio Imported functions: enable, init, disable, fl_exec, fl_eval, fl_print >>> import transport >>> import mixer >>> transport.start() >>> mixer.setTrackVolume(1, 0.8) >>> transport.stop() >>> exit() ``` -------------------------------- ### Register Custom Message Handler - Python Source: https://context7.com/maddyguthridge/flapi/llms.txt Demonstrates how to register a custom message handler for specialized communication protocols using the FlapiBaseClient. This allows for custom data serialization and command handling between the client and FL Studio. ```python from flapi.client.base_client import FlapiBaseClient from base64 import b64encode, b64decode import json client = FlapiBaseClient().open().hello() # Define server-side handler for custom JSON-based protocol def json_handler(client_id, status_code, msg_data, scope): import json from base64 import b64decode, b64encode data = json.loads(b64decode(msg_data).decode()) command = data.get("command") if command == "get_project_name": import ui result = {"name": ui.getProgTitle()} else: result = {"error": "Unknown command"} return (0, b64encode(json.dumps(result).encode())) # Register the handler and get sender function send_json_msg = client.register_message_type(json_handler) # Use custom message type request = json.dumps({"command": "get_project_name"}) response = send_json_msg(b64encode(request.encode())) # Parse response result = json.loads(b64decode(response.additional_data).decode()) print(f"Project name: {result['name']}") client.close() ``` -------------------------------- ### Enable Flapi Library for Remote API Calls Source: https://github.com/maddyguthridge/flapi/blob/main/README.md This Python code snippet shows how to enable the Flapi library within a script. Once enabled, all calls to functions within FL Studio's MIDI Controller Scripting API will be automatically forwarded to FL Studio for execution. This is the primary method for using Flapi as a library. ```python import flapi # Enable flapi flapi.enable() # Now all calls to functions in FL Studio's MIDI Controller Scripting API will # be forwarded to FL Studio to be executed. ``` -------------------------------- ### Direct Code Execution with Flapi Source: https://context7.com/maddyguthridge/flapi/llms.txt Executes Python statements directly within FL Studio without explicitly importing API modules. It supports `fl_exec` for statements without return values, `fl_eval` for expressions that return values, and `fl_print` to display messages in FL Studio's Python console. ```python import flapi flapi.enable() # Execute code (no return value) flapi.fl_exec("import transport") flapi.fl_exec("transport.start()") # Evaluate expressions (returns result) playing = flapi.fl_eval("transport.isPlaying()") print(f"Is playing: {playing}") # Is playing: True # Print to FL Studio's Python console flapi.fl_print("Debug message in FL Studio") flapi.disable() ``` -------------------------------- ### Encode and Decode Base64 in Python Source: https://github.com/maddyguthridge/flapi/blob/main/Protocol.md Demonstrates how to encode an integer to a base64 string and decode it back to an integer using Python's base64 module. This is used for transmitting exit codes safely. ```python from base64 import b64encode, b64decode code = 130 # Encode encoded = b64encode(str(code).encode()) # Decode decoded = int(b64decode(data).decode()) assert code == decoded ``` -------------------------------- ### Flapi Message Handler Interface in Python Source: https://github.com/maddyguthridge/flapi/blob/main/Protocol.md Defines the expected interface for message handler functions in the Flapi system. These functions process incoming messages, manage client state, and return status codes and optional data. ```python def message_handler( client_id: int, status_code: int, msg_data: Optional[bytes], scope: dict[str, Any], ) -> int | tuple[int, bytes]: ... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.