From: Roman Bazalevsky Date: Mon, 7 Nov 2016 12:18:25 +0000 (+0300) Subject: Добавлен ретранслятор MQTT-MYSQL X-Git-Url: https://git.rvb.name/weathermon.git/commitdiff_plain/3710dc777a1990a2868d3d187d9dd18efaa1f90a?hp=b0a690ee18f5c2f894edc7c30fd6204c262670fe Добавлен ретранслятор MQTT-MYSQL --- diff --git a/mqtt.conf b/mqtt.conf new file mode 100644 index 0000000..028cba4 --- /dev/null +++ b/mqtt.conf @@ -0,0 +1,10 @@ +[mqtt] +server=localhost +port=1883 +username=readonly +password=mypassword +[mysql] +server=dbhost +username=meteo +password=mydbpasswd +db=meteo diff --git a/weathermon-mqtt b/weathermon-mqtt new file mode 100755 index 0000000..6c5fd37 --- /dev/null +++ b/weathermon-mqtt @@ -0,0 +1,82 @@ +#!/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()