Skip to content

Commit

Permalink
bumped aircot dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
ampledata committed Jun 30, 2022
1 parent d4fe210 commit 4f56ed2
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 64 deletions.
1 change: 1 addition & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ The `adsbxcot` command-line program has 2 runtime arguments::
-h, --help show this help message and exit
-c CONFIG_FILE, --CONFIG_FILE CONFIG_FILE. Default: config.ini


Configuration
=============
Configuration parameters can be specified either via environment variables or in
Expand Down
2 changes: 1 addition & 1 deletion adsbxcot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
:source: <https://github.com/ampledata/adsbxcot>
"""

from .constants import LOG_FORMAT, LOG_LEVEL, DEFAULT_POLL_INTERVAL # NOQA
from .constants import DEFAULT_POLL_INTERVAL # NOQA

from .functions import adsbx_to_cot, create_tasks # NOQA

Expand Down
86 changes: 39 additions & 47 deletions adsbxcot/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@

import asyncio

from configparser import ConfigParser
from configparser import SectionProxy
from typing import Union

import aiohttp

Expand All @@ -38,12 +39,10 @@ class ADSBXWorker(pytak.QueueWorker):

"""Reads ADSBExchange.com ADS-B Data, renders to COT, and puts on Queue."""

def __init__(self, queue: asyncio.Queue, config: ConfigParser):
def __init__(self, queue: asyncio.Queue, config: SectionProxy) -> None:
super().__init__(queue, config)
_ = [x.setFormatter(adsbxcot.LOG_FORMAT) for x in self._logger.handlers]

self.known_craft = config.get("KNOWN_CRAFT")
self.known_craft_db = None
self.known_craft_db: Union[dict, None] = None
self.session: Union[aiohttp.ClientSession, None] = None

async def handle_data(self, data: list) -> None:
"""
Expand All @@ -57,28 +56,24 @@ async def handle_data(self, data: list) -> None:
self._logger.warning("Empty aircraft list")
return None

icao = None
_lac = len(data)
_acn = 1
lod = len(data)
i = 1
for craft in data:
icao = craft.get("hex", craft.get("icao")).strip().upper()
i += 1
if not isinstance(craft, dict):
self._logger.warning("Aircraft list item was not a Python `dict`.")
continue

if "~" in icao and not self.config.getboolean("INCLUDE_TISB"):
icao: str = craft.get("hex", craft.get("icao", ""))
if icao:
icao = icao.strip().upper()
else:
continue

known_craft = {}
if "~" in icao and not self.config.getboolean("INCLUDE_TISB"):
continue

if self.known_craft_db:
known_craft = (
list(
filter(
lambda x: x["HEX"].strip().upper() == icao,
self.known_craft_db,
)
)
or [{}]
)[0]
# self._logger.debug("known_craft='%s'", known_craft)
known_craft: dict = aircot.get_known_craft(self.known_craft_db, icao, "HEX")

# Skip if we're using known_craft CSV and this Craft isn't found:
if (
Expand All @@ -88,24 +83,16 @@ async def handle_data(self, data: list) -> None:
):
continue

event = adsbxcot.adsbx_to_cot(
event: Union[str, None] = adsbxcot.adsbx_to_cot(
craft, config=self.config, known_craft=known_craft
)

if not event:
self._logger.debug("Empty COT for craft=%s", craft)
_acn += 1
continue

self._logger.debug(
"Handling %s/%s %s %s",
_acn,
_lac,
craft.get("hex"),
craft.get("flight"),
)
self._logger.debug("Handling %s/%s ICAO: %s",i, lod, icao)
await self.put_queue(event)
_acn += 1

async def get_adsbx_feed(self, url: str) -> None:
"""
Expand All @@ -123,18 +110,22 @@ async def get_adsbx_feed(self, url: str) -> None:
else:
headers = {"api-auth": api_key}

async with aiohttp.ClientSession() as session:
response = await session.request(method="GET", url=url, headers=headers)
response.raise_for_status()
json_resp = await response.json()
data = json_resp.get("ac")
async with self.session.get(url=url, headers=headers) as resp:
if resp.status != 200:
response_content = await resp.text()
self._logger.error("Received HTTP Status %s for %s", resp.status, url)
self._logger.error(response_content)
return

if data:
aircraft_len = len(data)
else:
aircraft_len = "No"
self._logger.debug("Retrieved %s aircraft", aircraft_len)
json_resp = await resp.json()
if json_resp == None:
return

data = json_resp.get("ac")
if data == None:
return

self._logger.info("Retrieved %s aircraft messages.", str(len(data) or "No"))
await self.handle_data(data)

async def run(self, number_of_iterations=-1) -> None:
Expand All @@ -151,7 +142,8 @@ async def run(self, number_of_iterations=-1) -> None:
self._logger.info("Using KNOWN_CRAFT: %s", known_craft)
self.known_craft_db = aircot.read_known_craft(known_craft)

while 1:
self._logger.info("Polling every %ss: %s", poll_interval, url)
await self.get_adsbx_feed(url)
await asyncio.sleep(int(poll_interval))
async with aiohttp.ClientSession() as self.session:
while 1:
self._logger.info("%s polling every %ss: %s", self.__class__, poll_interval, url)
await self.get_adsbx_feed(url)
await asyncio.sleep(int(poll_interval))
13 changes: 0 additions & 13 deletions adsbxcot/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,4 @@
__license__ = "Apache License, Version 2.0"


if bool(os.environ.get("DEBUG")):
LOG_LEVEL = logging.DEBUG
LOG_FORMAT = logging.Formatter(
(
"%(asctime)s adsbxcot %(levelname)s %(name)s.%(funcName)s:%(lineno)d "
" - %(message)s"
)
)
logging.debug("adsbxcot Debugging Enabled via DEBUG Environment Variable.")
else:
LOG_LEVEL = logging.INFO
LOG_FORMAT = logging.Formatter(("%(asctime)s adsbxcot %(levelname)s - %(message)s"))

DEFAULT_POLL_INTERVAL: int = 30
21 changes: 18 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2022 Greg Albrecht <oss@undef.net>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author:: Greg Albrecht W2GMD <oss@undef.net>
#

"""ADSBXCOT Setup.
Source:: https://github.com/ampledata/adsbxcot
Expand All @@ -11,7 +26,7 @@
import setuptools

__title__ = "adsbxcot"
__version__ = "5.0.2"
__version__ = "5.0.3"
__author__ = "Greg Albrecht W2GMD <oss@undef.net>"
__copyright__ = "Copyright 2022 Greg Albrecht"
__license__ = "Apache License, Version 2.0"
Expand Down Expand Up @@ -46,7 +61,7 @@ def publish():
include_package_data=True,
install_requires=[
"pytak >= 5.0.0",
"aircot",
"aircot >= 1.2.0",
"aiohttp",
],
classifiers=[
Expand Down

0 comments on commit 4f56ed2

Please sign in to comment.