How to adjust the time to connect with python bleak module? - python

I consulted that python bleak module allows connection and processing with ble devices. But when I try to test the developer's example but I have a problem it can search but it can't connect. I think it's due to its advertising time but I don't know how to edit it
import asyncio
import platform
import sys
import bleak.exc
from bleak import BleakClient, BleakScanner
from bleak.exc import BleakError
ADDRESS = (
"C5:66:28:34:DC:A5"
if platform.system() != "Darwin"
else "B9EA5233-37EF-4DD6-87A8-2A875E821C46"
)
async def main(ble_address: str):
device = await BleakScanner.find_device_by_address(ble_address, timeout=12.0)
try:
if not device:
raise BleakError(f"A device with address {ble_address} could not be found.")
async with BleakClient(device, timeout=12.0) as client:
print("Services:")
for service in client.services:
print(service)
except bleak.exc.BleakError as e:
print(e)
except asyncio.exceptions.TimeoutError as e:
print(e)
while True:
asyncio.run(main(sys.argv[1] if len(sys.argv) == 2 else ADDRESS))
This is me that I am facing. It shows as being timeout. Can u help me?
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\asyncio\locks.py", line 213, in wait
await fut
asyncio.exceptions.CancelledError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\asyncio\tasks.py", line 458, in wait_for
fut.result()
asyncio.exceptions.CancelledError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\nguye\PycharmProjects\BLE_connect\main.py", line 35, in <module>
asyncio.run(main(sys.argv[1] if len(sys.argv) == 2 else ADDRESS))
File "C:\Program Files\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 641, in run_until_complete
return future.result()
File "C:\Users\nguye\PycharmProjects\BLE_connect\main.py", line 26, in main
async with BleakClient(device, timeout=12.0) as client:
File "C:\Users\nguye\PycharmProjects\BLE_connect\venv\lib\site-packages\bleak\backends\client.py", line 61, in __aenter__
await self.connect()
File "C:\Users\nguye\PycharmProjects\BLE_connect\venv\lib\site-packages\bleak\backends\winrt\client.py", line 249, in connect
await asyncio.wait_for(event.wait(), timeout=timeout)
File "C:\Program Files\Python310\lib\asyncio\tasks.py", line 460, in wait_for
raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError

Related

impossible to connect to a websocket

I'm trying to connect as a client to my websocket, but yet every time I try this error comes up, I've tried literally everything but the result is always the same
(with other languages, for example NodeJS, I can connect without problems)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 138, in read_http_response
status_code, reason, headers = await read_response(self.reader)
File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/http.py", line 122, in read_response
raise EOFError("connection closed while reading HTTP status line") from exc
EOFError: connection closed while reading HTTP status line
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 666, in __await_impl__
await protocol.handshake(
File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 326, in handshake
status_code, response_headers = await self.read_http_response()
File "/root/api/.venv/lib/python3.9/site-packages/websockets/legacy/client.py", line 144, in read_http_response
raise InvalidMessage("did not receive a valid HTTP response") from exc
websockets.exceptions.InvalidMessage: did not receive a valid HTTP response
code:
import websockets
from websockets import client
async def receiver(ws):
for message in ws:
print(f"{message}")
async for websocket in client.connect('wss://localhost:8777/password/AAAAAA/1/175/'):
try:
print('connecting')
except websockets.ConnectionClosed:
print('error')

How to async call without await in discord.py and flask website - python

So far I'm trying to load the website and the bot but how can I async await without using an async function in if __name__ == "__main__" so far I got this
from bot.bot import ConchBot
from web.main import flask_thread, run
import time
def run_bot():
bot = ConchBot()
bot.run()
def run_web():
run()
if __name__ == "__main__":
flask_thread(func=run)
print("------")
time.sleep(1)
print("------")
print("Loaded Website")
print("------")
run_bot()
But when I run it and press control + c it raises this error
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\pushe\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner
self.run()
File "C:\Users\pushe\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\gateway.py", line 150, in run
f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)
File "C:\Users\pushe\AppData\Local\Programs\Python\Python39\lib\asyncio\tasks.py", line 931, in run_coroutine_threadsafe
loop.call_soon_threadsafe(callback)
File "C:\Users\pushe\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 791, in call_soon_threadsafe
self._check_closed()
File "C:\Users\pushe\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
C:\Users\pushe\AppData\Local\Programs\Python\Python39\lib\threading.py:956: RuntimeWarning: coroutine 'DiscordWebSocket.send_heartbeat' was never awaited
self._invoke_excepthook(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
And I tried google it and tried using asyncio.run() by making def run_bot(): into async def run_bot(): and adding asyncio.run(run_bot()) it raises another error.
Traceback (most recent call last):
File "c:\Users\pushe\Documents\GitHub\UnsoughtedConchBot\launcher.py", line 20, in <module>
asyncio.run(run_bot())
File "C:\Users\pushe\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\pushe\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "c:\Users\pushe\Documents\GitHub\UnsoughtedConchBot\launcher.py", line 8, in run_bot
bot.run()
File "c:\Users\pushe\Documents\GitHub\UnsoughtedConchBot\bot\bot.py", line 174, in run
super().run(TOKEN, reconnect=True)
File "C:\Users\pushe\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 719, in run
_cleanup_loop(loop)
File "C:\Users\pushe\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 95, in _cleanup_loop
loop.close()
File "C:\Users\pushe\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 674, in close
raise RuntimeError("Cannot close a running event loop")
RuntimeError: Cannot close a running event loop
If I try to run the bot first. The flask website doesn't load and when I press control+c it loads
How can I fix this?

s3fs timeout on big S3 files

This is similar to dask read_csv timeout on Amazon s3 with big files, but that didn't actually resolve my question.
import s3fs
fs = s3fs.S3FileSystem()
fs.connect_timeout = 18000
fs.read_timeout = 18000 # five hours
fs.download('s3://bucket/big_file','local_path_to_file')
The error I then get is
Traceback (most recent call last):
File "/Users/christopherturnbull/PointTopic/PointTopic/lib/python3.9/site-packages/aiobotocore/response.py", line 50, in read
chunk = await self.__wrapped__.read(amt if amt is not None else -1)
File "/Users/christopherturnbull/PointTopic/PointTopic/lib/python3.9/site-packages/aiohttp/streams.py", line 380, in read
await self._wait("read")
File "/Users/christopherturnbull/PointTopic/PointTopic/lib/python3.9/site-packages/aiohttp/streams.py", line 306, in _wait
await waiter
aiohttp.client_exceptions.ServerTimeoutError: Timeout on reading data from socket
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/christopherturnbull/PointTopic/PointTopic/lib/python3.9/site-packages/fsspec/spec.py", line 1113, in download
return self.get(rpath, lpath, recursive=recursive, **kwargs)
File "/Users/christopherturnbull/PointTopic/PointTopic/lib/python3.9/site-packages/fsspec/asyn.py", line 281, in get
return sync(self.loop, self._get, rpaths, lpaths)
File "/Users/christopherturnbull/PointTopic/PointTopic/lib/python3.9/site-packages/fsspec/asyn.py", line 71, in sync
raise exc.with_traceback(tb)
File "/Users/christopherturnbull/PointTopic/PointTopic/lib/python3.9/site-packages/fsspec/asyn.py", line 55, in f
result[0] = await future
File "/Users/christopherturnbull/PointTopic/PointTopic/lib/python3.9/site-packages/fsspec/asyn.py", line 266, in _get
return await asyncio.gather(
File "/Users/christopherturnbull/PointTopic/PointTopic/lib/python3.9/site-packages/s3fs/core.py", line 701, in _get_file
chunk = await body.read(2**16)
File "/Users/christopherturnbull/PointTopic/PointTopic/lib/python3.9/site-packages/aiobotocore/response.py", line 52, in read
raise AioReadTimeoutError(endpoint_url=self.__wrapped__.url,
aiobotocore.response.AioReadTimeoutError: Read timeout on endpoint URL: "https://ptpiskiss.s3.eu-west-1.amazonaws.com/REBUILD%20FOR%20TIME%20SERIES/v30a%20sept%202019.accdb"
Which is strange, because I thought I was setting the appropriate timeouts on the worker copy of the class. It's solely due to my bad internet connection, but is there something I need to do on my s3 end to assist here?

Is there a way to not print any traceback error message in Python

I have some piece of code like this
import paramiko
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(IP, username=myusername,password=mypassword,timeout=3)
except:
print ("[-] Wrong : "+ip+" : "+username+" : "+password)
And when I run it, it keeps giving tracebacks about SSH problem such as this:
Traceback (most recent call last):
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner
I would like to know if it is possible to not print at all on the screen any Traceback messages?
Thanks
Here's the full error:
Traceback (most recent call last):
File "test123.py", line 50, in function1
client.connect(ip, username=myusername, password=mypassword,timeout=3)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/paramiko/client.py", line 380, in connect
look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/paramiko/client.py", line 621, in _auth
raise saved_exception
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/paramiko/client.py", line 608, in _auth
self._transport.auth_password(username, password)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/paramiko/transport.py", line 1271, in auth_password
return self.auth_handler.wait_for_response(my_event)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/paramiko/auth_handler.py", line 208, in wait_for_response
raise e
paramiko.ssh_exception.AuthenticationException: Authentication failed.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/work.py", line 920, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/work.py", line 868, in run
self._target(*self._args, **self._kwargs)
File "test123.py", line 56, in slaveWork
except paramiko.ssh_exception:
TypeError: catching classes that do not inherit from BaseException is not allowed
Exception: Error reading SSH protocol banner
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/paramiko/transport.py", line 1888, in _check_banner
buf = self.packetizer.readline(timeout)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/paramiko/packet.py", line 331, in readline
buf += self._read_timeout(timeout)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/paramiko/packet.py", line 498, in _read_timeout
raise EOFError()
EOFError
You could just finish your try and just do a general catch and then do nothing with it.
import paramiko
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(IP, username=myusername,password=mypassword,timeout=3)
except Exception as e:
pass
Probably the best alternative would be to use the tracebacklimit module.
For Python 2.x you could do:
import sys
import paramiko
sys.tracebacklimit = 0
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(IP, username=myusername,password=mypassword,timeout=3)
except:
print ("[-] Wrong : "+ip+" : "+username+" : "+password)
For Python 3.5 (tracebacklimit) some people have reported that this should be set to None to work, i.e.:
sys.tracebacklimit = None
For multiple exception raised some people reported is not guaranteed to work (In Python, how do I print an error message without printing a traceback and close the program when a condition is not met?).

Surviving icinga2 restart in a python requests stream

I have been working on a chatbot interface to icinga2, and have not found a persistent way to survive the restart/reload of the icinga2 server. After a week of moving try/except blocks, using requests sessions, et al, it's time to reach out to the community.
Here is the current iteration of the request function:
def i2api_request(url, headers={}, data={}, stream=False, *, auth=api_auth, ca=api_ca):
''' Do not call this function directly; it's a helper for the i2* command functions '''
# Adapted from http://docs.icinga.org/icinga2/latest/doc/module/icinga2/chapter/icinga2-api
# Section 11.10.3.1
try:
r = requests.post(url,
headers=headers,
auth=auth,
data=json.dumps(data),
verify=ca,
stream=stream
)
except (requests.exceptions.ChunkedEncodingError,requests.packages.urllib3.exceptions.ProtocolError, http.client.IncompleteRead,ValueError) as drop:
return("No connection to Icinga API")
if r.status_code == 200:
for line in r.iter_lines():
try:
if stream == True:
yield(json.loads(line.decode('utf-8')))
else:
return(json.loads(line.decode('utf-8')))
except:
debug("Could not produce JSON from "+line)
continue
else:
#r.raise_for_status()
debug('Received a bad response from Icinga API: '+str(r.status_code))
print('Icinga2 API connection lost.')
(The debug function just flags and prints the indicated error to the console.)
This code works fine handling events from the API and sending them to the chatbot, but if the icinga server is reloaded, as would be needed after adding a new server definition in /etc/icinga2..., the listener crashes.
Here is the error response I get when the server is restarted:
Exception in thread Thread-11:
Traceback (most recent call last):
File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 447, in _update_chunk_length
self.chunk_left = int(line, 16)
ValueError: invalid literal for int() with base 16: b''
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 228, in _error_catcher
yield
File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 498, in read_chunked
self._update_chunk_length()
File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 451, in _update_chunk_length
raise httplib.IncompleteRead(line)
http.client.IncompleteRead: IncompleteRead(0 bytes read)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/errbot/err3/lib/python3.4/site-packages/requests/models.py", line 664, in generate
for chunk in self.raw.stream(chunk_size, decode_content=True):
File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 349, in stream
for line in self.read_chunked(amt, decode_content=decode_content):
File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 526, in read_chunked
self._original_response.close()
File "/usr/lib64/python3.4/contextlib.py", line 77, in __exit__
self.gen.throw(type, value, traceback)
File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 246, in _error_catcher
raise ProtocolError('Connection broken: %r' % e, e)
requests.packages.urllib3.exceptions.ProtocolError: ('Connection broken: IncompleteRead(0 bytes read)', IncompleteRead(0 bytes read))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib64/python3.4/threading.py", line 920, in _bootstrap_inner
self.run()
File "/usr/lib64/python3.4/threading.py", line 868, in run
self._target(*self._args, **self._kwargs)
File "/home/errbot/plugins/icinga2bot.py", line 186, in report_events
for line in queue:
File "/home/errbot/plugins/icinga2bot.py", line 158, in i2events
for line in queue:
File "/home/errbot/plugins/icinga2bot.py", line 98, in i2api_request
for line in r.iter_lines():
File "/home/errbot/err3/lib/python3.4/site-packages/requests/models.py", line 706, in iter_lines
for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):
File "/home/errbot/err3/lib/python3.4/site-packages/requests/models.py", line 667, in generate
raise ChunkedEncodingError(e)
requests.exceptions.ChunkedEncodingError: ('Connection broken: IncompleteRead(0 bytes read)', IncompleteRead(0 bytes read))
With Icinga2.4, this crash happened every time the server was restarted. I thought the problem had gone away after we upgraded to 2.5, but it now appears to have turned into a heisenbug.
I wound up getting advice on IRC to reorder the try/except blocks and make sure they were in the right places. Here's the working result.
def i2api_request(url, headers={}, data={}, stream=False, *, auth=api_auth, ca=api_ca):
''' Do not call this function directly; it's a helper for the i2* command functions '''
# Adapted from http://docs.icinga.org/icinga2/latest/doc/module/icinga2/chapter/icinga2-api
# Section 11.10.3.1
debug(url)
debug(headers)
debug(data)
try:
r = requests.post(url,
headers=headers,
auth=auth,
data=json.dumps(data),
verify=ca,
stream=stream
)
debug("Connecting to Icinga server")
debug(r)
if r.status_code == 200:
try:
for line in r.iter_lines():
debug('in i2api_request: '+str(line))
try:
if stream == True:
yield(json.loads(line.decode('utf-8')))
else:
return(json.loads(line.decode('utf-8')))
except:
debug("Could not produce JSON from "+line)
return("Could not produce JSON from "+line)
except (requests.exceptions.ChunkedEncodingError,ConnectionRefusedError):
return("Connection to Icinga lost.")
else:
debug('Received a bad response from Icinga API: '+str(r.status_code))
print('Icinga2 API connection lost.')
except (requests.exceptions.ConnectionError,
requests.packages.urllib3.exceptions.NewConnectionError) as drop:
debug("No connection to Icinga API. Error received: "+str(drop))
sleep(5)
return("No connection to Icinga API.")

Categories

Resources