Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

PythonでMQTTの送受信するpahoライブラリを使う

前回までにUIFlowとNodeRedのMQTT通信ができる様になったので、今度はPC上のPythonから通信してみます。

実際のところ

from paho.mqtt import client as mqtt_client

import time
import random

## For MQTT
broker = '192.168.8.119'
port = 1883
topic = "/sensor"
client_id = f'python-mqtt-{random.randint(0, 1000)}'

threshold  = 500

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    # Set Connecting Client ID
    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def publish(client, val):
  msg = f"{val}"
  result = client.publish(topic, msg)
  
  status = result[0]
  if status == 0:
      print(f"Send `{msg}` to topic `{topic}`")
  else:
      print(f"Failed to send message to topic {topic}")

def run():
  client = connect_mqtt()
  client.loop_start()

  try:
    data   = 0
    while ( 1 ) :
      # Printing
      print("---")
      print(data)

      data = random.randint(0, 1000)

      if ( data > threshold ) :
        print("Detected")
        val = f"Detected"
        publish(client, val)

      time.sleep(0.01)

  except:
    print("error")
    ser.close()

if __name__ == '__main__':
  run()