Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import paho.mqtt.client as mqtt
- import json, time, jwt, getpass, socket, random
- # mqtt auth stuff
- MQTT_CLIENT_HOST = ""
- MQTT_CLIENT_PORT = 1883
- # device config
- dev_name = getpass.getuser()
- dev_id = socket.gethostname()
- class MSG_Constructor:
- def __init__(self):
- pass
- # create a simple json object
- def create_object(self):
- self.object = {
- "device": dev_name,
- "device_id": dev_id,
- "message": random.choice("ON", "OFF", "IDLING")
- }
- return self.object
- # publish message
- def publish(self, topic, message):
- try:
- self.topic = topic
- self.message = message or self.create_object
- # Try to publish the message to mqtt broker
- client.publish(self.topic, self.message)
- return True
- except KeyError:
- print('keyerror occured, request failed...')
- return False
- msg_object = MSG_Constructor()
- def on_connect(client, userdata, flags, rc):
- full_hostname = MQTT_CLIENT_HOST + ":" + str(MQTT_CLIENT_PORT)
- print(f"successfully connected to - {full_hostname}, as {dev_name}, code - {str(rc)}")
- client.subscribe(topic)
- def on_message(client, userdata, msg):
- try:
- mqtt_message = str(msg.payload.decode('utf-8'))
- # Inside the json message object should be a client id
- mqtt_object = json.loads(mqtt_message)
- mqtt_client_id = mqtt_object["client_id"]
- if " " in mqtt_client_id or len(mqtt_client_id) < 3:
- print("Received an incorrect message, continuing")
- print(f"New message from - {mqtt_client_id}, msg - {mqtt_message}.")
- except KeyError:
- print("Received an incorrect message, continuing")
- pass
- except Exception as error:
- print(error)
- def on_disconnect(self, client, userdata, rc):
- if rc != 0:
- full_hostname = MQTT_CLIENT_HOST + ":" + str(MQTT_CLIENT_PORT)
- print("Disconnected from -", full_hostname)
- def on_publish(client, userdata, mid):
- print("The publish request was successfully sent to mqtt.")
- def on_subscribe(client, userdata, mid, granted_qos):
- print("Successfully subscribing to -", topic)
- client = mqtt.Client()
- client.on_connect = on_connect
- client.on_subscribe = on_subscribe
- client.on_message = on_message
- client.on_publish = on_publish
- client.on_disconnect = on_disconnect
- # client authentication
- client.username_pw_set("user", "user")
- topic = "/dev2" # we connect to the other dev which is on dev2
- # connect to mqtt broker
- client.connect(MQTT_CLIENT_HOST, MQTT_CLIENT_PORT, 600)
- client.loop_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement