Advertisement
AntonioVillanueva

MQTT PUB & SUB RELAI IPX800V5

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