swbus/collector/management/commands/collectbusses.py
2020-04-25 18:32:32 +02:00

64 lines
2.5 KiB
Python

from django.core.management.base import BaseCommand, CommandError
from django.utils.timezone import make_aware
from django.contrib.gis.geos import Point
from collector.models import *
from urllib.request import urlopen
from datetime import datetime
import json
class Command(BaseCommand):
help = "Fetches current bus location data and stores it to the database"
def handle(self, *args, **options):
try:
positions = json.loads(urlopen("https://stadtwerke.24stundenonline.de/request.php?action=getpositions").read())
except:
raise CommandError("Could not load bus positions from the Interwebz.")
devices = [device["id"] for device in positions]
try:
status = json.loads(urlopen("http://stadtwerke.24stundenonline.de/request.php?action=getfmsdata&deviceid=%s" % ",".join(devices)).read())
except:
raise CommandError("Could not load bus status from the Interwebz.")
values = []
statuskeys = { key.key: key for key in list(StatusKey.objects.all()) }
for device in positions:
bus = Bus.objects.get_or_create(id=device["id"])[0]
locts = make_aware(datetime.fromtimestamp(device["unix_ts"]))
try:
Location.objects.get(bus=bus, timestamp=locts)
continue
except Location.DoesNotExist:
metats = make_aware(datetime.strptime(status["ts"][device["id"]], "%Y-%m-%d %H:%M:%S"))
try:
meta = Status.objects.get(bus=bus, timestamp=metats)
except:
try:
meta = Status(bus=bus, timestamp=metats)
meta.save()
except Exception as e:
raise CommandError("Could not create status object: " + repr(e))
for key, value in status["fields"][device["id"]].items():
if not key in statuskeys.keys():
statuskeys[key] = StatusKey.objects.create(key=key)
okey = statuskeys[key]
values.append(StatusValue(status=meta, key=okey, value=value))
try:
location = Point(device["WE"], device["NS"])
Location.objects.create(bus=bus, location=location, status=meta, timestamp=locts)
except Exception as e:
raise CommandError("Could not create location object: " + repr(e))
StatusValue.objects.bulk_create(values)