Socket error on client unknown disconnecting

Describe the issue you are experiencing I have in the log many errors like: 1647764072: New connection from 172.30.32.2 on port 1883. 1647764072: Socket error on client , disconnecti...

Describe the issue you are experiencing

I have in the log many errors like:

1647764072: New connection from 172.30.32.2 on port 1883.
1647764072: Socket error on client <unknown>, disconnecting.
1647764192: New connection from 172.30.32.2 on port 1883.
1647764192: Socket error on client <unknown>, disconnecting.
1647764313: New connection from 172.30.32.2 on port 1883.
1647764313: Socket error on client <unknown>, disconnecting.

In the configuration, the unsecure ports 1883 and 1884 disabled:

image

What type of installation are you running?

Home Assistant OS

Which operating system are you running on?

Debian

Which add-on are you reporting an issue with?

Mosquitto broker

What is the version of the add-on?

6.0.1

Steps to reproduce the issue

Anything in the Supervisor logs that might be useful for us?

No response

Anything in the add-on logs that might be useful for us?

...

1647766238: New connection from 172.30.32.2 on port 1883.
1647766238: Socket error on client <unknown>, disconnecting.
1647766358: New connection from 172.30.32.2 on port 1883.
1647766358: Socket error on client <unknown>, disconnecting.
1647766478: New connection from 172.30.32.2 on port 1883.
1647766478: Socket error on client <unknown>, disconnecting.
1647766598: New connection from 172.30.32.2 on port 1883.
1647766598: Socket error on client <unknown>, disconnecting.
1647766718: New connection from 172.30.32.2 on port 1883.
1647766718: Socket error on client <unknown>, disconnecting.
1647766838: New connection from 172.30.32.2 on port 1883.
1647766838: Socket error on client <unknown>, disconnecting.
1647766884: Client 2SFZ5UvrGPQMIdfhaOgTcn has exceeded timeout, disconnecting.
1647766898: New connection from 172.30.32.1 on port 1883.
1647766898: New client connected from 172.30.32.1 as 2SFZ5UvrGPQMIdfhaOgTcn (p2, c1, k60, u'homeassistant').
1647766958: New connection from 172.30.32.2 on port 1883.
1647766958: Socket error on client <unknown>, disconnecting.
1647767079: New connection from 172.30.32.2 on port 1883.
1647767079: Socket error on client <unknown>, disconnecting.
1647767199: New connection from 172.30.32.2 on port 1883.
1647767199: Socket error on client <unknown>, disconnecting.
1647767319: New connection from 172.30.32.2 on port 1883.
1647767319: Socket error on client <unknown>, disconnecting.
1647767439: New connection from 172.30.32.2 on port 1883.
1647767439: Socket error on client <unknown>, disconnecting.
1647767534: Saving in-memory database to /data/mosquitto.db.
1647767559: New connection from 172.30.32.2 on port 1883.
1647767559: Socket error on client <unknown>, disconnecting.

...

Additional information

No response

Содержание

  1. Ocasionally when trying to connect the broker gives «Socket error on client , disconnecting.» #1247
  2. Comments
  3. Add-On Mosquitto broker: Socket error on client , disconnecting. #2414
  4. Comments
  5. Describe the issue you are experiencing
  6. What type of installation are you running?
  7. Which operating system are you running on?
  8. Which add-on are you reporting an issue with?
  9. What is the version of the add-on?
  10. Steps to reproduce the issue
  11. Anything in the Supervisor logs that might be useful for us?
  12. Anything in the add-on logs that might be useful for us?
  13. Additional information
  14. Socket error on client , disconnecting. #523
  15. Comments
  16. socket error on client unknown disconnecting on CentOS 7 #199
  17. Comments
  18. Socket error on client, disconnecting. 1.4.8 on OSX. #7
  19. Comments
  20. 1470667782: Socket error on client mosqpub/16520-LEE-SOHAE, disconnecting.

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.

Источник

Add-On Mosquitto broker: Socket error on client , disconnecting. #2414

Describe the issue you are experiencing

I have in the log many errors like:

In the configuration, the unsecure ports 1883 and 1884 disabled:

What type of installation are you running?

Home Assistant OS

Which operating system are you running on?

Which add-on are you reporting an issue with?

What is the version of the add-on?

Steps to reproduce the issue

Anything in the Supervisor logs that might be useful for us?

Anything in the add-on logs that might be useful for us?

Additional information

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

Unfortunately, I have exactly the same problems.

This looks like you have a Client (172.30.32.2) attempting connection to MQTT Broker on port 1883 (Non SSL) but your Broker is not configured (Deactivated) on that port. You either need to:

  • Enable 1883 port by adding text «1883» in «Host» field where it currently says «Deaktiviert». This would allow unsecured MQTT.
  • Or change the Client MQTT config to use SSL and port 8883.

I have the same problem but my port 1883 IS active:

It’s the only thing that now still cluttering my log, it happens every 2 minutes:
`
2022-03-31T11:21:37: New connection from 172.30.32.2 on port 1883.

2022-03-31T11:21:37: Socket error on client , disconnecting.

2022-03-31T11:21:53: Saving in-memory database to /data/mosquitto.db.

2022-03-31T11:23:37: New connection from 172.30.32.2 on port 1883.

2022-03-31T11:23:37: Socket error on client , disconnecting.

2022-03-31T11:25:37: New connection from 172.30.32.2 on port 1883.

2022-03-31T11:25:37: Socket error on client , disconnecting.

2022-03-31T11:27:37: New connection from 172.30.32.2 on port 1883.

2022-03-31T11:27:37: Socket error on client , disconnecting.

2022-03-31T11:29:37: New connection from 172.30.32.2 on port 1883.

2022-03-31T11:29:37: Socket error on client , disconnecting.
`

I enable Port 1883 but the errors in log, always.

I think, it’s the related issue from @netweaver1970

It’s crazy that this supervisor-access floating the log with errors.

In my case, i got same issue but it’s not the related issue because the client is not unknown.
It’s another addon (tydom2mqtt) who seems to not be able to connect

does anyone have an ideas ?

I’m experiencing the same issue. the issue seems became active without reason. When port 1883 is enabled in the configuration, the port seems only accessible when connecting on the host itself by addressing localhost/127.0.0.1. When connecting to the configured IP address of the host on that same host the connection is denied. I’ve tested it while iptables enabled and disabled, but there is no difference.

In the supervisor log this entry is logged:
22-04-13 23:19:23 ERROR (MainThread) [supervisor.services.modules.mqtt] There is already a MQTT service in use from core_mosquitto

Update:
Assigning a different port than default, like for instance 1885 instead of 1883, works fine. So it seems that something stands in the way of using the default ports.

Do you change the port only on the mosquitto addon and the tydom addon ?
Or even in the MQTTT integration ?

Do you use a user setting into home assistant configuration or directly into the addon configuration ?

I try to change the port and still same issue for me.

I even got an another one in the supervisor log
22-04-15 17:39:06 WARNING (MainThread) [supervisor.misc.tasks] Watchdog found a problem with 6b64d821_tydom2mqtt!

The error you are seeing

is the supervisor doing health checks, ie I suspect it’s only doing a TCP connect to the mosquitto addon, hence the error in the log. Unfortunately «it’s normal and good». It’s the same issue as @netweaver1970 pointed at: core/issues/51603

If you’re running the SSH addon, you can do a name lookup on the IP address:

As you can see it’s the supervisor. If you have other logs with «strange» docker addresses you can always look them up that way. You will get the container host name for example:

Источник

Socket error on client , disconnecting. #523

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.

The rest in the Mosquitto folder is default.

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

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 (c1, k15). > 1503425228: Socket error on client , disconnecting. «« The rest in the Mosquitto folder is default.

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.

Is there any solution?

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»

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

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

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

Источник

socket error on client unknown disconnecting on CentOS 7 #199

I’m using CentOS with MQTT C client. When I ran my app I’m receiving the error : Failed to connect, return code -1 .
When I’m looking at mosquitto I’m see this output :

Why the connection is lost?

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

Please attach a trace of the client by setting environment variable:

and collecting stdout, if this is still a problem for you, and reopen the issue. Thanks.

The problem was that I used machines names and not IP addresses.

The problem was that I used machines names and not IP addresses.
I have the same issue can you show how you solved it?

@mhlg By machine names, do you mean TCP host names? Because host names, or IP addresses will work. «localhost» or «127.0.0.1» for instance. Host names, as long as they can be resolved by your DNS. Easy to check with ping.

@icraggs Hi I really do not understand what @liorko87 is referring to..
but I have the same mosquitto output

MQTTNetworkConnect returns OK but as soon as MQTTConnect is called and the packet is sent by sendPacket the «Socket error on client , disconnecting» error happens.
sendPacket which internally calls c->ipstack->mqttwrite returns the number of bytes sent and is successfull.

my mqttwrite implementation

I assume something inside the MQTTPacket_connectData is not set correctly but I’m not sure what.

My development env is composed of my laptop where mosquitto is running using
mosquitto -v
and an external development board with ETH connectivity where the MQTT client code is running.

Источник

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):

Источник

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

A problem that accompanied me for more than half a year, I spent evenings with error analysis and troubleshooting. After some update my Wemos D1 Mini (ESP8266) could not establish a TLS encrypted connection to the Mosquitto MQTT broker.

Error message in PlatformIO’s Serial Monitor:

Connection to MQTT broker failed with state failed with state -2 

Error message in the log /var/log/mosquitto.log of Mosquitto MQTT Broker:

New connection from 87.152.151.230 on port 8883. 
Socket error on client <unknown>, disconnecting.

First I searched in the reference of the PubSubClient, tried several previous versions here, because I suspected the error here first. https://pubsubclient.knolleary.net/api.html

-2 : MQTT_CONNECT_FAILED - the network connection failed 

Solutions on Mosquitto MQTT Broker

https://mosquitto.org/man/mosquitto-conf-5.html
The first is require_certificate, which may be set to true or false. If false, the SSL/TLS component of the client will verify the server but there is no requirement for the client to provide anything for the server: authentication is limited to the MQTT built in username/password.

/etc/mosquitto/mosquitto.conf

listener 8883 
certfile /etc/mosquitto/certs/mqtt_server.crt 
cafile /etc/mosquitto/certs/ca.crt 
keyfile /etc/mosquitto/certs/mqtt_server.key 
require_certificate false

Solutions on Arduino

Adding the right libraries

#include <ESP8266WiFi.h> 
#include <WiFiClientSecure.h> 

Increasing the MQTT max packet size

Sets the largest packet size, in bytes, the client will handle. Any packet received that exceeds this size will be ignored. Default: 128 bytes

#define MQTT_MAX_PACKET_SIZE 256 

Changing the Wifi mode

Add the following statement before the actual WiFi connect takes place.

WiFi.mode(WIFI_STA); 

Using the WifiClientSecure instead of the WifiClient

WiFiClientSecure

Make sure ESP8266 is set to 160MHz

platformio.ini

[env:d1_mini] 
board_build.f_cpu = 160000000L 

Reading out the TLS Buffer

To find out what happens during the TLS handshake you should read the buffer

Serial.print("Connection to MQTT broker failed with state: ");
Serial.println(client.state()); 
char puffer[100];
espClient.getLastSSLError(puffer,sizeof(puffer));
Serial.print("TLS connection failed with state: ");
Serial.println(puffer); 

Here I finally got the following error message, which led me to the actual solution of the problem.

Chain could not be linked to a trust anchor 

Add espClient.setInsecure(); to the setup section

If you are not afraid of DNS attacks and want to disable CA validation, this statement will ultimately lead to success.

void setup() {
Serial.begin(115200);
espClient.setInsecure();
reconnect(); 

For the sake of completeness, the PubSubClient also offers the possibility of integrating the certificate of the Certification Authority (CA) by which a higher security level can be achieved.

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

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

  • 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 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии