def on_connect(client, userdata, flags, rc):
log.debug("MQTT Client connection results: {}".format(mqtt.connack_string(rc)))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
# QOS 0: The broker will deliver the message once, with no confirmation.
# QOS 1: The broker will deliver the message at least once, with confirmation required.
# QOS 2: The broker will deliver the message exactly once by using a four step handshake.
#
# A list of tuples (i.e. topic, qos). Both topic and qos must be present in the tuple.
topics = [(settings.GPS_TOPIC, 2),
(settings.MODEM_TEMP_TOPIC, 1),
(settings.WAN_CONNECTION_STATE_TOPIC, 0)]
try:
client.subscribe(topics)
except Exception as ex:
log.error('Client Subscribe exception. ex={}'.format(ex))
# Called when a message has been received on a topic that the client subscribes
# to and the message does not match an existing topic filter callback. Use
# message_callback_add() to define a callback that will be called for specific
# topic filters. on_message will serve as fallback when none matched.
python类connack_string()的实例源码
def on_connect(client, userdata, flags, rc):
if rc == 0:
print('Connected.\n')
else:
print('Connection error with result code {} - {}'.format(str(rc), mqtt.connack_string(rc)), file=sys.stderr)
#kill main thread
os._exit(1)
def on_connect(self, mqtt, userdata, flags, rc):
"""
Callback when MQTT Client connects to Cloud
"""
unfinished = self.num_unfinished()
if (unfinished > 0):
self.logger.info("%s messages are pending..", unfinished)
# Check connection result from MQTT
self.logger.info("MQTT connected: %s", mqttlib.connack_string(rc))
if rc == 0:
self.state = constants.STATE_CONNECTED
else:
self.state = constants.STATE_DISCONNECTED
self.last_connected = datetime.utcnow()
def on_connect(mqttc, obj, flags, rc):
print("on_connect(): result code = {} ({})".format(rc, mqtt.connack_string(rc)))
def on_connect(mqttclient, userdata, flags, rc):
userdata.log("on_connect(): result code = {} ({})".format(rc, mqtt.connack_string(rc)))
def start_mqtt():
global mqtt_client
try:
log.debug('Start MQTT Client')
mqtt_client = mqtt.Client(client_id=settings.MQTT_CLIENT_ID)
if settings.MQTT_LOGGING:
# Add MQTT logging to the app logs
mqtt_client.enable_logger(AppLogger.logger)
else:
mqtt_client.disable_logger()
# Assign callback functions
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
mqtt_client.on_publish = on_publish
mqtt_client.on_subscribe = on_subscribe
# Set a Will to be sent by the broker in case the client disconnects unexpectedly.
# QOS 2: The broker will deliver the message exactly once by using a four step handshake.
mqtt_client.will_set('/will/oops', payload='{} has vanished!'.format(settings.MQTT_CLIENT_ID), qos=2)
connack_code = mqtt_client.connect(settings.MQTT_SERVER, settings.MQTT_PORT)
log.info('MQTT connect reply to {}, {}: {}'.format(settings.MQTT_SERVER, settings.MQTT_PORT,
mqtt.connack_string(connack_code)))
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
mqtt_client.loop_forever()
except Exception as ex:
log.error('Exception in start_mqtt()! exception: {}'.format(ex))
raise
def _on_connect(client, userdata, flags, rc):
"""Internal callback"""
#pylint: disable=invalid-name, unused-argument
if rc == 0:
if len(userdata) > 0:
_do_publish(client)
else:
raise mqtt.MQTTException(paho.connack_string(rc))
def _on_connect(client, userdata, flags, rc):
"""Internal callback"""
if rc != 0:
raise mqtt.MQTTException(paho.connack_string(rc))
if isinstance(userdata['topics'], list):
for topic in userdata['topics']:
client.subscribe(topic, userdata['qos'])
else:
client.subscribe(userdata['topics'], userdata['qos'])
def _on_mqtt_connect(self, _, __, ___, result):
if result:
errorMessage = "Error connecting to mqtt broker: " + mqtt.connack_string(result)
logger.error(errorMessage)
raise WolkMQTTClientException(errorMessage)
else:
logger.info("Connected %s to mqtt broker", self.clientConfig.username)
for topic in self.clientConfig.topics:
(res, ____) = self.client.subscribe(topic, self.clientConfig.qos)
if res == 0:
logger.info("Subscribed to topic: %s", topic)
else:
logger.error("Failed subscribing to topic: %s reason: %s", topic, mqtt.error_string(res))
def _start_client(self):
self.mqtt_client = mqtt.Client(self.config.mqtt_client_id)
if self.config.mqtt_user is not None:
self.mqtt_client.username_pw_set(self.config.mqtt_user, self.config.mqtt_password)
if self.config.mqtt_ca_cert is not None:
self.mqtt_client.tls_set(self.config.mqtt_ca_cert, cert_reqs=mqtt.ssl.CERT_REQUIRED)
def _on_connect(client, _, flags, return_code):
self.connected = True
logging.info("MQTT connection returned result: %s", mqtt.connack_string(return_code))
self.mqtt_client.on_connect = _on_connect
self.mqtt_client.connect(self.config.mqtt_server, self.config.mqtt_port, 60)
self.mqtt_client.loop_start()
def on_connect(client, userdata, flags, rc):
if rc == 0:
print_line('MQTT connection established', console=True, sd_notify=True)
print()
else:
print_line('Connection error with result code {} - {}'.format(str(rc), mqtt.connack_string(rc)), error=True)
#kill main thread
os._exit(1)