resq/utils/rider_location_cache/rider_location_cache.py

69 lines
1.7 KiB
Python

import paho.mqtt.client as mqtt
import ssl
import redis
import time
import signal
import sys
import os
import json
class RiderLocationCache(object):
def run(self, client):
print "running loop..."
client.loop_forever()
# TODO: fix this and put these guys back under the class
def init_subscriptions(client):
print "subscribing to wildcard #"
client.subscribe('#')
def on_connect(client, userdata, flags, rc):
init_subscriptions(client)
#print("Connected with result code "+str(rc))
# client.subscribe("$SYS/#")
def user_data_set(userdata):
conn = redis.StrictRedis(host='localhost', port=6379, db=0)
return conn
def on_publish(client, userdata, mid):
pass
def on_message(client, userdata, message):
redis_conn = user_data_set(userdata)
#print("message topic=", message.topic[0:10])
if message.topic[0:10] != 'motorider_':
return
#print repr(message)
# check if json decodable
res = json.loads(message.payload)
#print res
# get rider session id
sess_id = message.topic[10:]
# check if it has event
if 'event' not in res:
return
# check if event is driver_location
if res['event'] != 'driver_location':
return
# save the longitude and latitude
# get the rider id from sess_id
rider_key = "rider.location.%s" % sess_id
rider_long = str(res['longitude'])
rider_lat = str(res['latitude'])
# set the location
redis_conn.hmset(rider_key, {'longitude': rider_long, 'latitude': rider_lat})
# update our redis key
key = 'location_%s' % sess_id
#print "setting %s" % key
redis_conn.setex(key, 1600, message.payload)