Advertisement
AntonioVillanueva

MQTT TKINTER IPX800 V5 Ctrl.

Aug 17th, 2022
963
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.14 KB | None | 0 0
  1. """
  2. Antonio Villanueva Segura Tkinter MQTT IPX800V5 CTRL relai
  3. https://youtu.be/rt0O_GNc1sA
  4. """
  5. #!/usr/bin/env python
  6. # -*- coding: utf-8 -*-
  7. import tkinter as tk
  8. from tkinter import ttk
  9. import paho.mqtt.client as mqtt
  10. import time , json,threading
  11. import threading
  12. #import queue as Queue
  13.  
  14. LOGIN="tony"
  15. PWD="icaro"
  16.  
  17. TOPIC = "/strac/out/" #Topic
  18. address ="192.168.6.99" # Broker address UP with mosquitto MQTT server
  19. port =1883 # port
  20.  
  21. class Automate(tk.Tk):
  22.    
  23.     def __init__(self):
  24.         super().__init__()
  25.  
  26.         self.title('IPX800')
  27.         self.resizable( False, False )
  28.  
  29.         #Créer une copie de l'état des relais dans l'IPX800 V5
  30.         self.relais=[False] *9 #liste status relais ... [0]
  31.  
  32.         # Cree 8 buttons-relais
  33.  
  34.         for b in range (1,9):
  35.  
  36.             name =str(b)
  37.            
  38.             self.button = tk.Button(self, text=name, activebackground="red",
  39.                 command=lambda name=name :self.button_relai(name)) #Cree bouton num.
  40.             """
  41.             self.button = ttk.Button(self, text=name, activebackground="red",
  42.                 command=lambda name=name :self.button_relai(name)) #Cree bouton num.   
  43.             """                    
  44.             self.button.pack(side=tk.LEFT)
  45.        
  46.         #self.queue = Queue.Queue()
  47.         #MQTT Thread parallèle al thread principal tkinter
  48.         self.running = 1
  49.         self.thread1 = threading.Thread(target=self.Thread)
  50.         self.thread1.start( )
  51.        
  52.     def button_relai(self,relai):
  53.         """ click bouton-relai """
  54.    
  55.         if ( self.relais[ int(relai) ]==True):
  56.             status= '{"state":false}' #dictionary
  57.         else:
  58.             status= '{"state":true}' #dictionary
  59.            
  60.         #Save new status   
  61.         #self.relais[int (relai)]= not self.relais[int (relai)]
  62.        
  63.         #Make TOPIC MQTT
  64.         newTopic=TOPIC+str(relai) #Make TOPIC
  65.  
  66.         print ("Debug ",newTopic,status)
  67.        
  68.         while (not self.client_connect):
  69.             print (" ... waiting client thread ... ")
  70.            
  71.         #publish PUB MQTT
  72.         self.client.publish(newTopic,status) #Publish
  73.  
  74.     def on_connect(self,client,userdata,flags,rc):
  75.         """ When the client receives a CONNACK message from the broker
  76.         in response to the connect it generates an on_connect() callback. """
  77.  
  78.         self.client_connect=True
  79.         print ("Connected to ",client._host,"port :",client._port)
  80.         client.subscribe(TOPIC+'#',qos=0)
  81.  
  82.     def on_disconnect(self,client, userdata, rc):
  83.         self.client_connect=False      
  84.         """ Called when the client disconnects from the broker. """
  85.  
  86.     def on_message(self,client, userdata, message):
  87.         """ Called when a message has been received on a topic """
  88.         self.listStateRelais(message) #mise à jour des états des relais
  89.         #print(message.topic+" "+str(message.payload.decode("utf-8")))
  90.  
  91.     def on_subscribe(self,client, userdata, mid, granted_qos):
  92.         """ Called when the broker responds to a subscribe request. """
  93.         #print ("on_subscribe userdata ",userdata)
  94.  
  95.     def creeClient (self,name="Icarvs",login=LOGIN,pwd=PWD):                   
  96.         self.client =mqtt.Client (name,
  97.                                 clean_session=True,
  98.                                 userdata=None,
  99.                                 protocol=mqtt.MQTTv311,
  100.                                 transport="tcp")
  101.  
  102.         """ calls backs"""     
  103.         self.client.on_connect=self.on_connect #Attach function to callback            
  104.         self.client.on_message=self.on_message #Attach function to callback
  105.         self.client.on_subscribe=self.on_subscribe  #Attach function to callback
  106.  
  107.         """ login & pwd """
  108.         self.client.username_pw_set(login, password=pwd) #Login & Pwd
  109.  
  110.         """ Connect """
  111.         self.client.connect (address,port,keepalive=60) #Connet to broker (host, port,keepalive, bind_address="")      
  112.         #self.client.loop_start() #start loop to process received messages 
  113.            
  114.     def listStateRelais(self,message):
  115.         """Écrire l'état d'un relais dans la liste relais local """
  116.         self.relais[ int (message.topic[-1])]=all ( json.loads( (message.payload.decode("utf-8") ) ).values() )        
  117.    
  118.     def Thread(self):
  119.         """ MQTT Thread"""
  120.  
  121.         while self.running:        
  122.             self.creeClient()                      
  123.             self.client.loop_start() #start loop to process received messages              
  124.             time.sleep( 0.1)
  125.             #print ("Thread Debug")
  126.             #msg = "un mensaje"
  127.             #self.queue.put(msg)           
  128.             self.client.loop_stop()
  129.  
  130.     def endApplication(self):
  131.         self.running = 0           
  132.                
  133. if __name__ == "__main__":
  134.   app = Automate() #Instance automate tkinter
  135.   #app.creeClient() #Client
  136.   app.mainloop() #tkinter main loop
  137.  
  138.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement