Использование брокера Mosquitto для протокола MQTT – блог

Как настроить mqtt mosquitto server, чтобы защищать mqtt

Когда сертификаты будут готовы, нам нужно настроить сервер MQTT Mosquitto, чтобы он мог использовать эти сертификаты. Сертификаты, которые мы должны использовать:

  • Mosq-ca.crt
  • Mosq-serv.crt
  • Mosq-serv.key

Найдите файл mosquitto.conf который содержит все параметры конфигурации, и добавьте следующие строки:

где путь / home / pi / ssl-cert-mosq – это путь, по которому вы сохранили свой сертификат. Кроме того, мы изменили порт Mosquitto MQTT по умолчанию на 8883.

Теперь вам нужно остановить и перезапустить Mosquitto MQTT, чтобы он мог прочитать новый файл конфигурации:

Это все. Теперь наш протокол MQTT безопасен и зашифрован. Последний шаг – тестирование конфигурации и сервера MQTT.

Что означает безопасность mqtt?

По своей природе MQTT представляет собой простой протокол, в котором вся передаваемая информация представлена ​​в текстовом формате. Другими словами, каждый может получить доступ к этому сообщению и прочитать полезные данные. Это не может быть проблемой, если MQTT-клиент и MQTT-брокер обмениваются недостоверной информацией В любом случае, это несколько случаев использования, когда мы хотим сохранить конфиденциальность информации и гарантировать, что она не может быть прочитана или изменена в процессе передачи.

  1. Создать VPN между клиентами и сервером
  2. Используйте MQTT поверх SSL / TSL, который шифрует и защищает информацию между клиентами MQTT и брокером MQTT

Мы сосредоточим наше внимание на том, как создать MQTT поверх SSL . Чтобы сделать MQTT безопасным протоколом, мы должны выполнить следующие шаги:

  • Создать личный ключ (CA Key)
  • Создайте сертификат, используя закрытый ключ (CA cert)
  • Создайте сертификат для сервера Mosquitto MQTT с ключом

Последний шаг – настройка Mosquitto MQTT, чтобы он использовал эти сертификаты.

Обновляем систему

Первым делом перед началом установки нам необходимо обновить систему. Подключаеся к нашему Pi по SSH и вводим:

sudo apt-get updatesudo apt-get upgrade

Подробнее посмотреть как подключаться к Pi по SSH и что потом можно делать вы можете в нашей статье.

Устновка брокера и клиента “mosquitto”

К сожалению, обычные библиотеки “apt-get” Raspberry Pi (Orange Pi) не содержат последнюю версию Mosquitto software. Поэтому перед установкой нам нужно будет обновить библиотеки. Если на сервере будет установлена не последняя версия брокера, то могут появляться ошибки в процессе работы.

Добавляем ключ и обновляем репозиторий. Вводим эти строчки по очереди. Иногда надо будет вводить пароль от вашего пользователя и нажимать Y для согласия с установкой.

Останавливаем сервер для настройки

После установки сервер MQTT сразу запускается. Нам необходимо оставновить его, чтобы произвести последующую настройку.

sudo /etc/init.d/mosquitto stop

Настройка

Открываем файл настроек

sudo nano /etc/mosquitto/mosquitto.conf

и заменяем его содержимое на следующее:

# Place your local configuration in /etc/mosquitto/conf.d/## A full description of the configuration file is at# /usr/share/doc/mosquitto/examples/mosquitto.conf.example

pid_file /var/run/mosquitto.pid

persistence truepersistence_location /var/lib/mosquitto/

log_dest topic

log_type errorlog_type warninglog_type noticelog_type information

connection_messages truelog_timestamp true

include_dir /etc/mosquitto/conf.d

Сохраняем, закрываем программу nano и выходим обратно в терминал (ctrl o, Enter, ctrl x).

Запускаем сервер MQTT

sudo /etc/init.d/mosquitto start

Статус сервера MQTT

Проверить стаус вашего MQTT брокера вы всегда можете через терминал:

sudo /etc/init.d/mosquitto status

После этой команды в терминале будет показана подробная информация о состоянии вашего сервера.

Mosquitto.conf man page

acl_filefile path

Set the path to an access control list file. If
defined, the contents of the file are used to control
client access to topics on the broker.

If this parameter is defined then only the topics
listed will have access. Topic access is added with
lines of the format:

topic [read|write|readwrite|deny] <topic>

The access type is controlled using “read”, “write”,
“readwrite” or “deny”. This parameter is optional (unless
<topic> includes a space character) – if not
given then the access is read/write. <topic> can
contain the or # wildcards as in
subscriptions. The “deny” option can used to explicitly
deny access to a topic that would otherwise be granted
by a broader read/write/readwrite statement. Any “deny”
topics are handled before topics that grant read/write access.

The first set of topics are applied to anonymous
clients, assuming allow_anonymous is
true. User specific topic ACLs are added after a user
line as follows:

user <username>

The username referred to here is the same as in
password_file. It is not the
clientid.

It is also possible to define ACLs based on pattern
substitution within the topic. The form is the same as
for the topic keyword, but using pattern as the
keyword.

pattern [read|write|readwrite|deny] <topic>

The patterns available for substition are:

The substitution pattern must be the only text for
that level of hierarchy. Pattern ACLs apply to all
users even if the “user” keyword has previously been
given.

Example:

pattern write sensor/%u/data

Allow access for bridge connection messages:

pattern write $SYS/broker/connection/%c/state

If the first character of a line of the ACL file is a
# it is treated as a comment.

If per_listener_settings is
true, this option applies to
the current listener being configured only. If
per_listener_settings is
false, this option applies
to all listeners.

Reloaded on reload signal. The currently loaded ACLs
will be freed and reloaded. Existing subscriptions will
be affected after the reload.

See also
https://vhod-v-lichnyj-kabinet.ru/documentation/dynamic-security/

allow_anonymous [ true | false ]

Boolean value that determines whether clients that
connect without providing a username are allowed to
connect. If set to false
then another means of connection should be created to
control authenticated client access.

Defaults to false,
unless no listeners are defined in the configuration
file, in which case it set to true,
but connections are only allowed from the local machine.

If per_listener_settings is
true, this option applies to
the current listener being configured only. If
per_listener_settings is
false, this option applies
to all listeners.

Reloaded on reload signal.

allow_duplicate_messages [ true | false ]

This option is deprecated and will be removed in a
future version. The behaviour will default to true.

If a client is subscribed to multiple subscriptions
that overlap, e.g. foo/# and foo/ /baz , then MQTT
expects that when the broker receives a message on a
topic that matches both subscriptions, such as
foo/bar/baz, then the client should only receive the
message once.

Mosquitto keeps track of which clients a message has
been sent to in order to meet this requirement. This
option allows this behaviour to be disabled, which may
be useful if you have a large number of clients
subscribed to the same set of topics and want to
minimise memory usage.

It can be safely set to
true if you know in advance
that your clients will never have overlapping
subscriptions, otherwise your clients must be able to
correctly deal with duplicate messages even when then
have QoS=2.

Defaults to true.

This option applies globally.

Reloaded on reload signal.

allow_zero_length_clientid [ true | false ]

MQTT 3.1.1 and MQTT 5 allow clients to connect with a zero
length client id and have the broker generate a client
id for them. Use this option to allow/disallow this
behaviour. Defaults to true.

See also the auto_id_prefix option.

If per_listener_settings is
true, this option applies to
the current listener being configured only. If
per_listener_settings is
false, this option applies
to all listeners.

Reloaded on reload signal.

auth_plugin_deny_special_chars [ true | false ]

If true then before an ACL
check is made, the username/client id of the client
needing the check is searched for the presence of
either a ‘ ‘ or ‘#’ character. If either of these
characters is found in either the username or client
id, then the ACL check is denied before it is sent to
the plugin.

This check prevents the case where a malicious user
could circumvent an ACL check by using one of these
characters as their username or client id. This is the
same issue as was reported with mosquitto itself as
CVE-2022-7650.

If you are entirely sure that the plugin you are
using is not vulnerable to this attack (i.e. if you
never use usernames or client ids in topics) then you
can disable this extra check and hence have all ACL
checks delivered to your plugin by setting this option
to false.

Defaults to true.

Applies to the current authentication plugin being configured.

Not currently reloaded on reload signal.

auto_id_prefixprefix

If allow_zero_length_clientid is
true, this option allows you
to set a string that will be prefixed to the
automatically generated client ids to aid visibility in
logs. Defaults to auto-.

If per_listener_settings is
true, this option applies to
the current listener being configured only. If
per_listener_settings is
false, this option applies
to all listeners.

Reloaded on reload signal.

autosave_intervalseconds

The number of seconds that mosquitto will wait
between each time it saves the in-memory database to
disk. If set to 0, the in-memory database will only be
saved when mosquitto exits or when receiving the
SIGUSR1 signal. Note that this setting only has an
effect if persistence is enabled. Defaults to 1800
seconds (30 minutes).

This option applies globally.

Reloaded on reload signal.

autosave_on_changes [ true | false ]

If true, mosquitto will
count the number of subscription changes, retained
messages received and queued messages and if the total
exceeds autosave_interval then the
in-memory database will be saved to disk. If
false, mosquitto will save
the in-memory database to disk by treating
autosave_interval as a time in
seconds.

This option applies globally.

Reloaded on reload signal.

check_retain_source [ true | false ]

This option affects the scenario when a client
subscribes to a topic that has retained messages. It is
possible that the client that published the retained
message to the topic had access at the time they
published, but that access has been subsequently
removed. If check_retain_source is set
to true, the default, the source of a retained message
will be checked for access rights before it is
republished. When set to false, no check will be made
and the retained message will always be
published.

This option applies globally, regardless of the
per_listener_settings option.

clientid_prefixesprefix

This option is deprecated and will be removed in a
future version.

If defined, only clients that have a clientid with a
prefix that matches clientid_prefixes will be allowed
to connect to the broker. For example, setting
“secure-” here would mean a client “secure-client”
could connect but another with clientid “mqtt”
couldn’t. By default, all client ids are valid.

This option applies globally.

Reloaded on reload signal. Note that currently
connected clients will be unaffected by any
changes.

connection_messages [ true | false ]

If set to true, the log
will include entries when clients connect and
disconnect. If set to false,
these entries will not appear.

This option applies globally.

Reloaded on reload signal.

include_dirdir

External configuration files may be included by using
the include_dir option. This defines a directory that
will be searched for config files. All files that end
in ‘.conf’ will be loaded as a configuration file. It
is best to have this as the last option in the main
file. This option will only be processed from the main
configuration file. The directory specified must not
contain the main configuration file.

The configuration files in
include_dir are loaded in case
sensitive alphabetical order, with the upper case of
each letter ordered before the lower case of the same
letter.

If this option is used multiple times, then each
include_dir option is processed
completely in the order that they are written in the
main configuration file.


log_destdestinations

Send log messages to a particular destination.
Possible destinations are: stdoutstderrsyslogtopicfiledlt.

stdout and
stderr log to the console on the
named output.

syslog uses the userspace syslog
facility which usually ends up in /var/log/messages or
similar.

topic logs to the broker topic
‘$SYS/broker/log/<severity>’, where severity is
one of E, W, N, I, M which are error,
warning, notice, information and message. Message type
severity is used by the subscribe and unsubscribe
log_type options and publishes log messages at
$SYS/broker/log/M/subscribe and
$SYS/broker/log/M/unsubscribe. Debug messages are never
logged on topics.

The file destination requires an
additional parameter which is the file to be logged to,
e.g. “log_dest file /var/log/mosquitto.log”. The file
will be closed and reopened when the broker receives a
HUP signal. Only a single file destination may be
configured.

The dlt destination is for the
automotive `Diagnostic Log and Trace` tool. This
requires that Mosquitto has been compiled with DLT
support.

Use “log_dest none” if you wish to disable logging.
Defaults to stderr. This option may be specified
multiple times.

Note that if the broker is running as a Windows
service it will default to “log_dest none” and neither
stdout nor stderr logging is available.

Reloaded on reload signal.

log_facilitylocal facility

If using syslog logging (not on Windows), messages
will be logged to the “daemon” facility by default. Use
the log_facility option to choose
which of local0 to local7 to log to instead. The option
value should be an integer value, e.g. “log_facility 5”
to use local5.

log_timestamp [ true | false ]

Boolean value, if set to
true a timestamp value will
be added to each log entry. The default is
true.

Reloaded on reload signal.

log_timestamp_formatformat

Set the format of the log timestamp. If left unset,
this is the number of seconds since the Unix epoch.
This option is a free text string which will be passed
to the strftime function as the format specifier. To
get an ISO 8601 datetime, for example:

log_timestamp_format %Y-%m-%dT%H:%M:%S
					

Reloaded on reload signal.

log_typetypes

Choose types of messages to log. Possible types are:
debug,
error,
warning,
notice,
information,
subscribe,
unsubscribe,
websockets,
none,
all.

Defaults to error,
warning, notice
and
information. This option
may be specified multiple times. Note that the
debug type (used for
decoding incoming/outgoing network packets) is never
logged in topics.

Reloaded on reload signal.

max_inflight_bytescount

Outgoing QoS 1 and 2 messages will be allowed in flight until this byte
limit is reached. This allows control of outgoing message rate based on
message size rather than message count. If the limit is set to 100,
messages of over 100 bytes are still allowed, but only a single message
can be in flight at once. Defaults to 0. (No limit).

See also the max_inflight_messages option.

This option applies globally.

Reloaded on reload signal.

max_inflight_messagescount

The maximum number of outgoing QoS 1 or 2 messages that can be
in the process of being transmitted simultaneously.
This includes messages currently going through
handshakes and messages that are being retried.
Defaults to 20. Set to 0 for no maximum. If set to 1,
this will guarantee in-order delivery of
messages.

This option applies globally.

Reloaded on reload signal.

max_keepalivevalue

For MQTT v5 clients, it is possible to have the
server send a “server keepalive” value that will
override the keepalive value set by the client. This
is intended to be used as a mechanism to say that the
server will disconnect the client earlier than it
anticipated, and that the client should use the new
keepalive value. The max_keepalive option allows you to
specify that clients may only connect with keepalive
less than or equal to this value, otherwise they will
be sent a server keepalive telling them to use
max_keepalive. This only applies to MQTT v5 clients.
The maximum value allowable, and default value, is
65535.

Set to 0 to allow clients to set keepalive = 0, which
means no keepalive checks are made and the client will
never be disconnected by the broker if no messages are
received. You should be very sure this is the behaviour
that you want.

For MQTT v3.1.1 and v3.1 clients, there is no mechanism
to tell the client what keepalive value they should use.
If an MQTT v3.1.1 or v3.1 client specifies a keepalive
time greater than max_keepalive they will be sent a
CONNACK message with the “identifier rejected” reason
code, and disconnected.

This option applies globally.

Reloaded on reload signal.

max_packet_sizevalue

For MQTT v5 clients, it is possible to have the
server send a “maximum packet size” value that will
instruct the client it will not accept MQTT packets
with size greater than value bytes.
This applies to the full MQTT packet, not just the
payload. Setting this option to a positive value will
set the maximum packet size to that number of bytes. If
a client sends a packet which is larger than this
value, it will be disconnected. This applies to all
clients regardless of the protocol version they are
using, but v3.1.1 and earlier clients will of course
not have received the maximum packet size information.
Defaults to no limit.

This option applies to all clients, not just those
using MQTT v5, but it is not possible to notify clients
using MQTT v3.1.1 or MQTT v3.1 of the limit.

Setting below 20 bytes is forbidden because it is
likely to interfere with normal client operation even
with small payloads.

This option applies globally.

Reloaded on reload signal.

max_queued_bytescount

The number of outgoing QoS 1 and 2 messages above those currently in-flight will be
queued (per client) by the broker. Once this limit has been reached, subsequent
messages will be silently dropped. This is an important option if you are sending
messages at a high rate and/or have clients who are slow to respond or may be offline
for extended periods of time. Defaults to 0. (No maximum).

See also the
max_queued_messages option.
If both max_queued_messages and max_queued_bytes are specified,
packets will be queued until the first limit is reached.

This option applies globally.

Reloaded on reload signal.

max_queued_messagescount

The maximum number of QoS 1 or 2 messages to hold in the
queue (per client) above those messages that are currently
in flight. Defaults to 1000. Set to 0 for no maximum (not
recommended). See also the
queue_qos0_messages and
max_queued_bytes options.

This option applies globally.

Reloaded on reload signal.

memory_limitlimit

This option sets the maximum number of heap memory bytes that the broker
will allocate, and hence sets a hard limit on memory use by the broker.
Memory requests that exceed this value will be denied. The effect will
vary depending on what has been denied. If an incoming message is being
processed, then the message will be dropped and the publishing client
will be disconnected. If an outgoing message is being sent, then the
individual message will be dropped and the receiving client will be
disconnected. Defaults to no limit.

This option is only available if memory tracking support is compiled
in.

Reloaded on reload signal. Setting to a lower value and reloading will
not result in memory being freed.

message_size_limitlimit

This option sets the maximum publish payload size
that the broker will allow. Received messages that
exceed this size will not be accepted by the broker. This means that the
message will not be forwarded on to subscribing clients, but the QoS flow
will be completed for QoS 1 or QoS 2 messages. MQTT v5 clients using QoS 1
or QoS 2 will receive a PUBACK or PUBREC with the “implementation specific
error” reason code.

The default value is 0, which means that all valid MQTT
messages are accepted. MQTT imposes a maximum payload
size of 268435455 bytes.

This option applies globally.

Reloaded on reload signal.

password_filefile path

Set the path to a password file. If defined, the
contents of the file are used to control client access
to the broker. The file can be created using the
mosquitto_passwd(1)
utility. If mosquitto is compiled without TLS support
(it is recommended that TLS support is included), then
the password file should be a text file with each line
in the format “username:password”, where the colon and
password are optional but recommended. If
allow_anonymous is set to
false, only users defined in
this file will be able to connect. Setting
allow_anonymous to
true when
password_fileis defined is
valid and could be used with acl_file to have e.g. read
only guest/anonymous accounts and defined users that
can publish.

If per_listener_settings is
true, this option applies to
the current listener being configured only. If
per_listener_settings is
false, this option applies
to all listeners.

Reloaded on reload signal. The currently loaded
username and password data will be freed and reloaded.
Clients that are already connected will not be
affected.

See also
mosquitto_passwd(1) and
https://vhod-v-lichnyj-kabinet.ru/documentation/dynamic-security/

per_listener_settings [ true | false ]

If true, then
authentication and access control settings will be
controlled on a per-listener basis. The following
options are affected:

password_file,
acl_file, psk_file,
allow_anonymous,
allow_zero_length_clientid,
auto_id_prefix.

plugin,
plugin_opt_*,

Note that if set to true, then a durable client (i.e.
with clean session set to false) that has disconnected
will use the ACL settings defined for the listener that
it was most recently connected to.

The default behaviour is for this to be set to
false, which maintains the
settings behaviour from previous versions of
mosquitto.

Reloaded on reload signal.

persistence [ true | false ]

If true, connection,
subscription and message data will be written to the
disk in mosquitto.db at the location dictated by
persistence_location. When mosquitto is restarted, it
will reload the information stored in mosquitto.db. The
data will be written to disk when mosquitto closes and
also at periodic intervals as defined by
autosave_interval. Writing of the persistence database
may also be forced by sending mosquitto the SIGUSR1
signal. If false, the data
will be stored in memory only. Defaults to
false.

The persistence file may change its format in a new
version. The broker can currently read all old formats,
but will only save in the latest format. It should always
be safe to upgrade, but cautious users may wish to take a
copy of the persistence file before installing a new
version so that they can roll back to an earlier version
if necessary.

This option applies globally.

Reloaded on reload signal.

persistence_filefile name

The filename to use for the persistent database.
Defaults to mosquitto.db.

This option applies globally.

Reloaded on reload signal.

persistence_locationpath

The path where the persistence database should be
stored. If not given, then the current directory is used.

This option applies globally.

Reloaded on reload signal.

persistent_client_expirationduration

This option allows persistent clients (those with
clean session set to false) to be removed if they do
not reconnect within a certain time frame. This is a
non-standard option. As far as the MQTT spec is
concerned, persistent clients persist forever.

Badly designed clients may set clean session to false
whilst using a randomly generated client id. This leads
to persistent clients that will never reconnect. This
option allows these clients to be removed.

The expiration period should be an integer followed
by one of h d w m y for hour, day, week, month and year
respectively. For example:

As this is a non-standard option, the default if not
set is to never expire persistent clients.

This option applies globally.

Reloaded on reload signal.

pid_filefile path

Write a pid file to the file specified. If not given
(the default), no pid file will be written. If the pid
file cannot be written, mosquitto will exit.

If mosquitto is being automatically started by an
init script it will usually be required to write a pid
file. This should then be configured as e.g.
/var/run/mosquitto/mosquitto.pid

Not reloaded on reload signal.

plugin_opt_*value

Options to be passed to the most recent
plugin defined in the
configuration file. See the specific
plugin instructions for details of what
options are available.

Applies to the current plugin being configured.

This is also available as the auth_opt_*
option, but this use is deprecated and will be removed
in a future version.

pluginfile path

Specify an external module to use for authentication
and access control. This allows custom
username/password and access control functions to be
created.

Can be specified multiple times to load multiple
plugins. The plugins will be processed in the order
that they are specified.

If password_file, or
acl_file are used in the config file
alongsize plugin, the plugin
checks will run after the built in checks.

Not currently reloaded on reload signal.

See also
https://vhod-v-lichnyj-kabinet.ru/documentation/dynamic-security/

This is also available as the auth_plugin
option, but this use is deprecated and will be removed
in a future version.

psk_filefile path

Set the path to a pre-shared-key file. This option
requires a listener to be have PSK support enabled. If
defined, the contents of the file are used to control
client access to the broker. Each line should be in the
format “identity:key”, where the key is a hexadecimal
string with no leading “0x”. A client connecting to a
listener that has PSK support enabled must provide a
matching identity and PSK to allow the encrypted
connection to proceed.

If per_listener_settings is
true, this option applies to
the current listener being configured only. If
per_listener_settings is
false, this option applies
to all listeners.

Reloaded on reload signal. The currently loaded
identity and key data will be freed and reloaded.
Clients that are already connected will not be
affected.

queue_qos0_messages [ true | false ]

Set to true to queue
messages with QoS 0 when a persistent client is
disconnected. These messages are included in the limit
imposed by max_queued_messages. Defaults to
false.

Note that the MQTT v3.1.1 spec states that only QoS 1
and 2 messages should be saved in this situation so
this is a non-standard option.

This option applies globally.

Reloaded on reload signal.

retain_available [ true | false ]

If set to false, then retained messages are not
supported. Clients that send a message with the retain
bit will be disconnected if this option is set to
false. Defaults to true.

This option applies globally.

Reloaded on reload signal.

set_tcp_nodelay [ true | false ]

If set to true, the TCP_NODELAY option will be set on
client sockets to disable Nagle’s algorithm. This
has the effect of reducing latency of some messages
at potentially increasing the number of TCP packets
being sent. Defaults to false.

This option applies globally.

Reloaded on reload signal.

sys_intervalseconds

The integer number of seconds between updates of the
$SYS subscription hierarchy, which provides status
information about the broker. If unset, defaults to 10
seconds.

Set to 0 to disable publishing the $SYS hierarchy
completely.

This option applies globally.

Reloaded on reload signal.

upgrade_outgoing_qos [ true | false ]

The MQTT specification requires that the QoS of a
message delivered to a subscriber is never upgraded to
match the QoS of the subscription. Enabling this option
changes this behaviour. If
upgrade_outgoing_qos is set
true, messages sent to a
subscriber will always match the QoS of its
subscription. This is a non-standard option not
provided for by the spec. Defaults to
false.

This option applies globally.

Reloaded on reload signal.

userusername

When run as root, change to this user and its primary
group on startup. If set to “mosquitto” or left unset,
and if the “mosquitto” user does not exist, then
mosquitto will change to the “nobody” user instead.
If this is set to another value and mosquitto is unable
to change to this user and group, it will exit with an
error. The user specified must have read/write access
to the persistence database if it is to be written. If
run as a non-root user, this setting has no effect.
Defaults to mosquitto.

This setting has no effect on Windows and so you
should run mosquitto as the user you wish it to run
as.

Not reloaded on reload signal.

Mqtt mesquitto oesting security over ssl / tsl

На этом этапе мы проверим, правильно ли настроено соединение. Для этого мы используем MQTT. fx клиент MQTT на основе Java После того, как вы установили его, мы должны создать новый профиль, предоставляющий всю информацию, как показано на рисунке ниже:

Обратите внимание, что мы включили конфигурацию SSL / TSL, обеспечивающую создание mosq-ca.crt на предыдущих этапах.

Наконец, мы можем подключиться к серверу MQTT Mosquitto:

нажимая на подключение. Вы заметите, что клиент MQTT установит соединение с брокером MQTT, как вы можете проверить на вкладке журнала.

Теперь пришло время проверить, получает ли наш клиент сообщение. Выберите меню подписки и подпишите клиент MQTT на тему (выбирая название темы).

Со стороны Raspberry Pi мы можем отправить сообщение на тот же канал:

Результат показан на картинке ниже:

На стороне подписчика имеем:

Как вы можете заметить, мы получили сообщение, отправленное издателем.

Доступ к консоли linux ubuntu vm

Открываем созданный сервер:

Выбираем меню «Access» и нажимаем «Launch console»:

Откроется новое окно в браузере:

Введите логин и пароль для сервера и нажмите Enter:

Обзор облачного mqtt брокера

Из чего состоит данное приложение?

  • Две платы ESP32, подключенные к разным сетям;
  • Облачный брокер, на котором есть пара топиков – board2/output и board2/temperature;
  • Плата №1 публикует данные, определяющие включение и выключение выходов платы №2, в топике board2/output1, на который подписана плата №2. Таким образом, плата №1 управляет платой №2.
  • Похожим образом плата №2 публикует показания температуры в топике, на который подписана плата №1. Таким образом, плата №1 получает показания, снимаемые платой №2.

Вы также можете установить Node-RED на этом же хостинге для управления и мониторинга ваших плат с компьютера или смартфона.

Подписка на топик брокера

Следующий скетч реализует подписку платы к облачному брокеру для получения сообщения. Скопируйте его в свою среду разработки, укажите свои учетные данные сети, IP адрес дроплета, логин и пароль брокера.

Для работы кода введите учетные данные сети в этих строках:

Вводим IP адрес дроплета ( в нашем случае 178.62.83.231).

Если ваш брокер требует авторизации, то вводим логин и пароль:

Проверка правильности установки брокера

Для проверки установки вы можете открыть второе окно терминала и установить SSH соединение с сервером (можно использовать PuTTY или любой другой SSH клиент):

Оно должно появиться во втором терминале:

Публикация сообщений в облачном брокере с платы esp32

Скопируйте следующий код в вашу среду разработки. Для того, чтобы код у вас работал, потребуется ввести свои учетные данные сети, IP адрес дроплета, логин и пароль от брокера.

Для работы кода введите учетные данные сети в этих строках:

Вводим IP адрес дроплета ( в нашем случае 178.62.83.231).

Если ваш брокер требует авторизации, то вводим логин и пароль:

Создаем аккаунт в digital ocean

Переходим по ссылке Digital Ocean и нажимаем кнопку «Sign up»

После подтверждения аккаунта, зайдите в него:

Создаем дроплет (linux ubuntu vm)

В этом руководстве мы будем использовать Ubuntu 20.04 (LTS) x64. Вы можете использовать либо эту ОС, либо выбрать план «Basic»:

В меню ресурсов виртуальной машины стоит выбрать самый дешевый план за 5$ в месяц. Наш брокер будет нормально работать даже при таких ресурсах.

Выбираем местоположение ближайшего датацентра для виртуальной машины:

Создаем пароль для доступа к дроплету:

Ну и наконец, выбираем имя хоста для идентификации виртуальной машины (в нашем случае – «mqtt-cloud-server»). Осталось нажать большую зеленую кнопку «Create Droplet».

Ждем окончания процесса создания виртуальной машины.

Создание сертификата mqtt-сервера

Когда закрытый ключ и сертификат готовы, мы можем перейти к созданию сертификата сервера MQTT и личного ключа:

Затем сертификат сервера. На этом этапе мы должны создать CSR (запрос на подпись сертификата). Этот сертификат должен быть отправлен в центр сертификации, который после проверки личности автора возвращает сертификат. В этом уроке мы будем использовать самоподписанный сертификат:

Как вы можете заметить, мы использовали закрытый ключ, сгенерированный на предыдущем шаге. Наконец, мы можем создать сертификат для использования на нашем сервере MQTT Mosquitto:

Все сделано! Мы завершили шаги, необходимые для защиты нашего сервера MQTT. Вы можете подтвердить свой сертификат написания:

Теперь вы должны увидеть сертификат.

Тестирование публикации сообщений платой

Если вы загрузили код и открыли монитор порта, вы увидите, что плата публикует сообщения каждые 5 секунд:

Тестируем подписку платы на топик

Ваша плата должна получать эти сообщения и выводить их в монитор порта:

В этих примерах мы разобрали. как публиковать сообщения и подписываться на топики с помощью облачного брокера. Идея в том, чтобы использовать разные платы для публикации и приема сообщений для взаимодействия между платами.

Вывод

В конце этой статьи вы узнали о том, как обрабатывать настройки безопасности MQTT Mosquitto MQTT через SSL / TSL.

Похожее:  Как работает EMS Почта России - личный опыт. | Пикабу

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *