moth/pointscli.py

62 lines
1.3 KiB
Python
Raw Normal View History

2009-08-20 16:20:44 -06:00
#! /usr/bin/env python3
2009-08-20 12:51:47 -06:00
import optparse
import select
import points
import socket
import time
2009-08-20 16:20:44 -06:00
def submit(sock, cat, team, score):
2009-08-21 13:27:17 -06:00
begin = time.time()
mark = int(begin)
req = points.encode_request(mark, cat, team, score)
2009-08-20 16:20:44 -06:00
while True:
sock.send(req)
2009-08-21 13:27:17 -06:00
r, w, x = select.select([sock], [], [], begin + 2 - time.time())
if not r:
break
b = sock.recv(500)
try:
2009-08-20 16:20:44 -06:00
when, txt = points.decode_response(b)
2009-08-21 13:27:17 -06:00
except ValueError:
# Ignore invalid packets
continue
if when != mark:
# Ignore wrong timestamp
continue
if txt == 'OK':
return
else:
2009-08-20 16:20:44 -06:00
raise ValueError(txt)
2009-08-21 13:27:17 -06:00
2009-08-20 16:20:44 -06:00
def makesock(host):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((host, 6667))
return s
2009-08-20 12:51:47 -06:00
def main():
p = optparse.OptionParser(usage='%prog CATEGORY TEAM SCORE')
p.add_option('-s', '--host', dest='host', default='localhost',
help='Host to connect to')
opts, args = p.parse_args()
try:
cat, team, score = args
score = int(score)
except ValueError:
return p.print_usage()
2009-08-20 16:20:44 -06:00
s = makesock(opts.host)
2009-08-20 12:51:47 -06:00
2009-08-20 16:20:44 -06:00
try:
submit(s, cat, team, score)
except ValueError as err:
print(err)
raise
2009-08-20 12:51:47 -06:00
if __name__ == '__main__':
main()