socket.gaierror: [Errno -2] - mqtt

Here is my code on the bottom is the ERROR:
This is my config file:
[MQTT]
userMQTT = /
passwdMQTT = /
hostMQTT = broker.hivemq.com
poerMQTT = 1883
Above is mine config file where i used public broker. And now the rest of the code:
import configparser
from time import localtime, strftime
import json
import paho.mqtt.client as mqtt
config = configparser.ConfigParser()
config.read('/home/pi/bin/py.conf') # Broker connection config.
requestTopic = 'services/timeservice/request/+' # Request comes in
here. Note wildcard.
responseTopic = 'services/timeservice/response/' # Response goes
here. Request ID will be appended later
def onConnect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
def onMessage(client, userdata, message):
requestTopic = message.topic
requestID = requestTopic.split('/')[3] # obtain requestID as last
field from the topic
print("Received a time request on topic " + requestTopic + ".")
lTime = strftime('%H:%M:%S', localtime())
client.publish((responseTopic + requestID), payload=lTime, qos=0,
retain=False)
def onDisconnect(client, userdata, message):
print("Disconnected from the broker.")
# Create MQTT client instance
mqttc = mqtt.Client(client_id='raspberrypi', clean_session=True)
mqttc.on_connect = onConnect
mqttc.on_message = onMessage
mqttc.on_disconnect = onDisconnect
# Connect to the broker
mqttc.username_pw_set(config['MQTT']['userMQTT'], password=config['MQTT']
['passwdMQTT'])
BUT after i type:
mqttc.connect(config['MQTT']['hostMQTT'], port=int(config['MQTT']
['portMQTT']), keepalive=60, bind_address="")
I get an ERROR:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line
768, in connect
return self.reconnect()
File "/usr/local/lib/python3.5/dist-packages/paho/mqtt/client.py", line
895, in reconnect
sock = socket.create_connection((self._host, self._port), source_address=
(self._bind_address, 0))
File "/usr/lib/python3.5/socket.py", line 694, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "/usr/lib/python3.5/socket.py", line 733, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
I tried putting an address in bind_address="" but i keep getting the same ERROR. I tried putting bind_address="0.0.0.0" or my local address.

Your config file contains:
poerMQTT = 1883
Where as your code is accessing:
portMQTT

Related

Pyrogram raw functions.channels.GetFullChannel not working

For example, i wrote a simple echo-bot, but GetFullChannel is not working.
from pyrogram import Client, filters, enums
from pyrogram.raw import functions, types
app = Client(username, api_id, api_hash)
#app.on_message(filters.text)
async def echo(client, message):
if message.text == "test":
r = await app.invoke(functions.channels.GetFullChannel(channel=-100********21))
print(r)
My code failed and return this trace:
Traceback (most recent call last):
File "/home/******/.local/lib/python3.9/site-packages/pyrogram/dispatcher.py", line 240, in handler_worker
await handler.callback(self.client, *args)
File "**************.py", line 84, in echo
ret = await app.invoke(functions.channels.GetFullChannel(channel=-100********21))
File "/home/*****/.local/lib/python3.9/site-packages/pyrogram/methods/advanced/invoke.py", line 77, in invoke
r = await self.session.invoke(
File "/home/*****/.local/lib/python3.9/site-packages/pyrogram/session/session.py", line 361, in invoke
return await self.send(query, timeout=timeout)
File "/home/******/.local/lib/python3.9/site-packages/pyrogram/session/session.py", line 290, in send
message = self.msg_factory(data)
File "/home/*****/.local/lib/python3.9/site-packages/pyrogram/session/internals/msg_factory.py", line 37, in __call__
len(body)
File "/home/*****/.local/lib/python3.9/site-packages/pyrogram/raw/core/tl_object.py", line 79, in __len__
return len(self.write())
File "/home/******/.local/lib/python3.9/site-packages/pyrogram/raw/functions/channels/get_full_channel.py", line 69, in write
b.write(self.channel.write())
AttributeError: 'int' object has no attribute 'write'
The author of the Pyrogram framework says that there is no error in the libraries themselves, it is in my implementation.
Can you tell me what is wrong in my code?
Am I using the raw function incorrectly?
you should give InputChannel not peer id of it
Test :
channel = await app.resolve_peer(-100********21)
r = await app.invoke(functions.channels.GetFullChannel(channel=channel ))

MQTT Broker does not deliver the messages sent by publisher, on time

I wrote this MQTT publisher code:
import paho.mqtt.client as mqtt
import time
HOST = "localhost"
PORT = 1883
KEEP_ALIVE_INT = 100
TOPIC = "noti"
def sendMsg():
MSG = ["1111", "2222", "3333", "4444", "5555"]
i = 0
try:
while i<5:
client.publish(TOPIC, MSG[i], qos=0)
i+=1
time.sleep(1)
except Exception as e:
print("Caught Exception: " + e)
def onConnect(client, userdata, flags, rc):
if rc == 0:
print("Connected successfully")
sendMsg()
else:
print("Connection failed, result code: " + str(rc))
def onPublish(client, userdata, mid):
print ("Message is published")
client = mqtt.Client("pub")
client.on_connect = onConnect
client.on_publish = onPublish
client.connect(HOST, PORT, KEEP_ALIVE_INT)
client.loop_forever()
And, the following is the MQTT subscriber code:
import paho.mqtt.client as mqtt
import time
HOST = "localhost"
PORT = 1883
KEEP_ALIVE_INT = 100
TOPIC = "noti"
def onConnect(client, userdata, flags, rc):
if rc == 0:
print("=> Connected successfully")
client.subscribe(TOPIC, 0)
else:
print("=> Connection failed, result code: " + str(rc))
def onSubscribe(mosq, obj, mid, granted_qos):
print ("=> Subscribed to topic: " + TOPIC)
print ("Granted QOS: "+str(granted_qos))
def onMessage(client, userdata, msg):
print("=> Received message: " + msg.topic +" - " + msg.payload.decode("utf-8"))
client = mqtt.Client("sub")
client.on_message = onMessage
client.on_connect = onConnect
client.on_subscribe = onSubscribe
client.connect(HOST, PORT, KEEP_ALIVE_INT )
client.loop_forever()
I am using Mosquitto broker in my PC.
The publish is done in every 1 second, but I can see the print "Message is published" 5 times after all 5 messages are published. Also, the subscriber receives the messages together after 5 seconds, not in every 1 second.
Please help me understand the mistake, suggest modification.
This is because all callbacks and message handling happen on the client network loop thread and you are blocking that thread by not returning from the on_connect() callback.
So the calls to client.publish() are queued up until the on_connect() callback returns.
You need to find a way to trigger the sendMsg() function not on the client loop. (Probably on a separate thread)

Issues with controlling picamera using MQTT messages

I am trying to start a camera recording using Pi Zero W (which acts as MQTT client) upon receiving message and stop the recording on receiving the stop message. Below is my code:
continueRecording = 1
Broker = "192.168.0.105"
pub_topic = "picamera1"
sub_topics = ["Rpi_Master", 0]
def on_connect(client, userdata, flags, rc):
if rc == 0:
pass
else:
print("Bad Connection with result code: " + str(rc))
for topic in sub_topics:
client.subscribe(topic)
def on_message(client, userdata, msg):
global message_topic, message
global continueRecording
message = str(msg.payload.decode("utf-8"))
print("Received message is" + message)
message_start = str(message[:4])
print("Command to start recording is " + message_start)
if message_start == "shop":
print("Enter shop")
with picamera.PiCamera as camera:
camera.resolution = (640, 480)
camera.framerate=20
camera.start_recording("/home/pi/camera-recording/shop/shoprecording.h264")
time.sleep(0.5)
while continueRecording == 1:
camera.wait_recording(.01)
if message == "OK":
print("Stopping to record")
camera.stop_recording()
continueRecording = 0
def on_publish(mosq, obj, mid):
pass
# on mqtt disconnection#
def on_disconnect(client, userdata, rc):
if rc == 0:
pass
elif rc != 0:
print("Unexpected MQTT disconnection. Will try to reconnect")
try:
client.username_pw_set(username="ab", password="abcdef")
client.connect(Broker, 1883, 60)
except:
print("Error in trying to reconnect with the Broker")
# mqtt client broker Connection
def clientBrokerConnection():
print("Client Broker Function Running")
global client
client = mqtt.Client("piCamera1") # creating a new instance
##Defining the callback functions
client.username_pw_set(username="pi", password="lotus56789")
client.on_connect = on_connect
client.on_message = on_message
client.on_publish = on_publish
client.on_disconnect = on_disconnect
##End of callback functions
client.connect(Broker, 1883, 60) # Connecting to Broker
client.loop_start()
clientBrokerConnection()
The issue I am facing is that the Pi is recieving the correct message to start recording but it fails to enter the with picamera.PiCamera as camera: loop and the recording doesn't start. The compiler does not show any error in the code. I am unable understand why the recording doesn't start. I have checked the camera and it works fine. Thanks for your help and time in advance.

Getting authentication for a website with python

I am trying to get onto a website and download information using python. I know the downloading part of the code works.
However, the website requires authentication to get onto it - I am a member and I have a valid username and password.
I did some research and the following code should work - but it doesn't.
What am I missing?
Here is the code:
import urllib2
url = 'https://sample-website.com/'
username = '' #I've tried with leaving this empty and with putting in a valid username
password = '' # same as above
p = urllib2.HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, url, username, password)
handler = urllib2.HTTPBasicAuthHandler(p)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
page = urllib2.urlopen(url).read()
The error I get is this:
Traceback (most recent call last):
File "C:\Python27\smth_rand.py", line 14, in <module>
page = urllib2.urlopen(url).read()
File "C:\Python27\lib\urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python27\lib\urllib2.py", line 410, in open
response = meth(req, response)
File "C:\Python27\lib\urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python27\lib\urllib2.py", line 448, in error
return self._call_chain(*args)
File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
result = func(*args)
File "C:\Python27\lib\urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 401: Unauthorized
Ideally my code would prompt for the user to enter his/her username and password but I'm not sure how to code that part either.
Thanks
So you need both urllib and urllib2 to do this. The example code would look like
import urllib, urllib2
import webbrowser
opener = urllib2.build_opener()
username = ''
password = ''
values = {
'username': 'example_username',
'password': 'example_password',
}
params = urllib.urlencode(values)
response = opener.open("https://sample-website.com/",params)
response.read()
your response.read() would give you w/e information you want to get out of it. You can look up all the specific methods for more in depth explanation.

suds to call SOAP over python

i'm quite desperate...can't use suds in my code...I try this
#!/usr/bin/python2
import suds
url = "http://scsadx02:8080/lrs/webconnect/vpsx?trid=vpsx"
client = suds.client.Client(url)
Server = client.factory.create("ns0:string")
Serverin = client.factory.create("ns0:string")
UserID = client.factory.create("ns0:string")
Password = client.factory.create("ns0:string")
NewPassword = client.factory.create("ns0:string")
Server.value = 'SPLVSVK2'
Serverin.value = 'SPLVPSK2'
UserID.value = 'serviceudp'
Password.value = 'dpuecivres'
NewPassword.value = ''
#method I have to call
#Suds ( https://fedorahosted.org/suds/ ) version: 0.4 GA build: R699-20100913
#
#Service ( VPSXService ) tns="http://www.lrs.com"
# Prefixes (2)
# ns0 = "http://schemas.xmlsoap.org/soap/encoding/"
# ns1 = "http://www.lrs.com"
# Ports (1):
# (VPSXPort)
# Methods (95):
# Logoff(xs:string SessID, )
# Logon(xs:string Server, xs:string UserID, xs:string Password, xs:string NewPassword, )
client.service.Logon(Server, UserID, Password, NewPassword)
but I obtain this error...
[davide#archy PYTHON]$ ./testina.py
Traceback (most recent call last):
File "./testina.py", line 31, in <module>
client.service.Logon(Server, UserID, Password, NewPassword)
File "/usr/lib/python2.7/site-packages/suds/client.py", line 542, in __call__
return client.invoke(args, kwargs)
File "/usr/lib/python2.7/site-packages/suds/client.py", line 602, in invoke
result = self.send(soapenv)
File "/usr/lib/python2.7/site-packages/suds/client.py", line 637, in send
reply = transport.send(request)
File "/usr/lib/python2.7/site-packages/suds/transport/https.py", line 64, in send
return HttpTransport.send(self, request)
File "/usr/lib/python2.7/site-packages/suds/transport/http.py", line 77, in send
fp = self.u2open(u2request)
File "/usr/lib/python2.7/site-packages/suds/transport/http.py", line 118, in u2open
return url.open(u2request, timeout=tm)
File "/usr/lib/python2.7/urllib2.py", line 404, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 422, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1214, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1184, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno -2] Name or service not known>
How I can solve???
Try
C:\Python27>python -c "import urllib2; print urllib2.urlopen('http://scsadx02:8080/lrs/webconnect/vpsx?trid=vpsx').read()"
and import os; os.environ['http_proxy']='' before importing the other modules.

Resources