• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python client.topic_matches_sub函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中paho.mqtt.client.topic_matches_sub函数的典型用法代码示例。如果您正苦于以下问题:Python topic_matches_sub函数的具体用法?Python topic_matches_sub怎么用?Python topic_matches_sub使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了topic_matches_sub函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: on_message

def on_message(mosq, userdata, msg):
    """
    Message received from the broker
    """
    topic = msg.topic
    payload = str(msg.payload)
    logging.debug("Message received on %s: %s" % (topic, payload))

    hosts = None
    title = "Notification"
    
    # Try to find matching settings for this topic
    for sub in conf['topichost'].keys():
        if paho.topic_matches_sub(sub, topic):
            hosts = conf['topichost'][sub]
            break

    for sub in conf['topictitle'].keys():
        if paho.topic_matches_sub(sub, topic):
            title = conf['topictitle'][sub]
            break

    for host in hosts:
        logging.debug("Sending XBMC notification to %s [%s]..." % (host, title))
        xbmchost = conf['xbmchost'][host]
        notify_xbmc(xbmchost, title, payload)
开发者ID:sumnerboy12,项目名称:mqtt2xbmc,代码行数:26,代码来源:mqtt2xbmc.py


示例2: on_message

def on_message(mosq, userdata, msg):
    """
    Message received from the broker
    """
    topic = msg.topic
    payload = str(msg.payload)
    logging.debug("Message received on %s: %s" % (topic, payload))

    if msg.retain == 1:
        if cf.skipretained:
            logging.debug("Skipping retained message on %s" % topic)
            return

    # Try to find matching settings for this topic
    for section in get_sections():
        # Get the topic for this section (usually the section name but optionally overridden)
        match_topic = get_topic(section)
        if paho.topic_matches_sub(match_topic, topic):
            logging.debug("Section [%s] matches message on %s. Processing..." % (section, topic))
            # Check for any message filters
            if is_filtered(section, topic, payload):
                logging.debug("Filter in section [%s] has skipped message on %s" % (section, topic))
                continue
            # Send the message to any targets specified
            send_to_targets(section, topic, payload)
开发者ID:sjaca10,项目名称:mqttwarn-start,代码行数:25,代码来源:mqttwarn.py


示例3: __on_message

    def __on_message(self, client, obj, msg):
        # pylint: disable=W0613
        """
        A message has been received from a server

        :param client: Client that received the message
        :param obj: *Unused*
        :param msg: A Message bean
        """
        try:
            # Get the topic
            topic = msg.topic

            # Get all listeners matching this topic
            all_listeners = set()
            for subscription, listeners in self._topics.items():
                if paho.topic_matches_sub(subscription, topic):
                    all_listeners.update(listeners)

            # Notify them using the pool
            self._pool.enqueue(
                self.__notify_listeners,
                all_listeners,
                topic,
                msg.payload,
                msg.qos,
            )
        except KeyError:
            # No listener for this topic
            pass
开发者ID:tcalmant,项目名称:ipopo,代码行数:30,代码来源:mqtt.py


示例4: get_subscriptions

 def get_subscriptions(self, topic):
     """
     Find the subscriptions that match the given topic
     :param topic: Topic to check
     :return: list of found subscriptions
     """
     return [self.subscriptions[t] for t in self.subscriptions if mqtt.topic_matches_sub(t, topic)]
开发者ID:gonicus,项目名称:gosa,代码行数:7,代码来源:mqtt_client.py


示例5: on_message

def on_message(mosq, userdata, msg):
    """
    Message received from the broker
    """
    topic = msg.topic
    payload = str(msg.payload)
    logging.debug("Message received on %s: %s" % (topic, payload))

    username = conf['mailusername']
    password = conf['mailpassword']
    recipients = conf['recipient']
    subject = None

    # Try to find matching settings for this topic
    for sub in conf['topicsubject'].keys():
        if paho.topic_matches_sub(sub, topic):
            subject = conf['topicsubject'][sub]
            break
    
    if subject is None:
        return
        
    for recipient in recipients:
        logging.debug("Sending email to %s [%s]..." % (recipient, subject))
        send_mail(username, password, [recipient], subject, payload)
开发者ID:sumnerboy12,项目名称:mqtt2mail,代码行数:25,代码来源:mqtt2mail.py


示例6: _on_message_cb

def _on_message_cb(client, obj, msg):
        """
        This method will invoke the specified callback handler by the client app
        when a notification is received by the app based on the notification type.
        :param client: the client instance for this callback
        :param obj: the private user data as set in Client() or userdata_set()
        :param msg: an instance of Message. This is a class with members topic, payload, qos, retain
        """
        payload = msg.payload
        topic = msg.topic
        json_data = None
        decoder = json.JSONDecoder()
        json_data, end = decoder.raw_decode(payload)
        if json_data is None:
            logger.error('Received event has invalid JSON format')
            logger.error('Received payload: %s' % payload)
        if len(payload) != end:
            logger.error('Received event has additional invalid JSON format')
            logger.error('It has the following additional content: %s'
                         % payload[end:])
        callback_called = False
        for cbs in handlers:
            if cbs != '#':
                if mqtt.topic_matches_sub(cbs, topic):
                    for cb in handlers.get(cbs, []):
                        cb(json_data)
                        callback_called = True

        if callback_called is False:
            for cb in handlers.get('#', []):
                logger.debug('Sending data to callback %s' % cb)
                cb(json_data)
开发者ID:Juniper,项目名称:jet-app-store,代码行数:32,代码来源:utility.py


示例7: on_message

def on_message(mosq, userdata, msg):
    """
    Message received from the broker
    """

    topic = msg.topic
    payload = str(msg.payload)
    logging.debug("Message received on %s: %s" % (topic, payload))

    if msg.retain == 1:
        if cf.skipretained:
            logging.debug("Skipping retained message on %s" % topic)
            return

    # Try to find matching settings for this topic
    for section in get_sections():
        # Get the topic for this section (usually the section name but optionally overridden)
        match_topic = get_topic(section)
        if paho.topic_matches_sub(match_topic, topic):
            logging.debug("Section [%s] matches message on %s. Processing..." % (section, topic))
            # Check for any message filters
            if is_filtered(section, topic, payload):
                logging.debug("Filter in section [%s] has skipped message on %s" % (section, topic))
                continue
            
            targetlist = cf.getlist(section, 'targets')
            if type(targetlist) != list:
                logging.error("Target definition in section [%s] is incorrect" % section)
                cleanup(0)
                return

            for t in targetlist:
                logging.debug("Message on %s going to %s" % (topic, t))
                # Each target is either "service" or "service:target"
                # If no target specified then notify ALL targets
                service = t
                target = None

                # Check if this is for a specific target
                if t.find(':') != -1:
                    try:
                        service, target = t.split(':', 2)
                    except:
                        logging.warn("Invalid target %s - should be 'service:target'" % (t))
                        continue

                if not service in service_plugins:
                    logging.error("Invalid configuration: topic %s points to non-existing service %s" % (topic, service))
                    return

                sendtos = None
                if target is None:
                    sendtos = get_service_targets(service)
                else:
                    sendtos = [target]
                
                for sendto in sendtos:
                    job = Job(1, service, section, topic, payload, sendto)
                    q_in.put(job)
    return
开发者ID:sfromm,项目名称:mqttwarn,代码行数:60,代码来源:mqttwarn.py


示例8: on_message

def on_message(mosq, userdata, msg):

    sock = userdata['sock']
    host = userdata['carbon_server']
    port = userdata['carbon_port']
    lines = []
    now = int(time.time())

    map = userdata['map']
    # Find out how to handle the topic in this message: slurp through
    # our map 
    for t in map:
        if paho.topic_matches_sub(t, msg.topic):
            # print "%s matches MAP(%s) => %s" % (msg.topic, t, map[t])

            # Must we rename the received msg topic into a different
            # name for Carbon? In any case, replace MQTT slashes (/)
            # by Carbon periods (.)
            (type, remap) = map[t]
            if remap is None:
                carbonkey = msg.topic.replace('/', '.')
            else:
                carbonkey = remap.replace('/', '.')
            logging.debug("CARBONKEY is [%s]" % carbonkey)

            if type == 'n':
                '''Number: obtain a float from the payload'''
                try:
                    number = float(msg.payload)
                    #lines.append("%s %f %d" % (carbonkey, number, now))
                    lines.append("%s %f" % (carbonkey, number))
                except ValueError:
                    logging.info("Topic %s contains non-numeric payload [%s]" % 
                            (msg.topic, msg.payload))
                    return

            elif type == 'j':
                '''JSON: try and load the JSON string from payload and use
                   subkeys to pass to Carbon'''
                try:
                    st = json.loads(msg.payload)
                    for k in st:
                        if is_number(st[k]):
                            #lines.append("%s.%s %f %d" % (carbonkey, k, float(st[k]), now))
                            lines.append("%s.%s %f" % (carbonkey, k, float(st[k])))

                except:
                    logging.info("Topic %s contains non-JSON payload [%s]" %
                            (msg.topic, msg.payload))
                    return

            else:
                logging.info("Unknown mapping key [%s]", type)
                return

            message = '\n'.join(lines) + '\n'
            logging.debug("%s", message)

            sock.sendto(message, (host, port))
开发者ID:chaeplin,项目名称:mqtt2graphite,代码行数:59,代码来源:mqtt2graphite.py


示例9: topic_matches

    def topic_matches(cls, subscription_filter, topic):
        """
        Checks if the given topic matches the given subscription filter

        :param subscription_filter: A MQTT subscription filter
        :param topic: A topic
        :return: True if the topic matches the filter
        """
        return paho.topic_matches_sub(subscription_filter, topic)
开发者ID:isandlaTech,项目名称:cohorte-3rdparty,代码行数:9,代码来源:mqtt_client.py


示例10: get_messagefmt

def get_messagefmt(topic):
    ''' Find the message format from the topic '''
    fmt = None
    if 'formatmap' in conf:
        for key in conf['formatmap'].keys():
            if paho.topic_matches_sub(key, topic):
                fmt = conf['formatmap'][key]
                break
    return fmt
开发者ID:prologic,项目名称:mqttwarn,代码行数:9,代码来源:mqttwarn.py


示例11: get_messagefilter

def get_messagefilter(topic):
    ''' Find the message filter from the topic '''
    filter = None
    if 'filtermap' in conf:
        for key in conf['filtermap'].keys():
            if paho.topic_matches_sub(key, topic):
                filter = conf['filtermap'][key]
                break
    return filter
开发者ID:prologic,项目名称:mqttwarn,代码行数:9,代码来源:mqttwarn.py


示例12: get_priority

def get_priority(topic):
    ''' Find the "priority" (for pushover)
        from the topic. '''
    priority = None
    if 'prioritymap' in conf:
        for key in conf['prioritymap'].keys():
            if paho.topic_matches_sub(key, topic):
                priority = conf['prioritymap'][key]
                break
    return priority
开发者ID:prologic,项目名称:mqttwarn,代码行数:10,代码来源:mqttwarn.py


示例13: on_message

def on_message(client, userdata, msg):
    userdata.idMap_lock.acquire()
    try:
        for key in userdata.idMap.keys():
            if(mqtt.topic_matches_sub(key, str(msg.topic))): # check for wildcard matching
                ino_id = userdata.idMap[key]
                userdata.msgQ.put(str(ino_id) + " " + str(msg.payload)) # protocol-style convention needed
    except BaseException as e: # ignore clean session = false: msg from pre-subscribed topics
        pass
    userdata.idMap_lock.release()
开发者ID:Pillar1989,项目名称:AWS_Arduino_SDK,代码行数:10,代码来源:aws_iot_mqtt_client.py


示例14: get_title

def get_title(topic):
    ''' Find the "title" (for pushover) or "subject" (for smtp)
        from the topic. '''
    title = None
    if 'titlemap' in conf:
        for key in conf['titlemap'].keys():
            if paho.topic_matches_sub(key, topic):
                title = conf['titlemap'][key]
                break
    return title
开发者ID:prologic,项目名称:mqttwarn,代码行数:10,代码来源:mqttwarn.py


示例15: _callTriggers

	def _callTriggers(self, topic, data):
		for t in self.triggers:
			#print("testing topic: %s %s" % (t[0], topic) )
			if mqtt.topic_matches_sub(t[0], topic):
				#print "Trigger matches: %s %s" % (t[0] , t[1] )
				if (t[2]): # wants json
					#print("decoding json")
					#pprint(data)
					data = self._decodeJSON(str(data))
					#pprint(data)
				t[1](topic, data)
开发者ID:JohanZackrisson,项目名称:zmqtt,代码行数:11,代码来源:zmqtt.py


示例16: _on_mqtt_message

	def _on_mqtt_message(self, client, userdata, msg):
		if not client == self._mqtt:
			return

		from paho.mqtt.client import topic_matches_sub
		for subscription in self._mqtt_subscriptions:
			topic, callback, args, kwargs = subscription
			if topic_matches_sub(topic, msg.topic):
				args = [msg.topic, msg.payload] + args
				kwargs.update(dict(retained=msg.retain, qos=msg.qos))
				callback(*args, **kwargs)
开发者ID:Robo3D,项目名称:OctoPrint-MQTT,代码行数:11,代码来源:__init__.py


示例17: _on_message

 def _on_message(self, mqttc, userdata, msg):
     """
     接收消息处理
     :param mqttc:
     :param userdata:
     :param msg:
     :return:
     """
     #logger.info("MQTTCallback::on_message, mqttc:%s, userdata:%s, topic:%s, payload:%s" % (self, userdata, msg.topic, msg.payload))
     [handle_fun(self, userdata=userdata, topic=msg.topic, payload=msg.payload)
      for sub, handle_fun in self.topic_to_fun_dic.items()
      if topic_matches_sub(sub, msg.topic)]
     return True
开发者ID:duruo850,项目名称:HomeInternet,代码行数:13,代码来源:mqtt.py


示例18: on_message

def on_message(mosq, userdata, msg):
    """
    Message received from the broker
    """
    topic = msg.topic
    payload = str(msg.payload)
    logging.debug("Message received on %s: %s" % (topic, payload))

    # Try to find matching settings for this topic
    for sub in conf['topics']:
        if paho.topic_matches_sub(sub, topic):
            tweet(payload[0:138])
            break
开发者ID:sumnerboy12,项目名称:mqtt2twitter,代码行数:13,代码来源:mqtt2twitter.py


示例19: get_topic_data

def get_topic_data(topic):
    ''' Find out if there is a function in topicdatamap{} for
        adding topic into data. If there is, invoke that
        and return a dict of it '''
    data = None
    if 'topicdatamap' in conf:
        for key in conf['topicdatamap'].keys():
            if paho.topic_matches_sub(key, topic):
                func = conf['topicdatamap'][key]
                if hasattr(func, '__call__'):
                    try:
                        data = func(topic)
                    except Exception, e:
                        logging.warn("Cannot invoke func(%s): %s" % (topic, str(e)))
                break
开发者ID:prologic,项目名称:mqttwarn,代码行数:15,代码来源:mqttwarn.py


示例20: on_message

def on_message(mosq, userdata, msg):
    # print "%s (qos=%s, r=%s) %s" % (msg.topic, str(msg.qos), msg.retain, str(msg.payload))

    topic = msg.topic
    payload = msg.payload

    if paho.topic_matches_sub('ypom/+/+', topic):
        prefix, toidentifier, fromidentifier = topic.split('/', 3)

        try:
            u_from = userlist[fromidentifier]
            u_to = userlist[toidentifier]

            tst, msg = u_from.decrypt(msg.payload)
            msg = msg.decode('utf-8')
            print u'%s: %s  [%s]' % (u_from.identifier, msg, tst)
        except:
            raise
            print "SOMETHING WRONG"
开发者ID:jpmens,项目名称:ypom-cli,代码行数:19,代码来源:ypom-cli.py



注:本文中的paho.mqtt.client.topic_matches_sub函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python publish.single函数代码示例发布时间:2022-05-27
下一篇:
Python client.error_string函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap