#!/usr/bin/python
#
"""send hostnames and their ping times to wireTAP server
 based on ping-multi.py by daniel holth and clinton mcchesney

 usage: pingClient.py wireTAPhost port wireTAPchannel pinghost [pinghost]...[pinghost]

 author: michael branton

 This script is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this script; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

 uses danny holth/clinton mcchesney OSC.py module to convert data into OSC format
 and the python wireTAP API
 http://wiretap.stetson.edu/
"""

from wtMessenger import wtMessenger
import sys
import os
import re

# check arg count
if len(sys.argv) < 4:
	print 'usage:  pingClient.py wireTAPhost port wireTAPchannel pinghost [pinghost]...[pinghost]'
	sys.exit(1)

# parse args
host	= sys.argv[1]
port	= int(sys.argv[2])
channel = sys.argv[3]
pinghost= sys.argv[4:]

# get reg ex parser to pick off ping time
time = re.compile(".*time=(\d*(\.?\d*)) (ms|msec|usec)")

# put hosts to be pinged and processes to ping them
# in a list
pings=[]
for phost in pinghost:
	print "pinging "+phost
	pings.append((phost,os.popen("ping %s" % phost)))

# create connection to wireTAP server
mess=wtMessenger()
mess.setServerPort(port)
mess.serverConnect(host,channel)

# receive ping times and ship them off
while 1:
	try:
		for ping in pings:
			line  = ping[1].readline()
			match = time.match(line)
	
			if match != None:

				pingtime = float(match.group(1))
                		if(match.group(3) == "usec"): #convert to ms
                        		pingtime = pingtime / 1000

				mess.add(ping[0])
				mess.add(pingtime)

				print "Sending %s %d %s %s %f " % (host, port, channel, ping[0], pingtime)
    				mess.send()

        except KeyboardInterrupt:
		mess.serverDisconnect()
                print ' '
                print 'your ping session is now complete'
                print ' '
                sys.exit(0)
