1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
#!/usr/bin/env python
import datetime
#sudo apt-get insttal python-pika
import pika
import json
#http://packages.ubuntu.com/fr/precise/python-mysqldb
#sudo apt-get install python-mysqldb
#import _mysql
import MySQLdb
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='log',
type='topic')
result = channel.queue_declare(exclusive=True)
#queue_name = result.method.queue
queue_name = 'fona'
print(queue_name)
channel.queue_bind(exchange='log',
queue=queue_name)
print('[*] Waiting for logs. To exit press CTRL+C')
#preparing the myQSl request
add_position = ("INSERT INTO position "
"(imei, timestamp, value, lat, lng, alt, heading, speed, sensor, tower, battery) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)")
def callback(ch, method, properties, body):
print(" [x] %r" % body)
# {"position":{"value":1,"timestamp":"1483729658","context":{"lat":46.21984,"lng":6.14123,"imei":"865067020424381","alt":452,"heading":90,"speed":34,"battery":38,"sensor":"GSM","tower":"228,03,1771,2d6f,45,57"}},"battery":38}
data = json.loads(body)
#preparing the variable
imei = str(data["position"]["context"]["imei"])
timestamp = data["position"]["timestamp"]
value = data["position"]["value"]
lat = str(data["position"]["context"]["lat"])
lng = str(data["position"]["context"]["lng"])
if data["position"]["value"] == 1 :
alt = data["position"]["context"]["alt"]
heading = data["position"]["context"]["heading"]
speed = data["position"]["context"]["speed"]
else:
alt = 0
heading = 0
speed = 0
sensor = str(data["position"]["context"]["sensor"])
tower = str(data["position"]["context"]["tower"])
battery = data["battery"]
#DEBUG
print('')
print("IEMI:",imei)
print("Timestamp:",timestamp)
print("Value:",value)
print("Lat:",lat)
print("Lng:",lng)
if data["position"]["value"] == 1 :
print("Alt:",alt)
print("Heading:",heading)
print("Speed:",speed)
print("Sensor:",sensor)
print("Tower:",tower)
print("Battery:",battery)
print('')
#preparing the insertion
data_position = (imei,datetime.datetime.fromtimestamp(int(timestamp)).strftime('%Y-%m-%d %H:%M:%S'),value,lat,lng,alt,heading,speed,sensor,tower,battery)
#connection
db = MySQLdb.connect("localhost","root","pass","mqtt")
cursor = db.cursor()
# http://mysql-python.sourceforge.net/MySQLdb.html#mysqldb
try:
cursor.execute(add_position, data_position)
db.commit()
except:
db.rollback()
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming() |
Partager