Python MQTT callbacks in OOPCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?How to get the current time in PythonHow can I make a time delay in Python?Understanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?
How do I run a game when my PCs have different approaches to combat?
Memory capability and powers of 2
How to copy a file transactionally?
Q: What is a Checkmate Word™?
On the strategic interest of giving long lasting stock orders
Invert Some Switches on a Switchboard
Commercial jet accompanied by small plane near Seattle
How can I prevent corporations from growing their own workforce?
Send a single HTML email from Thunderbird, overriding the default "plain text" setting
What to do when you reach a conclusion and find out later on that someone else already did?
Anagramming in sixes
What are the exact meanings of roll, pitch and yaw?
Magento2: How can I logout customer from controller?
Why isn't there a serious attempt at creating a third mass-appeal party in the US?
How did C64 games handle music during gameplay?
Why did Saturn V not head straight to the moon?
Are the Cavalier's uses of Unwavering Mark or uses of the bonus attack granted limited per long rest?
Is it better to memorize verb's 1st person perfect tense?
What does "see" in "the Holy See" mean?
How may I concisely assign different values to a variable, depending on another variable?
Can the Artificer's infusions stack? Returning weapon + radiant weapon?
Why is my read in of data taking so long?
What should I say when a company asks you why someone (a friend) who was fired left?
Why are there not any MRI machines available in Interstellar?
Python MQTT callbacks in OOP
Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?How to get the current time in PythonHow can I make a time delay in Python?Understanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I'm currently trying to use the paho mqtt library in Python3 in a object oriented context.
However, for some reason, the callback functions don't get called.
import paho.mqtt.client as mqtt
import time
import logging
logger = logging.getLogger("IDS_LOGGER.refining")
logging.basicConfig(level=logging.INFO)
class refiner(object):
def __init__(self,configpath="./sampleconfig.xml"):
try:
self.CONFIGPATH = configpath
self.BROKER_IP = "localhost"
self.parse_config()
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.client.connect(self.BROKER_IP)
logging.info("Connected to 0, starting MQTT loop".format(self.BROKER_IP))
self.client.loop_forever()
except Exception as e:
print("error")
def on_message(self,client,userdata,msg):
"""MQTT Callback function for handling received messages"""
print("message received!")
def on_connect(self,client,userdata,msg):
print("connected!")
self.client.subscribe("TRACED")
why?
python python-3.x oop mqtt
add a comment |
I'm currently trying to use the paho mqtt library in Python3 in a object oriented context.
However, for some reason, the callback functions don't get called.
import paho.mqtt.client as mqtt
import time
import logging
logger = logging.getLogger("IDS_LOGGER.refining")
logging.basicConfig(level=logging.INFO)
class refiner(object):
def __init__(self,configpath="./sampleconfig.xml"):
try:
self.CONFIGPATH = configpath
self.BROKER_IP = "localhost"
self.parse_config()
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.client.connect(self.BROKER_IP)
logging.info("Connected to 0, starting MQTT loop".format(self.BROKER_IP))
self.client.loop_forever()
except Exception as e:
print("error")
def on_message(self,client,userdata,msg):
"""MQTT Callback function for handling received messages"""
print("message received!")
def on_connect(self,client,userdata,msg):
print("connected!")
self.client.subscribe("TRACED")
why?
python python-3.x oop mqtt
add a comment |
I'm currently trying to use the paho mqtt library in Python3 in a object oriented context.
However, for some reason, the callback functions don't get called.
import paho.mqtt.client as mqtt
import time
import logging
logger = logging.getLogger("IDS_LOGGER.refining")
logging.basicConfig(level=logging.INFO)
class refiner(object):
def __init__(self,configpath="./sampleconfig.xml"):
try:
self.CONFIGPATH = configpath
self.BROKER_IP = "localhost"
self.parse_config()
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.client.connect(self.BROKER_IP)
logging.info("Connected to 0, starting MQTT loop".format(self.BROKER_IP))
self.client.loop_forever()
except Exception as e:
print("error")
def on_message(self,client,userdata,msg):
"""MQTT Callback function for handling received messages"""
print("message received!")
def on_connect(self,client,userdata,msg):
print("connected!")
self.client.subscribe("TRACED")
why?
python python-3.x oop mqtt
I'm currently trying to use the paho mqtt library in Python3 in a object oriented context.
However, for some reason, the callback functions don't get called.
import paho.mqtt.client as mqtt
import time
import logging
logger = logging.getLogger("IDS_LOGGER.refining")
logging.basicConfig(level=logging.INFO)
class refiner(object):
def __init__(self,configpath="./sampleconfig.xml"):
try:
self.CONFIGPATH = configpath
self.BROKER_IP = "localhost"
self.parse_config()
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.client.connect(self.BROKER_IP)
logging.info("Connected to 0, starting MQTT loop".format(self.BROKER_IP))
self.client.loop_forever()
except Exception as e:
print("error")
def on_message(self,client,userdata,msg):
"""MQTT Callback function for handling received messages"""
print("message received!")
def on_connect(self,client,userdata,msg):
print("connected!")
self.client.subscribe("TRACED")
why?
python python-3.x oop mqtt
python python-3.x oop mqtt
asked Mar 26 at 16:29
Daniel SiegelDaniel Siegel
1711 gold badge2 silver badges13 bronze badges
1711 gold badge2 silver badges13 bronze badges
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
Replace your on_connect()
definition with:
def on_connect(self, client, userdata, flags, rc):
print("connected!")
self.client.subscribe("TRACED")
Also for debugging purposes, consider printing the actual exception in the exception handler instead of just printing "error"
:
try:
...
except Exception as e:
print(e)
With the fixes above, I tested your code by connecting to test.mosquitto.org
:
class refiner(object):
def __init__(self):
try:
self.BROKER_IP = "test.mosquitto.org"
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.connect(self.BROKER_IP, 1883, 60)
logging.info("Connected to 0, starting MQTT loop".format(self.BROKER_IP))
self.client.loop_forever()
except Exception as e:
print(e)
def on_connect(self, client, userdata, flags, rc):
print("connected!")
self.client.subscribe("TRACED")
x = refiner()
And it successfully outputs:
INFO:root:Connected to test.mosquitto.org, starting MQTT loop
connected!
add a comment |
I am Reading The Fine Docs.
They say you should:
def on_connect(client, userdata, flags, rc):
....
client = mqtt.Client()
client.on_connect = on_connect
Bbuuuttt, you didn't do that.
Within an OO class you have:
def on_connect(self, client, userdata, msg):
Hmmm. Initially I thought that adding self
was the problem, that your method would expect one more arg than paho provides when calling back.
But having written them both out, now I see that you turned flags, rc
into msg
, for reasons I cannot fathom.
I was thinking that somewhere behind the scenes paho might be logging a takes 5 positional arguments but 4 were given
python error, but now it's unclear what happened.
In any event, you could finesse this detail and put the concern to rest with this code:
def on_connect(*args, **kwargs:
with open('/tmp/log', 'a') as fout:
fout.write('connected!n')
I avoided print()
just in case sys.stdout
is no longer connected to your shell terminal.
Consider using enable_logger
at DEBUG level, and perhaps even the on_log
callback.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55361993%2fpython-mqtt-callbacks-in-oop%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Replace your on_connect()
definition with:
def on_connect(self, client, userdata, flags, rc):
print("connected!")
self.client.subscribe("TRACED")
Also for debugging purposes, consider printing the actual exception in the exception handler instead of just printing "error"
:
try:
...
except Exception as e:
print(e)
With the fixes above, I tested your code by connecting to test.mosquitto.org
:
class refiner(object):
def __init__(self):
try:
self.BROKER_IP = "test.mosquitto.org"
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.connect(self.BROKER_IP, 1883, 60)
logging.info("Connected to 0, starting MQTT loop".format(self.BROKER_IP))
self.client.loop_forever()
except Exception as e:
print(e)
def on_connect(self, client, userdata, flags, rc):
print("connected!")
self.client.subscribe("TRACED")
x = refiner()
And it successfully outputs:
INFO:root:Connected to test.mosquitto.org, starting MQTT loop
connected!
add a comment |
Replace your on_connect()
definition with:
def on_connect(self, client, userdata, flags, rc):
print("connected!")
self.client.subscribe("TRACED")
Also for debugging purposes, consider printing the actual exception in the exception handler instead of just printing "error"
:
try:
...
except Exception as e:
print(e)
With the fixes above, I tested your code by connecting to test.mosquitto.org
:
class refiner(object):
def __init__(self):
try:
self.BROKER_IP = "test.mosquitto.org"
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.connect(self.BROKER_IP, 1883, 60)
logging.info("Connected to 0, starting MQTT loop".format(self.BROKER_IP))
self.client.loop_forever()
except Exception as e:
print(e)
def on_connect(self, client, userdata, flags, rc):
print("connected!")
self.client.subscribe("TRACED")
x = refiner()
And it successfully outputs:
INFO:root:Connected to test.mosquitto.org, starting MQTT loop
connected!
add a comment |
Replace your on_connect()
definition with:
def on_connect(self, client, userdata, flags, rc):
print("connected!")
self.client.subscribe("TRACED")
Also for debugging purposes, consider printing the actual exception in the exception handler instead of just printing "error"
:
try:
...
except Exception as e:
print(e)
With the fixes above, I tested your code by connecting to test.mosquitto.org
:
class refiner(object):
def __init__(self):
try:
self.BROKER_IP = "test.mosquitto.org"
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.connect(self.BROKER_IP, 1883, 60)
logging.info("Connected to 0, starting MQTT loop".format(self.BROKER_IP))
self.client.loop_forever()
except Exception as e:
print(e)
def on_connect(self, client, userdata, flags, rc):
print("connected!")
self.client.subscribe("TRACED")
x = refiner()
And it successfully outputs:
INFO:root:Connected to test.mosquitto.org, starting MQTT loop
connected!
Replace your on_connect()
definition with:
def on_connect(self, client, userdata, flags, rc):
print("connected!")
self.client.subscribe("TRACED")
Also for debugging purposes, consider printing the actual exception in the exception handler instead of just printing "error"
:
try:
...
except Exception as e:
print(e)
With the fixes above, I tested your code by connecting to test.mosquitto.org
:
class refiner(object):
def __init__(self):
try:
self.BROKER_IP = "test.mosquitto.org"
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.connect(self.BROKER_IP, 1883, 60)
logging.info("Connected to 0, starting MQTT loop".format(self.BROKER_IP))
self.client.loop_forever()
except Exception as e:
print(e)
def on_connect(self, client, userdata, flags, rc):
print("connected!")
self.client.subscribe("TRACED")
x = refiner()
And it successfully outputs:
INFO:root:Connected to test.mosquitto.org, starting MQTT loop
connected!
answered Mar 29 at 9:14
glhrglhr
3,3131 gold badge9 silver badges21 bronze badges
3,3131 gold badge9 silver badges21 bronze badges
add a comment |
add a comment |
I am Reading The Fine Docs.
They say you should:
def on_connect(client, userdata, flags, rc):
....
client = mqtt.Client()
client.on_connect = on_connect
Bbuuuttt, you didn't do that.
Within an OO class you have:
def on_connect(self, client, userdata, msg):
Hmmm. Initially I thought that adding self
was the problem, that your method would expect one more arg than paho provides when calling back.
But having written them both out, now I see that you turned flags, rc
into msg
, for reasons I cannot fathom.
I was thinking that somewhere behind the scenes paho might be logging a takes 5 positional arguments but 4 were given
python error, but now it's unclear what happened.
In any event, you could finesse this detail and put the concern to rest with this code:
def on_connect(*args, **kwargs:
with open('/tmp/log', 'a') as fout:
fout.write('connected!n')
I avoided print()
just in case sys.stdout
is no longer connected to your shell terminal.
Consider using enable_logger
at DEBUG level, and perhaps even the on_log
callback.
add a comment |
I am Reading The Fine Docs.
They say you should:
def on_connect(client, userdata, flags, rc):
....
client = mqtt.Client()
client.on_connect = on_connect
Bbuuuttt, you didn't do that.
Within an OO class you have:
def on_connect(self, client, userdata, msg):
Hmmm. Initially I thought that adding self
was the problem, that your method would expect one more arg than paho provides when calling back.
But having written them both out, now I see that you turned flags, rc
into msg
, for reasons I cannot fathom.
I was thinking that somewhere behind the scenes paho might be logging a takes 5 positional arguments but 4 were given
python error, but now it's unclear what happened.
In any event, you could finesse this detail and put the concern to rest with this code:
def on_connect(*args, **kwargs:
with open('/tmp/log', 'a') as fout:
fout.write('connected!n')
I avoided print()
just in case sys.stdout
is no longer connected to your shell terminal.
Consider using enable_logger
at DEBUG level, and perhaps even the on_log
callback.
add a comment |
I am Reading The Fine Docs.
They say you should:
def on_connect(client, userdata, flags, rc):
....
client = mqtt.Client()
client.on_connect = on_connect
Bbuuuttt, you didn't do that.
Within an OO class you have:
def on_connect(self, client, userdata, msg):
Hmmm. Initially I thought that adding self
was the problem, that your method would expect one more arg than paho provides when calling back.
But having written them both out, now I see that you turned flags, rc
into msg
, for reasons I cannot fathom.
I was thinking that somewhere behind the scenes paho might be logging a takes 5 positional arguments but 4 were given
python error, but now it's unclear what happened.
In any event, you could finesse this detail and put the concern to rest with this code:
def on_connect(*args, **kwargs:
with open('/tmp/log', 'a') as fout:
fout.write('connected!n')
I avoided print()
just in case sys.stdout
is no longer connected to your shell terminal.
Consider using enable_logger
at DEBUG level, and perhaps even the on_log
callback.
I am Reading The Fine Docs.
They say you should:
def on_connect(client, userdata, flags, rc):
....
client = mqtt.Client()
client.on_connect = on_connect
Bbuuuttt, you didn't do that.
Within an OO class you have:
def on_connect(self, client, userdata, msg):
Hmmm. Initially I thought that adding self
was the problem, that your method would expect one more arg than paho provides when calling back.
But having written them both out, now I see that you turned flags, rc
into msg
, for reasons I cannot fathom.
I was thinking that somewhere behind the scenes paho might be logging a takes 5 positional arguments but 4 were given
python error, but now it's unclear what happened.
In any event, you could finesse this detail and put the concern to rest with this code:
def on_connect(*args, **kwargs:
with open('/tmp/log', 'a') as fout:
fout.write('connected!n')
I avoided print()
just in case sys.stdout
is no longer connected to your shell terminal.
Consider using enable_logger
at DEBUG level, and perhaps even the on_log
callback.
answered Mar 26 at 17:25
J_HJ_H
6,0551 gold badge9 silver badges24 bronze badges
6,0551 gold badge9 silver badges24 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55361993%2fpython-mqtt-callbacks-in-oop%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown