Advertisement
miketwo

MQTT Example

Jan 4th, 2025
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.98 KB | Fixit | 0 0
  1. # python 3.11
  2.  
  3. import random
  4. from paho.mqtt import client as mqtt_client
  5. # from paho.mqtt import publish as publish  # Not needed if we always use client
  6. from buildhat import Matrix, ForceSensor
  7.  
  8. ##############################################################################
  9. #                         GLOBAL VARIABLES / SETUP                           #
  10. ##############################################################################
  11.  
  12. # -----------------------#
  13. # MQTT Configuration    #
  14. # -----------------------#
  15. broker = '192.168.0.17'     # IP of your broker
  16. port = 1883                 # Port for MQTT (default is 1883)
  17. topic = "test/relay"        # Topic to subscribe/publish to
  18.  
  19. # We create a random ID just so multiple clients on the same broker
  20. # don't stomp on each other:
  21. client_id = f'subscribe-{random.randint(0, 100)}'
  22.  
  23. # Username / password for the broker (if needed)
  24. username = 'USERNAME_HERE'
  25. password = '************'
  26.  
  27. # -----------------------#
  28. # BuildHat Configuration #
  29. # -----------------------#
  30. # Create a matrix on port 'B' (adjust as needed for your setup)
  31. matrix = Matrix('B')
  32. matrix.clear(("yellow", 10))
  33.  
  34. # Create a ForceSensor on port 'C'
  35. button = ForceSensor('C')
  36.  
  37. # This will indicate the relay state:
  38. buttonFlag = 1
  39.  
  40. # -----------------------#
  41. # The Big Global Client  #
  42. # -----------------------#
  43. #
  44. # We declare 'client' here. We'll fill it in `connect_mqtt()`.
  45. # This is so that any function that needs it can do `global client`.
  46. client = None
  47.  
  48.  
  49. ##############################################################################
  50. #                            MQTT SETUP FUNCTIONS                            #
  51. ##############################################################################
  52.  
  53. def connect_mqtt():
  54.     """
  55.    Connects to the MQTT broker exactly once and assigns the resulting
  56.    mqtt_client.Client instance to the global 'client'.
  57.    Returns the same client, but we also store it in the global variable.
  58.    """
  59.     global client  # Tells Python we're referring to the global variable above.
  60.  
  61.     def on_connect(client, userdata, flags, rc):
  62.         """
  63.        Callback that fires when a connection to the broker is established.
  64.        """
  65.         if rc == 0:
  66.             print("Connected to MQTT Broker!")
  67.             # As an example, we publish a greeting on a different topic:
  68.             client.publish("test/time", "HI from PI!")
  69.         else:
  70.             print(f"Failed to connect. Return code={rc}")
  71.  
  72.     # Actually create the client object
  73.     client = mqtt_client.Client(client_id)
  74.  
  75.     # Assign credentials
  76.     client.username_pw_set(username, password)
  77.  
  78.     # Assign the on_connect callback
  79.     client.on_connect = on_connect
  80.  
  81.     # Connect to the broker
  82.     client.connect(broker, port)
  83.  
  84.     return client
  85.  
  86.  
  87. def subscribe():
  88.     """
  89.    Sets up subscription to a topic and defines how incoming messages are handled.
  90.    """
  91.     global client  # We'll need the client to call subscribe on it
  92.  
  93.     def on_message(client, userdata, msg):
  94.         """
  95.        Callback that fires when a message arrives on a topic we subscribed to.
  96.        """
  97.         print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
  98.        
  99.         # If the received payload is '1', turn the matrix green, else red.
  100.         # (Adjust logic if your messages are strings other than '1'/'0')
  101.         if msg.payload.decode() == '1':
  102.             matrix.clear(("green", 10))
  103.         else:
  104.             matrix.clear(("red", 10))
  105.  
  106.     # Subscribe to the desired topic
  107.     client.subscribe(topic)
  108.  
  109.     # Assign the on_message callback
  110.     client.on_message = on_message
  111.  
  112.  
  113. ##############################################################################
  114. #                       FUNCTIONS TO PUBLISH MESSAGES                        #
  115. ##############################################################################
  116.  
  117. def publish_message():
  118.     """
  119.    Publishes the current state of 'buttonFlag' to the MQTT broker.
  120.    """
  121.     global client  # We'll need the global client
  122.     print("Publishing message:", buttonFlag)
  123.     client.publish(topic, buttonFlag)
  124.  
  125.  
  126. ##############################################################################
  127. #                        BUILDHAT BUTTON-RELATED CODE                        #
  128. ##############################################################################
  129.  
  130. def handle_pressed(force):
  131.     """
  132.    Called automatically when the ForceSensor on port 'C' is pressed.
  133.    We'll flip the buttonFlag from 1 to 0 or 0 to 1 and then publish.
  134.    """
  135.     global buttonFlag  # Tells Python to use the global variable
  136.     if force > 10:
  137.         print("Button Pressed!")
  138.         # Flip the state of buttonFlag
  139.         if buttonFlag == 1:
  140.             buttonFlag = 0
  141.             matrix.clear(("red", 10))
  142.         else:
  143.             buttonFlag = 1
  144.             matrix.clear(("green", 10))
  145.  
  146.         # Now publish our updated buttonFlag via MQTT
  147.         publish_message()
  148.  
  149.  
  150. ##############################################################################
  151. #                             MAIN LOOP (run)                                #
  152. ##############################################################################
  153.  
  154. def run():
  155.     """
  156.    Main entry-point for our script. Connect to MQTT, subscribe,
  157.    and start the loop forever.
  158.    """
  159.     global client  # We'll store the client in the global variable
  160.    
  161.     # 1. Connect once
  162.     connect_mqtt()
  163.    
  164.     # 2. Subscribe once
  165.     subscribe()
  166.    
  167.     # 3. Start an infinite loop to process messages and keep the connection open
  168.     client.loop_forever()
  169.  
  170.  
  171. # Assign our 'handle_pressed' function to be called when the ForceSensor is pressed
  172. button.when_pressed = handle_pressed
  173.  
  174.  
  175. ##############################################################################
  176. #                          START THE PROGRAM HERE                            #
  177. ##############################################################################
  178.  
  179. if __name__ == '__main__':
  180.     run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement