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 @@
# This file is part of IPAACA, the
# "Incremental Processing Architecture
# for Artificial Conversational Agents".
# for Artificial Conversational Agents".
#
# Copyright (c) 2009-2013 Sociable Agents Group
# CITEC, Bielefeld University
# Copyright (c) 2009-2015 Social Cognitive Systems Group
# CITEC, Bielefeld University
#
# http://opensource.cit-ec.de/projects/ipaaca/
# http://purl.org/net/ipaaca
......@@ -23,7 +23,7 @@
# You should have received a copy of the LGPL along with this
# program. If not, go to http://www.gnu.org/licenses/lgpl.html
# 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
# Excellence Cluster EXC 277 Cognitive Interaction Technology.
......@@ -31,73 +31,76 @@
# Forschungsgemeinschaft (DFG) in the context of the German
# Excellence Initiative.
import logging
import sys
import time
from __future__ import division, print_function
import itertools
import os
import platform
import sys
import time
import ipaaca
def my_update_handler(iu, event_type, local):
print(event_type+': '+str(iu))
if len(sys.argv)<2:
print "Please use the program as follows:"
print " "+sys.argv[0]+" [--class IU|Message] [--timeout <sec>] <categoryname> [<payloadkey> <payloadvalue>] [<k2> <v2>] ..."
sys.exit(1)
def iu_update_handler(iu, event_type, local):
print(event_type + ': ' + str(iu))
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]
idx += 1
pl={}
while len(sys.argv)>idx+1:
pl[sys.argv[idx]] = sys.argv[idx+1]
idx+=2
parser = ipaaca.IpaacaArgumentParser(description='Ipaaca IU Injector -- Sent ipaaca messages or IUs from the command line')
parser.add_argument(
'-t', '--type',
default='Message',
dest='iu_type',
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')
ob.register_handler(my_update_handler)
iu_top = ipaaca.IU(cate)
iu_top.payload = pl
ob.add(iu_top)
print iu_class+" sent."
if __name__ == '__main__':
arguments = parser.parse_args()
if iu_class=="IU":
print "Waiting "+str(timeout)+" sec for remote modifications..."
time.sleep(timeout)
else:
time.sleep(0.1)
print "done."
except KeyboardInterrupt:
pass
if platform.system() == 'Windows':
os._exit(0)
else:
sys.exit(0)
ob = ipaaca.OutputBuffer('IpaacaIUInjector')
ob.register_handler(iu_update_handler)
iu = ipaaca.Message(arguments.category) if arguments.iu_type == 'Message' else ipaaca.IU(arguments.category)
iu.payload = {k: v for (k, v) in itertools.izip_longest(arguments.payload[::2], arguments.payload[1::2])}
ob.add(iu)
print(
'Sent {iu_type} with category "{category}" and payload {{'.format(**vars(arguments)),
end='\n' if len(iu.payload) > 0 else '')
for k, v in iu.payload.items():
print(' "{key}": "{value}",'.format(key=k, value=v))
print('}.')
try:
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 @@
# This file is part of IPAACA, the
# "Incremental Processing Architecture
# for Artificial Conversational Agents".
# for Artificial Conversational Agents".
#
# Copyright (c) 2009-2014 Social Cognitive Systems Group
# CITEC, Bielefeld University
# Copyright (c) 2009-2015 Social Cognitive Systems Group
# CITEC, Bielefeld University
#
# http://opensource.cit-ec.de/projects/ipaaca/
# http://purl.org/net/ipaaca
......@@ -23,7 +23,7 @@
# You should have received a copy of the LGPL along with this
# program. If not, go to http://www.gnu.org/licenses/lgpl.html
# 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
# Excellence Cluster EXC 277 Cognitive Interaction Technology.
......@@ -37,23 +37,20 @@ import logging
import re
import sys
import time
import argparse
import os
import platform
import ipaaca
color = False
regex = False
max_size = 2048
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):
s='{ '
for k,v in iu.payload.items():
v = str(v)
v2 = (('\''+v+'\'') if len(v)<=max_size else ('\''+v[:max_size]+'\'<excess length omitted>')).replace('\\','\\\\').replace('\n',highlight_if_color('\\n'))
v2 = (('\''+v+'\'') if len(v)<=arguments.max_size else ('\''+v[:arguments.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+=' }'
return s
......@@ -63,77 +60,90 @@ def event_type_color(typ):
return '1' if typ not in colors else colors[typ]
def pretty_printed_iu_event(iu, event_type, local):
s=''
t=time.time()
lt=time.localtime(t)
s = ''
t = time.time()
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('%-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
def my_update_handler(iu, event_type, local):
if regex:
for cat in cats: # actually now regexs, not cats
if arguments.regex:
for cat in arguments.categories: # actually now regexs, not categories
if re.match(cat, iu.category):
break
else:
return
t=time.localtime()
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)
ib.register_handler(my_update_handler)
print('')
print('Ipaaca IU Sniffer - run with --help to see options')
print('Listening for IU events of ', end='')
if len(cats) == 0:
print('any category ...')
else:
if regex:
print('whose category matches one of the regexes:')
parser = ipaaca.IpaacaArgumentParser(description='Ipaaca IU Sniffer -- Selectively listen to IPAACA traffic')
parser.add_argument(
'-r', '--regex',
action='store_true',
dest='regex',
help='match categories by regular expressions')
parser.add_argument(
'-c', '--color',
action='store_true',
dest='color',
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:
print('categories:')
for cat in cats:
print('\t' + cat)
print('')
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
if platform.system() == 'Windows':
os._exit(0)
else:
sys.exit(0)
if arguments.regex:
print('whose category matches one of the regexes:')
else:
print('categories:')
print('\t' + ', '.join(arguments.categories))
print('')
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
if platform.system() == 'Windows':
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