Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

import random

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.")

def encrypt_payload(self, payload):


cipher = AES.new(self.key, AES.MODE_ECB)
padded_payload = payload + ' ' * (16 - len(payload) % 16)
encrypted_payload = cipher.encrypt(padded_payload.encode())
return encrypted_payload.hex()

def decrypt_payload(self, encrypted_payload):


cipher = AES.new(self.key, AES.MODE_ECB)
decrypted_payload =
cipher.decrypt(bytes.fromhex(encrypted_payload)).decode().rstrip()
return decrypted_payload

def publish_message(self, topic, payload):


encrypted_payload = self.encrypt_payload(payload)
result = self.client.publish(topic, encrypted_payload)

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 II: Processing Data


# (No processing logic needed for this example, just collecting and
publishing)

# Task III: Display Temperature Value


print("Temperature Value: ", Fore.LIGHTBLUE_EX, temperature,
Style.RESET_ALL)

# Task IV: Publishing Data with MQTT as Encrypted String


self.publish_message(f"publisher/temperature", str(temperature))
self.publish_message(f"publisher/humidity", str(humidity))
self.publish_message(f"publisher/distance", str(distance))
self.publish_message(f"publisher/speed", str(speed))
self.publish_message(f"publisher/direction", direction)

# 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()

You might also like