Socket error on client mqtt

Hi, I want to write a MQTT message from an ESP8266/nodeMCU to my raspberry pi which is running Mosquitto broker. I programmed the ESP board via Arduino IDE, using ESP8266WiFi.h and PubSubClient.h. ...

@jay-pee

Hi,

I want to write a MQTT message from an ESP8266/nodeMCU to my raspberry pi which is running Mosquitto broker.

I programmed the ESP board via Arduino IDE, using ESP8266WiFi.h and PubSubClient.h. Mostly copy&paste from the examples.

It connects to the network and then I get the error code from the client.state() function
-4 : MQTT_CONNECTION_TIMEOUT — the server didn’t respond within the keepalive time
and after wards always
-2 : MQTT_CONNECT_FAILED — the network connection failed.

However the connection from the ESP to my Mac which is running also Mosquitto works fine, but I can’t explain myself why. I tried allot (e.g. set the ip with the IPAddress type or extended code with WiFi.mode(WIFI_STA);)

I hope you can help me.

ESP CODE:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "MYSSID";
const char* password = "MYPW";
//const char* mqtt_server = "192.168.178.100";
IPAddress mqtt_server(192, 168, 178, 100);

WiFiClient espClient;
PubSubClient client(espClient);

void setup()
{
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  //WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
}

void loop()
{
  if (client.connect("12rjpwasgdn")) {
    client.publish("test","hello world");
    client.subscribe("inTopic");
    Serial.println("Send: Hello World");
  }
  else
  {
      Serial.println("Not Connected");
      Serial.println(client.state());
  }
  delay(1000);
  client.loop();
}

/etc/mosquitto/conf.d/my.conf:

listener 1883
allow_anonymous true

/var/log/mosquitto/mosquitto.log:

> ...
> 1503425208: New client connected from xxx.xxx.xxx.x as <clientname> (c1, k15).
> 1503425228: Socket error on client <clientname>, disconnecting.

The rest in the Mosquitto folder is default…

@karlp

Why are you trying to connect in every loop?

Philip <notifications@github.com> wrote:

Hi,

I want to write a MQTT message from an ESP8266/nodeMCU to my
raspberry pi which is running Mosquitto broker.

I programmed the ESP board via Arduino IDE, using ESP8266WiFi.h
and PubSubClient.h. Mostly copy&paste from the examples.

It connects to the network and then I get the error code from
the `client.state()` function _-4 : MQTT_CONNECTION_TIMEOUT —
the server didn’t respond within the keepalive time_ and after
wards always _-2 : MQTT_CONNECT_FAILED — the network connection
failed_.

However the connection from the ESP to my Mac which is running
also Mosquitto works fine, but I can’t explain myself why. I
tried allot (e.g. set the ip with the IPAddress type or
extended code with `WiFi.mode(WIFI_STA);`)

I hope you can help me.

ESP CODE:
««
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = «MYSSID»;
const char* password = «MYPW»;
//const char* mqtt_server = «192.168.178.100»;
IPAddress mqtt_server(192, 168, 178, 100);

WiFiClient espClient;
PubSubClient client(espClient);

void setup()
{
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
}

void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print(«Connecting to «);
Serial.println(ssid);
//WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(«.»);
}

Serial.println(«»);
Serial.println(«WiFi connected»);
Serial.println(«IP address: «);
Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length)
{
// handle message arrived
}

void loop()
{
if (client.connect(«12rjpwasgdn»)) {
client.publish(«test»,»hello world»);
client.subscribe(«inTopic»);
Serial.println(«Send: Hello World»);
}
else
{
Serial.println(«Not Connected»);
Serial.println(client.state());
}
delay(1000);
client.loop();
}
««

/etc/mosquitto/conf.d/my.conf:

««
listener 1883
allow_anonymous true
««

/var/log/mosquitto/mosquitto.log:
««
> …
> 1503425208: New client connected from xxx.xxx.xxx.x as <clientname> (c1, k15).
> 1503425228: Socket error on client <clientname>, disconnecting.
««

The rest in the Mosquitto folder is default…

@jay-pee

Just an example. Could also only doing it in the setup function. But the weird thing is that I get at first the status code -4 and then -2 back in the second repeat…

@sisamiwe

@karlp

no, it’s not «just an example» what you’re doing is reconnecting with the same clientid on every loop, which immediately disconnects the existing connection with the same client id, per design. Your current code is along the lines of «it hurts when I do X => stop doing X»

@sisamiwe

But why is it working on several devices and on several others not?

@karlp

There’s no mention of that in the original report, nor is there enough information to have an opinion on it.

@sisamiwe

Ok, sorry.
I will start again from the beginning.

I bought 2 identical Sonoff Basic and flashed the lastest Tasmota firmware to it.
Both are booting and connecting to the WIFI, so that I can reach them via their website.

One Sonoff is connecting to my MQTT broker (mosquitto 1.4.10 in RPI3 using Raspbian stretch).
The other one does not connect, The Tasmota console says

00:00:00 Project sonoff_wz Sonoff_wz (Topic sonoff_wz, Fallback sonoff_test1, GroupTopic sonoffs) Version 5.10.0
00:00:00 WIF: Connecting to AP1 WLAN-Access in mode 11N as sonoff_wz-7273…
00:00:07 WIF: Connected
00:00:14 DNS: Initialized
00:00:21 HTP: Web server active on sonoff_wz-7273.local with IP address 192.168.2.127
00:00:29 MQT: Attempting connection…
00:00:43 MQT: Connect failed to 192.168.2.12:1883, rc -2. Retry in 10 sec
00:01:01 MQT: Attempting connection…
00:01:27 MQT: Connect failed to 192.168.2.12:1883, rc -4. Retry in 10 sec
00:01:55 MQT: Attempting connection…
00:02:07 MQT: Connect failed to 192.168.2.12:1883, rc -2. Retry in 10 sec<

The mosquitto log is telling:

1513544715: New connection from 192.168.2.127 on port 1883.
1513544715: New client connected from 192.168.2.127 as sonoff_test1 (c1, k120, u’test’).
1513544735: Socket error on client sonoff_test1, disconnecting.
1513544809: New connection from 192.168.2.127 on port 1883.
1513544809: New client connected from 192.168.2.127 as sonoff_test1 (c1, k120, u’test’).
1513544829: Socket error on client sonoff_test1, disconnecting.<

So why is one of the both Sonoff working fine and the other one is not connecting?
It get more curios: I started another mqtt broker on my tablet. Here both Sonoffs are connecting.
It seems to be an issue with mosquitto.

What do you mean?

@karlp

If you have a different issue, please open a separate issue.

@sisamiwe

Are you shure that this is a different issue?
All the description above fits to my issue.

The other guys may have just one SONOFF with mqtt firmware. So they might not notice, that some work and some don’t.

@jandrioli

karlp, it’s totally ok to say that you don’t know how to help further.
sisamiwe, I am having the same issue. The pubsubclient library can connect once, but to me it seems that if I have any other client executing requests on the WiFi then the pubsubclient will lose the connection and not be able to reconnect.

@mizrachiran

i’m having the same issue

@jandrioli

I’ve been investigating this now for 45 days. After this while I found a few pointers to help towards a solution:
1 — not all esp modules are made equal. Some have better WiFi signal than others
2 — WiFi reception signal affects directly all the software performance. This includes, of course, this error (connect fail)
3 — if you use serial interface to do debugging, it does not matter what levels of reception your ESP sketch reports to you. If you have this problem, please try to establish a direct line of sight from your WiFi router towards your ESP module

Good luck

@Deamon

Well, I just encountered the problem tonight.
And after few hours, I found that I need to connect to mosquitto with different login and password.
Until I do that (no matter that clientId is different) I get the error. I created an other set of login/password for my second device and it works like a charm.

Hope this help for anyone coming here after a google search.

marcoboers, pkalt, pauloeduardorocha, OldNewbold, iFloris, fundix, yves-vogl, JoeRu, webdevbrian, ChrisRomp, and 2 more reacted with thumbs up emoji
pauloeduardorocha, OldNewbold, fundix, yves-vogl, robertdijk, and justsux reacted with hooray emoji

@jandrioli

Deamon I did not have authentication enabled in any of my mosquitto services.
After my reply from 8 days ago, I also found that you can setup mosquitto keepalive/timeout parameters in the configuration file /etc/mosquitto/mosquitto.conf and /etc/mosquitto/conf.d/*

This relates to ESP’s signal reception and hence general WiFi performance

@arissaraiva

Hello Im having the same problem I have one sonoff with tasmota working fine but I flashed other esp for another program with mosquitto and one day was working the other gave me the same error, Im using rpi3 with hassio and mosquitto addon installed, any tips on how to solve this? Should I put two passwords and user?

@arissaraiva

Found out that my router was giving the same ip for two clients, resseted everything set static ip for botg and now its working

@sujitrp

I am having same issue RPI3b broker and Openhab is the same host . host is with fix IP.
not sure how to fix it. Guide me to fix it

@jandrioli

@arissaraiva

I needed to give fix ip for my nodemcu because it was conflicting with other clients on my dhcp list, just entered in my router deleted a couple of clients and gave new ips to each of them now it´s working

@denis-mrd

Well, I just encountered the problem tonight.
And after few hours, I found that I need to connect to mosquitto with different login and password.
Until I do that (no matter that clientId is different) I get the error. I created an other set of login/password for my second device and it works like a charm.

Hope this help for anyone coming here after a google search.

I have the same issue. Fix IPs and different logins not helps… Please, help me to fix «Socket error on client %name%, disconnecting.». I use Raspbian on RasPi Zero W, home-assistant and mosquitto in docker. Clients are Sonoff relays flashed to Tasmota

@yves-vogl

I’m using 4 Sonoff Tasmota devices with MQTT authentication enabled and can report the same issue (and verify the workaround provided by @Deamon).

1546101984: New connection from 192.168.0.73 on port 1883.
1546101984: New client connected from 192.168.0.73 as eheim-proxima-250 (c1, k15, u'openhabian').
1546101992: New connection from 192.168.0.157 on port 1883.
1546101992: Socket error on client <unknown>, disconnecting.
1546101992: New connection from 192.168.0.66 on port 1883.
1546101992: Socket error on client <unknown>, disconnecting.
1546101993: New connection from 192.168.0.90 on port 1883.
1546101993: Socket error on client <unknown>, disconnecting.
1546102003: New connection from 192.168.0.157 on port 1883.

I had different client names and the same username / credential as OpenHABian allows to configure just a single credential pair through openhabian-config.

After adding more credentials manually so that each client has its own combination of username and password, it works:

$ mosquitto_passwd -b /etc/mosquitto/passwd user1 secret
$ mosquitto_passwd -b /etc/mosquitto/passwd user2 secret

$ systemctl restart mosquitto.service 
1546102863: mosquitto version 1.4.10 (build date Wed, 17 Oct 2018 19:03:03 +0200) starting
1546102863: Config loaded from /etc/mosquitto/mosquitto.conf.
1546102863: Opening ipv4 listen socket on port 1883.
1546102863: Opening ipv6 listen socket on port 1883.
1546102870: New connection from 192.168.0.73 on port 1883.
1546102870: New client connected from 192.168.0.73 as eheim-proxima-250 (c1, k15, u'eheim-proxima-250').
1546102872: New connection from 192.168.0.90 on port 1883.
1546102872: New client connected from 192.168.0.90 as south-america-64 (c1, k15, u'south-america-64').
1546102873: New connection from 192.168.0.157 on port 1883.
1546102873: New client connected from 192.168.0.157 as dragon-stone-72 (c1, k15, u'dragon-stone-72').
1546102873: New connection from 192.168.0.66 on port 1883.
1546102873: New client connected from 192.168.0.66 as samurai-stone-64 (c1, k15, u'samurai-stone-64').

@ralight

I’m going to close this issue, it has become a bit of a mix of different people with different issues and not enough detail to sort anything out. If you still have a problem, please open a new issue and provide the details there.

@madleech

@jay-pee I notice you’re sending a message every loop, followed by delay(1000); client.loop();. You’re also attempting to connect every loop. A better approach may be:

void loop() {
  // connect to mqtt if not already connected
  if (!client.connected()) {
    client.connect(...);
    client.subscribe(...);
  }
  // if we're connected, then publish our message
  if (client.connected()) {
    client.publish(...);
  }
  // and now wait for 1s, regularly calling the mqtt loop function
  for (int i=0; i<1000; i++) {
    client.loop();
    delay(1);
  }
}

The PubSubClient documentation notes:

loop(): This should be called regularly to allow the client to process incoming messages and maintain its connection to the server.

@jay-pee

I stopped this project but know consider working on it again because some good ideas where mentioned. Thank you for your help.

@lock
lock
bot

locked as resolved and limited conversation to collaborators

Aug 7, 2019

Содержание

  1. Настройка MQTT брокера mosquitto
  2. Beetle
  3. Lnbed
  4. Старый Дуб
  5. Victor
  6. Старый Дуб
  7. Victor
  8. Старый Дуб
  9. Victor
  10. Старый Дуб
  11. anchorman
  12. sepbiy
  13. sepbiy
  14. prmres
  15. Ocasionally when trying to connect the broker gives «Socket error on client , disconnecting.» #1247
  16. Comments
  17. Socket error on client , disconnecting. ARMv7 subscriber only #1385
  18. Comments
  19. Socket error on client, disconnecting. 1.4.8 on OSX. #7
  20. Comments
  21. 1470667782: Socket error on client mosqpub/16520-LEE-SOHAE, disconnecting.

Настройка MQTT брокера mosquitto

Beetle

New member

Роутер — OpenWRT (15.05.1, r48532)
mosquitto — 1.4.7

Создал как в статье пользователя тест.
При попытке подключения в логах:

Какой конфиг он грузит тогда?
Или куда еще копать?

В общем то использую конфиг по умолчанию, изменил только 4 строчки:

Lnbed

New member

Beetle,у меня openwrt 15.05.1 mosquitto — 1.4.7. Сервис mosquitto не запускался.
Изменил в /etc/init.d/mosquito :

Старый Дуб

New member

Victor

Administrator

Старый Дуб

New member

Victor

Administrator

Старый Дуб

New member

Victor

Administrator

Старый Дуб

New member

anchorman

New member

sepbiy

New member

В чем может быть проблема?

sepbiy

New member

prmres

New member

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

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

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

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

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

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

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

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

файл /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 можно сделать основные настройки сервиса, а для каждого бриджа с внешними сервисами создать отдельные конфиги в этой же папочке и с соответствующими названиями
«основной» конфиг полон комментариев и потому его листать туда-сюда в поисках нужной строки очень неудобно, а так открыл «нужный» конфиг и всё сразу перед глазами

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

попросит ввести и подтвердить пароль, в только что созданный файл users.list добавится пользователь test

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

Видим что то похожее на » 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

Источник

Ocasionally when trying to connect the broker gives «Socket error on client , disconnecting.» #1247

There seems to be several related problems (#523, #1023, #7, #1197) but I am not sure, so I am posting a new issue.

I have a simple test where

  1. mosquitto broker is started.
  2. client connects.
  3. client disconnects.

Once every few 100 attempts I get from the broker

I am using v1.6 and the C++ interface in mosquittopp. Below is the test code.

The console output is.

I thought that the problem may be that disconnect is being sent too quickly, but that is not it. The output then is.

As you can see the client attempts the connection again if it fails.

I have another more complex test where publishing and subscribing are involved also. There I get the error more often.

The text was updated successfully, but these errors were encountered:

Do you think you could you try and capture wireshark trace of when this happens?

My Mosquitto broker instance has been running in the cluster for 178 days straight and worked fine. Today, suddenly it decided to repeatedly reject any client connections.

It started behaving this way relatively after I made an unrelated change in my kubernetes configuration: I exposed some unrelated TCP service through my Nginx Ingress.
The only way that unrelated change might have affected the mqtt broker is that it caused the nginx ingress to restart, which caused all mqtt client connections to close.
Soon after nginx booted up, clients started re-connecting but this time unsuccessfully with broker throwing Socket error on client X, disconnecting .

Edit:
I managed to get the broker not to disconnect a client by supplying unique username/password on the client. This frightens me since credentials should not play any role when authentication is disabled.

Hi,
I’m seeing something very similar using mosquittopp 1.6.4 on ARM, localhost connections:

1582069468: Sending CONNACK to auth_manager (0, 0)
1582069468: Received PUBLISH from auth_manager (d0, q1, r1, m1, ‘device/auth’, . (495 bytes))
1582069468: Sending PUBACK to auth_manager (m1, rc0)
1582069468: Sending PUBLISH to mosq/zD3DRWvoOKp2e4oeSb (d0, q0, r0, m0, ‘device/auth’, . (495 bytes))
1582069468: Received DISCONNECT from mosq/zD3DRWvoOKp2e4oeSb

The big concern for me is I have on_disconnect set and it does not fire with an error. The first message always fires, the next 4 usually do. When it fail’s the last 4 all fail to pub, but the first message always get’s pub’d.

I’d say this is more like 1/20 for me.

From time to time, I have the same Socket error on client , disconnecting. issue for some of my devices (anonymous connections, all devices have status IPs)

As all of my devices are exactly the same (hardware and software except devise’s name passed to MQTT) I can observe that the issue occurs more often on devices that stand further from my router (but I cannot replicate it when taking one of them with a power bank power supply of the range of the router).

From my perspective, another, noticeable, issue is that after the Socket error on client(. ) last will message is not triggered (it would allow me to force restart the device).

Any ideas if it’s possible to fetch «last will» on such kind of errors?

@kotu-pl What version of Mosquitto are you using? Are you absolutely sure that a Will message is being set on your client? If you are able to provide a wireshark/tcpdump trace of the broker we may be able to figure out what is happening.

Источник

Socket error on client , disconnecting. ARMv7 subscriber only #1385

Currently I’m working on a project where i need to use MQTT on an ARMv7 and i686 device. The current problem is that specificly on the ARMv7 device some problems arise.

i am running on both of the devices Debian 7 Wheezy.

When i try to connect the ARMv7 device to the broker it seems to connect but doesn’t receive anything at all. The broker returns the following

1566312615: New connection from 192.168.1.40 on port 1883.
1566312616: Socket error on client , disconnecting.
1566312616: New connection from 192.168.1.40 on port 1883.
1566312616: New client connected from 192.168.1.40 as mosq/qEidBqNY1Kx74MR3Ia (p2, c1, k60).
1566312616: No will message specified.
1566312616: Sending CONNACK to mosq/qEidBqNY1Kx74MR3Ia (0, 0)

The I686 devices show the following notice

1566313930: New connection from 192.168.1.20 on port 1883.
1566313930: New client connected from 192.168.1.20 as mosq/Y0ecobRZo5SXfWh1J1 (p2, c1, k60).
1566313930: No will message specified.
1566313930: Sending CONNACK to mosq/Y0ecobRZo5SXfWh1J1 (0, 0)
1566313930: Received SUBSCRIBE from mosq/Y0ecobRZo5SXfWh1J1
1566313930: diagnostics (QoS 1)
1566313930: mosq/Y0ecobRZo5SXfWh1J1 1 diagnostics
1566313930: Sending SUBACK to mosq/Y0ecobRZo5SXfWh1J1

  • the I686 device works normal as either publisher, subscriber or broker
  • the ARMv7 device works normal as publisher or broker
  • the same problem happens when using my pc (windows x64) as broker, while the I686 device works fine.

after little research i noticed that the broker does not forward anything to the ARMv7 device. i don’t know it this is a bug of something else.
Both devices use the same codebase, but are built with seperate compilers.

Thanks in advance.
Nick

The text was updated successfully, but these errors were encountered:

Источник

Socket error on client, disconnecting. 1.4.8 on OSX. #7

migrated from Bugzilla #488633
status ASSIGNED severity normal in component Mosquitto for 1.4
Reported in version 1.4 on platform PC
Assigned to: Roger Light

On 2016-02-27 19:02:59 -0500, James Lewis wrote:

Broker Process:
Run Mosquitto 1.4.8 in verbose mode
$ mosquitto -v

Subscriber Process:
Subscribe to localhost with a test topic «debug».
$ mosquitto_sub -h 127.0.0.1 -i testSub -t debug

Publisher Process:
Publish a message to localhost with the same test topic, «debug».
$ mosquitto_pub -h 127.0.0.1 -i testPublish -t debug -m ‘Hello World’

The Broker process will report;
1456617536: New connection from 127.0.0.1 on port 1883.
1456617536: New client connected from 127.0.0.1 as testPublish (c1, k60).
1456617536: Socket error on client testPublish, disconnecting.

No errors are reported from the publish process:
1456617552: New connection from 127.0.0.1 on port 1883.
1456617552: New client connected from 127.0.0.1 as testSub (c1, k60).

On my Mac I will still see the message on the Publisher process. However, I have heard from others that they have intermittent success. Even if I use 1.4.7 or 1.4.5 versions of mosquitto_pub and mosquitto_sub the Broker process will always report a «Socket error on client.»

If I change ONLY the broker to 1.4.5, the error never occurs. On the machine that has intermittent success, running 1.4.5 ss the broker (simply replacing only the mosquitto binary) results in expected functioning.

Verified firewall set to «allow incoming connections.»

On 2016-03-07 17:28:25 -0500, Roger Light wrote:

Thanks for this, I’ve found the problem which comes from a Windows related change. I’ve got a fix for OSX, but need to check there are no regressions on Windows.

The text was updated successfully, but these errors were encountered:

I am, unfortunately, experiencing this same problem. I’ve installed Mosquitto on my Mac using Home-brew (version 1.4.8). Any update on the fix? Thanks.

same problem here. 1.4.8 installed from home-brew

I apologise, this fell through the cracks for 1.4.9. I’ve pushed a fix that will be in the next release.

I got a same problem version 1.4.9 on OS X.
I hope this problem fix next release.

sohaenglee$ /usr/local/sbin/mosquitto -c /usr/local/etc/mosquitto/mosquitto.conf
1470667050: mosquitto version 1.4.9 (build date 2016-06-18 16:16:49+0100) starting
1470667050: Config loaded from /usr/local/etc/mosquitto/mosquitto.conf.
1470667050: Opening ipv4 listen socket on port 1883.
1470667050: Opening ipv6 listen socket on port 1883.
1470667051: New connection from 127.0.0.1 on port 1883.
1470667051: New client connected from 127.0.0.1 as mosqsub/15501-LEE-SOHAE (c1, k60).
1470667051: New connection from 127.0.0.1 on port 1883.
1470667051: New client connected from 127.0.0.1 as mqttjs_fbda98eb (c1, k10).
1470667062: New connection from 127.0.0.1 on port 1883.
1470667062: New client connected from 127.0.0.1 as mosqpub/15707-LEE-SOHAE (c1, k60).
1470667062: Socket error on client mosqpub/15707-LEE-SOHAE, disconnecting.
1470667330: Socket error on client mosqsub/15501-LEE-SOHAE, disconnecting.
1470667351: New connection from ::1 on port 1883.
1470667351: New client connected from ::1 as mosqsub/16056-LEE-SOHAE (c1, k60).
1470667394: New connection from ::1 on port 1883.
1470667394: New client connected from ::1 as mosqpub/16137-LEE-SOHAE (c1, k60).
1470667394: Socket error on client mosqpub/16137-LEE-SOHAE, disconnecting.
1470667683: New connection from 10.0.1.3 on port 1883.
1470667683: New client connected from 10.0.1.3 as testClient (c1, k30).
1470667737: Socket error on client testClient, disconnecting.
1470667741: Socket error on client mosqsub/16056-LEE-SOHAE, disconnecting.
1470667774: New connection from 127.0.0.1 on port 1883.
1470667774: New client connected from 127.0.0.1 as mosqsub/16495-LEE-SOHAE (c1, k60).
1470667779: New connection from ::1 on port 1883.
1470667779: New client connected from ::1 as mosqpub/16500-LEE-SOHAE (c1, k60).
1470667779: Socket error on client mosqpub/16500-LEE-SOHAE, disconnecting.
1470667780: New connection from ::1 on port 1883.
1470667780: New client connected from ::1 as mosqpub/16510-LEE-SOHAE (c1, k60).
1470667780: Socket error on client mosqpub/16510-LEE-SOHAE, disconnecting.
1470667782: New connection from ::1 on port 1883.
1470667782: New client connected from ::1 as mosqpub/16520-LEE-SOHAE (c1, k60).

1470667782: Socket error on client mosqpub/16520-LEE-SOHAE, disconnecting.

sub : mosquitto_sub -h 127.0.0.1 -t topic/state
pub : mosquitto_pub -h 127.0.0.1 -t topic/state -m «testtest»

This is fixed in the fixes branch and will be released as part of 1.4.10.

very thanks ralight

I am running 1.4.11 and I am still experiencing this problem.
Using Paho pYthon library to connect to broker. Another application connects to the same broke just fine using the same credentials.

after last system update my mosquitto also stopped working via WebSocket
(Ubuntu 14.04)
I just commented

now working mqtt protocol only
otherwise mosquitto not start at all

@flexiti Could you please open a separate issue? This one is not about websockets nor ubuntu.

@danobot The original issue is «running the broker on a mac, any client will have problems connecting». If you’re saying it is only the python client that has problems it doesn’t sound quite the same. The Python code does look ok though.

@ralight
sorry, wrong window by mistake 🙂

I’m experiencing the same issue intermittently.
Mac OS X
mosquitto 1.4.10

To reproduce I ran a broker:
$ mosquitto -v

I started a subscriber:
$ mosquitto_sub -t testtopic

I published several times:

The first 5 publishes were fine. They looked like this on the broker:

The last publish looked like this (note the socket error):

Источник

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

будущем

уже наступившем году строить дом, естественно задумался об автоматизации, Набрёл на «облачные» выключателипатроныреле китайской конторы 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

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...

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Snowrunner runtime error
  • Snowrunner error 1058406399
  • Snow layer minecraft ошибка
  • Snmpwalk usm generic error
  • Snmp agent item on host failed another network error wait for 15 seconds

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии