Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- PUB & SUB dans MQTT utilise un BROKER MOSQUITTO
- avec IP 192.168.6.99:1883
- user:pwd tony:icaro
- pour communiquer avec l'IPX800V5.
- l'IPX800V5 ,doit être configuré dans chaque relais
- pour PUB & SUB MQTT avec un TOPIC "/strac/out/{num.rele}"
- JSON , type IO et une KEY state
- la clé KEY prend ces deux états:
- {"state":false}
- or
- {"state":true}
- Antonio Villanueva Segura
- """
- import paho.mqtt.client as mqtt
- import time ,json
- TOPIC = "/strac/out/" #Topic to PUB
- address ="192.168.6.99" # Broker address UP with mosquitto MQTT server
- port =1883 # port
- relais=[False] *9 #liste status relais ... [0]
- def listStateRelais(message):
- """Écrire l'état d'un relais dans la liste relais """
- relais[ int (message.topic[-1])]=json.loads( (message.payload.decode("utf-8") ) ).values()
- def on_message(client, userdata, message):
- """ Called when a message has been received on a topic
- that the client subscribes to and the message does not match
- an existing topic filter callback.
- Use message_callback_add() to define a callback that will be called
- for specific topic filters. on_message will serve as fallback when none matched."""
- listStateRelais(message)
- print(message.topic+" "+str(message.payload.decode("utf-8")))
- #print("message topic=",message.topic)
- #print("message received " ,str(message.payload.decode("utf-8")))
- #print("message qos=",message.qos)
- #print("message retain flag=",message.retain,end="\n \n")
- def on_connect(client,userdata,flags,rc):
- """ When the client receives a CONNACK message from the broker
- in response to the connect it generates an on_connect() callback. """
- print ("Connected to ",client._host,"port :",client._port)
- #print ("Flags ",flags , "Returned code ", str (rc))
- # Subscribing in on_connect() means that if we lose the connection and
- # reconnect then subscriptions will be renewed.
- client.subscribe(TOPIC+'#',qos=0)
- def on_subscribe(client, userdata, mid, granted_qos):
- """ Called when the broker responds to a subscribe request. """
- print ("on_subscribe userdata ",userdata)
- #print ("on_subscribe mid ",mid)
- #print ("on_subscribe granted_qos ",userdata)
- def on_disconnect(client, userdata, rc):
- """ Called when the client disconnects from the broker. """
- print ( "on_disconnect userdata",userdata)
- #print ( "on_disconnect rc",rc)
- def on_publish(client, userdata, mid):
- """
- Called when a message that was to be sent using the publish()
- call has completed transmission to the broker.
- For messages with QoS levels 1 and 2,
- this means that the appropriate handshakes have completed.
- For QoS 0, this simply means that the message has left the client.
- The mid variable matches the mid variable returned
- from the corresponding publish() call, to allow outgoing messages
- to be tracked.
- This callback is important because even if the publish()
- call returns success,
- it does not always mean that the message has been sent.
- """
- print ("on_publish ",userdata," , mid ",mid)
- def creeClient (name="Icarvs",login="tony",pwd="icaro"):
- client =mqtt.Client (name,
- clean_session=True,
- userdata=None,
- protocol=mqtt.MQTTv311,
- transport="tcp")
- """ calls backs"""
- #client.on_message=on_message #Attach function to callback
- client.on_connect=on_connect #Attach function to callback
- client.on_subscribe=on_subscribe #Attach function to callback
- client.on_publish=on_publish #Attach function to callback
- client.on_disconnect=on_disconnect #Attach function to callback
- """ login & pwd """
- #client.username_pw_set(None, password=None) #Login & Pwd
- client.username_pw_set(login, password=pwd) #Login & Pwd
- """ Connect """
- client.connect (address,port,keepalive=60) #Connet to broker (host, port,keepalive, bind_address="")
- return client
- def releStatus(client):
- """ Read relai """
- status= '{"state":true}' #dictionary
- #Read user input , num. relai 1 to 8
- rele=''
- while (rele <'1' or rele >'9' or len(rele)==0 or len(rele)>1 ):
- rele = input("relai ? : ")
- #Make status for PUB MQTT
- print (rele," act. state ",list (relais[ int(rele) ]) )
- if list (relais[int(rele)])[0]:
- status= '{"state":false}' #dictionary
- else:
- status= '{"state":true}' #dictionary
- print (rele, " fut.state ",status)
- #Make TOPIC MQTT
- newTopic=TOPIC+rele #Make TOPIC
- #publish PUB MQTT
- client.publish(newTopic,status) #Publish
- print (newTopic,status)
- if __name__ == '__main__':
- while True:
- client=creeClient()
- client.on_message=on_message #Attach function to callback
- client.loop_start() #start loop to process received messages
- time.sleep (1)
- client.loop_stop()
- releStatus(client) #Read relai
- client.disconnect() #disconnect client
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement