when I run the sub_file.py program there is an error like this :
AttributeError: 'NoneType' object has no attribute 'recv'
this is the sub_file.py code:
import time
import paho.mqtt.client as mqtt #import the client1
import base64
broker_address="mqtt.eclipseprojects.io"
port = 1883
client = mqtt.Client("P2") #create new instance
client.connect(broker_address,port) #connect to broker
def on_message(cln, obj, msg):
print("new message")
data = msg.payload.decode()
msg = str(data)
img = msg.encode('ascii')
with open('iris.jpg', 'wb') as fd:
final_data = base64.b64decode(img)
fd.write(final_data)
fd.close()
def on_subscribe(client, userdata, mid, granted_qos):
print("subscribe success")
client.subscribe("photo_topic_file")
client.on_subscribe = on_subscribe
print("Subscribing...")
client.loop_start()
client.on_message = on_message
client.loop_forever()
and this the pub_file.py code:
import paho.mqtt.client as mqtt
import base64
import time
broker_address="mqtt.eclipseprojects.io"
port = 1883
client = mqtt.Client("P1")
f = open("data.jpg", "rb")
isi_file = f.read()
convert_result_ke_base64 = base64.b64encode(isi_file)
client.connect(broker_address, port)
client.loop_start()
result = client.publish("photo_topic_file", convert_result_ke_base64)
if result[0] == 0:
print("publish success")
else:
print("publish failed")
time.sleep(5)
client.loop_stop()
when i run the pub_file.py the program worked properly but when i run the sub_file.py it show the error
can someone fix this problem?
client.on_subscribe = on_subscribe
print("Subscribing...")
client.loop_start()
client.on_message = on_message
client.loop_forever()
You are starting two message loops:
client.loop_start()
client.loop_forever()
This causes issues because the code is written with an assumption that only one message loop will be running.
The simplest way to resolve this is to remove the client.loop_start()
.
Note that it's probably better to call subscribe
from on_connect
as shown in "Getting Started". I would also suggest setting the callbacks before you call connect
(setting on_message
after starting the loop could, potentially, lead to message loss).