otime-testing/otime.py

411 lines
16 KiB
Python
Raw Normal View History

import copy
2022-02-06 00:12:32 +00:00
import datetime
import csv
import re
import xml.etree.ElementTree as ET
2022-04-01 18:13:27 +00:00
from fpdf import FPDF
class event:
def __init__(self, eventid, name, **kwargs):
self.id = eventid
self.name = name
self.courses = []
self.o_classes = []
self.runners = []
self.card_punches= []
def add_course(self, *args):
for n in args:
self.courses.append(n)
def add_o_class(self, *args):
for n in args:
self.o_classes.append(n)
def add_runners(self, *args):
for n in args:
self.runners.append(n)
def import_ttime_cnf(self, ttime_file):
self.add_course(*courses_from_ttime_conf(ttime_file))
self.add_o_class(*classes_from_ttime_conf(ttime_file, self.courses))
def import_ttime_db(self, ttime_file):
2022-03-11 14:31:20 +00:00
csvreader = csv.reader(open(ttime_file, 'r', encoding='latin_1'), delimiter=';',)
runnerarray = []
for row in csvreader:
if len(row) == 0 or row[1] == '':
2022-03-11 14:31:20 +00:00
continue
runnerarray.append(runner.from_string(row, self.o_classes))
2022-03-11 14:31:20 +00:00
self.runners = runnerarray
def import_mtr_file(self, mtr_file):
2022-03-03 14:39:59 +00:00
self.card_punches = card_punch.list_from_mtr_f(mtr_file)
def match_runners_cards(self):
for n in self.runners:
for i in self.card_punches:
if n.card == i.card:
n.card_r = i
def get_xml_res(self):
root = ET.Element('ResultList')
root.set('xmlns', 'http://www.orienteering.org/datastandard/3.0')
root.set('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
root.set('iofVersion', '3.0')
root.set('createTime', datetime.datetime.now().isoformat(timespec='seconds'))
root.set('creator', 'oTime')
root.set('status', 'Complete')
tree = ET.ElementTree(root)
event = ET.SubElement(root, 'Event')
xml_child(event, 'Id', self.id)
xml_child(event, 'Name', self.name)
for i in self.o_classes:
#<ClassResult>
class_result = ET.SubElement(root, 'ClassResult')
#<Class>
t = ET.SubElement(class_result, 'Class')
xml_child(t, 'Name', i.name)
#<PersonResult>
runners_same_c = get_runners_in_class(self.runners, i)
runners_ranked = rank_runners(runners_same_c, i)
# Put the OK runners first and Active last
runners_sorted = [i for i in runners_same_c if i not in runners_ranked]
runners_ranked.extend(runners_sorted)
for n in runners_ranked:
person_result = ET.SubElement(class_result, 'PersonResult')
#<Person>
person = ET.SubElement(person_result, 'Person')
xml_child(person, 'Id', n.id)
#<Name>
name = ET.SubElement(person, 'Name')
xml_child(name, 'Family', n.last)
xml_child(name, 'Given', n.first)
#</Name>
#</Person>
#<Organisation>
org = ET.SubElement(person_result, 'Organisation')
xml_child(org, 'Id', '0')
xml_child(org, 'Name', n.club)
country = ET.SubElement(org, 'Country')
# TODO: hent land fra løperobjektet
country.text = 'Norway'
country.set('code', 'NOR')
#</Organisation>
#<Result>
result = ET.SubElement(person_result, 'Result')
if hasattr(n,'card_r') and len(n.card_r.splits) > 2:
xml_child(result, 'StartTime', n.card_r.s_time.isoformat())
xml_child(result, 'FinishTime', n.card_r.f_time.isoformat())
xml_child(result, 'Time', n.totaltime())
if n.status() == 'OK':
#<TimeBehind>
xml_child(result, 'TimeBehind', n.totaltime() - runners_ranked[0].totaltime())
#</TimeBehind>
xml_child(result, 'Position', n.rank(self.runners))
xml_child(result, 'Status', n.status())
#<SplitTime>
#TODO: ta utgangspunkt i løypa, ikke det brikka har stempla
for code,split in zip(n.card_r.controls,n.card_r.splits):
st = ET.SubElement(result, 'SplitTime')
xml_child(st, 'ControlCode', code)
xml_child(st, 'Time', split)
if code == n.o_class.course.codes[-1]:
break
#</SplitTime>
elif n.status() == 'Disqualified':
xml_child(result, 'Status', n.status())
for code in n.o_class.course.codes:
st = ET.SubElement(result, 'SplitTime')
xml_child(st, 'ControlCode', code)
for control,split in zip(n.card_r.controls,n.card_r.splits):
if code == control:
xml_child(st, 'Time', split)
else:
xml_child(result, 'Status', n.status())
else:
xml_child(result, 'Status', n.status())
#</Result>
#</PersonResult>
#</Class>
ET.indent(root, space=' ', level=0)
return tree
2022-04-01 18:13:27 +00:00
def create_start_list_pdf(self, file_name):
pdf = FPDF()
pdf.add_page()
pdf.add_font("DejaVuSans", fname="/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf")
pdf.set_font("DejaVuSans", size=10)
line_height = pdf.font_size * 2
col_width = pdf.epw / 4 # distribute content evenly
for runner in self.runners:
pdf.multi_cell(col_width, line_height, runner.fullname(), border=1, ln=3, max_line_height=pdf.font_size, align='L')
pdf.multi_cell(col_width, line_height, runner.o_class.name, border=1, ln=3, max_line_height=pdf.font_size)
pdf.multi_cell(col_width, line_height, str(runner.card), border=1, ln=3, max_line_height=pdf.font_size)
if runner.start_time != None:
pdf.multi_cell(col_width, line_height, str(runner.start_time), border=1, ln=3, max_line_height=pdf.font_size)
else:
pdf.multi_cell(col_width, line_height, '', border=1, ln=3, max_line_height=pdf.font_size)
pdf.ln(line_height)
pdf.output(file_name)
2022-02-06 00:12:32 +00:00
class runner:
2022-03-29 21:08:29 +00:00
def __init__(self, runner_id, first, last, club, country, card, o_class, start_time):
self.id = runner_id
2022-02-06 00:12:32 +00:00
self.first = first
self.last = last
self.club = club
self.country = country
self.card = card
self.o_class = o_class
2022-03-29 21:08:29 +00:00
self.start_time = start_time
def from_string(tt_line, o_classes):
2022-03-29 21:08:29 +00:00
#https://web.archive.org/web/20191229124046/http://wiki.ttime.no/index.php/Developer
eventorid = tt_line[0]
country = ''
name = tt_line[2].split(',')
try:
first = name[1].strip()
except:
first = ''
last = name[0]
try:
club = tt_line[4]
except:
club = "None"
try:
card = int(tt_line[6])
except:
card = 0
2022-03-26 21:18:05 +00:00
runner_o_class = None
try:
raw_class_str = tt_line[3]
except:
# VELDIG MIDLERTIDIG
runner_o_class = None
else:
if raw_class_str != '':
for i in o_classes:
if i.name == raw_class_str:
runner_o_class = i
break
else:
runner_o_class = None
# TODO: Gjør sånn at den lager nye o klasser om den ikke finnes fra før
2022-03-29 21:08:29 +00:00
try:
options = tt_line[5].split(',')
start_time = options[options.index('U')+1]
except:
start_time = None
return runner(eventorid, first, last, club, country, card, runner_o_class, start_time)
2022-02-14 06:41:31 +00:00
2022-02-06 00:12:32 +00:00
def fullname(self):
return '{} {}'.format(self.first, self.last)
def check_codes(self):
2022-02-10 19:42:01 +00:00
# Returns False if not ok and touple if ok
2022-03-26 21:18:05 +00:00
return contains(self.o_class.course.codes, list(self.card_r.controls))
def totaltime(self):
2022-03-03 16:50:53 +00:00
f_control = self.o_class.course.codes[-1]
try:
index = self.card_r.controls.index(f_control)
return self.card_r.splits[index]
2022-03-03 16:50:53 +00:00
except:
2022-04-10 18:25:33 +00:00
return 0
2022-02-10 19:42:01 +00:00
def status(self):
2022-03-11 14:31:20 +00:00
if hasattr(self, 'card_r') == False or self.o_class == None:
2022-02-10 19:42:01 +00:00
return 'Active'
elif self.check_codes():
return 'OK'
elif self.check_codes() == False:
return 'Disqualified'
2022-02-14 06:41:31 +00:00
def rank(self, allrunners):
c_ranked = rank_runners(allrunners, self.o_class)
return c_ranked.index(self) + 1
2022-02-14 18:03:13 +00:00
def res_splits(self):
splits_cpy = self.card_r.splits.copy()
for control in self.card_r.controls:
if control not in self.o_class.course.codes:
index = self.card_r.controls.index(control)
split = self.card_r.splits[index]
splits_cpy.remove(split)
return splits_cpy
2022-03-03 16:50:53 +00:00
class card_punch:
def __init__(self, card, controls, splits, read_time, s_time, f_time):
self.card = card
self.controls = controls
self.splits = splits
self.read_time = read_time
self.s_time = s_time
self.f_time = f_time
def __repr__(self):
return f'card({self.card}) controls({self.controls}) splits({self.splits})'
def from_mtr_bytes(datamsg):
card = int.from_bytes(datamsg[20:23], 'little')
#Extract codes and splits:
controls = []
splits = []
splits_offset = 26
code_numbytes = 1
time_numbytes = 2
split_numbytes = code_numbytes + time_numbytes
for split_index in range(50):
code_offset = splits_offset + split_index * split_numbytes
time_offset = code_offset + code_numbytes
code = int.from_bytes(datamsg[code_offset:code_offset+code_numbytes], 'little')
time = int.from_bytes(datamsg[time_offset:time_offset+time_numbytes], 'little')
if code != 0:
controls.append(code)
splits.append(time)
# Extract start time:
year = int.from_bytes(datamsg[8:9], 'little')
month = int.from_bytes(datamsg[9:10], 'little')
day = int.from_bytes(datamsg[10:11], 'little')
hours = int.from_bytes(datamsg[11:12], 'little')
minutes = int.from_bytes(datamsg[12:13], 'little')
seconds = int.from_bytes(datamsg[13:14], 'little')
milliseconds = int.from_bytes(datamsg[14:16], 'little')
read_time = datetime.datetime(year, month, day, hours, minutes, seconds, milliseconds)
if len(controls) > 2:
s_time = read_time - datetime.timedelta(seconds = splits[-1])
f_time = read_time - (datetime.timedelta(seconds = splits[-1]) + datetime.timedelta(seconds = splits[-2]))
else:
s_time = read_time
f_time = read_time
return(card_punch(card, controls, splits, read_time, s_time, f_time))
def list_from_mtr_f(mtr_f):
csvreader = csv.reader(open(mtr_f))
rows = []
cards = []
# hver rad er brikkenummer med tilhørende info
for row in csvreader:
if len(row) == 0:
continue
rows.append(row)
controls = []
splits = []
# postkodene kommer på oddetall fra og med den 11. De blir hevet inn i controls
for item in row[11::2]:
if item == '250':
controls.append(int(item))
break
elif item == '000':
break
else:
controls.append(int(item))
# strekktidene kommer på partall fra og med den 12. De blir hevet i splits.
for item in row[12::2]:
if item == '00000':
break
else:
splits.append(int(item))
# looper gjonnom løperobjektene og legger til poster og strekktider + start og sluttid
# usikker på om dette er riktig klokeslett
tl = row[5].split(' ')
tl[0] = tl[0].split('.')
tl[0][2] = '20' + tl[0][2]
tl[0] = list(map(int, tl[0]))
tl[1] = tl[1].split(':')
tl[1][2] = float(tl[1][2])
tl[1] = list(map(int, tl[1]))
read_time = datetime.datetime(tl[0][2], tl[0][1], tl[0][0], tl[1][0], tl[1][1], tl[1][2])
2022-03-11 14:31:20 +00:00
if len(controls) > 2:
s_time = read_time - datetime.timedelta(seconds = splits[-1])
f_time = read_time - (datetime.timedelta(seconds = splits[-1]) + datetime.timedelta(seconds = splits[-2]))
else:
s_time = read_time
f_time = read_time
cards.append(card_punch(int(row[6]), controls, splits, read_time, s_time, f_time))
return cards
2022-02-06 00:12:32 +00:00
class course:
def __init__(self, name, codes):
self.name = name
self.codes = codes
def __repr__(self):
return f'name({self.name})'
2022-02-06 00:12:32 +00:00
class o_class:
def __init__(self, name, course):
self.name = name
self.course = course
def __repr__(self):
return f'name({self.name})'
2022-02-06 00:12:32 +00:00
def courses_from_ttime_conf(ttime_file = 'sc_2021_ttime/ttime.cnf.txt'):
courses = []
2022-02-21 11:51:54 +00:00
conf = open(ttime_file, 'r', encoding='latin_1').readlines()
2022-02-06 00:12:32 +00:00
for line in conf:
if '-codes' in line:
code_list = re.search(r'(?<=\")(.*?)(?=\")', line).group().split(';')
loops = 0
for n in code_list:
n = n.split(',')
loops += 1
n = list(map(int, n))
2022-02-06 00:12:32 +00:00
courses.append(course('course_'+str(loops), n))
return courses
def classes_from_ttime_conf(ttime_file, courses):
o_classes = []
conf = open(ttime_file, 'r', encoding='latin_1').readlines()
2022-02-06 00:12:32 +00:00
for line in conf:
if '-courses' in line:
raw_courselist = re.search(r'(?<=\")(.*?)(?=\")', line).group().split(';')
loops = 0
for n in raw_courselist:
2022-03-26 21:18:05 +00:00
split = n.split(',')
for i in split:
2022-02-06 00:12:32 +00:00
o_classes.append(o_class(i,courses[loops]))
loops += 1
return o_classes
2022-02-09 20:44:13 +00:00
2022-02-14 06:41:31 +00:00
def contains(small, big):
2022-03-11 14:31:20 +00:00
# Checks if small list is in big list
valid = True
mark = 0
map_bl = []
for i in small:
for n,control in enumerate(big[mark:]):
if i == control:
mark += n
map_bl.append(mark)
break
else:
valid = False
if valid:
return map_bl
else:
return False
2022-02-14 06:41:31 +00:00
def get_runners_in_class(runners, o_class):
2022-03-11 14:31:20 +00:00
# Filters out runner objects that dont have the correct o_class
2022-02-10 19:42:01 +00:00
list_filtrd = []
for i in runners:
marker = 0
2022-02-10 19:42:01 +00:00
if i.o_class == o_class:
list_filtrd.append(i)
return list_filtrd
2022-02-14 06:41:31 +00:00
def rank_runners(allrunners, o_class):
runners = get_runners_in_class(allrunners, o_class)
runners_ranked = []
for i in runners:
if i.status() == 'OK':
runners_ranked.append(i)
runners_ranked.sort(key=lambda x: x.totaltime())
2022-02-14 06:41:31 +00:00
return runners_ranked
2022-02-18 10:01:55 +00:00
def xml_child(parent, tag, content):
2022-03-11 14:31:20 +00:00
# Used to make creating xml files easier
2022-02-18 10:01:55 +00:00
e = ET.SubElement(parent, tag)
e.text = str(content)