-
Notifications
You must be signed in to change notification settings - Fork 0
/
notify.py
executable file
·187 lines (144 loc) · 5.98 KB
/
notify.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/env python3
"""Given ADS-B data, send notifications to users if a HEMS is heading
towards one of the user defined destinations within a certain distance.
"""
import argparse
import sys
import json
import re
import subprocess
from pathlib import Path
from gcmath import (
LatLon,
calc_bearing,
calc_distance,
)
TRACK_DEVIATION = 5 # degrees
MAX_DISTANCE = 70 # km
def get_user_settings(path):
"""Return user settings from JSON file"""
# pylint: disable=redefined-outer-name
try:
with open(path, "r", encoding="utf-8") as settings:
return json.load(settings)
except FileNotFoundError:
pass # for now...
except json.JSONDecodeError as ex:
print(f"{ex}:\n{settings}", file=sys.stderr)
return []
def format_flight_params(alt: float, vrate: float, distance: float, speed: float):
"""Format flight parameters for the notification to be sent"""
if int == type(alt):
result = f"alt {float(alt) * 0.3048:.0f}m"
elif float == type(alt):
result = f"alt {alt * 0.3048:.0f}m"
elif str == type(alt):
result = f"alt {alt}"
else:
result = ""
if len(result):
if int == type(vrate):
result += f"{float(vrate) * 0.3048:+.0f}"
elif float == type(vrate):
result += f"{vrate * 0.3048:+.0f}"
if len(result):
result += ", "
result += f"dist {distance:.0f}km"
if int == type(speed) or str == type(speed):
speed = float(speed)
if float == type(speed) and speed:
speed = speed * 1.852
eta = distance / speed * 60
mins = int(eta)
eta -= mins
eta *= 60
secs = int(eta)
eta = f"eta {mins:02d}:{secs:02d} min"
result += f", speed {speed:.0f}km/h eta {eta}"
return result
def get_notifications(data: list[list], settings: list[dict]) -> list[dict]:
"""Iterate over adsb data to determine whether HEMS are heading towards
user locations by calculating bearing and distance for each combination.
Return a list of notifications"""
# pylint: disable=redefined-outer-name
# pylint: disable=too-many-locals
# pylint: disable=too-many-nested-blocks
notifications = []
try:
for state in data:
# squawk is currently not needed, -> _
icao, callsign, reg, _, lat, lon, alt, vrate, track, speed = state
if track is not None:
if alt is None:
alt = "unknown"
if alt != "ground":
for user in settings:
receipient, locations = user["phone"], user["locations"]
for loc in locations:
location, pos = loc["name"], LatLon(loc["lat"], loc["lon"])
bearing = calc_bearing(LatLon(lat, lon), pos)
deviation = bearing - track
# Catch track/bearing wrapping around 0°
deviation = (deviation + 180.0) % 360.0 - 180.0
if abs(deviation) <= TRACK_DEVIATION:
dist = calc_distance(LatLon(lat, lon), pos)
if dist <= MAX_DISTANCE:
params = format_flight_params(
alt, vrate, dist, speed
)
callsign = (
re.sub(" *$", " ", callsign) if callsign else ""
)
message = (
f"{callsign}{reg}\n"
f"{location}\n"
f"{params}\n"
f"https://globe.adsbexchange.com/?icao={icao}"
)
notifications.append(
{
"receipient": receipient,
"message": message,
}
)
except ValueError as exception:
print(f"{exception}: {state}", file=sys.stderr)
return notifications
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--stdout", action="store_true")
args, files = parser.parse_known_args()
try:
scriptdir = Path(__file__).parent
filename = scriptdir / "notify.json"
with open(filename, "r", encoding="utf-8") as file:
settings = json.load(file)
for filename in files:
with open(filename, "r", encoding="utf-8") as file:
adsb = json.load(file)
notifications = get_notifications(adsb["states"], settings)
if args.stdout:
if notifications:
print(f"=== {filename} ===\n")
for notification in notifications:
print(
f"*** {notification['receipient']} ***\n"
f"{notification['message']}\n"
)
else:
for notification in notifications:
subprocess.call(
[
"signal-cli",
"send",
"-m",
notification["message"],
notification["receipient"],
],
stdout=subprocess.DEVNULL,
timeout=15,
)
except FileNotFoundError as exception:
print(f"{exception}", file=sys.stderr)
except json.JSONDecodeError as exception:
print(f"'{filename}': {exception}", file=sys.stderr)