Python paho.mqtt.client.MQTTMessage() Examples

The following are 30 code examples of paho.mqtt.client.MQTTMessage(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module paho.mqtt.client , or try the search function .
Example #1
Source File: test_basic.py    From pai with Eclipse Public License 2.0 7 votes vote down vote up
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() 
Example #2
Source File: manager.py    From openag-device-software with GNU General Public License v3.0 6 votes vote down vote up
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}") 
Example #3
Source File: MqttManager.py    From ProjectAlice with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: MqttManager.py    From ProjectAlice with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: DialogApi.py    From ProjectAlice with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #6
Source File: bridge.py    From mqtt_bridge with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: test_core.py    From tavern with MIT License 6 votes vote down vote up
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 
Example #8
Source File: test_core.py    From tavern with MIT License 6 votes vote down vote up
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 
Example #9
Source File: Recorder.py    From ProjectAlice with GNU General Public License v3.0 6 votes vote down vote up
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}') 
Example #10
Source File: MultiIntentManager.py    From ProjectAlice with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #11
Source File: test_basic.py    From pai with Eclipse Public License 2.0 6 votes vote down vote up
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() 
Example #12
Source File: test_basic.py    From pai with Eclipse Public License 2.0 6 votes vote down vote up
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() 
Example #13
Source File: test_mqtt.py    From squeeze-alexa with GNU General Public License v3.0 5 votes vote down vote up
def react_to_msg(self, payload):
        """Fake the round trip entirely"""
        msg = MQTTMessage(topic=self.settings.topic_resp)
        msg.payload = b"%s%s" % (self.PREFIX.encode('utf-8'), payload)
        self.on_message(self, None, msg) 
Example #14
Source File: mqtt_integration_test.py    From squeeze-alexa with GNU General Public License v3.0 5 votes vote down vote up
def test_real_publishing(self, mqtt_settings, client, broker, transport):
        log.info("Broker running: %s", broker)
        self.published = []
        self.subscribed = False

        def on_message(client: Client, userdata, msg: MQTTMessage):
            msg = msg.payload.decode('utf-8').strip()
            client.publish(mqtt_settings.topic_resp,
                           "GOT: {m}".format(m=msg).encode('utf-8'))

        def on_subscribe(client, data, mid, granted_qos):
            self.subscribed = True

        def on_publish(client, userdata, mid):
            self.published.append(mid)

        client.on_publish = on_publish
        replier = CustomTlsCustomClient(mqtt_settings,
                                        on_subscribe=on_subscribe,
                                        on_message=on_message)
        replier.connect()
        transport.start()
        replier.subscribe(mqtt_settings.topic_req)
        assert replier.loop_start() != MQTT_ERR_INVAL
        wait_for(lambda x: self.subscribed,
                 what="confirming subscription", timeout=3)
        reply = transport.communicate(TEST_MSG, timeout=3)
        wait_for(lambda x: self.published,
                 what="confirming publish", timeout=3)
        assert len(self.published) == 1
        log.debug("Received reply: %s", reply)
        assert reply == "GOT: {msg}".format(msg=TEST_MSG) 
Example #15
Source File: MqttManager.py    From ProjectAlice with GNU General Public License v3.0 5 votes vote down vote up
def onSnipsSayFinished(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)

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


	# noinspection PyUnusedLocal 
Example #16
Source File: MqttManager.py    From ProjectAlice with GNU General Public License v3.0 5 votes vote down vote up
def onNluPartialCapture(self, client, data, msg: mqtt.MQTTMessage):
		sessionId = self.Commons.parseSessionId(msg)
		session = self.DialogSessionManager.getSession(sessionId)

		if session:
			session.update(msg)
			payload = self.Commons.payload(msg)
			self.broadcast(method=constants.EVENT_PARTIAL_TEXT_CAPTURED, exceptions=[self.name], propagateToSkills=True, session=session, text=payload['text'], likelihood=payload['likelihood'], seconds=payload['seconds'])


	# noinspection PyUnusedLocal 
Example #17
Source File: MqttManager.py    From ProjectAlice with GNU General Public License v3.0 5 votes vote down vote up
def onVADUp(self, client, data, msg: mqtt.MQTTMessage):
		siteId = self.Commons.parseSiteId(msg)
		self.broadcast(method=constants.EVENT_VAD_UP, exceptions=[self.name], propagateToSkills=True, siteId=siteId)


	# noinspection PyUnusedLocal 
Example #18
Source File: MqttManager.py    From ProjectAlice with GNU General Public License v3.0 5 votes vote down vote up
def onEventEndSession(self, client, data, msg: mqtt.MQTTMessage):
		sessionId = self.Commons.parseSessionId(msg)
		session = self.DialogSessionManager.getSession(sessionId)
		if session:
			session.update(msg)
			self.broadcast(method=constants.EVENT_END_SESSION, exceptions=[self.name], propagateToSkills=True, session=session) 
Example #19
Source File: test_mqtt_transport.py    From azure-iot-sdk-python with MIT License 5 votes vote down vote up
def message(self):
        message = mqtt.MQTTMessage(mid=fake_mid, topic=fake_topic.encode())
        message.payload = fake_payload
        message.qos = fake_qos
        return message 
Example #20
Source File: test_mqtt_transport.py    From azure-iot-sdk-python-preview with MIT License 5 votes vote down vote up
def message(self):
        message = mqtt.MQTTMessage(mid=fake_mid, topic=fake_topic.encode())
        message.payload = fake_payload
        message.qos = fake_qos
        return message 
Example #21
Source File: test.py    From django_mqtt with GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        self.command = CommandUpdater()
        self.message = MQTTMessage()
        self.message.topic = '/topic/name'
        self.message.qos = 0
        self.message.payload = 'payload' 
Example #22
Source File: manager.py    From openag-device-software with GNU General Public License v3.0 5 votes vote down vote up
def on_command_message(self, message: mqtt.MQTTMessage) -> None:
        """Processes command messages received from iot cloud."""
        self.logger.debug("Processing command message")

        # Route command type
        if "recipe/start" in message.topic:
            self.start_recipe(message)
        elif "recipe/stop" in message.topic:
            self.logger.debug("Received stop recipe command")
            self.stop_recipe(message)
        else:
            self.logger.error("Received unknown command: {}".format(command.topic)) 
Example #23
Source File: MqttManager.py    From ProjectAlice with GNU General Public License v3.0 5 votes vote down vote up
def onSnipsStopListening(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_STOP_LISTENING, exceptions=[self.name], propagateToSkills=True, session=session)


	# noinspection PyUnusedLocal 
Example #24
Source File: test_pubsub.py    From openag-device-software with GNU General Public License v3.0 5 votes vote down vote up
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

    # Process message
    ref_self.process_message(message) 
Example #25
Source File: mq.py    From omnipy with MIT License 5 votes vote down vote up
def on_message(self, client, userdata, message: mqtt.MQTTMessage):
        ratestr = message.payload.decode()
        self.logger.info("Message %s %s %s " % (message.topic, message.timestamp, ratestr))
        try:
            ratespl = ratestr.split(' ')
            rate1 = Decimal(ratespl[0])
            rate2 = Decimal(ratespl[1])
            self.set_rate(rate1, rate2)
        except:
            self.send_msg("failed to parse message") 
Example #26
Source File: util.py    From mqttwarn with Eclipse Public License 2.0 5 votes vote down vote up
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) 
Example #27
Source File: ASRManager.py    From ProjectAlice with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #28
Source File: DialogSession.py    From ProjectAlice with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #29
Source File: DialogSession.py    From ProjectAlice with GNU General Public License v3.0 5 votes vote down vote up
def update(self, message: MQTTMessage):
		self.addToHistory(self.intentName)

		commonsManager = SuperManager.getInstance().commonsManager
		self.message = message
		self.intentName = message.topic
		self.payload = commonsManager.payload(message)
		self.slots.update(commonsManager.parseSlots(message))
		self.slotsAsObjects.update(commonsManager.parseSlotsToObjects(message))

		if self.customData:
			self.customData.update(commonsManager.parseCustomData(message))
		else:
			self.customData = dict() 
Example #30
Source File: DialogSessionManager.py    From ProjectAlice with GNU General Public License v3.0 5 votes vote down vote up
def addTempSession(self, sessionId: str, message: MQTTMessage) -> DialogSession:
		"""
		Adds a temporary session. This is usefull for sessions that are not
		Snips handeled and aren't ended
		:param sessionId: str
		:param message: dict
		"""
		session = self.addSession(sessionId, message)
		self.ThreadManager.doLater(interval=20, func=self._sessions.pop, args=[sessionId])
		return session