From d66ccb417ce626f4f3b909a4926f0aca2a205af4 Mon Sep 17 00:00:00 2001 From: "Michael O'Mara (omaram)" Date: Mon, 10 Feb 2020 12:06:07 +0000 Subject: [PATCH] Added new files Added all the required files for 4009cem for the location tracker --- index.html | 188 ++++++++++++++++++++++++++++++++ locations-jinja.py | 84 ++++++++++++++ map.html | 76 +++++++++++++ mqtt.coventry.ac.uk.crt | 31 ++++++ owntracks-subscriber-MQTT-DB.py | 47 ++++++++ 5 files changed, 426 insertions(+) create mode 100644 index.html create mode 100644 locations-jinja.py create mode 100644 map.html create mode 100644 mqtt.coventry.ac.uk.crt create mode 100644 owntracks-subscriber-MQTT-DB.py diff --git a/index.html b/index.html new file mode 100644 index 0000000..0d37768 --- /dev/null +++ b/index.html @@ -0,0 +1,188 @@ + + + + +Location Tracker + + + + + + + + +

My Map

+
+ + + + + + +
Location Tracker
+ + + + + + + + + + {% for item in locations %} + + + + + + + + {% endfor %} + +
TIDLongitudeLatitudeDateTime
{{ item[4] }}{{ item[0] }}{{ item[1] }}{{ item[2] }}{{ item[3] }}
+ + \ No newline at end of file diff --git a/locations-jinja.py b/locations-jinja.py new file mode 100644 index 0000000..ac652d4 --- /dev/null +++ b/locations-jinja.py @@ -0,0 +1,84 @@ +import cherrypy +import jinja2 +import sqlite3 as sql +import math, os +import time + +JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),'templates')),extensions=['jinja2.ext.autoescape']) + +DB = 'locations.db' + +class LocationsWebsite(object): + @cherrypy.expose + @cherrypy.tools.gzip() + def index(self): + template = JINJA_ENVIRONMENT.get_template('index.html') + template_values = {'locations': self.get_locations()} #template_values is a dict. key is 'locations', values is a list of lists of two items (long, lat) + return template.render(template_values) #make and serve the webpage + + def get_locations(self): + locations = [] + latitudes = self.get_latitudes() + longitudes = self.get_longitudes() + dates = self.get_dates() + #times = [time[:-7] for time in self.get_times()] + tids = self.get_tids() + times = self.get_report_times() + for i in range(len(latitudes)): + locations.append([longitudes[i],latitudes[i],dates[i],times[i],tids[i]]) #make list of lists to enable jinja render as columns + return locations + + def get_latitudes(self): + latitudes = [] + with sql.connect(DB) as cur: + results = cur.execute('''SELECT latitude FROM Location ORDER BY tid DESC;''') + for latitude, in results: + latitudes.append(str(latitude)) + return latitudes + + def get_longitudes(self): + longitudes = [] + with sql.connect(DB) as cur: + results = cur.execute('''SELECT longitude FROM Location ORDER BY tid DESC;''') + for longitude, in results: + longitudes.append(str(longitude)) + return longitudes + + def get_dates(self): + dates = [] + with sql.connect(DB) as cur: + results = cur.execute('''SELECT date FROM Location ORDER BY tid DESC;''') + for date, in results: + readabledate = time.strftime('%Y-%m-%d', time.localtime(date)) + dates.append(str(readabledate)) + return dates + + def get_times(self): + times = [] + with sql.connect(DB) as cur: + results = cur.execute('''SELECT time FROM Location ORDER BY tid DESC;''') + for time, in results: + times.append(str(time)) + return times + + def get_tids(self): + tids = [] + with sql.connect(DB) as cur: + results = cur.execute('''SELECT tid FROM Location ORDER BY tid DESC;''') + for tid, in results: + tids.append(str(tid)) + return tids + + def get_report_times(self): + times = [] + with sql.connect(DB) as cur: + results = cur.execute('''SELECT time FROM Location ORDER BY tid DESC;''') + for Time, in results: + readabletime = time.strftime('%H:%M:%S', time.localtime(Time)) + times.append(str(readabletime)) + return times + +if __name__ == '__main__': + cherrypy.config.update({'server.socket_host': '0.0.0.0'}) + cherrypy.config.update({'server.socket_port': 3000}) + cherrypy.quickstart(LocationsWebsite(), '/', {'/': {'tools.gzip.on': True}}) \ No newline at end of file diff --git a/map.html b/map.html new file mode 100644 index 0000000..20fd7fc --- /dev/null +++ b/map.html @@ -0,0 +1,76 @@ + + + + + + + + OpenLayers example + + +
+ + + \ No newline at end of file diff --git a/mqtt.coventry.ac.uk.crt b/mqtt.coventry.ac.uk.crt new file mode 100644 index 0000000..d30f409 --- /dev/null +++ b/mqtt.coventry.ac.uk.crt @@ -0,0 +1,31 @@ +-----BEGIN CERTIFICATE----- +MIIFYDC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BTADAQH/MA4GA1UdDwEB/wQEAwIB +BjAdBgNVHQ4EFgQU7edvdlq/YOxJW8ald7tyFnGbxD0wDQYJKoZIhvcNAQELBQAD +ggIBAJHfgD9DCX5xwvfrs4iP4VGyvD11+ShdyLyZm3tdquXK4Qr36LLTn91nMX66 +AarHakE7kNQIXLJgapDwyM4DYvmL7ftuKtwGTTwpD4kWilhMSA/ohGHqPHKmd+RC +roijQ1h5fq7KpVMNqT1wvSAZYaRsOPxDMuHBR//47PERIjKWnML2W2mWeyAMQ0Ga +W/ZZGYjeVYg3UQt4XAoeo0L9x52ID8DyeAIkVJOviYeIyUqAHerQbj5hLja7NQ4n +lv1mNDthcnPxFlxHBlRJAHpYErAK74X9sbgzdWqTHBLmYF5vHX/JHyPLhGGfHoJE ++V+tYlUkmlKY7VHnoX6XOuYvHxHaU4AshZ6rNRDbIl9qxV6XU/IyAgkwo1jwDQHV +csaxfGl7w/U2Rcxhbl5MlMVerugOXou/983g7aEOGzPuVBj+D77vfoRrQ+NwmNtd +dbINWQeFFSM51vHfqSYP1kjHs6Yi9TM3WpVHn3u6GBVv/9YUZINJ0gpnIdsPNWNg +KCLjsZWDzYWm3S8P52dSbrsvhXz1SnPnxT7AvSESBT/8twNJAlvIJebiVDj1eYeM +HVOyToV7BjjHLPj4sHKNJeV3UvQDHEimUF+IIDBu8oJDqz2XhOdT+yHBTw8imoa4 +WSr2Rz0ZiC3oheGe7IUIarFsNMkd7EgrO3jtZsSOeWmD3n+M +-----END CERTIFICATE----- diff --git a/owntracks-subscriber-MQTT-DB.py b/owntracks-subscriber-MQTT-DB.py new file mode 100644 index 0000000..d29106d --- /dev/null +++ b/owntracks-subscriber-MQTT-DB.py @@ -0,0 +1,47 @@ +""" connect to MQTT and write owntracks data to a database """ + +import paho.mqtt.client as mqtt #necessary imports +import sqlite3 as sql +import json, os +from datetime import date, datetime +import time + +""" callback function for connection """ +def on_connect(client, userdata, flags, rc): #client method to connect + if rc == 0: + client.connected_flag = True #set flag + print("connected OK") #let us know we connected to the broker + client.subscribe("owntracks/4009user/#") #we are connected, so subscribe to the topic. wildcard means any device + else: + print("Bad connection. Returned code = ", rc) #if we can't connect + +""" callback function for messages received """ +def on_message( client, userdata, msg ): #client method to get messages from topic + con = sql.connect('locations.db') #name of the database. You might want to change it. + cur = con.cursor() + try: + cur.execute("CREATE TABLE Location(longitude NUMBER(10,6), latitude NUMBER(10,6), date INT, time INT, tid VARCHAR2(20));") + except: + pass #if it already exists + data = json.loads(msg.payload.decode("utf8")) #decode message + #day = date.today() #time functions + clock = datetime.now() + #timestamp = datetime.time(clock) + + cur.execute("INSERT INTO Location values (?,?,?,?,?);",(data["lon"], data["lat"], data["tst"], data["tst"], data["tid"])) + #puts the latitude, longitude from the posted message as well as the date and time when it was posted into the database + print ("TID = {0} is currently at {1},{2},{3},{4}".format(data['tid'], data['lon'], data['lat'], data["tst"], data["tst"])) + #print device, latitude and longitude from the message; add time data (same as db) + print(str(data)) #print the entire message just for fun + con.commit() + cur.close() + con.close() #close the database + + +client = mqtt.Client() #bind all functions to mqtt class +client.on_connect = on_connect +client.on_message = on_message +client.username_pw_set("4009user", "mqttBROKER") #associate authentication details with the client +client.tls_set("mqtt.coventry.ac.uk.crt") #certificate for client. needs to be in the same directory as this script +client.connect("mqtt.coventry.ac.uk", 8883) #connect to the broker on an appropriate port +client.loop_forever() \ No newline at end of file