首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Perl模块Net::MQTT::Simple (MQTT接口)中设置ClientID?

如何在Perl模块Net::MQTT::Simple (MQTT接口)中设置ClientID?
EN

Stack Overflow用户
提问于 2020-11-22 12:07:03
回答 3查看 625关注 0票数 1

我想使用Perl模块Net::MQTT::Simple向MQTT服务器发送MQTT消息。这是一个基于CPAN网络文档::MQTT::Simple的简单MVP脚本

代码语言:javascript
复制
#!/usr/bin perl
use warnings;
use strict;
use autodie;
use Net::MQTT::Simple;
 
# Allow unencrypted connection with credentials
$ENV{MQTT_SIMPLE_ALLOW_INSECURE_LOGIN} = 1;
 
# Connect to broker
my $mqtt = Net::MQTT::Simple->new('localhost:1883');
 
my $mqtt_username = 'username';
my $mqtt_password = 'verysecretpassword';

# Depending if authentication is required, login to the broker
if($mqtt_username and $mqtt_password) {
    $mqtt->login($mqtt_username, $mqtt_password);
}

# Publish a message
$mqtt->publish("home/temperature", "20.5");
$mqtt->disconnect();

我的问题是:我需要在传输中指定一个客户端id,以便接收MQTT服务器正确地处理消息。任何帮助都是非常感谢的!丹尼尔

编辑:好的,已经回答了。不可能。我想我必须坚持当前的解决方案,在Per中执行mosquitto_pub,让我指定一个客户机ID。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-11-22 18:50:35

_client_identifier()提供覆盖可能解决您的问题:

代码语言:javascript
复制
#!/usr/bin perl
use warnings;
use strict;
use autodie;
use Net::MQTT::Simple;

package Net::MQTT::Simple::ID;

our @ISA = 'Net::MQTT::Simple';

sub _client_identifier{
    return 'My_custom_client_id';
}

package main;
# Allow unencrypted connection with credentials
$ENV{MQTT_SIMPLE_ALLOW_INSECURE_LOGIN} = 1;
 
# Connect to broker
my $mqtt = Net::MQTT::Simple::ID->new('localhost:1883');
 
my $mqtt_username = 'username';
my $mqtt_password = 'verysecretpassword';

# Depending if authentication is required, login to the broker
if($mqtt_username and $mqtt_password) {
    $mqtt->login($mqtt_username, $mqtt_password);
}

# Publish a message
$mqtt->publish("home/temperature", "20.5");
$mqtt->disconnect();

__END__

nc -lv 127.0.0.1 1883 | od -c
Listening on localhost 1883
Connection received on localhost 55172
0000000 020   =  \0 004   M   Q   T   T 004 302  \0   <  \0 023   M   y
0000020   _   c   u   s   t   o   m   _   c   l   i   e   n   t   _   i
0000040   d  \0  \b   u   s   e   r   n   a   m   e  \0 022   v   e   r
0000060   y   s   e   c   r   e   t   p   a   s   s   w   o   r   d   0
0000100 026  \0 020   h   o   m   e   /   t   e   m   p   e   r   a   t
0000120   u   r   e   2   0   .   5 340  \0
0000131
票数 2
EN

Stack Overflow用户

发布于 2020-11-22 13:35:18

看看你不知道的源代码

该代码生成一个随机的客户端id,并且无法更新它。

我建议您考虑另一种方法,例如Python库。

票数 1
EN

Stack Overflow用户

发布于 2022-01-13 08:26:32

您需要重写Net::MQTT::Simple的_client_identifier方法。

你可以用一行来做:

代码语言:javascript
复制
*{Net::MQTT::Simple::_client_identifier} = sub { return 'my_client_id'; };
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64953915

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档