3 import paho.mqtt.client as paho
5 from ConfigParser import ConfigParser
7 from pprint import pprint
9 from dateutil.parser import parser
12 def on_message(mosq, obj, msg):
14 payload=json.loads(msg.payload)
15 timestamp=tparser.parse(payload['Time'])
16 for sensor_type in payload:
17 if sensor_type != 'Time' and sensor_type != 'TempUnit':
18 sensor_data=payload[sensor_type]
19 for param in sensor_data:
21 value=sensor_data[param]
24 c.execute('CALL meteo.submit_mqtt(%s,%s,%s,%s,NULL)', (topic,sensor_type,param,value))
26 print topic,sensor_type,param,value
28 print "Failed to submit data"
37 select topic from mqtt_topics where topic<>""
47 global client,database
49 conffile = sys.argv[1]
51 config = ConfigParser()
52 config.add_section('mqtt')
53 # set defaults for anonymous auth
54 config.set('mqtt', 'username', '')
55 config.set('mqtt', 'password', '')
56 config.set('mqtt', 'port', '1883')
59 mqtt_server = config.get('mqtt', 'server')
60 mqtt_port = config.getint('mqtt', 'port')
61 mqtt_username = config.get('mqtt', 'username')
62 mqtt_password = config.get('mqtt', 'password')
64 mysql_server = config.get('mysql', 'server')
65 mysql_username = config.get('mysql','username')
66 mysql_password = config.get('mysql','password')
67 mysql_db = config.get('mysql','db')
69 client = paho.Client('weather')
70 client.username_pw_set(mqtt_username, mqtt_password)
71 client.on_message=on_message
72 client.connect(mqtt_server, port=mqtt_port)
74 database = MySQLdb.connect(host=mysql_server,user=mysql_username,passwd=mysql_password,db=mysql_db,use_unicode=True,connect_timeout=10)
75 database.set_character_set('utf8')
77 c.execute('SET NAMES utf8;')
80 for topic in Topics():
81 topics.append((topic[0].encode('UTF-8'),1))
83 client.subscribe(topics)