MQTT error: Connection reset by peer

I have openHAB running on a PC running mqtt broker. (specs at end of post) I have a Pi4 running openHAB. I have a DHT22 sensor hooked up to the pi and a script sending the data via mqtt to the PC with the broker on it. It works but throws an error every time it runs

I followed this (old but still great) tutorial (thanks @Kees_van_Gelder :+1:)

warning: I am a total python noobs!

script that is running can be found here

here is full error

16:22:42.074 [ERROR] [o.moquette.broker.NewNettyMQTTHandler] - Unexpected exception while processing MQTT message. Closing Netty channel. CId=python_pub
java.io.IOException: Connection reset by peer
	at sun.nio.ch.FileDispatcherImpl.read0(Native Method) ~[?:1.8.0_222]
	at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39) ~[?:1.8.0_222]
	at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223) ~[?:1.8.0_222]
	at sun.nio.ch.IOUtil.read(IOUtil.java:192) ~[?:1.8.0_222]
	at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380) ~[?:1.8.0_222]
	at io.netty.buffer.PooledByteBuf.setBytes(PooledByteBuf.java:247) ~[bundleFile:4.1.42.Final]
	at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1147) ~[bundleFile:4.1.42.Final]
	at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:347) ~[bundleFile:4.1.42.Final]
	at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:148) [bundleFile:4.1.42.Final]
	at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:700) [bundleFile:4.1.42.Final]
	at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:635) [bundleFile:4.1.42.Final]
	at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:552) [bundleFile:4.1.42.Final]
	at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:514) [bundleFile:4.1.42.Final]
	at io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1044) [bundleFile:4.1.42.Final]
	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) [bundleFile:4.1.42.Final]
	at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) [bundleFile:4.1.42.Final]
	at java.lang.Thread.run(Thread.java:748) [?:1.8.0_222]

here is the script

#!/usr/bin/python
# DHT Sensor Data-logging to MQTT Temperature channel

# Requies a Mosquitto Server Install On the destination.

# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# MQTT Encahncements: David Cole (2016)

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import json
import requests
import sys
import time
import datetime
import paho.mqtt.client as mqtt
import Adafruit_DHT


#==================================================================================================================================================
#Usage
#python mqtt.channel.py <temp topic> <humidity topic> <gpio pin> <optional update frequency>
# eg python mqtt.channel.py 'cupboard/temperature1' 'cupboard/humidity1' 4
# will start an instance using 'cupboard/temperature1' as the temperature topic, and using gpio port 4 to talk to a DHT22 sensor
# it will use the default update time of 300 secons.
#==================================================================================================================================================

# Type of sensor, can be Adafruit_DHT.DHT11, Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
DHT_TYPE = Adafruit_DHT.DHT22

# Example of sensor connected to Raspberry Pi pin 23
DHT_PIN  = sys.argv[3]
# Example of sensor connected to Beaglebone Black pin P8_11
#DHT_PIN  = 'P8_11'

if (len(sys.argv) < 2):
   raise  ValueError('Input arguments of mqtt channel temperature humidity not passed')

MOSQUITTO_HOST = 'servername'
MOSQUITTO_PORT = 1883
MOSQUITTO_TEMP_MSG = str(sys.argv[1]) # Old channel name in here
MOSQUITTO_HUMI_MSG = str(sys.argv[2]) # Old channel name now passed by argument
print('Mosquitto Temp MSG {0}'.format(MOSQUITTO_TEMP_MSG))
print('Mosquitto Humidity MSG {0}'.format(MOSQUITTO_HUMI_MSG))

# How long to wait (in seconds) between measurements.
print "Args length: " + str(len(sys.argv))
FREQUENCY_SECONDS      = 300

if (len(sys.argv) > 4):
	FREQUENCY_SECONDS = float(sys.argv[4])


print('Logging sensor measurements to {0} every {1} seconds.'.format('MQTT', FREQUENCY_SECONDS))
print('Press Ctrl-C to quit.')
print('Connecting to MQTT on {0}'.format(MOSQUITTO_HOST))
mqttc = mqtt.Client("python_pub")
try:

    while True:
        # Attempt to get sensor reading.
        humidity, temp = Adafruit_DHT.read(DHT_TYPE, DHT_PIN)

        # Skip to the next reading if a valid measurement couldn't be taken.
        # This might happen if the CPU is under a lot of load and the sensor
        # can't be reliably read (timing is critical to read the sensor).
        if humidity is None or temp is None:
           time.sleep(2)
           continue

        currentdate = time.strftime('%Y-%m-%d %H:%M:%S')
        print('Date Time:   {0}'.format(currentdate))
        print('Temperature: {0:0.2f} C'.format(temp))
        print('Humidity:    {0:0.2f} %'.format(humidity))

        # Publish to the MQTT channel
        try:
     	    mqttc.connect(MOSQUITTO_HOST,MOSQUITTO_PORT);
            print 'Updating {0}'.format(MOSQUITTO_TEMP_MSG)
            (result1,mid) = mqttc.publish(MOSQUITTO_TEMP_MSG,temp)
            print 'Updating {0}'.format(MOSQUITTO_HUMI_MSG)
	    time.sleep(1)
            (result2,mid) = mqttc.publish(MOSQUITTO_HUMI_MSG,humidity)
            print 'MQTT Updated result {0} and {1}'.format(result1,result2)
            if result1 == 1 or result2 == 1:
                raise ValueError('Result for one message was not 0')
	    mqttc.disconnect()

        except Exception,e:
            # Error appending data, most likely because credentials are stale.
            # Null out the worksheet so a login is performed at the top of the loop.
	    mqttc.disconnect()
            print('Append error, logging in again: ' + str(e))
            continue

        # Wait 30 seconds before continuing
        print('Wrote a message to MQTT broker')
        time.sleep(FREQUENCY_SECONDS)

except Exception as e:
    print('Error connecting to the moqtt server: {0}'.format(e))
  • Platform information:
    • Hardware: PC I3 8Gbs 1Tbs h/d
    • OS: Mint 19
    • Java Runtime Environment: 8
    • openHAB version: 2.5.0 M5

thanks for any help

I used that tutorial a couple of weeks ago with no issues. I have an rPi 3B+ running openHAB, Mosquitto MQTT broker and the script you linked, and the DHT22 sensor is of course also connected to this same rPi.

I’m curious about your setup - you have two instances of openHAB running - one on a PC, and one on an rPi? What does openHAB on the rPi do?

It’s generally recommended to use the 3rd party Mosquitto broker, rather than the in-built and soon to be deprecated Moquette broker - may be worth changing if you’ve only just started down the MQTT route!

Just to check: the script you’ve quoted (not the one you linked) - is that exactly what you’re using? It doesn’t have the

filled in with your server IP address.

yeah, I changed the script to include my actual ip address of PC with Moquette running on it

yes, I have a production (well not in the truest sense, it is experimental really, I live alone so
 no waf) instance running on the PC. I brought a Pi to experiment and test. The Pi instance of OpenHAB really doesn’t do much yet. I have astro and network binding running and NGRE just so I can begin to learn scripting. Got a DHT22 to see if I could do something with it and mqtt is the only connection between the two

I’ve been running Moquette forever and it has always worked in spite of everybody on this forum saying it is deprecated, it works for me.
and edit to add: it is still working, the script throws this error, but the data is reported in openHAB correctly

Does every client that connects to the MQTT broker use a unique client id (“python_pub” in your script)? All clients must have a unique ID. When a new client with the same ID connects, the already connected client will be kicked off the broker.

It works until it doesn’t. When it doesn’t, the only viable solution is to move to Mosquitto or some other third party broker.

1 Like

How would I check that?
There is only one script of this type on the Pi. The Pi is for learning and experimenting and has no other stuff loaded on it. I don’t think there are any more mqtt clients unless OpenHAB itself is a client but figure they would not have a ID of ‘python_pub’

It is, it has to be a client. That’s how MQTT works, everybody’s an equal client of the broker.
You can assign an ID in your broker thing or it will generate a random ID. You can see what it actually uses just by looking in your openhab.log, as the MQTT binding leaves a connect message.

It doesn’t matter what is running on just that one RPi. What matters is what all connects to the same broker. They all need to have a unique client ID. So if you have anything else connecting to this broker using the same client ID you will see this type of error.

I can’t think of any other reason why the broker would reset the connection like that.