Commit 7c6582e9 authored by Mohd Bilal's avatar Mohd Bilal
Browse files

error handling added

parent 758d52fc
......@@ -5,7 +5,7 @@
"tle_l2": "",
"tle_source": "",
"planning_horizon": 86400,
"refresh_rate": 43200,
"refresh_rate": 43200000,
"plan":[
{
"contact_type": "TELEMETRY",
......
......@@ -5,7 +5,7 @@
"tle_l2": "",
"tle_source": "",
"planning_horizon": 86400,
"refresh_rate": 43200,
"refresh_rate": 43200000,
"plan":[
{
"contact_type": "TELEMETRY",
......
......@@ -7,7 +7,7 @@
"band_rx": "UHF",
"band_tx": "UHF",
"scheduling_horizon": 86400,
"refresh_rate": 43200,
"refresh_rate": 43200000,
"schedule": {
"timgsn": [
{
......
......@@ -50,9 +50,14 @@ class Satellite(ThreadedModule):
action['contact_type'])
logger.info(response)
responses.append(response)
logger.info(f"{self.name}: "
f"requested all overpasses in planning horizon")
logger.info(f"{self.name}: next request phase will start at "
f"{self.next_refresh_utc} UTC")
except Exception as err:
logger.debug(traceback.format_exc())
self.force_loop()
def _parse_json_data(self, data):
self.name = data.get("name")
......
......@@ -6,6 +6,7 @@ import config
import datetime
import requests
import logging
import traceback
import json
logger = logging.getLogger(__name__)
......@@ -28,8 +29,8 @@ class Station(ThreadedModule):
self.schedule = []
self.owner = None
self._is_setup = False
self.planning_horizon = kwargs[
'planning_horizon'] if 'planning_horizon' in kwargs else 86400
self.scheduling_horizon = kwargs[
'scheduling_horizon'] if 'scheduling_horizon' in kwargs else 86400
def __str__(self) -> str:
return f"Ground station: {self.name} | lat: {self.latitude} | long: {self.longitutde}"
......@@ -43,12 +44,24 @@ class Station(ThreadedModule):
logger.info(f"{self.name}: Stopping operation...")
def _loop(self):
received_requests = self.fetch_received_requests()
responses = []
for tracking_request in received_requests:
response = self.respond_to_request(tracking_request)
logger.info(response)
responses.append(response)
try:
start = datetime.datetime.utcnow()
end = datetime.datetime.utcnow() + datetime.timedelta(
seconds=self.scheduling_horizon)
received_requests = self.fetch_received_requests(start, end)
responses = []
for tracking_request in received_requests:
response = self.respond_to_request(tracking_request)
logger.info(response)
responses.append(response)
logger.info(f"{self.name}: "
f"responded to all requests in scheduling horizon")
logger.info(f"{self.name}: next response phase will start at "
f"{self.next_refresh_utc} UTC")
except Exception as err:
logger.debug(traceback.format_exc())
self.force_loop()
def respond_to_request(self, tracking_request):
request_uid = tracking_request['uid']
......@@ -60,28 +73,22 @@ class Station(ThreadedModule):
end = datetime.datetime.strptime(
overpass['end_date_str'] + ' ' + overpass['end_time_str'],
config.time_format)
satellite = self.owner.get_satellite(overpass['norad'])
busy = self.is_busy(start, end)
response = create_response(False, [], "No condition matched")
if status == "PENDING" and not busy:
response = self.accept_request(request_uid)
elif status == "ACCEPTED":
# do nothing
pass
elif status == "REJECTED" and not busy:
# if request is for the satellite of the owner, then always accept
if status == "PENDING" or status == "REJECTED" and satellite:
response = self.accept_request(request_uid)
elif status == "SCHEDULED":
# do nothing
pass
elif status == "FAILED":
# do nothing
pass
elif status == "DATA_UPLOADED":
# do nothing
pass
else:
# reject
response = self.reject_request(request_uid)
return response
## if some other user's satellite then check if busy
if busy and status == "PENDING" or status == "ACCEPTED" or status == "REJECTED":
response = self.reject_request()
elif not busy and status == "PENDING" or status == "REJECTED":
response = self.accept_request()
return response
def create_request_url(self, request_uid):
......@@ -173,7 +180,11 @@ class Station(ThreadedModule):
return response
@setup_required
def fetch_received_requests(self):
def fetch_received_requests(self, start=None, end=None):
if start is None:
start = datetime.datetime.utcnow()
if end is None:
end = start + datetime.timedelta(seconds=self.scheduling_horizon)
logger.info("fetching received requests...")
tracking_requests = [] # tracking requests for this station
data = {"direction": "received"}
......@@ -187,8 +198,22 @@ class Station(ThreadedModule):
filter(
lambda req: req['overpass']['station_name'] == self.name,
received_requests))
logger.info(f"fetched {len(received_requests)} received requests.")
return tracking_requests
def check_start_end(req):
req_start = datetime.datetime.strptime(
req['overpass']['start_time'], config.time_format)
req_end = datetime.datetime.strptime(
req['overpass']['end_time'], config.time_format)
check = False
if req_start >= start and req_end <= end:
check = True
return check
tracking_requests_se = filter(lambda req: check_start_end(req),
tracking_requests)
logger.info(f"fetched {len(tracking_requests_se)} "
"received requests.")
return tracking_requests_se
def set_owner(self, owner):
self.owner = owner
......
......@@ -2,7 +2,9 @@ import abc
import time
import threading
import logging
import datetime
timeformat = "%Y-%m-%d %H:%M:%S"
logger = logging.getLogger(__name__)
......@@ -30,6 +32,9 @@ class ThreadedModule(IThreadedModule, threading.Thread):
self.refresh_rate = kwargs['refresh_rate'] if 'refresh_rate' in kwargs else 1000
self.t_start = 0
self.last_refresh_time = 0
self.t_start_utc = None
self.last_refresh_utc = None
self.next_refresh_utc = None
def _set_up(self):
"""Set up the instance variables if any extra
......@@ -55,11 +60,14 @@ class ThreadedModule(IThreadedModule, threading.Thread):
def run(self):
self._set_up()
self.t_start = int(time.monotonic_ns()/1e6)
self.t_start_utc = datetime.datetime.utcnow()
while self.keep_alive:
try:
if int(time.monotonic_ns()/1e6) - self.last_refresh_time > self.refresh_rate:
logger.debug(f'{self.name}: starting')
self.last_refresh_time = int(time.monotonic_ns()/1e6)
self.last_refresh_utc = datetime.datetime.utcnow()
self.next_refresh_utc = self.last_refresh_utc + datetime.timedelta(seconds=int(self.refresh_rate/1e3))
self._loop()
except:
logger.info(f"An exception occurred in Thread: {self.name}.")
......@@ -68,4 +76,13 @@ class ThreadedModule(IThreadedModule, threading.Thread):
logger.info('Thread tear down requested. Cleaning up thread.')
self._tear_down()
logger.info('Thread cleanup finished.')
def force_loop(self):
if self.keep_alive:
self.last_refresh_time = int(time.monotonic_ns()/1e6)
self.last_refresh_utc = datetime.datetime.utcnow()
self.next_refresh_utc = self.last_refresh_utc + datetime.timedelta(seconds=int(self.refresh_rate/1e3))
self._loop()
else:
logger.info(f"{self.name}: Cannot force loop.")
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment