我想使用Perl模块Net::MQTT::Simple向MQTT服务器发送MQTT消息。这是一个基于CPAN网络文档::MQTT::Simple的简单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服务器正确地处理消息。任何帮助都是非常感谢的!丹尼尔
编辑:好的,已经回答了。不可能。我想我必须坚持当前的解决方案,在Per中执行mosquitto_pub,让我指定一个客户机ID。
发布于 2020-11-22 18:50:35
为_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发布于 2020-11-22 13:35:18
发布于 2022-01-13 08:26:32
您需要重写Net::MQTT::Simple的_client_identifier方法。
你可以用一行来做:
*{Net::MQTT::Simple::_client_identifier} = sub { return 'my_client_id'; };https://stackoverflow.com/questions/64953915
复制相似问题