Skip to content
Permalink
main
Switch branches/tags

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?
Go to file
 
 
Cannot retrieve contributors at this time
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()