MQTT Broker Connection Refused Error in Python - python-3.x

I have been trying to connect to broker port 1884. But it gets every time connection refused error.
def __init__(self, host='127.0.0.1', port=8080, broker_address='127.0.0.1', broker_port=1884, start_config=None):
self.app = Bottle()
"""Create the http service app"""
self.broker = SimpleBroker(address=broker_address, port=broker_port)
self.broker.start()
"""Create and run the broker (broker always runs as a daemon)"""
self.brokerAddress = broker_address
"""address of the API broker - usually identical to own address, but others for testing"""
self.mqttc = Client()
"""mqtt client for publishing messages to API broker - delivered to edge and preprocessing layer"""
self.mqttc.connect(host=broker_address, port=broker_port)
"""connect to the broker upon startup"""
and then the execution part:
if __name__ == "__main__":
myAPI = APIServer('127.0.0.1', 8080, '127.0.0.1', start_config='all wheels')
myAPI.start()
The error message:
Traceback (most recent call last):
File "/root/PycharmProjects/Thesis2019/API/APIServer.py", line 328, in <module>
myAPI = APIServer('127.0.0.1', 8080, '127.0.0.1', start_config='all wheels')
File "/root/PycharmProjects/Thesis2019/API/APIServer.py", line 42, in __init__
self.mqttc.connect(host=broker_address, port=broker_port)
File "/root/PycharmProjects/Thesis2019/venv/lib/python3.6/site-packages/paho/mqtt/client.py", line 839, in connect
return self.reconnect()
File "/root/PycharmProjects/Thesis2019/venv/lib/python3.6/site-packages/paho/mqtt/client.py", line 962, in reconnect
sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
File "/usr/lib/python3.6/socket.py", line 724, in create_connection
raise err
File "/usr/lib/python3.6/socket.py", line 713, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
On the other hand when i execute it in debug mode, i got :
[2019-04-09 23:43:05,243] :: WARNING :: hbmqtt.broker.plugins.topic_taboo :: 'topic-check' section not found in context configuration
[2019-04-09 23:43:05,243] :: INFO :: transitions.core :: Exited state new
[2019-04-09 23:43:05,244] :: INFO :: transitions.core :: Entered state starting
[2019-04-09 23:43:05,248] :: INFO :: hbmqtt.broker :: Listener 'default' bind to 127.0.0.1:1884 (max_connections=100)
[2019-04-09 23:43:05,248] :: INFO :: transitions.core :: Exited state starting
[2019-04-09 23:43:05,248] :: INFO :: transitions.core :: Entered state started
Additional to all the connection refused part, it just starts it without problem in debug mode i guess?
The Pycharm is launched with root privilege.
Firewall is checked, and it is disabled.
None of these ports are open, checked it with lsof.
I use Python 3.6, hbmqtt 0.9.5
It works on Windows, but not on Mac or Linux
Why i have connection refused error each time i try to execute it ? What am i missing?
Thanks in advance for the ideas.

The solution is:
The Mosquitto default port connection is set to 1883 in the config file, where I was trying to connect through port 1884.
I thought that, this properties are set whenever you change the number. Which is not correct since they are static. not changing dynamically.(sure there is a way too.)
Apart from that, the API Broker and Broker port numbers have to be swapped. I don't know why but windows can bind on top of it without problems. but Mac OS and Linux are throwing Connection Refused error.
The Pycharm is launched with root privilege.
Firewall is checked, and it is disabled.
None of these ports are open, checked it with lsof.
Check config file of the Mosquitto, if the allow_annoymous is True
Control your port connections 10 times.
These are still valid check before going crazy. %90 of the problems are caused because of one of these issues.
If you have further help or questions, you can comment in here and I will try to help for future inquiries.

Related

Multi-node processing using DistributedDataParallel giving me a permission denied error

I'm trying to implement a multi-node job using Pytorch's DistributedDataParallel on a University supercomputer where I'm logging in via ssh using port 22. Following this tutorial, when I set MASTER_PORT=12340 or some other number on the SLURM script, I obviously get no response since there's nothing happening on it. If I set MASTER_PORT=22, I get permission denied when the code reaches the dist.init_process_group() method:
dist.init_process_group(backend=opt.dist_backend, init_method=opt.dist_url,
world_size=opt.world_size, rank=opt.rank)
GIVES ME
Traceback (most recent call last):
File "train_dist.py", line 262, in <module>
main()
File "train_dist.py", line 220, in main
world_size=opt.world_size, rank=opt.rank)
File "/home/miniconda3/envs/vit/lib/python3.7/site-packages/torch/distributed/distributed_c10d.py", line 595, in init_process_group
store, rank, world_size = next(rendezvous_iterator)
File "/home/miniconda3/envs/vit/lib/python3.7/site-packages/torch/distributed/rendezvous.py", line 232, in _env_rendezvous_handler
store = _create_c10d_store(master_addr, master_port, rank, world_size, timeout)
File "/home/miniconda3/envs/vit/lib/python3.7/site-packages/torch/distributed/rendezvous.py", line 161, in _create_c10d_store
hostname, port, world_size, start_daemon, timeout, multi_tenant=True
RuntimeError: The server socket has failed to listen on any local network address. The server socket has failed to bind to [::]:22 (errno: 13 - Permission denied). The server socket has failed to bind to 0.0.0.0:22 (errno: 13 - Permission denied).
I have also tried to re-route the port 22 traffic to some other port (eg. 65000) but I also get permission denied for even attempting this rerouting. I'm not sure what else I can try to do at this point, anyone has any suggestions or is this something that I need to ask the administrator for?

Connect TCP socket failed with: 111 (No connection between python in linux and twincat in windows)

I have been trying to get a connection between TwinCAT 3 on Windows and Python on Ubuntu. I already have the connection between Twincat 3 Windows and Python Windows working, but not to Ubuntu. I have a virtual machine set up through Oracle VM Virtualbox. I tried many things but so far had no success in creating the connection.
I have a bridged adapter network and tried to open the port of the IP address of the virtual machine in linux through sudo ufw allow
I have the following code:
pyads.open_port()
pyads.add_route('10.11.104.206.1.1','127.0.0.1')
pyads.close_port()
plc = pyads.Connection('10.11.104.206.1.1', 851)
plc.open()
try:
# try to connect to PLC
plc.read_state()
print('Connection succeeded')
except Exception:
print('Connection failed')
And this is the error I get:
2020-11-22T22:45:46+0100 Error: Connect TCP socket failed with: 111
Traceback (most recent call last):
File "/home/laurence/ws_moveit/devel/lib/moveit_tutorials/move_panda_LKO.py", line 15, in <module>
exec(compile(fh.read(), python_script, 'exec'), context)
File "/home/laurence/ws_moveit/src/moveit_tutorials/doc/move_panda_LKO/scripts/move_panda_LKO.py", line 64, in <module>
pyads.add_route('10.11.104.206.1.1','127.0.0.1')
File "/usr/local/lib/python3.8/dist-packages/pyads/ads.py", line 188, in add_route
return adsAddRoute(adr.netIdStruct(), ip_address)
File "/usr/local/lib/python3.8/dist-packages/pyads/pyads_ex.py", line 155, in wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/pyads/pyads_ex.py", line 177, in adsAddRoute
raise ADSError(error_code)
pyads.pyads_ex.ADSError: ADSError: target port not found ADS Server not started (6).
These are the netid/IPadresses.
-
-
-
CX-52EE70
169.254.64.202
5.82.238.112.1.1
TCP_IP
-
LEENLAPTOP19
127.0.0.1
10.11.104.206.1.1
TCP_IP
I have tried combinations with other netid/IP addresses so sometimes I get other errors (110,113) but usually 111 which means connection refused, but I do not know what I am doing wrong. Any ideas?
Please make sure the plc runtime is running (a plc program) when you connect. If the plc is in config or exception mode the plc runtime ads port (851 (or 801 for TC2)) is not present. That is what the ADS error 6 target port not found is trying to tell us.

Why are my COM ports busy?

I have a python program I am using to talk to a microcontroler. It opens the com ports like this:
def STM32_connect():
ports = list(serial.tools.list_ports.comports())
for p in ports:
if "STM32" in p.description:
connection = serial.Serial(p.device, timeout = .01)
return(connection)
print("ERROR: No STM32 Device Found")
sys.exit()
serial_connection = STM32_connect()
And then does a bunch of things, sending and receiving data until I close the program like this with a keyboard interput:
except:
print("\n Program Interrupted...")
finally:
print("\n Closing Serial Port\n")
serial_connection.close()
This all works fine. My problem is when the python script is improperly killed by disconnecting the USB cable or powering off the board I can no longer connect to the micro on any COM port. I receive this error:
Traceback (most recent call last):
File "/home/---/.local/lib/python3.5/site-packages/serial/serialposix.py", line 265, in open
self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
OSError: [Errno 16] Device or resource busy: '/dev/ttyACM2'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "flextester.py", line 1, in <module>
from flex_usb_class import *
File "/home/---/Code/RobotFlexTester/flex_usb_class.py", line 30, in <module>
serial_connection = STM32_connect()
File "/home/---/Code/RobotFlexTester/flex_usb_class.py", line 25, in STM32_connect
connection = serial.Serial(p.device, timeout = .01)
File "/home/---/.local/lib/python3.5/site-packages/serial/serialutil.py", line 240, in __init__
self.open()
File "/home/janey/.local/lib/python3.5/site-packages/serial/serialposix.py", line 268, in open
raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 16] could not open port /dev/ttyACM2: [Errno 16] Device or resource busy: '/dev/ttyACM2'
I can change COM ports and I receive the exact same error at a different ttyACM port. But I can connect to the same device on the same port if I try to run a different python script. The problem seems to somehow be locked to the initial test script but ps -a does not show it to still be running. The problem goes away without me doing anything after about 30 seconds - 1 min.
the 30s to 1min delay are due to the internals of RS232 protocol. see the closing_wait option ( default 30 sec ) in setserial command ( http://manpages.ubuntu.com/manpages/zesty/man8/setserial.8.html ) when disconnecting USB cable and connection is killed the protocol waits for the time specified in the closing_wait option until it closes the port / session. session_lockout forbids attaching a second process to an open port...

Why a simple UDP Socket gives me OSError: WinError 10048?

I am trying to write a simple socket (server side) to communicate with a process on the same machine, using UDP as Transport Protocol. This is the code:
from socket import *
serverPortS = 1234
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('localhost', serverPortS))
print ('Il server e pronto a ricevere')
messageS, clientAddressS =serverSocket.recvfrom(2048)
modifiedMessageS = messageS.upper()
serverSocket.sendto(modifiedMessageS, clientAddressS)
serverSocket.close()
The console gives me the error, just launching the server (no client yet):
Traceback (most recent call last):
File "E:\Laboratorio Python\udp_server.py", line 12, in <module>
serverSocket.bind(('localhost', serverPortS))
OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
I don't know how to fix it or how does it means, and searching on the Web I found more complex problem; would love to hear a possible solution!

What do the Sockets Error mean and how can I fix them?

I know there are some other questions on Sockets, but nothing really worked for me. I am new to this and I work on Python 3.4.
For my server this is my code:
import socket
s = socket.socket()
host = socket.gethostname()
port = 80
s.bind(host, port))
s.listen(5)
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send("Thank you for connecting")
c.close()
My client code:
import socket
s = socket.socket()
host = socket.gethostname
port = 80
s.connect((host, port))
print (s.recv(1024))
s.close
For the SERVER code, I got an error saying:
Traceback (most recent call last):
File "/Users/Gautam/Documents/server.py", line 6, in <module>
s.bind((host, port))
PermissionError: [Errno 13] Permission denied
For the CLIENT I got an error saying:
Traceback (most recent call last):
File "/Users/Gautam/Documents/client.py", line 7, in <module>
s.connect((host, port))
ConnectionRefusedError: [Errno 61] Connection refused
Port numbers below 1024 are reserved for the system, you need to have special privileges to bind sockets to those ports. You need to use another port number, above 1024.
The second error should be pretty simple to figure out, as the error message explicitly say
Connection refused
As the server won't run, how do you expect the client to connect to it?
On a related note, don't use "well-known" port numbers for your own servers, unless you are actually planning to do what the ports are "well-known" for. For example, port 80 is usually used by web-servers, so unless you plan to make a web-server you should not use that port.
Even ports above 1024 are sometimes so called "well-known" ports. Start by checking /etc/services to see the port you picked is commonly available. Do note that some services are pretty obscure and not used very much, but you should still avoid using a port number that's already "reserved" according to /etc/services.

Resources