Advertisement
AntonioVillanueva

MQTT PUB + SUB python example

Aug 11th, 2022
1,015
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.00 KB | None | 0 0
  1. """ Antonio Villanueva Segura Test Mqtt with MOSQUITTO BROKER """
  2. import paho.mqtt.client as mqtt
  3. import time ,json
  4.  
  5. TOPIC = "/strac/out/" #Topic to PUB
  6.  
  7. address ="192.168.6.99" # Broker address UP with mosquitto MQTT server
  8. port =1883 # port
  9.  
  10. def on_message(client, userdata, message):
  11.     """ Called when a message has been received on a topic
  12.     that the client subscribes to and the message does not match
  13.     an existing topic filter callback.
  14.     Use message_callback_add() to define a callback that will be called
  15.     for specific topic filters. on_message will serve as fallback when none matched."""
  16.    
  17.     print(message.topic+" "+str(message.payload.decode("utf-8")))
  18.     #print("message topic=",message.topic) 
  19.     #print("message received " ,str(message.payload.decode("utf-8")))
  20.     #print("message qos=",message.qos)
  21.     #print("message retain flag=",message.retain,end="\n \n")
  22.  
  23. def on_connect(client,userdata,flags,rc):
  24.     """ When the client receives a CONNACK message from the broker
  25.     in response to the connect it generates an on_connect() callback. """
  26.  
  27.     print ("Connected to ",client._host,"port :",client._port)
  28.     #print ("Flags ",flags , "Returned code ", str (rc))
  29.  
  30.     # Subscribing in on_connect() means that if we lose the connection and
  31.     # reconnect then subscriptions will be renewed.
  32.     client.subscribe(TOPIC+'#',qos=0)
  33.  
  34. def on_subscribe(client, userdata, mid, granted_qos):
  35.     """ Called when the broker responds to a subscribe request. """
  36.     print ("on_subscribe userdata ",userdata)
  37.     #print ("on_subscribe mid ",mid)   
  38.     #print ("on_subscribe granted_qos ",userdata)  
  39.  
  40. def on_disconnect(client, userdata, rc):
  41.     """ Called when the client disconnects from the broker. """
  42.     print ( "on_disconnect userdata",userdata)
  43.     #print ( "on_disconnect rc",rc)
  44. """ Client """ 
  45.  
  46. def on_publish(client, userdata, mid):
  47.     """
  48.     Called when a message that was to be sent using the publish()
  49.     call has completed transmission to the broker.
  50.     For messages with QoS levels 1 and 2,
  51.     this means that the appropriate handshakes have completed.
  52.     For QoS 0, this simply means that the message has left the client.
  53.     The mid variable matches the mid variable returned
  54.     from the corresponding publish() call, to allow outgoing messages
  55.     to be tracked.
  56.  
  57.     This callback is important because even if the publish()
  58.     call returns success,
  59.     it does not always mean that the message has been sent.
  60.     """
  61.     print ("on_publish ",userdata," , mid ",mid)
  62.  
  63. def creeClient (name="Icarvs",login="tony",pwd="icaro"):
  64.                
  65.     client =mqtt.Client (name,
  66.                             clean_session=True,
  67.                             userdata=None,
  68.                             protocol=mqtt.MQTTv311,
  69.                             transport="tcp")
  70.  
  71.     """ calls backs"""
  72.     #client.on_message=on_message #Attach function to callback
  73.  
  74.     client.on_connect=on_connect #Attach function to callback
  75.  
  76.     client.on_subscribe=on_subscribe  #Attach function to callback
  77.  
  78.     client.on_publish=on_publish #Attach function to callback
  79.  
  80.     client.on_disconnect=on_disconnect #Attach function to callback
  81.  
  82.     """ login & pwd """
  83.     #client.username_pw_set(None, password=None) #Login & Pwd
  84.     client.username_pw_set(login, password=pwd) #Login & Pwd
  85.  
  86.     """ Connect """
  87.     client.connect (address,port,keepalive=60) #Connet to broker (host, port,keepalive, bind_address="")
  88.     return client
  89.  
  90.  
  91. def releStatus(client):
  92.     """ Read relai """ 
  93.    
  94.     status= '{"state":true}' #dictionary
  95.  
  96.     #Read user input
  97.  
  98.     rele = input("relai ? : ")
  99.     state= int (input ("0 - 1 ? : "));
  100.  
  101.     #Make state
  102.     if state==0:#Select relay state 0 or 1
  103.         status= '{"state":false}' #dictionary
  104.     else:
  105.         status= '{"state":true}' #dictionary
  106.  
  107.     #Make TOPIC
  108.     newTopic=TOPIC+rele #Make TOPIC
  109.  
  110.     #publish PUB
  111.     client.publish(newTopic,status) #Publish
  112.    
  113.     print (newTopic,status)
  114.            
  115. if __name__ == '__main__':
  116.    
  117.     while True:
  118.         client=creeClient()        
  119.         releStatus(client) #Read rele
  120.        
  121.         client.on_message=on_message #Attach function to callback
  122.         client.loop_start() #start loop to process received messages
  123.        
  124.         time.sleep (2)
  125.        
  126.         client.disconnect() #disconnect
  127.         client.loop_stop()
  128.    
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement