123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- """General function module"""
- import random
- from datetime import datetime, timedelta
- from app import LOGGER, SCHEDULER, RESOURCE_IDS, RESOURCE_MAX, jobs, api
- def check_resources(resource_id):
- """Check resources and refill if necessary"""
- regions = api.download_resources(resource_id)
- LOGGER.info('Check resource %s', RESOURCE_IDS[resource_id])
- print_resources(regions, resource_id)
- refill_percentage = 25
- if need_refill(regions, refill_percentage):
- max_seconds = max_refill_seconds(regions, refill_percentage, 900)
- random_seconds = random.randint(0, max_seconds)
- random_time_delta = timedelta(seconds=random_seconds)
- scheduled_date = datetime.now() + random_time_delta
- job_id = 'refill_{}'.format(resource_id)
- LOGGER.info(
- 'Refill resource %s at %s (%s minutes)', RESOURCE_IDS[resource_id],
- scheduled_date, round(random_time_delta.seconds / 60)
- )
- SCHEDULER.add_job(
- jobs.refill_resource,
- 'date',
- args=[resource_id],
- id=job_id,
- run_date=scheduled_date,
- replace_existing=True
- )
- def print_resources(regions, resource_id):
- """print resources"""
- if regions:
- LOGGER.info('----- %s region(s)', len(regions))
- LOGGER.info('region expl max D left c % t %')
- for region in regions.values():
- region['explored_percentage'] = 100 / region['maximum'] * region['explored']
- region['total_left'] = region['explored'] + region['limit_left']
- region['total_percentage'] = 100 / RESOURCE_MAX[resource_id] * region['total_left']
- row = '{:25}: {:7.2f}{:4}{:4}{:5}{:7.2f}{:7.2f}'.format(
- region['region_name'], region['explored'], region['maximum'],
- region['deep_exploration'], region['limit_left'],
- region['explored_percentage'], region['total_percentage']
- )
- LOGGER.info(row)
- LOGGER.info('-----')
- else:
- LOGGER.error('no region to print data')
- def need_refill(regions, limit):
- """Check if refill is needed"""
- for region in regions.values():
- percentage = 100 / region['maximum'] * region['explored']
- if percentage < limit and region['limit_left']:
- return True
- return False
- def max_refill_seconds(regions, limit, max_time):
- """Give random seconds for next refill"""
- lowest_percentage = limit
- for region in regions.values():
- percentage = 100 / region['maximum'] * region['explored']
- if percentage < lowest_percentage:
- lowest_percentage = percentage
- return int(max_time / limit * lowest_percentage)
|