Skip to content

Commit

Permalink
Implement MopClient.send_punch
Browse files Browse the repository at this point in the history
  • Loading branch information
lukipuki committed Oct 29, 2023
1 parent ca573ce commit 4b9d6bc
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
4 changes: 4 additions & 0 deletions src/yaroc/clients/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ class Client(ABC):
If the client fails to connect or access a device, it should not crash, but maybe try later.
"""

@abstractmethod
async def loop(self):
pass

@abstractmethod
async def send_punch(
self,
Expand Down
40 changes: 35 additions & 5 deletions src/yaroc/clients/mop.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import logging
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from datetime import timedelta
from datetime import datetime, timedelta
from typing import List

import aiohttp
Expand Down Expand Up @@ -136,8 +136,7 @@ def _result_to_xml(result: MeosResult) -> ET.Element:
return root

async def loop(self):
timeout = aiohttp.ClientTimeout(total=20)
self.session = aiohttp.ClientSession(timeout)
self.session = aiohttp.ClientSession()
async with self.session:
await asyncio.sleep(1000000)

Expand All @@ -146,7 +145,36 @@ def results_from_file(filename: str) -> List[MeosResult]:
xml = ET.parse(filename)
return MopClient._results_from_meos_xml(xml.getroot())

async def send_result(self, result: MeosResult):
async def send_punch(
self,
card_number: int,
sitime: datetime,
code: int,
mode: int,
process_time: datetime | None = None,
) -> bool:
sitime.replace(microsecond=0)
idx = -1
for i, res in enumerate(self.results):
if res.competitor.card == card_number:
idx = i

if idx != -1:
result = self.results[idx]
sitime_midnight = sitime.replace(hour=0, minute=0, second=0)
tim = sitime - sitime_midnight
if code == 1:
result.start = tim
elif code == 2:
result.time = tim - result.start
result.stat = MopClient.STAT_OK
return await self.send_result(result)
else:
logging.error("Competitor with card {card_number} not in database")
return False
# TODO: log to a file

async def send_result(self, result: MeosResult) -> bool:
root = ET.Element("MOPDiff", {"xmlns": "http://www.melin.nu/mop"})
root.append(MopClient._result_to_xml(result))
headers = {"pwd": self.api_key}
Expand All @@ -157,9 +185,11 @@ async def send_result(self, result: MeosResult):
) as response:
if response.status == 200:
logging.info("Sending to OResults successful")
logging.debug("Response: {} {}", response, await response.text())
logging.debug("Response: {} {}", response.headers, await response.text())
return True
else:
logging.error("Sending unsuccessful: {} {}", response, await response.text())
return False
except Exception as e:
logging.error(f"MOP error: {e}")
return False
Expand Down

0 comments on commit 4b9d6bc

Please sign in to comment.