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

Event system for logs and web socket communication #1523

Merged
merged 14 commits into from
Jul 29, 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
1 change: 1 addition & 0 deletions configs/config.json.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"gmapkey": "GOOGLE_MAPS_API_KEY",
"max_steps": 5,
"catch_pokemon": true,
"websocket_server": false,
"spin_forts": true,
"walk": 4.16,
"action_wait_min": 1,
Expand Down
12 changes: 10 additions & 2 deletions pokecli.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,14 @@ def init_config():
help="Username",
default=None
)
add_config(
parser,
load,
short_flag="-ws",
long_flag="--websocket_server",
help="Start websocket server (format 'host:port')",
default=False
)
add_config(
parser,
load,
Expand Down Expand Up @@ -351,13 +359,13 @@ def add_config(parser, json_config, short_flag=None, long_flag=None, **kwargs):
else:
args = (long_flag,)
parser.add_argument(*args, **kwargs)

def parse_unicode_str(string):
try:
return string.decode('utf8')
except UnicodeEncodeError:
return string


if __name__ == '__main__':
main()
53 changes: 40 additions & 13 deletions pokemongo_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,12 @@
from human_behaviour import sleep
from item_list import Item
from metrics import Metrics
from pokemongo_bot.event_handlers import LoggingHandler
from pokemongo_bot.event_handlers import SocketIoHandler
from pokemongo_bot.socketio_server.runner import SocketIoRunner
from spiral_navigator import SpiralNavigator
from worker_result import WorkerResult
from event_manager import EventManager
from api_wrapper import ApiWrapper


Expand All @@ -39,12 +43,31 @@ def __init__(self, config):
self.latest_inventory = None
self.cell = None


def start(self):
self._setup_logging()
self._setup_api()
self.navigator = SpiralNavigator(self)
random.seed()

def _setup_event_system(self):
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you put this lower in the file?

Copy link
Member Author

Choose a reason for hiding this comment

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

@TheSavior sure, I was putting here to allow easier merge of #1253

Copy link
Contributor

Choose a reason for hiding this comment

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

Why does this belong here and not in the pokecli.py file? If it was in the cli file we'd be able to send an event on startup with the bag information we are currently printing to the console, right?

Copy link
Member Author

@douglascamata douglascamata Jul 29, 2016

Choose a reason for hiding this comment

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

@TheSavior the event system is set up before the api setup (where bag info is being print). We can still use the event system to log it.

Nothing is printed in the CLI file.

handlers = [LoggingHandler()]
if self.config.websocket_server:
websocket_handler = SocketIoHandler(self.config.websocket_server)
handlers.append(websocket_handler)

self.sio_runner = SocketIoRunner(self.config.websocket_server)
self.sio_runner.start_listening_async()

self.event_manager = EventManager(*handlers)

# Registering event:
# self.event_manager.register_event("location", parameters=['lat', 'lng'])
#
# Emitting event should be enough to add logging and send websocket
# message: :
# self.event_manager.emit('location', 'level'='info', data={'lat': 1, 'lng':1}),

def tick(self):
self.cell = self.get_meta_cell()

Expand Down Expand Up @@ -184,14 +207,22 @@ def _setup_logging(self):
# log format
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')
format='%(asctime)s [%(name)10s] [%(levelname)5s] %(message)s')

if self.config.debug:
logging.getLogger("requests").setLevel(logging.DEBUG)
logging.getLogger("websocket").setLevel(logging.DEBUG)
logging.getLogger("socketio").setLevel(logging.DEBUG)
logging.getLogger("engineio").setLevel(logging.DEBUG)
logging.getLogger("socketIO-client").setLevel(logging.DEBUG)
logging.getLogger("pgoapi").setLevel(logging.DEBUG)
logging.getLogger("rpc_api").setLevel(logging.DEBUG)
else:
logging.getLogger("requests").setLevel(logging.ERROR)
logging.getLogger("websocket").setLevel(logging.ERROR)
logging.getLogger("socketio").setLevel(logging.ERROR)
logging.getLogger("engineio").setLevel(logging.ERROR)
logging.getLogger("socketIO-client").setLevel(logging.ERROR)
logging.getLogger("pgoapi").setLevel(logging.ERROR)
logging.getLogger("rpc_api").setLevel(logging.ERROR)

Expand Down Expand Up @@ -396,18 +427,14 @@ def _set_starting_position(self):
return

if self.config.location:
try:
location_str = self.config.location.encode('utf-8')
location = (self._get_pos_by_name(location_str.replace(" ", "")))
self.api.set_position(*location)
logger.log('')
logger.log(u'Location Found: {}'.format(self.config.location))
logger.log('GeoPosition: {}'.format(self.position))
logger.log('')
has_position = True
except Exception:
logger.log('[x] The location given in the config could not be parsed. Checking for a cached location.')
pass
location_str = self.config.location.encode('utf-8')
location = (self._get_pos_by_name(location_str.replace(" ", "")))
self.api.set_position(*location)
logger.log('')
logger.log(u'Location Found: {}'.format(self.config.location))
logger.log('GeoPosition: {}'.format(self.position))
logger.log('')
has_position = True

if self.config.location_cache:
try:
Expand Down
2 changes: 2 additions & 0 deletions pokemongo_bot/event_handlers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from logging_handler import LoggingHandler
from socketio_handler import SocketIoHandler
9 changes: 9 additions & 0 deletions pokemongo_bot/event_handlers/logging_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import logging
from pokemongo_bot.event_manager import EventHandler


class LoggingHandler(EventHandler):
def handle_event(self, event, sender, level, data):
logger = logging.getLogger(type(sender).__name__)
message = '{}: {}'.format(event, str(data))
getattr(logger, level)(message)
16 changes: 16 additions & 0 deletions pokemongo_bot/event_handlers/socketio_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from pokemongo_bot.event_manager import EventHandler
from socketIO_client import SocketIO


class SocketIoHandler(EventHandler):


def __init__(self, url):
super(EventHandler, self).__init__()
self.host, port_str = url.split(':')
self.port = int(port_str)


def handle_event(self, event, sender, level, data):
with SocketIO(self.host, self.port) as sio:
sio.emit('bot:broadcast', {'event': event, 'data': data})
49 changes: 49 additions & 0 deletions pokemongo_bot/event_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@


class EventNotRegisteredException(Exception):
pass


class EventMalformedException(Exception):
pass


class EventHandler(object):
def __init__(self):
pass

def handle_event(self, event, kwargs):
raise NotImplementedError("Please implement")


class EventManager(object):
def __init__(self, *handlers):
self._registered_events = dict()
self._handlers = handlers or []

def add_handler(self, event_handler):
self._handlers.append(event_handler)

def register_event(self, name, parameters=None):
self._registered_events[name] = parameters

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

levels = ['info', 'warning', 'error', 'critical', 'debug']
if not level in levels:
raise ArgumentError('Event level needs to be in: {}'.format(levels))

if event not in self._registered_events:
raise EventNotRegisteredException("Event %s not registered..." % event)

# verify params match event
parameters = self._registered_events[event]
for k, v in data.iteritems():
if k not in parameters:
raise EventMalformedException("Event %s does not require parameter %s" % (event, k))

# send off to the handlers
for handler in self._handlers:
handler.handle_event(event, sender, level, data)
Empty file.
23 changes: 23 additions & 0 deletions pokemongo_bot/socketio_server/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import socketio
import logging
from eventlet import wsgi
from flask import Flask, render_template
Copy link
Contributor

Choose a reason for hiding this comment

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

FAILED pylint inspection: E: 4, 0: Unable to import 'flask' (import-error)

Copy link
Member Author

@douglascamata douglascamata Jul 29, 2016

Choose a reason for hiding this comment

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

🔔 shaaaaaaaame 🔔

from pokemongo_bot.event_manager import EventManager
from pokemongo_bot.event_handlers import LoggingHandler

sio = socketio.Server(async_mode='eventlet', logging=logging.NullHandler)
app = Flask(__name__)

event_manager = EventManager()
event_manager.add_handler(LoggingHandler())
event_manager.register_event(
"websocket_client_connected",
)

@sio.on('bot:broadcast')
def bot_broadcast(sid, env):
sio.emit(env['event'], data=env['data'])

@sio.on('disconnect')
def disconnect(sid):
print('disconnect ', sid)
33 changes: 33 additions & 0 deletions pokemongo_bot/socketio_server/runner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import threading
import eventlet
import socketio
import logging
from eventlet import patcher, wsgi
from app import app, sio

patcher.monkey_patch(all=True)

class SocketIoRunner(object):

def __init__(self, url):
self.host, port_str = url.split(':')
self.port = int(port_str)
self.server = None

# create the thread object
self.thread = threading.Thread(target=self._start_listening_blocking)

# wrap Flask application with socketio's middleware
self.app = socketio.Middleware(sio, app)

def start_listening_async(self):
wsgi.is_accepting = True
self.thread.start()

def stop_listening(self):
wsgi.is_accepting = False

def _start_listening_blocking(self):
# deploy as an eventlet WSGI server
listener = eventlet.listen((self.host, self.port))
self.server = wsgi.server(listener, self.app, log_output=False, debug=False)
Empty file added pokemongo_bot/test/__init__.py
Empty file.
15 changes: 15 additions & 0 deletions pokemongo_bot/test/socketio-client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from socketIO_client import SocketIO, LoggingNamespace, BaseNamespace


def on_location(msg):
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we please make this a unit test? It should be run as part of travis. Nobody is ever going to go into this file again to run it and make sure it works. An automated test will ensure that nobody ever breaks it.

Copy link
Member Author

Choose a reason for hiding this comment

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

I can do it (:

print('received location: {}'.format(msg))

if __name__ == "__main__":
try:
socketio = SocketIO('localhost', 4000)
socketio.on('location', on_location)
while True:
socketio.wait(seconds=5)

except (KeyboardInterrupt, SystemExit):
print "Exiting"
4 changes: 4 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,8 @@ enum34==1.1.6
pyyaml==3.11
haversine==0.4.5
polyline==1.3.1
python-socketio==1.4.2
flask==0.11.1
socketIO_client==0.7.0
eventlet==0.19.0
universal-analytics-python==0.2.4