79 lines
2.2 KiB
Python
79 lines
2.2 KiB
Python
import time
|
|
import logging
|
|
import os
|
|
from configparser import ConfigParser
|
|
from pathlib import Path
|
|
from initialise_app import initialise_app
|
|
from bandwidth import measure as measure_bandwidth
|
|
from database import connect
|
|
|
|
|
|
# load default values
|
|
config = ConfigParser()
|
|
config.read(Path(__file__).parent / 'defaults.ini')
|
|
REPLICATES = int(config.get('main', 'replicates'))
|
|
USER_ID = int(config.get('main', 'user_id'))
|
|
TRIGGER_INTERVAL_SECONDS = float(
|
|
config.get(
|
|
'main',
|
|
'trigger_interval_seconds'
|
|
)
|
|
)
|
|
|
|
|
|
def event(
|
|
replicates: int = REPLICATES,
|
|
user_id: int = USER_ID
|
|
):
|
|
logging.debug('started event')
|
|
# load environment variables
|
|
replicates = int(os.getenv('REPLICATES', default=REPLICATES))
|
|
user_id = int(os.getenv('USER_ID', default=USER_ID))
|
|
# setup database connection
|
|
db = connect()
|
|
# run event
|
|
for rep_num in range(replicates):
|
|
logging.info(f'running replicate {rep_num}')
|
|
# do measurement
|
|
try:
|
|
res = measure_bandwidth()
|
|
except Exception as e:
|
|
logging.error(f'failed to measure bandwidth: {e}')
|
|
continue
|
|
# upload result to database
|
|
payload_dict = {
|
|
'user_id': user_id,
|
|
'data': res
|
|
}
|
|
try:
|
|
db_id = db.insert_one(payload_dict).inserted_id
|
|
except Exception as e:
|
|
logging.error(f'failed sending results to database: {e}')
|
|
continue
|
|
logging.debug(f'data sent to database received db_id: {db_id}')
|
|
time.sleep(1)
|
|
logging.debug('finished')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
initialise_app()
|
|
trigger_time = time.time()
|
|
while True:
|
|
if time.time() >= trigger_time:
|
|
# set new trigger time
|
|
trigger_interval = float(
|
|
os.getenv(
|
|
'TRIGGER_INTERVAL_SECONDS',
|
|
default=TRIGGER_INTERVAL_SECONDS
|
|
)
|
|
)
|
|
trigger_time += trigger_interval
|
|
# run event
|
|
try:
|
|
event()
|
|
except Exception as e:
|
|
logging.error(e)
|
|
else:
|
|
logging.info('finished event')
|
|
time.sleep(1)
|