Juerd / Net-MQTT-Simple

Net::MQTT::Simple - Minimal MQTT version 3 publisher
10 stars 8 forks source link

Wishlist - Add one_shot method #21

Closed mrdvt92 closed 3 weeks ago

mrdvt92 commented 1 year ago

I need a "one shot" method where I can send a command and then received the response via MQTT to control and query a device that only knows MQTT.

This Python script https://stackoverflow.com/questions/61189974/how-to-get-a-one-shot-message-with-mqtt does the exact process that I need (just not in Perl).

Process

  1. Instantiate an MQTT object
  2. Subscribe to command topic
  3. Publish to status topic
  4. Wait for first response (timeout if not received)

For example, to toggle a Tasmota device but you don't know if it is currently on or off.

my $host      = "mqtt";
my $mqtt      = Net::MQTT::Simple->new($host);
my $topic_sub = "stat/my_switch/POWER1";
my $topic_pub = "cmnd/my_switch/POWER1";
my $message   = "TOGGLE";
my $value = $mqtt->one_shot($topic_sub, $topic_pub => $message);
print "value: $value\n";

Returns

value: OFF
Juerd commented 1 year ago

Why should this be in the module, and not in a script you write? I think everyone's requirements for RPC-like protocols over MQTT will be different.

mrdvt92 commented 1 year ago

I think everyone's requirements for RPC-like protocols over MQTT will be different.

I think a one-shot capability will be a very common capability needed for the IoT revolution that is here/coming. There were a few edge cases to this development that need to be baked in so that users can depend on them.

I think many IoT devices will prefer MQTT message/response pattern so, that they only need to support one protocol instead of two (e.g. MQTT for events and HTTP for status). I'm working with Tasmota today which does have an HTTP API.

If MQTT stays as the hub for IoT automation, I would like for Perl to be in the ecosphere.

Why should this be in the module, and not in a script you write?

I plan to use this capability in multiple places. So, I will package it. However, I would like for this capability to be in your namespace and not in an overlay package (i.e., login).

mrdvt92 commented 1 year ago

my $value = $mqtt->one_shot($topic_sub, $topic_pub => $message);

Feel free to change the method name or the context-based return to an object or a hash ref with error code, if you have a better convention.

Juerd commented 3 weeks ago

I believe the new functionality introduced in v1.30 provides the requested feature.