全部产品
云市场

自定义MQTT Topic通信

更新时间:2018-11-27 21:44:13

本文介绍如何直接基于MQTT Topic向云端发送消息,以及从云端接收消息。

从云端接收消息

订阅云端消息

  1. rc, mid = lk.subscribe_topic(lk.to_full_topic("user/test"))

注:上面的代码示例中lk为调用linkkit.LinkKit()后返回的示例。

订阅结果通过on_subscribe_topic通知用户:

  1. lk.on_subscribe_topic = on_subscribe_topic
  2. def on_subscribe_topic(mid, granted_qos, userdata):
  3. print("on_subscribe_topic mid:%d, granted_qos:%s" %
  4. (mid, str(','.join('%s' % it for it in granted_qos))))
  5. pass

granded_qos 为订阅topic列表对应的qos返回结果,正常值为0或1,128表示订阅失败

接收与处理来自云端的消息

通过on_topic_message()回调告知用户

  1. lk.on_topic_message = on_topic_message
  2. def on_topic_message(topic, payload, qos, userdata):
  3. print("on_topic_message:" + topic + " payload:" + str(payload) + " qos:" + str(qos))
  4. pass

发送消息到云端

发送消息

通过调用publish_topic()实现将消息发送到云端:

  1. rc, mid = lk.publish_topic(lk.to_full_topic("user/pub"), "123")

发布消息结果通知

消息发送后,云端是否成功接收通过on_publish_topic回调通知用户:

  1. lk.on_publish_topic = on_publish_topic
  2. def on_publish_topic(mid, userdata):
  3. print("on_publish_topic mid:%d" % mid)

注:publish_topic rc返回值为0则表明已经写入到了发送缓冲区,回调on_publish_topic 表明publish成功

取消消息订阅

通过调用unsubscribe_topic()取消对指定topic消息的订阅:

  1. rc, mid = lk.unsubscribe_topic(lk.to_full_topic("user/test"))

取消订阅的结果通过on_unsubscribe_topic回调通知用户:

  1. lk.on_unsubscribe_topic = on_unsubscribe_topic
  2. def on_unsubscribe_topic(mid, userdata):
  3. print("on_unsubscribe_topic mid:%d" % mid)
  4. pass

unsubscribe_topic 返回值rc 为0表明请求已写入缓存区,其它值失败。当回调on_unsubscribe_topic时表明取消成功