Question

When my python code tries to connect to the MQTT broker it gives me this Type Error:

Update- I added the Complete Error

Traceback (most recent call last):
  File "test.py", line 20, in <module>
    mqttc.connect(broker, 1883, 60, True)
  File "/usr/local/lib/python2.7/dist-packages/mosquitto.py", line 563, in connect
    return self.reconnect()
  File "/usr/local/lib/python2.7/dist-packages/mosquitto.py", line 632, in reconnect
    self._sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
  File "/usr/lib/python2.7/socket.py", line 561, in create_connection
    sock.bind(source_address)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
TypeError: coercing to Unicode: need string or buffer, bool found

The code of the python file is:

#! /usr/bin/python
import mosquitto
broker = "localhost"
#define what happens after connection
    def on_connect(rc):
        print "Connected"
#On recipt of a message do action
    def on_message(msg):
        n = msg.payload
        t = msg.topic
        if t == "/test/topic":
            if n == "test": 
        print "test message received"

# create broker
mqttc = mosquitto.Mosquitto("python_sub")
#define callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
#connect
mqttc.connect(broker, 1883, 60, True)
#Subscribe to topic
mqttc.subscribe("/test/topic", 2)

#keep connected
while mqttc.loop() == 0:
    pass    

I have no idea why its giving me this it work 2 days ago.

Was it helpful?

Solution

My guess is that you're using Debian testing. The Debian package for mosquitto finally got upgraded from the old 0.15 to 1.2.1. One of the changes with 1.0 was a rejig of the API.

This means that your call

mqttc.connect(broker, 1883, 60, True)

should become

mqttc.connect(broker, 1883, 60)

The True from the original call was setting the clean_session parameter, which is deemed to be a property of the client (so has moved to the Mosquitto() constructor) rather than a connection parameter.

Version 1.2 added the bind_address parameter to the connect() call. This expects a string, hence your error about needing a string but having a bool.

Something else you might find useful - if you don't specify a client id (python_sub in your example), then the mosquitto module will generate a random id for you and give a smaller chance of there being a collision on the broker.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top