adsms/adsms.py

86 lines
2.0 KiB
Python
Raw Normal View History

2023-05-04 12:39:37 -07:00
#!/usr/bin/env python3
2023-05-04 19:09:20 -07:00
# Partially written with ChatGPT
2023-05-04 12:35:25 -07:00
import os
import time
import json
import sqlite3
import argparse
import requests
2023-05-04 19:09:20 -07:00
def load_config(config_file):
with open(config_file) as f:
return json.load(f)
2023-05-04 12:35:25 -07:00
2023-05-04 19:09:20 -07:00
def load_database(config):
2023-05-04 12:35:25 -07:00
con = sqlite3.connect(config["database"])
con.execute(
"CREATE TABLE IF NOT EXISTS subscriptions(phone VARCHAR, icao VARCHAR, description VARCHAR, last_seen INTEGER)"
)
con.commit()
2023-05-04 19:09:20 -07:00
return con
def update_last_seen_time(con, sub_id):
con.execute(
"UPDATE subscriptions SET last_seen = ? WHERE rowid = ?", (time.time(), sub_id)
)
def send_text_message(phone, message, key):
request = {"phone": phone, "message": message, "key": key}
resp = requests.post("https://textbelt.com/text", request)
print(resp.json())
2023-05-04 12:35:25 -07:00
2023-05-04 19:09:20 -07:00
def process_subscriptions(con, config, data):
cur = con.execute(
"SELECT rowid, phone, icao, description, last_seen FROM subscriptions"
)
for sub_id, phone, icao, description, last_seen in cur.fetchall():
if icao in data and data[icao]["seen"] < config["max_age"]:
if last_seen + config["min_disappearance"] < time.time():
message = f"{description}\n{config['tracker']}?icao={icao}"
2023-05-04 12:35:25 -07:00
2023-05-04 19:09:20 -07:00
send_text_message(phone, message, config["textbelt_key"])
2023-05-04 12:35:25 -07:00
2023-05-04 19:09:20 -07:00
print(f"{phone}: {message}")
2023-05-04 12:35:25 -07:00
2023-05-04 19:09:20 -07:00
update_last_seen_time(con, sub_id)
2023-05-04 12:35:25 -07:00
2023-05-04 19:09:20 -07:00
con.commit()
def get_current_data(config):
response = requests.get(config["data"])
planes = response.json()["aircraft"]
return {plane["hex"]: plane for plane in planes}
def run(config):
con = load_database(config)
while True:
data = get_current_data(config)
process_subscriptions(con, config, data)
2023-05-04 12:35:25 -07:00
time.sleep(config["delay"])
2023-05-04 19:09:20 -07:00
con.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("config_file")
args = parser.parse_args()
config = load_config(args.config_file)
run(config)