eclipse / paho.mqtt.python

paho.mqtt.python
Other
2.19k stars 723 forks source link

Question: How to use return in on_message #742

Closed rdrigos closed 1 year ago

rdrigos commented 1 year ago

I'm developing a function and I needed to access the values returned from paho's callback: 'on_message', as it is an automatic and recursive method when a message arrives. How could I add a return to work with the message?

Example:

def receive_payload(
     client: mqtt.Client,
     userdata: dict[str, Any] | None,
     message: mqtt.MQTTMessage,
) -> dict[str, Any]:
     payload_message: dict[str, Any] = json.loads(message.payload.decode())
     payload_topic: str = message.topic

     return {
         'payloadTopic': payload_topic,
         'payloadMessage': payload_message,
     }

client: mqtt.Client = mqtt.Client()
client.on_message = receive_payload

How do I access the return value of the 'receive_payload' function? Because I couldn't just call it receive_payload(), because I would need to pass the arguments and it wouldn't work correctly, because it's not in the on_message callback

FabricioMoraes-Dev commented 1 year ago

I'm developing a function and I needed to access the values returned from paho's callback: 'on_message', as it is an automatic and recursive method when a message arrives. How could I add a return to work with the message?

Example:

def receive_payload(
     client: mqtt.Client,
     userdata: dict[str, Any] | None,
     message: mqtt.MQTTMessage,
) -> dict[str, Any]:
     payload_message: dict[str, Any] = json.loads(message.payload.decode())
     payload_topic: str = message.topic

     return {
         'payloadTopic': payload_topic,
         'payloadMessage': payload_message,
     }

client: mqtt.Client = mqtt.Client()
client.on_message = receive_payload

How do I access the return value of the 'receive_payload' function? Because I couldn't just call it receive_payload(), because I would need to pass the arguments and it wouldn't work correctly, because it's not in the on_message callback

Tente usar a propriedade "content" para acessar o valor retornado da função. Segue abaixo um caso de uso. Não sei se irá funcionar no seu caso, mas é válido tentar!


def main(req: func.HttpRequest) -> func.HttpResponse:

    nome = req.params.get('nome')
    sobrenome = req.params.get('sobrenome')
    email = req.params.get('email')

    new_user =  create_user(email, nome, sobrenome)

    user_id = json.loads(new_user.content)[0]["id"]
    enrol_users(user_id)
    #userid = req.params.get(user_id)
    #func.HttpResponse(f'{new_user.content}',status_code=200),

    return func.HttpResponse(f'user_id = {user_id}',status_code=200)
rdrigos commented 1 year ago

Estou desenvolvendo uma função e precisava acessar os valores retornados do callback do paho: 'on_message', pois é um método automático e recursivo quando chega uma mensagem. Como eu poderia adicionar um retorno ao trabalho com a mensagem? Exemplo:

def receive_payload(
     client: mqtt.Client,
     userdata: dict[str, Any] | None,
     message: mqtt.MQTTMessage,
) -> dict[str, Any]:
     payload_message: dict[str, Any] = json.loads(message.payload.decode())
     payload_topic: str = message.topic

     return {
         'payloadTopic': payload_topic,
         'payloadMessage': payload_message,
     }

client: mqtt.Client = mqtt.Client()
client.on_message = receive_payload

Como faço para acessar o valor de retorno da função 'receive_payload'? Pois não poderia simplesmente chamar de receive_payload(), pois precisaria passar os argumentos e não funcionaria corretamente, pois não está no callback on_message

Tente usar a propriedade "content" para acessar o valor retornado da função. Segue abaixo um caso de uso. Não sei se irá funcionar no seu caso, mas é válido tentar!

def main(req: func.HttpRequest) -> func.HttpResponse:

    nome = req.params.get('nome')
    sobrenome = req.params.get('sobrenome')
    email = req.params.get('email')

    new_user =  create_user(email, nome, sobrenome)

    user_id = json.loads(new_user.content)[0]["id"]
    enrol_users(user_id)
    #userid = req.params.get(user_id)
    #func.HttpResponse(f'{new_user.content}',status_code=200),

    return func.HttpResponse(f'user_id = {user_id}',status_code=200)

Obrigado, vou tentar executar esse solução!