test-tutorial-framework/solvable/src/custom_event_handlers.py

70 lines
2.4 KiB
Python

import logging
from ast import literal_eval
from tfw.components import MessageSender
from tfw.builtins import TerminalCommandsEventHandler
from tfw.main import TFWUplinkConnector
LOG = logging.getLogger(__name__)
class CenatorEventHandler:
keys = ['history.bash']
# pylint: disable=no-self-use
"""
Logs commands executed in terminal to messages and invokes an
additional callback function to handle special commands.
!! Please remove from production code. !!
"""
def handle_event(self, message, server_connector):
command = message['value']
LOG.debug('User executed command: "%s"', command)
MessageSender(server_connector).send('JOHN CENA', f'You\'ve executed "{command}"')
class TestCommandsEventHandler(TerminalCommandsEventHandler):
"""
Some example commands useful for debugging.
!! Please remove from production code !! and inherit your own
class from TerminalCommands if you need to define custom
commands in your challenge.
"""
# pylint: disable=unused-argument, attribute-defined-outside-init, no-self-use
def command_sendmessage(self, *args):
"""
Insert TFW message template as first argument if executed without args.
Evaluate first argumen as a dict and send it to the frontend.
This is useful for playing around with frontend APIs.
"""
if not args:
message_template = """'{"key": "", "data": {"command": ""}}'"""
TFWUplinkConnector().send_message({
'key': 'shell',
'data': {
'command': 'write',
'value': f'sendmessage {message_template}'
}
})
else:
TFWUplinkConnector().send_message(literal_eval(args[0]))
class MessageFSMStepsEventHandler:
# pylint: disable=no-self-use
"""
This example EventHandler is capable of detecting FSM state.
!! Please remove from production code !!
"""
def handle_event(self, message, server_connector):
"""
When the FSM steps this method is invoked.
Receives a 'data' field from an fsm_update message as kwargs.
"""
MessageSender(server_connector).send(
'FSM info',
f'FSM has stepped from state "{message["last_event"]["from_state"]}" '
f'to state "{message["current_state"]}" in response to trigger "{message["last_event"]["trigger"]}"'
)