I have setup MQTT on a Raspberry Pi and configured an Arduino Uno to the broker, but I am seeing the following entry in the /var/log/mosquitto/mosquitto.log file:

New connection from 192.168.10.114 on port 1883.
Socket error on client <unknown>, disconnecting.

The Pi is setup with ETH0 wired to my local LAN and has an IP address of 192.168.1.50

There is also a WiFi AP setup on the Pi. The Arduino Uno connects via WiFi to send/receive MQTT messages. The WiFi AP has an IP address of 192.168.10.1 and provides DHCP leases via dnsmasq.

I have tried publishing and subscribing test on the local MQTT broker server (the Pi) and get the same error:

Command:
mosquitto_sub -h 192.168.10.1 -t topic

mosquitto.log:
New connection from 192.168.10.1 on port 1883.
New client connected from 192.168.10.1 as mosqsub/1837-raspberryp (cl, k60).
Socket error on client <unknown>, disconnecting.

Here is /etc/mosquitto/mosquitto.conf:

pid_file /var/run/mosquitto.pid

persistence true
log_dest file /var/log/mosquitto/mosquitto.log

allow_anonymous true

include_dir /etc/mosquitto/conf.d

sudo service mosquitto stop
sudo service mosquitto start:

mosquitto version 1.4.8 terminating
mosquitto version 1.4.8 (build date Sun, 14 Feb 2016 15:06:55 +0000) starting
Config loaded from /etc/mosquitto/mosquitto.conf.
Opening ipv4 listen socket on port 1883.
Opening ipv6 listen socket on port 1883.

There might be an issue in my interfaces configuration. Here is /etc/network/interfaces:

source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback

iface eth0 inet manual

auto wlan0
allow-hotplug wlan0
iface wlan0 inet static
    address 192.168.10.1
    netmask 255.255.255.0

Can anyone point me on where the socket error is coming from on MQTT?

I have setup MQTT on a Raspberry Pi and configured an Arduino Uno to the broker, but I am seeing the following entry in the /var/log/mosquitto/mosquitto.log file:

New connection from 192.168.10.114 on port 1883.
Socket error on client <unknown>, disconnecting.

The Pi is setup with ETH0 wired to my local LAN and has an IP address of 192.168.1.50

There is also a WiFi AP setup on the Pi. The Arduino Uno connects via WiFi to send/receive MQTT messages. The WiFi AP has an IP address of 192.168.10.1 and provides DHCP leases via dnsmasq.

I have tried publishing and subscribing test on the local MQTT broker server (the Pi) and get the same error:

Command:
mosquitto_sub -h 192.168.10.1 -t topic

mosquitto.log:
New connection from 192.168.10.1 on port 1883.
New client connected from 192.168.10.1 as mosqsub/1837-raspberryp (cl, k60).
Socket error on client <unknown>, disconnecting.

Here is /etc/mosquitto/mosquitto.conf:

pid_file /var/run/mosquitto.pid

persistence true
log_dest file /var/log/mosquitto/mosquitto.log

allow_anonymous true

include_dir /etc/mosquitto/conf.d

sudo service mosquitto stop
sudo service mosquitto start:

mosquitto version 1.4.8 terminating
mosquitto version 1.4.8 (build date Sun, 14 Feb 2016 15:06:55 +0000) starting
Config loaded from /etc/mosquitto/mosquitto.conf.
Opening ipv4 listen socket on port 1883.
Opening ipv6 listen socket on port 1883.

There might be an issue in my interfaces configuration. Here is /etc/network/interfaces:

source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback

iface eth0 inet manual

auto wlan0
allow-hotplug wlan0
iface wlan0 inet static
    address 192.168.10.1
    netmask 255.255.255.0

Can anyone point me on where the socket error is coming from on MQTT?

The problem

Unsure what I done but it was working last week, but this week i’m not getting the published messages into HA, they are being sent from my devices as I have subscribed to the topics on other brokers and I am receiving them.

I have done full reboots, uninstalls and the problem remains.

Environment

  • Add-on with the issue: Mosquitto broker
  • Add-on release with the issue: 6.0.1
  • Last working add-on release (if known):
  • Operating environment (OS/Supervised): Supervised

Problem-relevant configuration

logins: []
customize:
  active: false
  folder: mosquitto
certfile: fullchain.pem
keyfile: privkey.pem
require_certificate: false

Traceback/Error logs

[s6-init] making user provided files available at /var/run/s6/etc...exited 0.
[s6-init] ensuring user provided files have correct perms...exited 0.
[fix-attrs.d] applying ownership & permissions fixes...
[fix-attrs.d] done.
[cont-init.d] executing container initialization scripts...
[cont-init.d] mosquitto.sh: executing... 
[08:20:15] INFO: Certificates found: SSL is available
[cont-init.d] mosquitto.sh: exited 0.
[cont-init.d] nginx.sh: executing... 
[cont-init.d] nginx.sh: exited 0.
[cont-init.d] done.
[services.d] starting services
[services.d] done.
[08:20:15] INFO: Starting NGINX for authentication handling...
[08:20:16] INFO: Starting mosquitto MQTT broker...
1624926016: mosquitto version 1.6.12 starting
1624926016: |-- *** auth-plug: startup
[08:20:16] INFO: Successfully send discovery information to Home Assistant.
[08:20:17] INFO: Successfully send service information to the Supervisor.
1624926016: Config loaded from /etc/mosquitto/mosquitto.conf.
1624926016: Loading plugin: /usr/share/mosquitto/auth-plug.so
1624926016:  ├── Username/password checking enabled.
1624926016:  ├── TLS-PSK checking enabled.
1624926016:  └── Extended authentication not enabled.
1624926016: Opening ipv4 listen socket on port 1883.
1624926016: Opening ipv6 listen socket on port 1883.
1624926016: Opening websockets listen socket on port 1884.
1624926016: Opening ipv4 listen socket on port 8883.
1624926016: Opening ipv6 listen socket on port 8883.
1624926016: Opening websockets listen socket on port 8884.
1624926016: Warning: Mosquitto should not be run as root/administrator.
1624926016: mosquitto version 1.6.12 running
1624926016: New connection from 127.0.0.1 on port 1883.
1624926016: Socket error on client <unknown>, disconnecting.
1624926016: New connection from 172.30.32.1 on port 1883.
1624926016: New client connected from 172.30.32.1 as mqttjs_dec8d72b (p2, c1, k60, u'addons').
1624926017: New connection from 192.168.1.4 on port 1883.
1624926017: New client connected from 192.168.1.4 as mqtt-explorer-0cd99e23 (p2, c1, k60).
1624926017: New connection from 172.30.32.1 on port 1883.
1624926017: New client connected from 172.30.32.1 as 64fpGnTXcGnpKwRBx48aPL (p2, c1, k60, u'homeassistant').
1624926018: New connection from 192.168.1.34 on port 1883.
1624926018: New client connected from 192.168.1.34 as auto-9F3815E0-18E0-88AF-6E09-5DCCDF3850A9 (p2, c1, k60).
1624926018: New connection from 192.168.1.23 on port 1883.
{"result": "ok", "data": {}}1624926018: New client connected from 192.168.1.23 as DVES_4A98B7 (p2, c1, k30, u'kane').
1624926019: New connection from 192.168.1.50 on port 1883.
1624926019: New client connected from 192.168.1.50 as DVES_58883C (p2, c1, k30, u'kane').
1624926019: New connection from 192.168.1.55 on port 1883.
1624926019: New client connected from 192.168.1.55 as DVES_3330FD (p2, c1, k30, u'kane').
1624926039: New connection from 192.168.1.22 on port 1883.
1624926039: New client connected from 192.168.1.22 as DVES_4AA443 (p2, c1, k30, u'kane').
1624926061: New connection from 172.30.32.2 on port 1883.
1624926061: Socket error on client <unknown>, disconnecting.
1624926181: New connection from 172.30.32.2 on port 1883.
1624926181: Socket error on client <unknown>, disconnecting.
1624926301: New connection from 172.30.32.2 on port 1883.
1624926301: Socket error on client <unknown>, disconnecting.
1624926421: New connection from 172.30.32.2 on port 1883.
1624926421: Socket error on client <unknown>, disconnecting.
1624926541: New connection from 172.30.32.2 on port 1883.
1624926541: Socket error on client <unknown>, disconnecting.
1624926661: New connection from 172.30.32.2 on port 1883.
1624926661: Socket error on client <unknown>, disconnecting.
1624926781: New connection from 172.30.32.2 on port 1883.
1624926781: Socket error on client <unknown>, disconnecting.
1624926901: New connection from 172.30.32.2 on port 1883.
1624926901: Socket error on client <unknown>, disconnecting.
1624927021: New connection from 172.30.32.2 on port 1883.
1624927021: Socket error on client <unknown>, disconnecting.
1624927141: New connection from 172.30.32.2 on port 1883.
1624927141: Socket error on client <unknown>, disconnecting.
1624927261: New connection from 172.30.32.2 on port 1883.
1624927261: Socket error on client <unknown>, disconnecting.
1624927288: Client mqtt-explorer-0cd99e23 disconnected.
1624927290: New connection from 192.168.1.4 on port 1883.
1624927290: New client connected from 192.168.1.4 as mqtt-explorer-0cd99e23 (p2, c1, k60).
1624927381: New connection from 172.30.32.2 on port 1883.
1624927381: Socket error on client <unknown>, disconnecting.
1624927392: Client mqtt-explorer-0cd99e23 disconnected.
1624927501: New connection from 172.30.32.2 on port 1883.
1624927501: Socket error on client <unknown>, disconnecting.
1624927621: New connection from 172.30.32.2 on port 1883.
1624927621: Socket error on client <unknown>, disconnecting.
1624927741: New connection from 172.30.32.2 on port 1883.
1624927741: Socket error on client <unknown>, disconnecting.

Additional information

HA Log:

Logger: homeassistant.components.mqtt
Source: components/mqtt/init.py:913
Integration: MQTT (documentation, issues)
First occurred: 3:53:50 PM (1 occurrences)
Last logged: 3:53:50 PM

Disconnected from MQTT server core-mosquitto:1883 (1)

Home Assistant Mosquitto Tasmota Device Socket Error

I have just completed a fresh install of Home Assistant OS 6.4 (core-2021.9.7 upgraded to 2021.10.0, supervisor-2021.09.6) on a Raspberry Pi 4, together with Mosquitto 6.0.1 configured as an add-on. As far as I can tell that installation seemed to work fine.

But the problem I’m having is when trying to configure my first Tasmoto (9.5.0) device via MQTT. I’m getting a

1633680390: New connection from 192.168.1.28 on port 1883.
1633680390: Socket error on client <unknown>, disconnecting.

This error seems to crop up quite a lot in other posts, and most times boils down to an authentication problem. But no matter what I do, I can’t seem to fix the problem, or even have an affect on it. I always get the same error.

Does anyone have any ideas what the problem might be, or more importantly how I can diagnose the problem? While the Tasmoto device seems to be working OK, I can’t rule that out as the source of the problem.

  1. Installed HA following the instructions described here: https://www.home-assistant.io/installation/raspberrypi/ on a Pi 4 and went through the onboarding process and this step seems to have completed fine.

  2. I installed Mosquito as an MQTT Broker as a Home Assistant Add-on using the process described here: https://github.com/home-assistant/addons/blob/master/mosquitto/DOCS.md, and this seemed to work OK too.

The MQTT configuration looks like this, but I’ve tried it with logins: [] and anonymous: true as well.

logins:
  - username: username
    password: password
customize:
  active: false
  folder: mosquitto
certfile: fullchain.pem
keyfile: privkey.pem
require_certificate: false
anonymous: false
  1. I’ve configured the MQTT Device, a Localbytes pre-flashed tasmota plug with the following MQTT confirmation information.

Tasmota MQTT Config 1
Tasmota MQTT Config 2
Tasmota MQTT Config 3

192.168.1.32 is the address of the Home Assistant node. 192.168.1.28 is the Tasmota device. I’ve used SetOption19 1 to make the Tasmota device discoverable.


The log files look like this:

  1. MQTT Broker via HA
[s6-init] making user provided files available at /var/run/s6/etc...exited 0.
[s6-init] ensuring user provided files have correct perms...exited 0.
[fix-attrs.d] applying ownership & permissions fixes...
[fix-attrs.d] done.
[cont-init.d] executing container initialization scripts...
[cont-init.d] mosquitto.sh: executing... 
[09:02:51] INFO: SSL is not enabled
[cont-init.d] mosquitto.sh: exited 0.
[cont-init.d] nginx.sh: executing... 
[cont-init.d] nginx.sh: exited 0.
[cont-init.d] done.
[services.d] starting services
[services.d] done.
[09:02:52] INFO: Starting NGINX for authentication handling...
[09:02:52] INFO: Starting mosquitto MQTT broker...
1633680172: mosquitto version 1.6.12 starting
1633680172: |-- *** auth-plug: startup
[09:02:53] INFO: Successfully send discovery information to Home Assistant.
[09:02:53] INFO: Successfully send service information to the Supervisor.
1633680172: Config loaded from /etc/mosquitto/mosquitto.conf.
1633680172: Loading plugin: /usr/share/mosquitto/auth-plug.so
1633680172:  ├── Username/password checking enabled.
1633680172:  ├── TLS-PSK checking enabled.
1633680172:  └── Extended authentication not enabled.
1633680172: Opening ipv4 listen socket on port 1883.
1633680172: Opening ipv6 listen socket on port 1883.
1633680172: Opening websockets listen socket on port 1884.
1633680172: Warning: Mosquitto should not be run as root/administrator.
1633680172: mosquitto version 1.6.12 running
1633680172: New connection from 127.0.0.1 on port 1883.
1633680172: Socket error on client <unknown>, disconnecting.
1633680177: New connection from 172.30.32.1 on port 1883.
401: Unauthorized1633680178: Socket error on client <unknown>, disconnecting.
1633680179: New connection from 192.168.1.28 on port 1883.
401: Unauthorized1633680179: Socket error on client <unknown>, disconnecting.
1633680200: New connection from 192.168.1.28 on port 1883.
1633680200: Socket error on client <unknown>, disconnecting.
1633680231: New connection from 192.168.1.28 on port 1883.
1633680231: Socket error on client <unknown>, disconnecting.
  1. From the Tasmota Device..
09:21:12.302 MQT: Attempting connection...
09:21:12.324 MQT: Connect failed to 192.168.1.32:1883, rc 5. Retry in 120 sec
09:23:13.518 MQT: Attempting connection...
09:23:13.542 MQT: Connect failed to 192.168.1.32:1883, rc 5. Retry in 120 sec
09:25:14.541 MQT: Attempting connection...
09:25:14.564 MQT: Connect failed to 192.168.1.32:1883, rc 5. Retry in 120 sec
09:25:54.414 RSL: HASS_STATE = {"Version":"9.5.0(tasmota)","BuildDateTime":"2021-06-17T08:26:35","Module or Template":"LocalBytes PM","RestartReason":"Software/System restart","Uptime":"0T00:20:00","Hostname":"plug1-3601","IPAddress":"192.168.1.28","RSSI":"100","Signal (dBm)":"-50","WiFi LinkCount":1,"WiFi Downtime":"0T00:00:03","MqttCount":0,"LoadAvg":19}
09:25:58.392 RSL: STATE = {"Time":"2021-10-08T09:25:58","Uptime":"0T00:20:04","UptimeSec":1204,"Heap":27,"SleepMode":"Dynamic","Sleep":50,"LoadAvg":19,"MqttCount":0,"POWER":"ON","Wifi":{"AP":1,"SSId":"<redacted>","BSSId":"00:50:7F:F1:42:9A","Channel":12,"Mode":"11n","RSSI":96,"Signal":-52,"LinkCount":1,"Downtime":"0T00:00:03"}}
09:25:58.399 RSL: SENSOR = {"Time":"2021-10-08T09:25:58","ENERGY":{"TotalStartTime":"2021-09-29T17:59:48","Total":0.011,"Yesterday":0.000,"Today":0.000,"Period":0,"Power":0,"ApparentPower":0,"ReactivePower":0,"Factor":0.00,"Voltage":232,"Current":0.000}}
09:27:15.528 MQT: Attempting connection...

Здравствуйте, уважаемые.
Собираюсь в

будущем

уже наступившем году строить дом, естественно задумался об автоматизации, Набрёл на “облачные” выключатели\патроны\реле китайской конторы Sonoff после чего выяснилась их “начинка”, а дальше путь привёл на ваш форум и теперь я готовлюсь “вступать в ряды” ESP-шников, не в первые конечно, но надеюсь осилю сделать какие то несложные вещи. Форум изучаю, китайские модули и адаптеры USB-TTL вкупе с проводочками и прочей мелочёвкой уже едут. Скилл пайки имеется, образование профильное радиоэлектронное, так что я думаю вникнуть смогу, надо только

освежить

отыскать в голове позабытое за давностью лет и за непрофильной работой.

Начну с самого простого – перепрошью выключатель Sonoff, отвяжу его от китайского облака и буду “ковырять” на предмет чего бы из него сделать ещё, наверняка как минимум можно прикрутить датчик температуры\влажности, превратив выключатель в мини-метеостанцию.

А покамест детальки в пути – самое время заняться службами “обеспечения”.
Имея в наличии рабочий Web-сервер на CentOS7 + VestaCP провёл так сказать “удачный эксперимент” с комариком, результатами которого хочу поделиться.
Думаю этот небольшой опыт кому то да пригодится

небольшое уточнение: в линуксах опыт минимальный

вооружаемся WinSCP (удобно ходить по каталогам и вносить правки в текстовые файлы встроенным редактором) + PuTTY и действуем

1. подключаем mosquitto репозиторий

Код:

cd /etc/yum.repos.d
wget http://download.opensuse.org/repositories/home:/oojah:/mqtt/CentOS_CentOS-7/home:oojah:mqtt.repo
yum -y update

2. Установка Mosquitto

Код:

yum -y install mosquitto
yum -y install mosquitto-clients

3. добавляем комарика в автозагрузку

Код:

systemctl enable mosquitto.service

при этом centos ругнётся мол москитто не является native серсивом, и сделает как нужно:

mosquitto.service is not a native service, redirecting to /sbin/chkconfig.
Executing /sbin/chkconfig mosquitto on

т.е. ЦентОСь нам подсказала (да ещё и сама по-правильному сделала) что правильная команда на включение автозапуска москитты –

Код:

/sbin/chkconfig mosquitto on

проверять не стал, поверил на слово :)

4. настраиваем конфиг\конфиги
файл /etc/mosquitto/mosquitto.conf переносим в /etc/mosquitto/conf.d и переименовываем например в main.conf
открываем main.conf двойным кликом и вносим в него следующее содержимое:

Код:

# Place your local configuration in /etc/mosquitto/conf.d/

# =================================================================
# General configuration
# =================================================================

pid_file /var/run/mosquitto.pid

# =================================================================
# Default listener
# =================================================================

#bind_address 1.2.3.4     #если надо привязываем сервис к ip или domain.name
#port 1883      #по умолчанию 1883 порт, можно задать другой

# =================================================================
# Persistence
# =================================================================

persistence true
persistence_file mosquitto.db
persistence_location /etc/mosquitto/

# =================================================================
# Logging
# =================================================================

log_dest syslog
log_dest file /var/log/mosquitto/mosquitto.log
log_facility 5
log_type debug
log_type error
log_type warning
log_type notice
log_type information

# =================================================================
# Default authentication and topic access control
# =================================================================

password_file /etc/mosquitto/users.list
acl_file /etc/mosquitto/mosquitto.acl

файл /etc/mosquitto/mosquitto.conf.example переименовываем в /etc/mosquitto/mosquitto.conf (это полноценный конфиг с пояснениями для каждого параметра)
дважды кликая (WinSCP) по переименнованному полноценному конфигу /etc/mosquitto/mosquitto.conf он открывается строенным текстовым редактором
вносим единственную правку – в секцию External config files добавляем include_dir /etc/mosquitto/conf.d
сие действо говорит сервису подгружать дополнительные конфиги из указанной папки (в нашем случае это main.conf )

на мой неискушенный взгляд так просто удобно – “полноценны” конфиг существует в девственном виде (за исключением лишь строки указывающей откуда подгружать дополнительные конфиги) и используется для изучения комментариев к нужным опциям, нужные опции вносятся в конфиг\конфиги находящиеся в папке /etc/mosquitto/conf.d, например в файле main.conf можно сделать основные настройки сервиса, а для каждого бриджа с внешними сервисами создать отдельные конфиги в этой же папочке и с соответствующими названиями
“основной” конфиг полон комментариев и потому его листать туда-сюда в поисках нужной строки очень неудобно, а так открыл “нужный” конфиг и всё сразу перед глазами

5. логины\пароли\доступ

создаём файл /etc/mosquitto/mosquitto.acl
и сразу настраиваем нужный доступ по нужным пользователям (их ведь можно “придумать” заранее), для начала даём доступ пользователю test доступ ко всем топикам
сдержимое:

создаём пустой файл /etc/mosquitto/users.list
и сразу создаём пользователя\пользователей
синтаксис очень простой:

Код:

mosquitto_passwd /etc/mosquitto/users.list test

попросит ввести и подтвердить пароль, в только что созданный файл users.list добавится пользователь test
2017-01-18_21-14-07.png

6. старт сервиса и проверка

стартуем сервис:

Код:

systemctl start mosquitto

проверим стартовал ли:

Код:

systemctl status mosquitto

2017-01-18_16-11-00.png

Видим что то похожее на ” Active: active (running) since ….” и пары “SUCCESS” – хорошо, сервис стартовал

в логе /var/log/mosquitto/mosquitto.log должно быть “mosquitto version 1.4.10 (build date 2016-12-05 08:26:01+0000) starting”

это означает что всё получилось

проверяем работу подключившись mqtt-spy
2017-01-18_16-08-37.png

используемые материалы:
ESP8266 подключаемся к OpenWRT+Mosquitto+mqttwarn и передаем данные на ThingSpeak, EMAIL, Android, iOS, Twitter, CloudMQTT в 100 строчек кода в Arduino IDE – esp8266
Installing Mosquitto Under CentOS 7
Добавлении сервиса в автозагрузку (CentOS 6/7)
Downloads | Mosquitto

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

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