The first function, sqlPull()
, connects to a local MySQL database and pulls the last 20 rows from the database every 5 seconds. The data coming in is a list of tuples, where MAC
, RSSI
and TimeStamp
are the 3 elements in each tuple. The data is entering the database at a variable rate, where sometimes I'll have tons of entries in a minute and sometimes I will have very few. The data that is coming in consists of a MAC address, an RSSI
and a TimeStamp
for every time a user's device pings our hardware. So, we will have unique MAC addresses that will have changing RSSIs
and TimeStamps
over a period of time.
Since I never know how many database entries will be added within the 5 seconds that the first function runs on, the second function, dupCatch()
is used to detect and eliminate duplicates.
The third function, post()
, just sends a POST request to Google Analytics with the data stripped of duplicates.
Here is how I would like to optimize my code:
My next step in this process is to calculate the length of time between a users first and last entries in the database. We can assume that the max time between a user's entry and exit is 2 hours (in this time, the users would probably have 10-15 pings with different RSSI
s and timestamps). I have been trying to think of the best way to do this with the current code, but everything I am thinking of seems so unwieldy. In my mind, sqlPull()
and/or dupCatch()
could be rewritten/optimized to better serve my purposes for a function to calculate length of time between entry and exit.
How would you pull data that is coming in at a variable and unpredictable rate?
import mysql.connector
import datetime
import requests
import time
run = True
def sqlPull():
connection = mysql.connector.connect(user='XXXXX', password='XXXXX', host='XXXXX', database='XXXXX')
cursor = connection.cursor()
cursor.execute("SELECT TimeStamp, MAC, RSSI FROM wifiscan ORDER BY TimeStamp DESC LIMIT 20;")
data = cursor.fetchall()
connection.close()
time.sleep(5)
return data
seen = set()
def dupCatch():
data = sqlPull()
new_data = []
for (TimeStamp, MAC, RSSI) in data:
if (TimeStamp, MAC, RSSI) not in seen:
seen.add((TimeStamp, MAC, RSSI))
new_data.append((TimeStamp, MAC, RSSI))
print new_data
return new_data
def post():
new_data = dupCatch()
for ((TimeStamp, MAC, RSSI)) in new_data:
payload = {'v':'1','tid':'XXXXXX','cid': '1','t':'event', 'ec': MAC, 'ea': 'InStore', 'el': RSSI}
requests.post("http://www.google-analytics.com/collect", data = payload)
while run is True:
post()