Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Foundation for remote control of the bot over websocket #2000

Merged
merged 6 commits into from
Jul 31, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 18 additions & 5 deletions pokecli.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,24 @@ def init_config():
parser,
load,
short_flag="-ws",
long_flag="--websocket_server",
help="Start websocket server (format 'host:port')",
long_flag="--websocket.server_url",
help="Connect to websocket server at given url",
default=False
)
add_config(
parser,
load,
short_flag="-wss",
long_flag="--websocket.start_embedded_server",
help="Start embedded websocket server",
default=False
)
add_config(
parser,
load,
short_flag="-wsr",
long_flag="--websocket.remote_control",
help="Enable remote control through websocket (requires websocekt server url)",
default=False
)
add_config(
Expand Down Expand Up @@ -245,7 +261,6 @@ def init_config():
type=str,
default=None
)

add_config(
parser,
load,
Expand Down Expand Up @@ -374,9 +389,7 @@ def init_config():
config.item_filter = load.get('item_filter', {})
config.action_wait_max = load.get('action_wait_max', 4)
config.action_wait_min = load.get('action_wait_min', 1)

config.raw_tasks = load.get('tasks', [])

config.vips = load.get('vips',{})

if len(config.raw_tasks) == 0:
Expand Down
7 changes: 4 additions & 3 deletions pokemongo_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,12 @@ def start(self):
def _setup_event_system(self):
handlers = [LoggingHandler()]
if self.config.websocket_server:
websocket_handler = SocketIoHandler(self.config.websocket_server)
websocket_handler = SocketIoHandler(self.config.websocket_server_url)
handlers.append(websocket_handler)

self.sio_runner = SocketIoRunner(self.config.websocket_server)
self.sio_runner.start_listening_async()
if self.config.websocket_start_embedded_server:
self.sio_runner = SocketIoRunner(self.config.websocket_server_url)
self.sio_runner.start_listening_async()

self.event_manager = EventManager(*handlers)

Expand Down
7 changes: 5 additions & 2 deletions pokemongo_bot/event_handlers/logging_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@


class LoggingHandler(EventHandler):
def handle_event(self, event, sender, level, data):
def handle_event(self, event, sender, level, formatted_msg, data):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do we need this formatted_msg for? It seems like it would make logging more complicated if things are sending event, formatted_msg and data.

Copy link
Member Author

@douglascamata douglascamata Jul 31, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

because we might want to have logger messages with real text, Pokemon Foobar (CP X IV Y) was caught! instead of just parameters for events event: catch pokemon, data: {CP: X, name: Foobar, IV: Y}

logger = logging.getLogger(type(sender).__name__)
message = '{}: {}'.format(event, str(data))
if formatted_msg:
message = formatted_msg
else:
message = '{}: {}'.format(event, str(data))
getattr(logger, level)(message)
13 changes: 10 additions & 3 deletions pokemongo_bot/event_handlers/socketio_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,14 @@ def __init__(self, url):
self.host, port_str = url.split(':')
self.port = int(port_str)


def handle_event(self, event, sender, level, data):
def handle_event(self, event, sender, level, msg, data):
if msg:
date['msg'] = msg
with SocketIO(self.host, self.port) as sio:
sio.emit('bot:broadcast', {'event': event, 'data': data})
sio.emit(
'bot:broadcast',
{
'event': event,
'data': data,
}
)
6 changes: 4 additions & 2 deletions pokemongo_bot/event_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def add_handler(self, event_handler):
def register_event(self, name, parameters=None):
self._registered_events[name] = parameters

def emit(self, event, sender=None, level='info', data={}):
def emit(self, event, sender=None, level='info', formatted=None, data={}):
if not sender:
raise ArgumentError('Event needs a sender!')

Expand All @@ -42,6 +42,8 @@ def emit(self, event, sender=None, level='info', data={}):
if k not in parameters:
raise EventMalformedException("Event %s does not require parameter %s" % (event, k))

formatted_msg = formatted.format(**data)

# send off to the handlers
for handler in self._handlers:
handler.handle_event(event, sender, level, data)
handler.handle_event(event, sender, level, formatted_msg, data)
10 changes: 10 additions & 0 deletions pokemongo_bot/socketio_server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@
"websocket_client_connected",
)

# client asks for data
@sio.on('remote:send_request')
def remote_control(sid, command):
sio.emit('bot:process_request', data=command)

# sending bot response to client
@sio.on('bot:send_reply')
def request_reply(sid, response):
sio.emit(response['command'], response['response'])

@sio.on('bot:broadcast')
def bot_broadcast(sid, env):
sio.emit(env['event'], data=env['data'])
Expand Down
48 changes: 48 additions & 0 deletions pokemongo_bot/websocket_remote_control.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import threading
from socketIO_client import SocketIO, BaseNamespace


class WebsocketRemoteControl(object):


def __init__(self, bot):
self.bot = bot
self.host, port_str = self.bot.config.websocket_server_url.split(':')
self.port = int(port_str)
self.sio = SocketIO(self.host, self.port)
self.sio.on('bot:process_request', self.on_remote_command)
self.thread = threading.Thread(target=self.process_messages)

def start(self):
self.thread.start()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is self.thread defined?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh shit, I deleted a line

return self

def process_messages(self):
self.sio.wait()

def on_remote_command(self, command):
name = command['name']
command_handler = getattr(self, name, None)
if not command_handler or not callable(command_handler):
self.sio.emit(
'bot:send_reply',
{
'response': '',
'command': 'command_not_found'
}
)
return
if 'args' in command:
command_handler(*args)
return
command_handler()

def get_player_info(self):
player_info = self.bot.get_inventory()['responses']['GET_INVENTORY']
self.sio.emit(
'bot:send_reply',
{
'response': player_info,
'command': 'get_player_info'
}
)