+#!/usr/bin/python
+
+import paho.mqtt.client as paho
+import sys
+from ConfigParser import ConfigParser
+import MySQLdb
+from pprint import pprint
+
+def on_message(mosq, obj, msg):
+ topic=msg.topic
+ payload=msg.payload
+ try:
+ c = database.cursor()
+ c.execute('CALL meteo.submit_mqtt(%s,%s,NULL)', (topic,payload))
+ database.commit()
+ print topic,payload
+ except:
+ print "Failed to submit data"
+
+def Topics():
+
+ c = database.cursor()
+ c.execute(
+ '''
+ select topic from mqtt_topics
+ '''
+ )
+
+ topics=c.fetchall()
+ return topics
+
+
+def Init():
+
+ global client,database
+
+ conffile = sys.argv[1]
+
+ config = ConfigParser()
+ config.add_section('mqtt')
+ # set defaults for anonymous auth
+ config.set('mqtt', 'username', '')
+ config.set('mqtt', 'password', '')
+ config.set('mqtt', 'port', '1883')
+ config.read(conffile)
+
+ mqtt_server = config.get('mqtt', 'server')
+ mqtt_port = config.getint('mqtt', 'port')
+ mqtt_username = config.get('mqtt', 'username')
+ mqtt_password = config.get('mqtt', 'password')
+
+ mysql_server = config.get('mysql', 'server')
+ mysql_username = config.get('mysql','username')
+ mysql_password = config.get('mysql','password')
+ mysql_db = config.get('mysql','db')
+
+ client = paho.Client('weather')
+ client.username_pw_set(mqtt_username, mqtt_password)
+ client.on_message=on_message
+ client.connect(mqtt_server, port=mqtt_port)
+
+ database = MySQLdb.connect(host=mysql_server,user=mysql_username,passwd=mysql_password,db=mysql_db,use_unicode=True,connect_timeout=10)
+ database.set_character_set('utf8')
+ c = database.cursor()
+ c.execute('SET NAMES utf8;')
+
+ topics=[]
+ for topic in Topics():
+ topics.append((topic[0].encode('UTF-8'),1))
+
+ client.subscribe(topics)
+
+Init()
+
+try:
+ while True:
+ try:
+ client.loop()
+ except:
+ break
+finally:
+ exit()