From 1eb05e36a6a8ee597a80e008badc386c6b18acd9 Mon Sep 17 00:00:00 2001
From: Hendrik Buschmeier <hbuschme@uni-bielefeld.de>
Date: Thu, 22 Jan 2015 10:44:22 +0100
Subject: [PATCH] Modern versions of ipaaca-iu-injector/sniffer.

---
 ipaacatools/scripts/ipaaca-iu-injector    | 106 +++++++++++++++
 ipaacatools/scripts/ipaaca-iu-injector.py | 103 ---------------
 ipaacatools/scripts/ipaaca-iu-sniffer     | 149 ++++++++++++++++++++++
 ipaacatools/scripts/ipaaca-iu-sniffer.py  | 139 --------------------
 4 files changed, 255 insertions(+), 242 deletions(-)
 create mode 100755 ipaacatools/scripts/ipaaca-iu-injector
 delete mode 100755 ipaacatools/scripts/ipaaca-iu-injector.py
 create mode 100755 ipaacatools/scripts/ipaaca-iu-sniffer
 delete mode 100755 ipaacatools/scripts/ipaaca-iu-sniffer.py

diff --git a/ipaacatools/scripts/ipaaca-iu-injector b/ipaacatools/scripts/ipaaca-iu-injector
new file mode 100755
index 0000000..ea47a8b
--- /dev/null
+++ b/ipaacatools/scripts/ipaaca-iu-injector
@@ -0,0 +1,106 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# This file is part of IPAACA, the
+#  "Incremental Processing Architecture
+#   for Artificial Conversational Agents".
+#
+# Copyright (c) 2009-2015 Social Cognitive Systems Group
+#                         CITEC, Bielefeld University
+#
+# http://opensource.cit-ec.de/projects/ipaaca/
+# http://purl.org/net/ipaaca
+#
+# This file may be licensed under the terms of of the
+# GNU Lesser General Public License Version 3 (the ``LGPL''),
+# or (at your option) any later version.
+#
+# Software distributed under the License is distributed
+# on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
+# express or implied. See the LGPL for the specific language
+# governing rights and limitations.
+#
+# 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.
+#
+# The development of this software was supported by the
+# Excellence Cluster EXC 277 Cognitive Interaction Technology.
+# The Excellence Cluster EXC 277 is a grant of the Deutsche
+# Forschungsgemeinschaft (DFG) in the context of the German
+# Excellence Initiative.
+
+from __future__ import division, print_function
+
+import itertools
+import os
+import platform
+import sys
+import time
+
+import ipaaca
+
+
+def iu_update_handler(iu, event_type, local):
+	print(event_type + ': ' + str(iu))
+
+
+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 ')
+
+
+if __name__ == '__main__':
+	arguments = parser.parse_args()
+
+	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)
diff --git a/ipaacatools/scripts/ipaaca-iu-injector.py b/ipaacatools/scripts/ipaaca-iu-injector.py
deleted file mode 100755
index 58d1e9a..0000000
--- a/ipaacatools/scripts/ipaaca-iu-injector.py
+++ /dev/null
@@ -1,103 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-# This file is part of IPAACA, the
-#  "Incremental Processing Architecture
-#   for Artificial Conversational Agents".	
-#
-# Copyright (c) 2009-2013 Sociable Agents Group
-#                         CITEC, Bielefeld University	
-#
-# http://opensource.cit-ec.de/projects/ipaaca/
-# http://purl.org/net/ipaaca
-#
-# This file may be licensed under the terms of of the
-# GNU Lesser General Public License Version 3 (the ``LGPL''),
-# or (at your option) any later version.
-#
-# Software distributed under the License is distributed
-# on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
-# express or implied. See the LGPL for the specific language
-# governing rights and limitations.
-#
-# 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.	
-#
-# The development of this software was supported by the
-# Excellence Cluster EXC 277 Cognitive Interaction Technology.
-# The Excellence Cluster EXC 277 is a grant of the Deutsche
-# Forschungsgemeinschaft (DFG) in the context of the German
-# Excellence Initiative.
-
-import logging
-import sys
-import time
-import os
-import platform
-
-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)
-
-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
-
-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 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)
-
-
diff --git a/ipaacatools/scripts/ipaaca-iu-sniffer b/ipaacatools/scripts/ipaaca-iu-sniffer
new file mode 100755
index 0000000..b636e03
--- /dev/null
+++ b/ipaacatools/scripts/ipaaca-iu-sniffer
@@ -0,0 +1,149 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# This file is part of IPAACA, the
+#  "Incremental Processing Architecture
+#   for Artificial Conversational Agents".
+#
+# Copyright (c) 2009-2015 Social Cognitive Systems Group
+#                         CITEC, Bielefeld University
+#
+# http://opensource.cit-ec.de/projects/ipaaca/
+# http://purl.org/net/ipaaca
+#
+# This file may be licensed under the terms of of the
+# GNU Lesser General Public License Version 3 (the ``LGPL''),
+# or (at your option) any later version.
+#
+# Software distributed under the License is distributed
+# on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
+# express or implied. See the LGPL for the specific language
+# governing rights and limitations.
+#
+# 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.
+#
+# The development of this software was supported by the
+# Excellence Cluster EXC 277 Cognitive Interaction Technology.
+# The Excellence Cluster EXC 277 is a grant of the Deutsche
+# Forschungsgemeinschaft (DFG) in the context of the German
+# Excellence Initiative.
+
+from __future__ import print_function
+
+import logging
+import re
+import sys
+import time
+import argparse
+import os
+import platform
+
+import ipaaca
+
+
+def highlight_if_color(s, c='1'):
+	return s if not arguments.color else '['+c+'m'+s+''
+
+def pretty_printed_iu_payload(iu):
+	s='{ '
+	for k,v in iu.payload.items():
+		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
+
+def event_type_color(typ):
+	colors={'ADDED':'32;1', 'RETRACTED':'31;1', 'UPDATED':'33;1', 'MESSAGE':'34;1'}
+	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 += 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 arguments.regex:
+		for cat in arguments.categories: # actually now regexs, not categories
+			if re.match(cat, iu.category):
+				break
+		else:
+			return
+	print(pretty_printed_iu_event(iu, event_type, local))
+
+
+
+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:
+		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
diff --git a/ipaacatools/scripts/ipaaca-iu-sniffer.py b/ipaacatools/scripts/ipaaca-iu-sniffer.py
deleted file mode 100755
index 442e2ec..0000000
--- a/ipaacatools/scripts/ipaaca-iu-sniffer.py
+++ /dev/null
@@ -1,139 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-# This file is part of IPAACA, the
-#  "Incremental Processing Architecture
-#   for Artificial Conversational Agents".	
-#
-# Copyright (c) 2009-2014 Social Cognitive Systems Group
-#                         CITEC, Bielefeld University	
-#
-# http://opensource.cit-ec.de/projects/ipaaca/
-# http://purl.org/net/ipaaca
-#
-# This file may be licensed under the terms of of the
-# GNU Lesser General Public License Version 3 (the ``LGPL''),
-# or (at your option) any later version.
-#
-# Software distributed under the License is distributed
-# on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
-# express or implied. See the LGPL for the specific language
-# governing rights and limitations.
-#
-# 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.	
-#
-# The development of this software was supported by the
-# Excellence Cluster EXC 277 Cognitive Interaction Technology.
-# The Excellence Cluster EXC 277 is a grant of the Deutsche
-# Forschungsgemeinschaft (DFG) in the context of the German
-# Excellence Initiative.
-
-from __future__ import print_function
-
-import logging
-import re
-import sys
-import time
-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+''
-
-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'))
-		s += '\n' + '\t\t\'' + highlight_if_color(unicode(k),'1')+'\': '+unicode(v2)+', '
-	s+=' }'
-	return s
-
-def event_type_color(typ):
-	colors={'ADDED':'32;1', 'RETRACTED':'31;1', 'UPDATED':'33;1', 'MESSAGE':'34;1'}
-	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 += 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 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:')
-	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)
-
-- 
GitLab