perl - 如何在 Perl 模块 Net::MQTT::Simple(MQTT 接口)中设置 ClientID?
问题描述
我想使用 Perl 模块Net::MQTT::Simple
将 MQTT 消息发送到 MQTT 服务器。这是一个基于Net::MQTT::Simple 的 CPAN 文档的简单 MVP 脚本:
#!/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 服务器正确处理消息。任何帮助表示赞赏!丹尼尔
编辑:好的,它的回答。不可能。我想我必须坚持mosquitto_pub
在 Per 脚本中执行当前的解决方案,让我指定一个客户端 ID。
解决方案
提供覆盖_client_identifier()
可能会解决您的问题:
#!/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
推荐阅读
- ajax - AJAX 请求后光标插入符号总是改变
- javascript - React:渲染箭头函数内部定义的方法?
- r - SelectizeGroup 输入的默认初始值
- java - 如何在 wffweb 中正确呈现 HTML 树中的任意文本内容
- artifactory - AQL 包含多值属性仅返回第一个值
- node.js - 无法同时启动客户端和服务器
- azure - Azure Front Door - 更改上线的时间
- javascript - Javascript 正则表达式模式:找到秘密词
- sql - 选择比例 > X 的十进制值
- ruby - 使用 page_sections 时有没有办法定义范围?