openwebrx-clone/owrx/map.py

149 lines
4.6 KiB
Python
Raw Normal View History

2019-07-07 13:52:24 +00:00
from datetime import datetime, timedelta
from owrx.config import Config
from owrx.bands import Band
import threading
import time
2020-01-05 17:41:46 +00:00
import sys
2019-07-07 13:52:24 +00:00
import logging
2019-07-07 13:52:24 +00:00
logger = logging.getLogger(__name__)
2020-03-26 19:13:36 +00:00
logger.setLevel(logging.INFO)
class Location(object):
def __dict__(self):
return {}
class Map(object):
sharedInstance = None
2020-01-05 17:41:46 +00:00
creationLock = threading.Lock()
@staticmethod
def getSharedInstance():
2020-01-05 17:41:46 +00:00
with Map.creationLock:
if Map.sharedInstance is None:
Map.sharedInstance = Map()
return Map.sharedInstance
def __init__(self):
self.clients = []
self.positions = {}
self.positionsLock = threading.Lock()
2019-07-07 13:52:24 +00:00
def removeLoop():
loops = 0
2019-07-07 13:52:24 +00:00
while True:
try:
self.removeOldPositions()
except Exception:
logger.exception("error while removing old map positions")
loops += 1
# rebuild the positions dictionary every once in a while, it consumes lots of memory otherwise
if loops == 60:
try:
self.rebuildPositions()
except Exception:
logger.exception("error while rebuilding positions")
loops = 0
2019-07-07 13:52:24 +00:00
time.sleep(60)
2020-08-14 18:22:25 +00:00
threading.Thread(target=removeLoop, daemon=True, name="map_removeloop").start()
super().__init__()
def broadcast(self, update):
for c in self.clients:
c.write_update(update)
def addClient(self, client):
self.clients.append(client)
client.write_update(
[
{
2022-11-30 00:07:16 +00:00
"source": record["source"],
"location": record["location"].__dict__(),
"lastseen": record["updated"].timestamp() * 1000,
"mode": record["mode"],
"band": record["band"].getName() if record["band"] is not None else None,
}
2022-11-30 00:07:16 +00:00
for record in self.positions.values()
]
)
def removeClient(self, client):
try:
self.clients.remove(client)
except ValueError:
pass
2022-11-30 00:07:16 +00:00
def _sourceToKey(self, source):
if "ssid" in source:
return "{callsign}-{ssid}".format(**source)
return source["callsign"]
def updateLocation(self, source, loc: Location, mode: str, band: Band = None):
2019-07-07 13:52:24 +00:00
ts = datetime.now()
2022-11-30 00:07:16 +00:00
key = self._sourceToKey(source)
with self.positionsLock:
2022-11-30 00:07:16 +00:00
self.positions[key] = {"source": source, "location": loc, "updated": ts, "mode": mode, "band": band}
self.broadcast(
[
{
2022-11-30 00:07:16 +00:00
"source": source,
"location": loc.__dict__(),
"lastseen": ts.timestamp() * 1000,
"mode": mode,
"band": band.getName() if band is not None else None,
}
]
)
2019-07-07 13:52:24 +00:00
2022-11-30 00:07:16 +00:00
def touchLocation(self, source):
# not implemented on the client side yet, so do not use!
ts = datetime.now()
2022-11-30 00:07:16 +00:00
key = self._sourceToKey(source)
with self.positionsLock:
2022-11-30 00:07:16 +00:00
if key in self.positions:
self.positions[key]["updated"] = ts
self.broadcast([{"source": source, "lastseen": ts.timestamp() * 1000}])
2022-11-30 00:07:16 +00:00
def removeLocation(self, key):
with self.positionsLock:
2022-11-30 00:07:16 +00:00
del self.positions[key]
# TODO broadcast removal to clients
2019-07-07 13:52:24 +00:00
def removeOldPositions(self):
pm = Config.get()
2019-07-07 13:52:24 +00:00
retention = timedelta(seconds=pm["map_position_retention_time"])
cutoff = datetime.now() - retention
2022-11-30 00:07:16 +00:00
to_be_removed = [key for (key, pos) in self.positions.items() if pos["updated"] < cutoff]
for key in to_be_removed:
self.removeLocation(key)
def rebuildPositions(self):
2020-01-05 17:41:46 +00:00
logger.debug("rebuilding map storage; size before: %i", sys.getsizeof(self.positions))
with self.positionsLock:
p = {key: value for key, value in self.positions.items()}
self.positions = p
2020-01-05 17:41:46 +00:00
logger.debug("rebuild complete; size after: %i", sys.getsizeof(self.positions))
class LatLngLocation(Location):
2019-09-18 16:50:48 +00:00
def __init__(self, lat: float, lon: float):
self.lat = lat
self.lon = lon
def __dict__(self):
res = {"type": "latlon", "lat": self.lat, "lon": self.lon}
return res
class LocatorLocation(Location):
def __init__(self, locator: str):
self.locator = locator
def __dict__(self):
return {"type": "locator", "locator": self.locator}