Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
MQTT-SAPTS-4005/newmain1.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
52 lines (42 sloc)
1.59 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from paho.mqtt import client as mqtt_client | |
import json | |
import myfile | |
# Connect. | |
broker = 'broker.hivemq.com' | |
port = 1883 | |
topic = "client/live/location" | |
client_id = f'subscribe-{random.randint(0, 100)}' | |
def on_connect(client, userdata, flags, rc): | |
if rc == 0: | |
client.subscribe(topic) | |
print("Connected to MQTT Broker!") | |
else: | |
print(f"Failed to connect, return code {rc}") | |
def on_message(client, userdata, msg): | |
if msg.topic == topic: # Check if the message is for the subscribed topic | |
try: | |
data = json.loads(msg.payload.decode()) | |
latitude = data[0] | |
longitude = data[1] | |
print('Received data:', data) | |
# Decrypt the data | |
decrypted_data = myfile.decrypt(latitude, longitude) | |
latitude = decrypted_data[0] | |
longitude = decrypted_data[1] | |
print("Decrypted lat/long:", latitude, longitude) | |
if not latitude or not longitude: | |
print("Error: Invalid latitude or longitude") | |
return | |
# Check if the coordinates are within certain bounds | |
if int(latitude) >= 40 and int(longitude) >= 40: | |
print("Alert: Coordinates outside secured area") | |
else: | |
print("Inside the secured area") | |
except Exception as e: | |
print("Error processing message:", e) | |
client = mqtt_client.Client(client_id) | |
client.on_connect = on_connect | |
client.on_message = on_message | |
client.connect(broker, port) | |
client.loop_forever() |