daily pastebin goal
17%
SHARE
TWEET

Untitled

a guest Apr 21st, 2018 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python
  2. import paho.mqtt.client as mqttClient
  3. import MySQLdb as mdb
  4. import time
  5.  
  6. #broker_address= "m11.cloudmqtt.com"  #Broker address
  7. broker_address = "localhost"
  8. broker_port = 1883                           #Broker broker_port
  9. #broker_user = "yourUser"                    #Connection username
  10. #broker_password = "yourPassword"            #Connection password
  11.  
  12. db_hostname = "localhost"  # MySQL host ip address or name
  13. db_database = "mqtt"       # MySQL database name
  14. db_username = "mqttuser"   # MySQL database user name
  15. db_password = "mqttpass"   # MySQL database password
  16.  
  17. #Connected = False   #global variable for the state of the connection
  18.  
  19. def on_connect(client, userdata, flags, rc):
  20.     if rc == 0:
  21.         print("Connected to broker")
  22.         #global Connected                #Use global variable
  23.         #Connected = True                #Signal connection
  24.         #Subscribing in on_connect() means that if we lose the connection and reconnect then subscriptions will be renewed.
  25.         client.subscribe([("#",0),("/#",0),("$SYS/broker/log/#",0)]) #subscribe all
  26.     else:
  27.         print("Connection failed")
  28.  
  29. def on_message(client, userdata, msg):
  30.    print "MQTT subscribed |",msg.topic,"|",str(msg.qos),"|",str(msg.payload),"|"
  31.    db_insert(msg)
  32.  
  33.  
  34. def db_insert(msg):
  35.     with con:
  36.         cur = con.cursor()
  37.         cur.execute("INSERT INTO messages (topic , qos, message) VALUES (%s, %s, %s)", (msg.topic, msg.qos, msg.payload))
  38.         print "MySQL INSERT INTO messages (topic_id , qos, message_id) VALUES (",str(msg.topic),", ",str(msg.qos),", ",str(msg.payload),")"
  39.  
  40.  
  41. def main():
  42.     global con
  43.     #Try connect databank
  44.     db_connected = 0
  45.     while db_connected == 0:
  46.         try:
  47.             con = mdb.connect(db_hostname, db_username, db_password, db_database)
  48.             db_connected = 1
  49.             print "Connected to database"
  50.         except:
  51.             print "Warning: No database (connection) found. Retry in one minute."
  52.             time.sleep(60)
  53.         pass
  54.  
  55.     client = mqttClient.Client("PythonMQTT-MySQL")               #create new instance
  56.     #client.username_pw_set(broker_user, password=broker_password)    #set username and password
  57.     client.on_connect= on_connect                      #attach function to callback
  58.     client.on_message= on_message                      #attach function to callback
  59.      
  60.     rc = 1
  61.     while rc == 1:
  62.         try:
  63.             client.connect(broker_address, port=broker_port)
  64.             rc = 0
  65.         except:
  66.             print "Warning: No broker found. Retry in one minute."
  67.             time.sleep(60)
  68.             pass
  69.  
  70.     while rc == 0:
  71.         try:
  72.             rc = client.loop()
  73.         except:
  74.             rc = 1
  75.  
  76.     print("Warning: Connection error - Restarting.")
  77.  
  78.     #client.connect(broker_address, port=broker_port)          #connect to broker
  79.      
  80.     #client.loop_start()        #start the loop
  81.      
  82.     #while Connected != True:    #Wait for connection
  83.     #    time.sleep(0.1)
  84.      
  85.    
  86.  
  87.    
  88.  
  89. if __name__ == "__main__":
  90.     try:
  91.         while True:
  92.             main()
  93.             #time.sleep(1)
  94.      
  95.     except KeyboardInterrupt:
  96.         print "exiting"
  97.         client.disconnect()
  98.         client.loop_stop()
  99.         quit()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top