当前位置: 首页>>代码示例>>Python>>正文


Python client.MQTTMessage方法代码示例

本文整理汇总了Python中paho.mqtt.client.MQTTMessage方法的典型用法代码示例。如果您正苦于以下问题:Python client.MQTTMessage方法的具体用法?Python client.MQTTMessage怎么用?Python client.MQTTMessage使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在paho.mqtt.client的用法示例。


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

示例1: test_mqtt_handle_partition_control

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def test_mqtt_handle_partition_control(command, expected, mocker):
    interface = get_interface(mocker)
    try:
        await asyncio.sleep(0.01)

        message = MQTTMessage(topic=b'paradox/control/partition/First_floor')
        message.payload = command

        interface._mqtt_handle_partition_control(None, None, message)
        await asyncio.sleep(0.01)

        interface.alarm.control_partition.assert_called_once_with(
            "First_floor",
            expected
        )
    finally:
        interface.stop()
        interface.join()
        assert not interface.is_alive() 
开发者ID:ParadoxAlarmInterface,项目名称:pai,代码行数:21,代码来源:test_basic.py

示例2: test_mqtt_handle_zone_control

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def test_mqtt_handle_zone_control(mocker):
    interface = get_interface(mocker)
    try:
        await asyncio.sleep(0.01)

        message = MQTTMessage(topic=b'paradox/control/zones/El_t_r')
        message.payload = b'clear_bypass'

        interface._mqtt_handle_zone_control(None, None, message)
        await asyncio.sleep(0.01)

        interface.alarm.control_zone.assert_called_once_with(
            "El_t_r",
            "clear_bypass"
        )
    finally:
        interface.stop()
        interface.join()
        assert not interface.is_alive() 
开发者ID:ParadoxAlarmInterface,项目名称:pai,代码行数:21,代码来源:test_basic.py

示例3: test_mqtt_handle_zone_control_utf8

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def test_mqtt_handle_zone_control_utf8(mocker):
    interface = get_interface(mocker)
    try:
        await asyncio.sleep(0.01)

        message = MQTTMessage(topic='paradox/control/zones/Előtér'.encode('utf-8'))
        message.payload = b'clear_bypass'

        interface._mqtt_handle_zone_control(None, None, message)

        await asyncio.sleep(0.01)
        interface.alarm.control_zone.assert_called_once_with(
            "Előtér",
            "clear_bypass"
        )
    finally:
        interface.stop()
        interface.join()
        assert not interface.is_alive() 
开发者ID:ParadoxAlarmInterface,项目名称:pai,代码行数:21,代码来源:test_basic.py

示例4: onAudioFrame

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def onAudioFrame(self, message: mqtt.MQTTMessage):
		try:
			riff, size, fformat = struct.unpack('<4sI4s', message.payload[:12])

			if riff != b'RIFF':
				self.logError('Frame parse error')
				return

			if fformat != b'WAVE':
				self.logError('Frame wrong format')
				return

			chunkOffset = 52
			while chunkOffset < size:
				subChunk2Id, subChunk2Size = struct.unpack('<4sI', message.payload[chunkOffset:chunkOffset + 8])
				chunkOffset += 8
				if subChunk2Id == b'data':
					self._buffer.put(message.payload[chunkOffset:chunkOffset + subChunk2Size])

				chunkOffset = chunkOffset + subChunk2Size + 8

		except Exception as e:
			self.logError(f'Error recording user speech: {e}') 
开发者ID:project-alice-assistant,项目名称:ProjectAlice,代码行数:25,代码来源:Recorder.py

示例5: processMessage

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def processMessage(self, message: MQTTMessage) -> bool:
		sessionId = self.Commons.parseSessionId(message)
		session = self.DialogSessionManager.getSession(sessionId)
		if not session or self.isProcessing(sessionId):
			return False

		payload = session.payload
		if 'input' in payload:
			separators = self.LanguageManager.getStrings('intentSeparator')
			GLUE_SPLITTER = '__multi_intent__'
			userInput = payload['input']

			for separator in separators:
				userInput.replace(separator, GLUE_SPLITTER)

			if GLUE_SPLITTER in userInput:
				self._multiIntents[session.sessionId] = MultiIntent(
					session=session,
					processedString=userInput,
					intents=deque(userInput.split(GLUE_SPLITTER)))

				return self.processNextIntent(session.sessionId)

		return False 
开发者ID:project-alice-assistant,项目名称:ProjectAlice,代码行数:26,代码来源:MultiIntentManager.py

示例6: onSnipsIntentParsed

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def onSnipsIntentParsed(self, client, data, msg: mqtt.MQTTMessage):
		sessionId = self.Commons.parseSessionId(msg)
		session = self.DialogSessionManager.getSession(sessionId=sessionId)

		if session:
			session.update(msg)
			self.broadcast(method=constants.EVENT_INTENT_PARSED, exceptions=[self.name], propagateToSkills=True, session=session)

			if session.isAPIGenerated:
				intent = Intent(session.payload['intent']['intentName'])
				message = mqtt.MQTTMessage(topic=str.encode(str(intent)))
				message.payload = json.dumps(session.payload)
				self.onMqttMessage(client=client, userdata=data, message=message)


	# noinspection PyUnusedLocal 
开发者ID:project-alice-assistant,项目名称:ProjectAlice,代码行数:18,代码来源:MqttManager.py

示例7: onSnipsSay

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def onSnipsSay(self, client, data, msg: mqtt.MQTTMessage):
		sessionId = self.Commons.parseSessionId(msg)
		payload = self.Commons.payload(msg)

		session = self.DialogSessionManager.getSession(sessionId)
		if session:
			session.update(msg)
			siteId = session.siteId
		else:
			siteId = self.Commons.parseSiteId(msg)

		if 'text' in payload:
			skill = self.SkillManager.getSkillInstance('ContextSensitive')
			if skill:
				skill.addChat(text=payload['text'], siteId=siteId)

		self.broadcast(method=constants.EVENT_SAY, exceptions=[self.name], propagateToSkills=True, session=session)


	# noinspection PyUnusedLocal 
开发者ID:project-alice-assistant,项目名称:ProjectAlice,代码行数:22,代码来源:MqttManager.py

示例8: process

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def process(self):
		try:
			siteId = request.form.get('siteId') if request.form.get('siteId', None) is not None else constants.DEFAULT_SITE_ID

			sessionId = str(uuid.uuid4())
			message = MQTTMessage()
			message.payload = json.dumps({'sessionId': sessionId, 'siteId': siteId})

			session = self.DialogSessionManager.addSession(sessionId=sessionId, message=message)
			session.isAPIGenerated = True
			self.MqttManager.publish(topic=constants.TOPIC_NLU_QUERY, payload={
				'input'    : request.form.get('query'),
				'sessionId': session.sessionId
			})
			return jsonify(success=True)
		except Exception as e:
			self.logError(f'Failed processing: {e}')
			return jsonify(success=False) 
开发者ID:project-alice-assistant,项目名称:ProjectAlice,代码行数:20,代码来源:DialogApi.py

示例9: _callback_mqtt

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def _callback_mqtt(self, client, userdata, mqtt_msg):
        u""" callback from MQTT

        :param mqtt.Client client: MQTT client used in connection
        :param userdata: user defined data
        :param mqtt.MQTTMessage mqtt_msg: MQTT message
        """
        rospy.logdebug("MQTT received from {}".format(mqtt_msg.topic))
        now = rospy.get_time()

        if self._interval is None or now - self._last_published >= self._interval:
            try:
                ros_msg = self._create_ros_message(mqtt_msg)
                self._publisher.publish(ros_msg)
                self._last_published = now
            except Exception as e:
                rospy.logerr(e) 
开发者ID:groove-x,项目名称:mqtt_bridge,代码行数:19,代码来源:bridge.py

示例10: on_message

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def on_message(
    client: mqtt.Client, ref_self: IotManager, message: mqtt.MQTTMessage
) -> None:
    """Callback for when the mqtt broker receives a message on a subscription."""
    ref_self.logger.debug("Received message from broker")

    # Increment received message count
    ref_self.received_message_count += 1

    # Route message
    if ref_self.config_topic in message.topic:
        ref_self.on_config_message(message)
    elif ref_self.command_topic in message.topic:
        ref_self.on_command_message(message)
    else:
        ref_self.logger.error(
            "Recevied unknown message topic: {}".format(message.topic)
        )
        ref_self.logger.debug(f"Config topic: {ref_self.config_topic}")
        ref_self.logger.debug(f"Command topic: {ref_self.command_topic}") 
开发者ID:OpenAgricultureFoundation,项目名称:openag-device-software,代码行数:22,代码来源:manager.py

示例11: test_format_request_var_dict

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def test_format_request_var_dict(self, fulltest, includes):
        """Variables from request should be available to format in response -
        this is the original keys in the input file, NOT the formatted ones
        where 'json' is converted to 'payload' in the actual MQTT publish"""

        stage = fulltest["stages"][0]
        sent = stage["mqtt_publish"]["json"]

        mockargs = {
            "spec": paho.MQTTMessage,
            "payload": json.dumps({"echo": sent["message"]}).encode("utf8"),
            "topic": stage["mqtt_publish"]["topic"],
        }
        mock_response = Mock(**mockargs)

        fake_client = MagicMock(
            spec=MQTTClient, message_received=Mock(return_value=mock_response)
        )

        with patch("tavern._plugins.mqtt.client.paho.Client", fake_client), patch(
            "tavern.core.get_extra_sessions", return_value={"paho-mqtt": fake_client}
        ) as pmock:
            run_test("heif", fulltest, includes)

        assert pmock.called 
开发者ID:taverntesting,项目名称:tavern,代码行数:27,代码来源:test_core.py

示例12: test_format_request_var_value

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def test_format_request_var_value(self, fulltest, includes):
        """Same as above but with plain keys"""
        stage = fulltest["stages"][0]
        sent = stage["mqtt_publish"]["payload"]

        mockargs = {
            "spec": paho.MQTTMessage,
            "payload": sent.encode("utf8"),
            "topic": stage["mqtt_publish"]["topic"],
        }
        mock_response = Mock(**mockargs)

        fake_client = MagicMock(
            spec=MQTTClient, message_received=Mock(return_value=mock_response)
        )

        with patch("tavern._plugins.mqtt.client.paho.Client", fake_client), patch(
            "tavern.core.get_extra_sessions", return_value={"paho-mqtt": fake_client}
        ) as pmock:
            run_test("heif", fulltest, includes)

        assert pmock.called 
开发者ID:taverntesting,项目名称:tavern,代码行数:24,代码来源:test_core.py

示例13: send_message

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def send_message(topic=None, payload=None):

    # Mock an instance of an Eclipse Paho MQTTMessage
    message = MQTTMessage(mid=42, topic=topic.encode('utf-8'))
    message.payload = payload.encode('utf-8')

    # Signal the message to the machinery
    on_message(None, None, message)

    # Give the machinery some time to process the message
    time.sleep(0.05) 
开发者ID:jpmens,项目名称:mqttwarn,代码行数:13,代码来源:util.py

示例14: onAudioFrame

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def onAudioFrame(self, message: mqtt.MQTTMessage, siteId: str):
		if siteId not in self._streams or not self._streams[siteId].isRecording:
			return

		self._streams[siteId].onAudioFrame(message) 
开发者ID:project-alice-assistant,项目名称:ProjectAlice,代码行数:7,代码来源:ASRManager.py

示例15: extend

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTMessage [as 别名]
def extend(self, message: MQTTMessage, sessionId: str = None):
		if sessionId:
			self.sessionId = sessionId

		self.addToHistory(self.intentName)

		commonsManager = SuperManager.getInstance().commonsManager
		self.message = message
		self.intentName = message.topic
		self.payload = commonsManager.payload(message)
		self.slots = commonsManager.parseSlots(message)
		self.slotsAsObjects = commonsManager.parseSlotsToObjects(message)
		self.customData = commonsManager.parseCustomData(message) 
开发者ID:project-alice-assistant,项目名称:ProjectAlice,代码行数:15,代码来源:DialogSession.py


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