Skip to content

Commit

Permalink
Implement client goodbye in client
Browse files Browse the repository at this point in the history
  • Loading branch information
MaddyGuthridge committed Apr 7, 2024
1 parent deb2d58 commit 9870549
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 8 deletions.
35 changes: 30 additions & 5 deletions flapi/__comms.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
FlapiServerError,
FlapiClientError,
FlapiServerExit,
FlapiClientExit,
)


Expand Down Expand Up @@ -78,7 +79,7 @@ def handle_received_message(msg: bytes) -> Optional[bytes]:
if remaining_msg[2] == MessageType.CLIENT_GOODBYE:
code = int(b64decode(remaining_msg[3:]).decode())
log.info(f"Received exit command with code {code}")
raise SystemExit(code)
raise FlapiClientExit(code)

# Handle server disconnect
if remaining_msg[2] == MessageType.SERVER_GOODBYE:
Expand Down Expand Up @@ -154,10 +155,8 @@ def receive_message() -> bytes:

def hello() -> bool:
"""
Send a heartbeat message to FL Studio, and check whether we receive another
heartbeat in response.
If no data is received, this function returns `False`.
Send a "client hello" message to FL Studio to attempt to establish a
connection.
"""
client_id = get_context().client_id
log.debug(f"Attempt hello with {client_id=}")
Expand All @@ -179,6 +178,32 @@ def hello() -> bool:
return False


def client_goodbye(code: int) -> None:
"""
Send a "client goodbye" message to FL Studio to close the connection.
"""
client_id = get_context().client_id
log.debug(f"Attempt hello with {client_id=}")
assert client_id is not None
send_msg(
consts.SYSEX_HEADER
+ bytes([
MessageOrigin.CLIENT,
client_id,
MessageType.CLIENT_GOODBYE,
])
+ b64encode(str(code).encode())
)
try:
res = receive_message()
# We should never reach this point, as receiving the message should
# have raised a SystemExit
log.critical(f"Failed to SystemExit -- instead received message {res}")
assert False
except FlapiClientExit:
return


def version_query() -> tuple[int, int, int]:
"""
Query and return the version of Flapi installed to FL Studio.
Expand Down
20 changes: 17 additions & 3 deletions flapi/__enable.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,13 @@
from mido.ports import BaseOutput, BaseInput # type: ignore
from . import _consts as consts
from .__context import set_context, get_context, pop_context, FlapiContext
from .__comms import fl_exec, hello, version_query, poll_for_message
from .__comms import (
fl_exec,
hello,
version_query,
poll_for_message,
client_goodbye,
)
from .__decorate import restore_original_functions, add_wrappers
from .errors import FlapiPortError, FlapiConnectionError, FlapiVersionError

Expand Down Expand Up @@ -183,12 +189,20 @@ def version_check():
# If we reach this point, the versions match


def disable():
def disable(code: int = 0):
"""
Disable Flapi, closing its MIDI ports and its connection to FL Studio
Disable Flapi, closing its MIDI ports and its connection to FL Studio.
This restores the original functions for the FL Studio API.
## Args
* `code` (`int`, optional): the exit code to relay to the server. Defaults
to `0`.
"""
# Send a client goodbye
client_goodbye(code)

# Close all the ports
ctx = pop_context()
ctx.req_port.close()
Expand Down
1 change: 1 addition & 0 deletions flapi/cli/repl.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ def start_server_shell():
line = input(">>> " if not len(lines) else "... ")
except KeyboardInterrupt:
if last_was_interrupted:
disable()
exit()
else:
print("\nKeyboard interrupt. Press again to quit")
Expand Down
9 changes: 9 additions & 0 deletions flapi/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,15 @@ def __init__(self) -> None:
)


class FlapiClientExit(SystemExit):
"""
The flapi client requested to exit
"""

def __init__(self, code: int) -> None:
super().__init__(code)


class FlapiClientError(Exception):
"""
An unexpected error occurred on the client side.
Expand Down

0 comments on commit 9870549

Please sign in to comment.