Skip to content
Permalink
6cedebc0b4
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
59 lines (42 sloc) 1.38 KB
from paho.mqtt import client as mqtt_client
import base64
import json
from datetime import datetime
broker = 'broker.hivemq.com'
port = 8883
topic_sub = "image"
client_id = 'tracid'
def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Successfully connected to MQTT broker")
else:
print("Failed to connect, return code %d", rc)
client = mqtt_client.Client(client_id)
client.on_connect = on_connect
client.username_pw_set("username","password")
client.connect(broker, port)
return client
def subscribe(client: mqtt_client):
def on_message(client, userdata, msg):
y = json.loads(msg.payload.decode())
print(msg.payload.decode())
category = y["category"]
image_data = y["image"]
msg = str(image_data)
img = msg.encode('ascii')
now = datetime.now() # current date and time
filename = now.strftime("%m%d%Y-%H:%M:%S.jpg")
f = open("./"+category+"/"+filename, 'wb')
final_img = base64.b64decode(img)
print(final_img)
f.write(final_img)
f.close()
client.subscribe(topic_sub)
client.on_message = on_message
def main():
client = connect_mqtt()
subscribe(client)
client.loop_forever()
if __name__ == '__main__':
main()