Professional Documents
Culture Documents
Publisher Mou Ad
Publisher Mou Ad
import time
import paho.mqtt.client as mqtt
from Crypto.Cipher import AES
from colorama import Fore, Style
class MQTTPublisher:
def __init__(self, broker, port, username, password, delay, key):
self.broker = broker
self.port = port
self.client_id = f'python-mqtt-{random.randint(0, 1000)}'
self.client = mqtt.Client(self.client_id)
self.delay = delay
self.client.username_pw_set(username, password)
self.key = key
print("Unique AES Key:", self.key.hex())
def connect(self):
try:
self.client.connect(self.broker, self.port)
self.client.loop_start()
except ConnectionRefusedError:
print("Connection to MQTT broker refused.")
status = result[0]
if status == 0:
print("Data Published: ", Fore.LIGHTBLUE_EX, encrypted_payload,
Style.RESET_ALL,
" Using Topic: ", Fore.LIGHTCYAN_EX, topic, Style.RESET_ALL)
print("Decrypted Data: ", Fore.LIGHTBLUE_EX,
self.decrypt_payload(encrypted_payload), Style.RESET_ALL)
else:
print(f"Failed to publish on topic: {topic}")
def run(self):
self.connect()
try:
while True:
# Task I: Collecting Data
temperature = round(random.uniform(0.0, 40.0), 2)
humidity = round(random.uniform(0.0, 100.0), 2)
distance = round(random.uniform(0.0, 100.0), 2)
speed = round(random.uniform(0.0, 100.0), 2)
direction = random.choice(['left', 'right', 'stop', 'IDLE'])
# Task V: Delay
print("Applying a delay of: ", Fore.LIGHTBLUE_EX, self.delay,
Style.RESET_ALL, "Seconds")
time.sleep(self.delay)
except KeyboardInterrupt:
self.client.loop_stop()
print("Exiting publisher...")
if __name__ == '__main__':
key = bytes.fromhex('61b48132631aa9d8532f2ae2b26f3b00') # Updated AES Key
publisher = MQTTPublisher("127.0.0.1", 1883, "mouad", "mouad", 5, key) #
Updated MQTT Credentials
publisher.run()