2020-12-17 10:00:47 -05:00
|
|
|
import logging
|
2020-12-24 12:39:48 -05:00
|
|
|
import select
|
2020-12-17 10:00:47 -05:00
|
|
|
import time
|
|
|
|
|
|
|
|
import aprslib
|
2021-01-11 12:43:51 -05:00
|
|
|
from aprslib import is_py3
|
2021-04-01 23:12:25 -04:00
|
|
|
from aprslib.exceptions import (
|
2021-08-23 12:14:19 -04:00
|
|
|
ConnectionDrop, ConnectionError, GenericError, LoginError, ParseError,
|
2021-04-01 23:12:25 -04:00
|
|
|
UnknownFormat,
|
|
|
|
)
|
2020-12-17 10:00:47 -05:00
|
|
|
|
2021-08-23 12:14:19 -04:00
|
|
|
import aprsd
|
|
|
|
from aprsd import stats
|
|
|
|
|
|
|
|
|
2020-12-17 10:00:47 -05:00
|
|
|
LOG = logging.getLogger("APRSD")
|
|
|
|
|
|
|
|
|
2021-01-08 15:47:30 -05:00
|
|
|
class Client:
|
2020-12-17 10:00:47 -05:00
|
|
|
"""Singleton client class that constructs the aprslib connection."""
|
|
|
|
|
|
|
|
_instance = None
|
|
|
|
aprs_client = None
|
|
|
|
config = None
|
|
|
|
|
2021-01-12 09:31:04 -05:00
|
|
|
connected = False
|
2021-03-30 10:43:31 -04:00
|
|
|
server_string = None
|
2021-01-12 09:31:04 -05:00
|
|
|
|
2020-12-17 10:00:47 -05:00
|
|
|
def __new__(cls, *args, **kwargs):
|
|
|
|
"""This magic turns this into a singleton."""
|
|
|
|
if cls._instance is None:
|
2021-01-08 15:47:30 -05:00
|
|
|
cls._instance = super().__new__(cls)
|
2020-12-17 10:00:47 -05:00
|
|
|
# Put any initialization here.
|
|
|
|
return cls._instance
|
|
|
|
|
|
|
|
def __init__(self, config=None):
|
|
|
|
"""Initialize the object instance."""
|
|
|
|
if config:
|
|
|
|
self.config = config
|
|
|
|
|
2021-05-03 10:28:31 -04:00
|
|
|
def new(self):
|
|
|
|
obj = super().__new__(Client)
|
|
|
|
obj.config = self.config
|
|
|
|
return obj
|
|
|
|
|
2020-12-17 10:00:47 -05:00
|
|
|
@property
|
|
|
|
def client(self):
|
|
|
|
if not self.aprs_client:
|
|
|
|
self.aprs_client = self.setup_connection()
|
|
|
|
return self.aprs_client
|
|
|
|
|
|
|
|
def reset(self):
|
|
|
|
"""Call this to force a rebuild/reconnect."""
|
|
|
|
del self.aprs_client
|
|
|
|
|
|
|
|
def setup_connection(self):
|
|
|
|
user = self.config["aprs"]["login"]
|
|
|
|
password = self.config["aprs"]["password"]
|
|
|
|
host = self.config["aprs"].get("host", "rotate.aprs.net")
|
|
|
|
port = self.config["aprs"].get("port", 14580)
|
|
|
|
connected = False
|
2020-12-20 12:14:51 -05:00
|
|
|
backoff = 1
|
2020-12-17 10:00:47 -05:00
|
|
|
while not connected:
|
|
|
|
try:
|
|
|
|
LOG.info("Creating aprslib client")
|
2020-12-24 12:39:48 -05:00
|
|
|
aprs_client = Aprsdis(user, passwd=password, host=host, port=port)
|
2020-12-17 10:00:47 -05:00
|
|
|
# Force the logging to be the same
|
|
|
|
aprs_client.logger = LOG
|
|
|
|
aprs_client.connect()
|
|
|
|
connected = True
|
2020-12-20 12:14:51 -05:00
|
|
|
backoff = 1
|
2021-01-12 09:31:04 -05:00
|
|
|
except LoginError as e:
|
2021-08-23 12:14:19 -04:00
|
|
|
LOG.error(f"Failed to login to APRS-IS Server '{e}'")
|
2021-01-12 09:31:04 -05:00
|
|
|
connected = False
|
|
|
|
raise e
|
2020-12-17 10:00:47 -05:00
|
|
|
except Exception as e:
|
2021-08-23 12:14:19 -04:00
|
|
|
LOG.error(f"Unable to connect to APRS-IS server. '{e}' ")
|
2020-12-20 12:14:51 -05:00
|
|
|
time.sleep(backoff)
|
|
|
|
backoff = backoff * 2
|
2020-12-17 10:00:47 -05:00
|
|
|
continue
|
2021-08-23 12:14:19 -04:00
|
|
|
LOG.debug(f"Logging in to APRS-IS with user '{user}'")
|
2020-12-17 10:00:47 -05:00
|
|
|
return aprs_client
|
|
|
|
|
|
|
|
|
2020-12-24 12:39:48 -05:00
|
|
|
class Aprsdis(aprslib.IS):
|
|
|
|
"""Extend the aprslib class so we can exit properly."""
|
|
|
|
|
|
|
|
# flag to tell us to stop
|
|
|
|
thread_stop = False
|
|
|
|
|
|
|
|
# timeout in seconds
|
2021-08-24 13:31:33 -04:00
|
|
|
select_timeout = 1
|
2020-12-24 12:39:48 -05:00
|
|
|
|
|
|
|
def stop(self):
|
|
|
|
self.thread_stop = True
|
2020-12-29 10:31:16 -05:00
|
|
|
LOG.info("Shutdown Aprsdis client.")
|
2020-12-24 12:39:48 -05:00
|
|
|
|
2021-02-25 21:01:52 -05:00
|
|
|
def send(self, msg):
|
|
|
|
"""Send an APRS Message object."""
|
|
|
|
line = str(msg)
|
|
|
|
self.sendall(line)
|
|
|
|
|
2020-12-24 12:39:48 -05:00
|
|
|
def _socket_readlines(self, blocking=False):
|
|
|
|
"""
|
|
|
|
Generator for complete lines, received from the server
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
self.sock.setblocking(0)
|
2021-01-08 15:47:30 -05:00
|
|
|
except OSError as e:
|
2021-08-23 12:14:19 -04:00
|
|
|
self.logger.error(f"socket error when setblocking(0): {str(e)}")
|
2020-12-24 12:39:48 -05:00
|
|
|
raise aprslib.ConnectionDrop("connection dropped")
|
|
|
|
|
|
|
|
while not self.thread_stop:
|
|
|
|
short_buf = b""
|
|
|
|
newline = b"\r\n"
|
|
|
|
|
|
|
|
# set a select timeout, so we get a chance to exit
|
|
|
|
# when user hits CTRL-C
|
|
|
|
readable, writable, exceptional = select.select(
|
2021-01-08 15:47:30 -05:00
|
|
|
[self.sock],
|
|
|
|
[],
|
|
|
|
[],
|
|
|
|
self.select_timeout,
|
2020-12-24 12:39:48 -05:00
|
|
|
)
|
|
|
|
if not readable:
|
2021-08-27 15:10:37 -04:00
|
|
|
if not blocking:
|
|
|
|
#self.logger.warning("not fucking readable, not blocking, break!")
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
#self.logger.warning("not fucking readable, continue")
|
|
|
|
continue
|
2020-12-24 12:39:48 -05:00
|
|
|
|
|
|
|
try:
|
|
|
|
short_buf = self.sock.recv(4096)
|
|
|
|
|
|
|
|
# sock.recv returns empty if the connection drops
|
|
|
|
if not short_buf:
|
2021-08-26 20:58:07 -04:00
|
|
|
if not blocking:
|
|
|
|
# We could just not be blocking, so empty is expected
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
self.logger.error("socket.recv(): returned empty")
|
|
|
|
raise aprslib.ConnectionDrop("connection dropped")
|
2021-01-08 15:47:30 -05:00
|
|
|
except OSError as e:
|
2020-12-24 12:39:48 -05:00
|
|
|
# self.logger.error("socket error on recv(): %s" % str(e))
|
|
|
|
if "Resource temporarily unavailable" in str(e):
|
|
|
|
if not blocking:
|
|
|
|
if len(self.buf) == 0:
|
|
|
|
break
|
|
|
|
|
|
|
|
self.buf += short_buf
|
|
|
|
|
|
|
|
while newline in self.buf:
|
|
|
|
line, self.buf = self.buf.split(newline, 1)
|
|
|
|
|
|
|
|
yield line
|
|
|
|
|
2021-01-11 12:43:51 -05:00
|
|
|
def _send_login(self):
|
|
|
|
"""
|
|
|
|
Sends login string to server
|
|
|
|
"""
|
|
|
|
login_str = "user {0} pass {1} vers github.com/craigerl/aprsd {3}{2}\r\n"
|
|
|
|
login_str = login_str.format(
|
|
|
|
self.callsign,
|
|
|
|
self.passwd,
|
|
|
|
(" filter " + self.filter) if self.filter != "" else "",
|
|
|
|
aprsd.__version__,
|
|
|
|
)
|
|
|
|
|
|
|
|
self.logger.info("Sending login information")
|
|
|
|
|
|
|
|
try:
|
|
|
|
self._sendall(login_str)
|
|
|
|
self.sock.settimeout(5)
|
|
|
|
test = self.sock.recv(len(login_str) + 100)
|
|
|
|
if is_py3:
|
|
|
|
test = test.decode("latin-1")
|
|
|
|
test = test.rstrip()
|
|
|
|
|
|
|
|
self.logger.debug("Server: %s", test)
|
|
|
|
|
2021-03-30 10:43:31 -04:00
|
|
|
a, b, callsign, status, e = test.split(" ", 4)
|
|
|
|
s = e.split(",")
|
|
|
|
if len(s):
|
|
|
|
server_string = s[0].replace("server ", "")
|
|
|
|
else:
|
|
|
|
server_string = e.replace("server ", "")
|
|
|
|
|
2021-08-23 12:14:19 -04:00
|
|
|
self.logger.info(f"Connected to {server_string}")
|
2021-03-30 10:43:31 -04:00
|
|
|
self.server_string = server_string
|
2021-04-01 23:12:25 -04:00
|
|
|
stats.APRSDStats().set_aprsis_server(server_string)
|
2021-01-11 12:43:51 -05:00
|
|
|
|
|
|
|
if callsign == "":
|
|
|
|
raise LoginError("Server responded with empty callsign???")
|
|
|
|
if callsign != self.callsign:
|
2021-08-23 12:14:19 -04:00
|
|
|
raise LoginError(f"Server: {test}")
|
2021-01-11 12:43:51 -05:00
|
|
|
if status != "verified," and self.passwd != "-1":
|
|
|
|
raise LoginError("Password is incorrect")
|
|
|
|
|
|
|
|
if self.passwd == "-1":
|
|
|
|
self.logger.info("Login successful (receive only)")
|
|
|
|
else:
|
|
|
|
self.logger.info("Login successful")
|
|
|
|
|
|
|
|
except LoginError as e:
|
|
|
|
self.logger.error(str(e))
|
|
|
|
self.close()
|
|
|
|
raise
|
2021-04-01 23:12:25 -04:00
|
|
|
except Exception as e:
|
2021-01-11 12:43:51 -05:00
|
|
|
self.close()
|
2021-08-23 12:14:19 -04:00
|
|
|
self.logger.error(f"Failed to login '{e}'")
|
2021-01-11 12:43:51 -05:00
|
|
|
raise LoginError("Failed to login")
|
|
|
|
|
2021-04-01 23:12:25 -04:00
|
|
|
def consumer(self, callback, blocking=True, immortal=False, raw=False):
|
|
|
|
"""
|
|
|
|
When a position sentence is received, it will be passed to the callback function
|
|
|
|
|
|
|
|
blocking: if true (default), runs forever, otherwise will return after one sentence
|
|
|
|
You can still exit the loop, by raising StopIteration in the callback function
|
|
|
|
|
|
|
|
immortal: When true, consumer will try to reconnect and stop propagation of Parse exceptions
|
|
|
|
if false (default), consumer will return
|
|
|
|
|
|
|
|
raw: when true, raw packet is passed to callback, otherwise the result from aprs.parse()
|
|
|
|
"""
|
|
|
|
|
|
|
|
if not self._connected:
|
|
|
|
raise ConnectionError("not connected to a server")
|
|
|
|
|
|
|
|
line = b""
|
|
|
|
|
2021-08-27 15:10:37 -04:00
|
|
|
while True and not self.thread_stop:
|
2021-04-01 23:12:25 -04:00
|
|
|
try:
|
|
|
|
for line in self._socket_readlines(blocking):
|
|
|
|
if line[0:1] != b"#":
|
|
|
|
if raw:
|
|
|
|
callback(line)
|
|
|
|
else:
|
|
|
|
callback(self._parse(line))
|
|
|
|
else:
|
|
|
|
self.logger.debug("Server: %s", line.decode("utf8"))
|
|
|
|
stats.APRSDStats().set_aprsis_keepalive()
|
|
|
|
except ParseError as exp:
|
2021-08-13 10:31:45 -04:00
|
|
|
self.logger.log(
|
|
|
|
11,
|
|
|
|
"%s\n Packet: %s",
|
|
|
|
exp,
|
|
|
|
exp.packet,
|
|
|
|
)
|
2021-04-01 23:12:25 -04:00
|
|
|
except UnknownFormat as exp:
|
2021-08-13 10:31:45 -04:00
|
|
|
self.logger.log(
|
|
|
|
9,
|
|
|
|
"%s\n Packet: %s",
|
|
|
|
exp,
|
|
|
|
exp.packet,
|
|
|
|
)
|
2021-04-01 23:12:25 -04:00
|
|
|
except LoginError as exp:
|
2021-08-13 10:31:45 -04:00
|
|
|
self.logger.error("%s: %s", exp.__class__.__name__, exp)
|
2021-04-01 23:12:25 -04:00
|
|
|
except (KeyboardInterrupt, SystemExit):
|
|
|
|
raise
|
|
|
|
except (ConnectionDrop, ConnectionError):
|
|
|
|
self.close()
|
|
|
|
|
|
|
|
if not immortal:
|
|
|
|
raise
|
|
|
|
else:
|
|
|
|
self.connect(blocking=blocking)
|
|
|
|
continue
|
|
|
|
except GenericError:
|
|
|
|
pass
|
|
|
|
except StopIteration:
|
|
|
|
break
|
|
|
|
except Exception:
|
|
|
|
self.logger.error("APRS Packet: %s", line)
|
|
|
|
raise
|
|
|
|
|
|
|
|
if not blocking:
|
2021-08-27 15:10:37 -04:00
|
|
|
#self.logger.error("Not blocking, bail bitch")
|
2021-04-01 23:12:25 -04:00
|
|
|
break
|
2021-08-27 15:10:37 -04:00
|
|
|
#self.logger.error("Consumer exiting")
|
2021-04-01 23:12:25 -04:00
|
|
|
|
2020-12-24 12:39:48 -05:00
|
|
|
|
2020-12-17 10:00:47 -05:00
|
|
|
def get_client():
|
|
|
|
cl = Client()
|
|
|
|
return cl.client
|