Skip to content
Snippets Groups Projects
Commit 1eb05e36 authored by Hendrik Buschmeier's avatar Hendrik Buschmeier
Browse files

Modern versions of ipaaca-iu-injector/sniffer.

parent fd47f548
No related branches found
No related tags found
No related merge requests found
...@@ -3,10 +3,10 @@ ...@@ -3,10 +3,10 @@
# This file is part of IPAACA, the # This file is part of IPAACA, the
# "Incremental Processing Architecture # "Incremental Processing Architecture
# for Artificial Conversational Agents". # for Artificial Conversational Agents".
# #
# Copyright (c) 2009-2013 Sociable Agents Group # Copyright (c) 2009-2015 Social Cognitive Systems Group
# CITEC, Bielefeld University # CITEC, Bielefeld University
# #
# http://opensource.cit-ec.de/projects/ipaaca/ # http://opensource.cit-ec.de/projects/ipaaca/
# http://purl.org/net/ipaaca # http://purl.org/net/ipaaca
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
# You should have received a copy of the LGPL along with this # You should have received a copy of the LGPL along with this
# program. If not, go to http://www.gnu.org/licenses/lgpl.html # program. If not, go to http://www.gnu.org/licenses/lgpl.html
# or write to the Free Software Foundation, Inc., # or write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# #
# The development of this software was supported by the # The development of this software was supported by the
# Excellence Cluster EXC 277 Cognitive Interaction Technology. # Excellence Cluster EXC 277 Cognitive Interaction Technology.
...@@ -31,73 +31,76 @@ ...@@ -31,73 +31,76 @@
# Forschungsgemeinschaft (DFG) in the context of the German # Forschungsgemeinschaft (DFG) in the context of the German
# Excellence Initiative. # Excellence Initiative.
import logging from __future__ import division, print_function
import sys
import time import itertools
import os import os
import platform import platform
import sys
import time
import ipaaca import ipaaca
def my_update_handler(iu, event_type, local):
print(event_type+': '+str(iu))
if len(sys.argv)<2: def iu_update_handler(iu, event_type, local):
print "Please use the program as follows:" print(event_type + ': ' + str(iu))
print " "+sys.argv[0]+" [--class IU|Message] [--timeout <sec>] <categoryname> [<payloadkey> <payloadvalue>] [<k2> <v2>] ..."
sys.exit(1)
iu_class = 'Message'
timeout = 3.0
idx = 1
keep_going = True
while keep_going:
keep_going = False
if sys.argv[idx]=='--class':
t = sys.argv[idx+1]
if t in ['Message', 'IU']:
iu_class = t
else:
print "Unknown IU class: "+t
sys.exit(1)
idx += 2
keep_going = True
elif sys.argv[idx]=='--timeout':
timeout = float(sys.argv[idx+1])
idx += 2
keep_going = True
cate = sys.argv[idx] parser = ipaaca.IpaacaArgumentParser(description='Ipaaca IU Injector -- Sent ipaaca messages or IUs from the command line')
idx += 1 parser.add_argument(
pl={} '-t', '--type',
while len(sys.argv)>idx+1: default='Message',
pl[sys.argv[idx]] = sys.argv[idx+1] dest='iu_type',
idx+=2 choices = ['Message', 'IU'],
help="choose IU type to be send (default: 'Message')")
parser.add_argument(
'-k', '--keep-alive',
default=3.0,
dest='keep_alive',
metavar='SECONDS',
type=float,
help='set time in seconds to wait for potential IU updates (default: 3.0)')
parser.add_argument(
'-c', '--category',
dest='category',
metavar='CATEGORY',
required=True,
help='set Message/IU category')
parser.add_argument(
'-p', '--payload',
default=[],
dest='payload',
metavar='KEY VALUE',
nargs='+',
help='set Message/IU payload ')
try:
print "Sending "+iu_class+" of category "+cate
print " with payload "+str(pl)
ob = ipaaca.OutputBuffer('IUInjector') if __name__ == '__main__':
ob.register_handler(my_update_handler) arguments = parser.parse_args()
iu_top = ipaaca.IU(cate)
iu_top.payload = pl
ob.add(iu_top)
print iu_class+" sent."
if iu_class=="IU": ob = ipaaca.OutputBuffer('IpaacaIUInjector')
print "Waiting "+str(timeout)+" sec for remote modifications..." ob.register_handler(iu_update_handler)
time.sleep(timeout) iu = ipaaca.Message(arguments.category) if arguments.iu_type == 'Message' else ipaaca.IU(arguments.category)
else: iu.payload = {k: v for (k, v) in itertools.izip_longest(arguments.payload[::2], arguments.payload[1::2])}
time.sleep(0.1) ob.add(iu)
print "done." print(
'Sent {iu_type} with category "{category}" and payload {{'.format(**vars(arguments)),
except KeyboardInterrupt: end='\n' if len(iu.payload) > 0 else '')
pass for k, v in iu.payload.items():
print(' "{key}": "{value}",'.format(key=k, value=v))
if platform.system() == 'Windows': print('}.')
os._exit(0)
else: try:
sys.exit(0) if arguments.iu_type == 'IU':
print('Waiting %s s for the IU to be updated.' % arguments.keep_alive)
time.sleep(arguments.keep_alive)
else:
time.sleep(0.1)
except KeyboardInterrupt:
pass
if platform.system() == 'Windows':
os._exit(0)
else:
sys.exit(0)
...@@ -3,10 +3,10 @@ ...@@ -3,10 +3,10 @@
# This file is part of IPAACA, the # This file is part of IPAACA, the
# "Incremental Processing Architecture # "Incremental Processing Architecture
# for Artificial Conversational Agents". # for Artificial Conversational Agents".
# #
# Copyright (c) 2009-2014 Social Cognitive Systems Group # Copyright (c) 2009-2015 Social Cognitive Systems Group
# CITEC, Bielefeld University # CITEC, Bielefeld University
# #
# http://opensource.cit-ec.de/projects/ipaaca/ # http://opensource.cit-ec.de/projects/ipaaca/
# http://purl.org/net/ipaaca # http://purl.org/net/ipaaca
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
# You should have received a copy of the LGPL along with this # You should have received a copy of the LGPL along with this
# program. If not, go to http://www.gnu.org/licenses/lgpl.html # program. If not, go to http://www.gnu.org/licenses/lgpl.html
# or write to the Free Software Foundation, Inc., # or write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# #
# The development of this software was supported by the # The development of this software was supported by the
# Excellence Cluster EXC 277 Cognitive Interaction Technology. # Excellence Cluster EXC 277 Cognitive Interaction Technology.
...@@ -37,23 +37,20 @@ import logging ...@@ -37,23 +37,20 @@ import logging
import re import re
import sys import sys
import time import time
import argparse
import os import os
import platform import platform
import ipaaca import ipaaca
color = False
regex = False
max_size = 2048
def highlight_if_color(s, c='1'): def highlight_if_color(s, c='1'):
return s if not color else '['+c+'m'+s+'' return s if not arguments.color else '['+c+'m'+s+''
def pretty_printed_iu_payload(iu): def pretty_printed_iu_payload(iu):
s='{ ' s='{ '
for k,v in iu.payload.items(): for k,v in iu.payload.items():
v = str(v) v2 = (('\''+v+'\'') if len(v)<=arguments.max_size else ('\''+v[:arguments.max_size]+'\'<excess length omitted>')).replace('\\','\\\\').replace('\n',highlight_if_color('\\n'))
v2 = (('\''+v+'\'') if len(v)<=max_size else ('\''+v[:max_size]+'\'<excess length omitted>')).replace('\\','\\\\').replace('\n',highlight_if_color('\\n'))
s += '\n' + '\t\t\'' + highlight_if_color(unicode(k),'1')+'\': '+unicode(v2)+', ' s += '\n' + '\t\t\'' + highlight_if_color(unicode(k),'1')+'\': '+unicode(v2)+', '
s+=' }' s+=' }'
return s return s
...@@ -63,77 +60,90 @@ def event_type_color(typ): ...@@ -63,77 +60,90 @@ def event_type_color(typ):
return '1' if typ not in colors else colors[typ] return '1' if typ not in colors else colors[typ]
def pretty_printed_iu_event(iu, event_type, local): def pretty_printed_iu_event(iu, event_type, local):
s='' s = ''
t=time.time() t = time.time()
lt=time.localtime(t) lt = time.localtime(t)
s += highlight_if_color('%.3f'%t, '1')+' '+"%02d:%02d:%02d"%(lt.tm_hour, lt.tm_min, lt.tm_sec) s += highlight_if_color('%.3f'%t, '1')+' '+"%02d:%02d:%02d"%(lt.tm_hour, lt.tm_min, lt.tm_sec)
s += ' '+highlight_if_color('%-9s'%event_type,event_type_color(event_type))+' category='+highlight_if_color(iu.category,event_type_color(event_type))+' uid='+iu.uid+' owner='+iu.owner_name+' payload='+pretty_printed_iu_payload(iu) s += ' '+highlight_if_color('%-9s'%event_type,event_type_color(event_type))+' category='+highlight_if_color(iu.category,event_type_color(event_type))+' uid='+iu.uid+' owner='+iu.owner_name+' payload='+pretty_printed_iu_payload(iu)
return s return s
def my_update_handler(iu, event_type, local): def my_update_handler(iu, event_type, local):
if regex: if arguments.regex:
for cat in cats: # actually now regexs, not cats for cat in arguments.categories: # actually now regexs, not categories
if re.match(cat, iu.category): if re.match(cat, iu.category):
break break
else: else:
return return
t=time.localtime()
print(pretty_printed_iu_event(iu, event_type, local)) print(pretty_printed_iu_event(iu, event_type, local))
cats = []
keep_going=True
idx = 1
while keep_going:
opt = sys.argv[idx] if idx<len(sys.argv) else None
if opt=='--help':
print('IU sniffer - usage:')
print(' '+sys.argv[0]+' [--options] [<category1> [<category2 ...]]')
print(' Listen to specified categories (default: all)')
print(' Option --color : colorize output')
print(' Option --regex : match categories by regular expressions')
print(' Option --size-limit <size> : limit payload display, chars (def: 2048)')
sys.exit(0)
elif opt=='--color':
color = True
idx += 1
elif opt=='--regex':
regex = True
idx += 1
elif opt=='--size-limit':
if len(sys.argv)<idx+2:
print('Please specify a max size')
sys.exit(1)
max_size = int(sys.argv[idx+1])
idx += 2
else:
cats = sys.argv[idx:]
keep_going = False
ib = ipaaca.InputBuffer('SnifferIn', [''] if (len(cats) == 0 or regex) else cats) parser = ipaaca.IpaacaArgumentParser(description='Ipaaca IU Sniffer -- Selectively listen to IPAACA traffic')
ib.register_handler(my_update_handler) parser.add_argument(
'-r', '--regex',
print('') action='store_true',
print('Ipaaca IU Sniffer - run with --help to see options') dest='regex',
print('Listening for IU events of ', end='') help='match categories by regular expressions')
if len(cats) == 0: parser.add_argument(
print('any category ...') '-c', '--color',
else: action='store_true',
if regex: dest='color',
print('whose category matches one of the regexes:') help='colorize output')
parser.add_argument(
'--channels',
dest='channels',
default=['default'],
metavar='CHANNEL',
nargs='+',
help="set the channels to listen on (otherwise 'default')")
parser.add_argument(
'--categories',
default=[''],
dest='categories',
metavar='CATEGORY',
nargs='+',
help='set categories (or regex patterns) to be matched')
parser.add_argument(
'--size-limit',
default=2048,
dest='max_size',
metavar='LIMIT',
type=int,
help='limit payload display chars (default: 2048)')
if __name__ == '__main__':
arguments = parser.parse_args()
buffers = {}
for channel in arguments.channels:
buffers[channel] = ipaaca.InputBuffer('IpaacaIUSniffer', arguments.categories if not arguments.regex else [''], channel)
buffers[channel].register_handler(my_update_handler)
print('')
print('Ipaaca IU Sniffer - run with --help to see options')
channellist = 's ' if len(arguments.channels) > 1 else ' '
channellist += ', '.join(arguments.channels)
print('Listening on channel' + channellist + ' for IU events of ', end='')
if arguments.categories == ['']:
print('any category ...')
else: else:
print('categories:') if arguments.regex:
for cat in cats: print('whose category matches one of the regexes:')
print('\t' + cat) else:
print('') print('categories:')
try: print('\t' + ', '.join(arguments.categories))
while True: print('')
time.sleep(1) try:
except KeyboardInterrupt: while True:
pass time.sleep(1)
except KeyboardInterrupt:
if platform.system() == 'Windows': pass
os._exit(0)
else: if platform.system() == 'Windows':
sys.exit(0) os._exit(0)
else:
sys.exit(0)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment