title: How send and recived mqtt message in same script
body: <p>Hi can someone help me?
  I´m trying to send every 2 minutes a mqtt message but I also need to receive messages at any time.</p>
  <p>The message every 2 minutes is the state message to know that the server is running and i need to receive messages to execute the shutdown commands.</p>
  <p>I try this but this only send  one message...</p>
  <pre><code>import time
  from paho.mqtt import client as mqtt_client
  from paramiko import SSHClient, AutoAddPolicy
  
  broker = '192.168.15.210'
  port = 1883
  topic = &quot;LV-Automation/Server&quot;
  topicState = &quot;LV-Automation/Server/State&quot;
  client_id = 'ServerPower'
  
  msgState = f&quot;ON&quot;
  
  lastms = 10
  
  def connect_mqtt():
      def on_connect(client, userdata, flags, rc):
          if rc == 0:
              print(&quot;Connected to MQTT Broker!&quot;)
          else:
              print(&quot;Failed to connect, return code %d\n&quot;, rc)
  
      client = mqtt_client.Client(client_id)
      client.username_pw_set(&quot;user&quot;, &quot;password&quot;)
      client.on_connect = on_connect
      client.connect(broker, port)
      return client
  
  
  def subscribe(client: mqtt_client):
      def on_message(client, userdata, msg):
          print(f&quot;Received `{msg.payload.decode()}` from `{msg.topic}` topic&quot;)
          message = msg.payload.decode()
          if message == &quot;OFF&quot;:
              client.publish(topicState, &quot;OFF&quot;)
              client = SSHClient()
              client.load_system_host_keys()
              client.set_missing_host_key_policy(AutoAddPolicy())
              client.connect('192.168.15.220', username= 'root', password= 'Caro1992')
              stdin, stdout, stderr = client.exec_command('powerdown')
  
  
      client.subscribe(topic)
      client.on_message = on_message
  
      global lastms
      nowms = round(time.time() * 1000)
      print(&quot;Last Value: &quot; , type(lastms))
      print (&quot;New Value: &quot; , type(nowms))
      if (nowms - lastms &gt; 120000):
          lastms = round(time.time() * 1000)
          publish(client)
  
  def publish(client):
      #msg_count = 0
      msg0 = f&quot;ENCENDIDO&quot;
      result = client.publish(topic, msg0)
      result = client.publish(topicState, msgState)
      status = result[0]
      if status == 0:
          print(f&quot;Send `{msg0}` to topic `{topic}`&quot;)
      else:
          print(f&quot;Failed to send message to topic {topic}&quot;)
  
  def firstms():
      global lastms
      lastms = round(time.time() * 1000)
      return lastms
  
  def run():
      firstms()
      client = connect_mqtt()
      publish(client)
      subscribe(client)
      client.loop_forever()
  
  
  if __name__ == '__main__':
      run()
  </code></pre>