Saravanan666/pypi-org huggingface dataset:
Package: aiommgpio
aiommgpioMMAP Based GPIO & PWM for Raspberry Pi w/ asyncio support.Support ModelsRaspberry Pi 1 (BCM2835)Raspberry Pi 2 (BCM2836/BCM2837)Raspberry Pi 3 (BCM2837)Raspberry Pi 4 (BCM2711)UsageimportasynciofromaiommgpioimportRPiMMIO,PWM_MODE,GPIO_MODEasyncdefmain():mmio=RPiMMIO()pwm=awaitmmio.get_pwm(18,PWM_MODE.HARDWARE)gpio=awaitmmio.get_gpio(12,GPIO_MODE.OUTPUT)awaitpwm.set_frequency(25000)# 25KHz frequencyawaitpwm.set_duty(20000)# 20000 nanoseconds dutyawaitpwm.start()print(f'PWM Period:{pwm.period}')print(f'PWM Frequency:{pwm.frequency}')print(f'PWM Duty:{pwm.duty}')awaitgpio.write(True)awaitasyncio.sleep(5)awaitgpio.write(False)awaitpwm.cleanup()awaitgpio.cleanup()if__name__=='__main__':asyncio.run(main())Seesrc/aiommgpio/example.py.
Package: aiommost
aiommostAsyncio Mattermost client. Useful to write bots.UsagefromaiommostimportMattermostClientclient=MattermostClient(host,token)# create direct channeluser=awaitclient.users.get_by_username('someuser')channel=awaitclient.channels.direct(user.uid,user.uid)Contributing GuideMain dependencies:httpxpydanticDeveloper dependencies:mypywemake-python-styleguidepytestInstall dependencies:makedev.installBefore push:$makelint&&maketest...
Package: aio-modbus-client
#aio modbus clientThe main purpose is to create classes of devices connected via modbus by describing their properties.Not intended to transfer bytes to modbus.The library allows you to organize work with devices connected to a TCP modbus server, and a serial port. It also assumes the possibility of having devices operating at different speeds and different connection parameters on the bus.##UseCreate your class inheriting from ModbusDevice. It is important to specify the static variable file in your class file =fileCreate a JSON file with the description of the registers of your deviceTo access the device, use an instance of your class and the package API.see example: example / Wirenboard / TestWirenBoardDimmer.pyif someone likes the implementation, I will add documentation##async APIread_param(param_id) - gets device property valuewrite_param(param_id, value) - writes the value to the property of the deviceis_device() - should return true if the device at the current address can be served by this classfind_devices() - returns the list of addresses of these devices. The function calls is_device for each modbus address.##LicensingThis published under the MIT License, seeLICENSEfor details.Copyright (c) 2019 Mikhail Razgovorov
Package: aiomodelz
TensorChord Modelz Python SDK and CLImodelz-pywith aiohttpBasically,aioclient.pyimplements the async / aiohttp versions ofModelz*classes,andclient.pywraps around them withasyncio.run()calls.TensorChord Modelz Python SDK and CLIInstallationpipxpipCLI UsageExample UsageCLI InferencePython InterfaceDevelopInstallationpipxThis is the recommended installation method if you only want to use the CLI.$ pipx install aiomodelzpip$ pip install aiomodelzCLI Usage$modelz--help

usage:modelz[-h]{inference,metrics,build}...

modelzCLI

positionalarguments:{inference,metrics,build}options:-h,--helpshowthishelpmessageandexitExample UsageCLI Inferenceecho"cute cat"|modelzinference$PROJECT--serdemsgpack--write-filecat.jpg--read-stdinPython Interface# use dotenv to load envfromdotenvimportload_dotenvload_dotenv()# example .env:# MODELZ_API_KEY=mzi-*****# MODELZ_HOST=https://{}.cloud.modelz.dev/ # use this if you're using the dev modelz cluster# MODELZ_SSL_VERIFY=0 # disable ssl verificationfrommodelzimportAioModelzClient,ModelzClient...Develop$ git clone https://github.com/tddschn/aiomodelz.git
$ cd aiomodelz
$ pdm install
Package: aiomodernforms
Python: Async IO Modern Forms API ClientAsynchronous Python client for Modern Forms Fans.AboutThis package allows you to control and monitor Modern Forms fans
programmatically. It is mainly created to allow third-party programs to automate
the behavior of the Modern Forms fansInstallationpipinstallaiomodernformsUsage"""Asynchronous Python client for Async IO Modern Forms fan."""importasynciofromdatetimeimportdatetime,timedeltaimportaiomodernformsfromaiomodernforms.constimportLIGHT_POWER_ONasyncdefmain():"""Turn on the fan light."""asyncwithaiomodernforms.ModernFormsDevice("192.168.3.197")asfan:awaitfan.update()print(fan.status)awaitfan.light(on=LIGHT_POWER_ON,brightness=50,sleep=datetime.now()+timedelta(minutes=2),)print(fan.status)if__name__=="__main__":loop=asyncio.get_event_loop()loop.run_until_complete(main())
Package: aiomoe
AioMoeFully asynchronous trace.moe API wrapperInstallationYou can install the stable version from PyPI:$ pip install aiomoeOr get it from github:$ pip install https://github.com/FeeeeK/aiomoe/archive/refs/heads/master.zipUsageGet info about your accountimportasynciofromaiomoeimportAioMoetm=AioMoe()# or AioMoe(token="xxxxxxxx")asyncdefmain():me=awaittm.me()print(me)print(f"Used quota:{me.quota_used}/{me.quota}")asyncio.run(main())The output will be like this:User(error=None, id='your ip', priority=0, concurrency=1, quota=1000, quota_used=0)
Used quota: 0/1000Search animeimportasynciofromaiomoeimportAioMoetm=AioMoe()asyncdefmain():image="https://i.imgur.com/Xrb06w5.png"search_results=awaittm.search(file_source=image,anilist_info=True)print(search_results.result[0].anilist.title.romaji)# 'Steins;Gate 0'asyncio.run(main())You can pass a link to an image, bytes or file-like object (io.BytesIO)withopen("image.png","rb")asfile:search_results=awaittm.search(file)And use additional parameters such as:anilist_info - Return anAnilistobject instead of anilist idcut_borders - Cut out black borders from screenshotsanilist_id - Filter results by anilist idSee AlsoResponse objectstrace.moe API docstrace.moe API swagger docsContributingFork itCreate your feature branch (git checkout -b my-new-feature)Commit your changes (git commit -am 'Add some feature')Push to the branch (git push origin my-new-feature)Create new Pull RequestLicenseReleased under the MIT license.Copyright byFeeeeK.
Package: aiomonetaclient
Aio Moneta clientThis client for moneta merchant apihttps://www.moneta.ru/doc/MONETA.MerchantAPI.v2.ru.pdfInstalationpipinstallaiomonetaclientUsageimportasynciofromaiomonetacleintimportClientif__name__=='__main__':moneta_client=Client(username='<moneta username>',password='<moneta password>')loop=asyncio.get_event_loop()profiles=loop.run_until_complete(# request FindProfileRequestmoneta_client.find_profile_info('<phone without +>'))# print first profile attributesprint(profiles.Envelope.Body.FindProfileInfoResponse.to_json(indent=4))
Package: aiomoney
aiomoney — простая асинхронная библиотека для работы с API ЮMoneyАвторизация приложенияЗарегистрируйте новое приложение YooMoney по ссылкеhttps://yoomoney.ru/myservices/new(без указания чекбокса OAuth2!).Получите и скопируйтеclient_idпосле создания приложенияСоздайте запрос на получение api-токена.О правах приложенияimportasynciofromosimportenvironfromaiomoneyimportauthorize_appasyncdefmain():awaitauthorize_app(client_id=environ.get("CLIENT_ID"),redirect_uri=environ.get("REDIRECT_URI"),app_permissions=["account-info","operation-history","operation-details","incoming-transfers","payment-p2p","payment-shop",])if__name__=="__main__":asyncio.run(main())Во время перенаправления поredirect_uriв адресной строке появится параметрcode=.
Скопируйте значение и вставьте его в консольЕсли авторизация прошла успешно, в консоли отобразится Ваш api-token.
Сохраните его в переменную окружения (рекомендация)Получение основной информации об аккаунтеimportasynciofromaiomoney.typesimportAccountInfo,Operation,OperationDetailsfromaiomoney.walletimportYooMoneyWalletasyncdefmain():wallet=YooMoneyWallet(access_token="ACCESS_TOKEN")account_info:AccountInfo=awaitwallet.account_infooperation_history:list[Operation]=awaitwallet.get_operation_history()operation_details:OperationDetails=awaitwallet.get_operation_details(operation_id="999")if__name__=="__main__":asyncio.run(main())Создание платёжной формы и проверка оплатыimportasynciofromaiomoney.walletimportYooMoneyWallet,PaymentSourceasyncdefmain():wallet=YooMoneyWallet(access_token="ACCESS_TOKEN")payment_form=awaitwallet.create_payment_form(amount_rub=990,unique_label="myproject_second_unicorn",payment_source=PaymentSource.YOOMONEY_WALLET,success_redirect_url="https://t.me/fofmow (nonono =/)")# проверка платежа по labelpayment_is_completed:bool=awaitwallet.check_payment_on_successful(payment_form.payment_label)print(f"Ссылка на оплату:\n{payment_form.link_for_customer}\n\n"f"Форма оплачена:{'Да'ifpayment_is_completedelse'Нет'}")if__name__=="__main__":asyncio.run(main())
Package: aiomono
AIOMono (Alpha)Theaiomonois fully asynchronous library forMonobank APIwritten in Python 3.8 withasyncio,aiohttpandpydantic.SetupYou get token for your client fromMonobankAPI.Install thelatest versionof theaiomono:pip install aiomonoExamplesWe have 3 different classes for use Monobank API:MonoClientis simple base class for others, can only get currenciesPersonalMonoClient- this class for talk to personal Monobank APICorporateMonoClient- this class for talk to corporate Monobank API(soon)Simpleget_currencyrequestimportasynciofromaiomonoimportMonoClientmono_client=MonoClient()asyncdefmain():asyncwithmono_clientasclient:client_info=awaitclient.get_currency()print(client_info)asyncio.run(main())client_inforequestimportasynciofromaiomonoimportPersonalMonoClientMONOBANK_API_TOKEN='your token'asyncdefmain():try:mono_client=PersonalMonoClient(MONOBANK_API_TOKEN)client_info=awaitmono_client.client_info()print(f'User name{client_info.name}😍')finally:awaitmono_client.close()asyncio.run(main())Resources:# TODO
Package: aiomonobank
Asynchronous Python library formonobankAPISetupYou get token for your client fromMonobankAPI.Install thelatest versionof theaiomonobank:pip install aiomonobankExamplesWe currently have 2 different classes for using the Monobank API:MonoPublicis simple base class for others, can only get currenciesMonoPersonal- this class for talk to personal Monobank APIget_currencyrequestimportjsonimportasynciofromaiomonobankimportMonoPublic,typesasyncdefmain():asyncwithMonoPublic()asmono_client:currencies:list[types.Currency]=awaitmono_client.get_currency()forcurrencyincurrencies:print(currency)if__name__=='__main__':asyncio.run(main())get_client_inforequestimportasynciofromaiomonobankimportMonoPersonalMONOBANK_API_TOKEN='your_token'asyncdefmain():mono_client=MonoPersonal(MONOBANK_API_TOKEN)try:client_info=awaitmono_client.get_client_info()print(f"Client name:{client_info.name}")print(client_info)finally:awaitmono_client.close()if__name__=='__main__':asyncio.run(main())get_statementrequestimportasynciofromdatetimeimportdatetime,timedeltafromaiomonobankimportMonoPersonalMONOBANK_API_TOKEN='your_token'asyncdefmain():mono_client=MonoPersonal(MONOBANK_API_TOKEN)try:transactions=awaitmono_client.get_statement(account_id='0',from_datetime=datetime.utcnow()-timedelta(days=3),to_datetime=datetime.utcnow()-timedelta(days=2))fortransactionintransactions:print(transaction)finally:awaitmono_client.close()if__name__=='__main__':asyncio.run(main())Resources:PyPI:aiomonobankDocumentation: (soon)
Package: aiomonobnk
AiomonobnkAsync Python3.11 Monobank APIIntroductionAiomonobnk- python lib for:• MonoPay - Monobank Acquiringofficial docs:https://api.monobank.ua/docs/acquiring.htmllib docs:https://github.com/yeghorkikhai/mbnk/blob/master/docs/monopay_api.mdGithubhttps://github.com/yeghorkikhai/aiomonobnkInstallationpip install aiomonobnkGet Started with Monobank Open APIimportosimportasynciofromaiomonobnkimportMonoPayasyncdefmain():async_mono=MonoPay(token=os.getenv("MONOBANK_API_TOKEN"))invoice=awaitasync_mono.create_invoice(...)if__name__=="__main__":asyncio.run(main())
Package: aiomothr
aiomothrInstallationpip install aiomothrUsageBasic example submitting a job requestfromaiomothrimportAsyncJobRequestrequest=AsyncJobRequest(service="echo")request.add_parameter(value="Hello MOTHR!")result=awaitrequest.run_job()print(result)Submitting a job request UsingAsyncMothrClient. This allows you to reuse the
client connection when making multiple requests.frommothrpyimportAsyncJobRequest,AsyncMothrClientclient=AsyncMothrClient()# Send one requestrequest=AsyncJobRequest(client=client,service="echo")request.add_parameter(value="Hello MOTHR!")result=awaitrequest.run_job()print(result)# Reuse the client in another requestrequest=AsyncJobRequest(client=client,service="echo")request.add_parameter(value="Hello again MOTHR!")result=awaitrequest.run_job()print(result)Submit concurrent job requestsimportasynciofrommothrpyimportAsyncJobRequest,AsyncMothrClientclient=AsyncMothrClient()request_a=AsyncJobRequest(client=client,service="echo")request_a.add_parameter(value="Hello MOTHR!")request_b=AsyncJobRequest(client=client,service="echo")request_b.add_parameter(value="Hello again MOTHR!")# Execute both requests concurrentlytasks=[request_a.run_job(),request_b.run_job()]results=awaitasyncio.gather(*tasks)forresultinresults:print(result)
Package: aiompd
Usage example:importasyncioimportaiompdURLS=["http://mega5.fast-serv.com:8134","http://176.31.240.114:8326","http://74.86.186.4:10042","http://s14.myradiostream.com:4668",]PLAY_TIME=10@asyncio.coroutinedefnexter(mpc):yield frommpc.clear()forurlinURLS:yield frommpc.add(url)forninrange(len(URLS)):yield frommpc.play(track=n)yield fromasyncio.sleep(PLAY_TIME)@asyncio.coroutinedefvolumer(mpc):timeout=(len(URLS)*PLAY_TIME)/200forvolumeinrange(0,101,1):yield frommpc.set_volume(volume)yield fromasyncio.sleep(timeout)forvolumeinrange(100,-1,-1):yield frommpc.set_volume(volume)yield fromasyncio.sleep(timeout)defmain():loop=asyncio.get_event_loop()mpc=loop.run_until_complete(aiompd.Client.make_connection())loop.run_until_complete(asyncio.wait([nexter(mpc),volumer(mpc)]))if__name__=='__main__':main()
Package: aiompesa
aiompesaA package for accessing theMPESA Daraja APIfromasyncio.UsageimportasynciofromaiompesaimportMpesaCONSUMER_KEY="nF4OwB2XiuYZwmdMz3bovnzw2qMls1b7"CONSUMER_SECRET="biIImmaAX9dYD4Pw"loop=asyncio.get_event_loop()mpesa=Mpesa(True,CONSUMER_KEY,CONSUMER_SECRET)token_response=loop.run_until_complete(mpesa.generate_token())access_token=token_response.get("access_token",None)expires_in=token_response.get("expires_in",None)ifaccess_tokenisNone:print("Error: Wrong credentials used to get the access_token")else:print(f"access_token ={access_token}, expires_in ={expires_in}secs")RequirementsPython 3.6+Installation$ pip install aiompesaMotivationTo learn a little more aboutasyncioand put it to some practise.To develop an async wrapper for theSafaricom daraja api.ContributionFollow thecontribution guidelines
Package: aiomq
aiomq每个客户端都是节点，与服务端本质应该没有主次区别，仅因为位置的不同，导致承载的代码不同.不同节点数据交互方式应该是多样性的。渐进式异步任务构建服务，用于快速构建异步任务，定时任务。支持结构有 队列，订阅/监听，分发，RPC。
可视化任务池界面，在线设备，手动触发，下发任务，上报任务。版本要求python: 3.8.5 以上
aiohttp版本0.2.0 事件基本任务注册和分发和基础的仪表盘, 支持多客户端如果有更好建议或者写协作开发，请联系联系方式:sqxccdy@icloud.com18.5.4.2.1. Protocol classes
class asyncio.Protocol
The base class for implementing streaming protocols (for use with e.g. TCP and SSL transports).

class asyncio.DatagramProtocol
The base class for implementing datagram protocols (for use with e.g. UDP transports).

class asyncio.SubprocessProtocol
The base class for implementing protocols communicating with child processes (through a set of unidirectional pipes).
Package: aiomqtt
The idiomatic asyncio MQTT client 🙌(formerly known as asyncio-mqtt)Write code like this:PublishasyncwithClient("test.mosquitto.org")asclient:awaitclient.publish("humidity/outside",payload=0.38)SubscribeasyncwithClient("test.mosquitto.org")asclient:awaitclient.subscribe("humidity/#")asyncformessageinclient.messages:print(message.payload)aiomqtt combines the stability of the time-provenpaho-mqttlibrary with an idiomatic asyncio interface:No more callbacks! 👍No more return codes (welcome to theMqttError)Graceful disconnection (forget abouton_unsubscribe,on_disconnect, etc.)Supports MQTT versions 5.0, 3.1.1 and 3.1Fully type-hintedDid we mention no more callbacks?Read the documentation at sbtinstruments.github.io/aiomqttInstallationaiomqtt can be installed viapip install aiomqtt. The only dependency ispaho-mqtt.If you can't wait for the latest version, you can install aiomqtt directly from GitHub with:pip install git+https://github.com/sbtinstruments/aiomqttNote for Windows usersSince Python3.8, the default asyncio event loop is theProactorEventLoop. Said loopdoesn't support theadd_readermethodthat is required by aiomqtt. Please switch to an event loop that supports theadd_readermethod such as the built-inSelectorEventLoop:# Change to the "Selector" event loop if platform is Windowsifsys.platform.lower()=="win32"oros.name.lower()=="nt":fromasyncioimportset_event_loop_policy,WindowsSelectorEventLoopPolicyset_event_loop_policy(WindowsSelectorEventLoopPolicy())# Run your async application as usualasyncio.run(main())LicenseThis project is licensed under theBSD 3-clause License.Note that the underlying paho-mqtt library is dual-licensed. One of the licenses is the so-calledEclipse Distribution License v1.0. It is almost word-for-word identical to the BSD 3-clause License. The only differences are:One use of "COPYRIGHT OWNER" (EDL) instead of "COPYRIGHT HOLDER" (BSD)One use of "Eclipse Foundation, Inc." (EDL) instead of "copyright holder" (BSD)ContributingWe're very happy about contributions to aiomqtt! ✨ You can get started by readingCONTRIBUTING.md.VersioningThis project adheres toSemantic Versioning. Breaking changes will only occur in majorX.0.0releases.ChangelogThe changelog lives inCHANGELOG.md. It follows the principles ofKeep a Changelog.Related projectsIs aiomqtt not what you're looking for? There are a few other clients you can try:paho-mqtt: Synchronous clientmicropython-mqtt: Asynchronous client for microcontrollers in MicroPythongmqtt: Asynchronous clientfastapi-mqtt: Asynchronous wrapper around gmqtt; Simplifies integration with FastAPIamqtt: Asynchronous client; Includes a brokertrio-paho-mqtt: Asynchronous wrapper around paho-mqtt; Based on trio instead of asyncio
Package: aio-mqtt
AboutAsynchronous MQTT client for 3.1.1 protocol version.InstallationRecommended way (via pip):$pipinstallaio-mqttExampleSimple echo server:importasyncioasaioimportloggingimporttypingastyimportaio_mqttlogger=logging.getLogger(__name__)classEchoServer:def__init__(self,reconnection_interval:int=10,loop:ty.Optional[aio.AbstractEventLoop]=None)->None:self._reconnection_interval=reconnection_intervalself._loop=looporaio.get_event_loop()self._client=aio_mqtt.Client(loop=self._loop)self._tasks=[self._loop.create_task(self._connect_forever()),self._loop.create_task(self._handle_messages())]asyncdefclose(self)->None:fortaskinself._tasks:iftask.done():continuetask.cancel()try:awaittaskexceptaio.CancelledError:passifself._client.is_connected():awaitself._client.disconnect()asyncdef_handle_messages(self)->None:asyncformessageinself._client.delivered_messages('in'):whileTrue:try:awaitself._client.publish(aio_mqtt.PublishableMessage(topic_name='out',payload=message.payload,qos=aio_mqtt.QOSLevel.QOS_1))exceptaio_mqtt.ConnectionClosedErrorase:logger.error("Connection closed",exc_info=e)awaitself._client.wait_for_connect()continueexceptExceptionase:logger.error("Unhandled exception during echo message publishing",exc_info=e)breakasyncdef_connect_forever(self)->None:whileTrue:try:connect_result=awaitself._client.connect('localhost')logger.info("Connected")awaitself._client.subscribe(('in',aio_mqtt.QOSLevel.QOS_1))logger.info("Wait for network interruptions...")awaitconnect_result.disconnect_reasonexceptaio.CancelledError:raiseexceptaio_mqtt.AccessRefusedErrorase:logger.error("Access refused",exc_info=e)exceptaio_mqtt.ConnectionLostErrorase:logger.error("Connection lost. Will retry in%dseconds",self._reconnection_interval,exc_info=e)awaitaio.sleep(self._reconnection_interval,loop=self._loop)exceptaio_mqtt.ConnectionCloseForcedErrorase:logger.error("Connection close forced",exc_info=e)returnexceptExceptionase:logger.error("Unhandled exception during connecting",exc_info=e)returnelse:logger.info("Disconnected")returnif__name__=='__main__':logging.basicConfig(level='DEBUG')loop=aio.new_event_loop()server=EchoServer(reconnection_interval=10,loop=loop)try:loop.run_forever()exceptKeyboardInterrupt:passfinally:loop.run_until_complete(server.close())loop.run_until_complete(loop.shutdown_asyncgens())loop.close()LicenseCopyright 2019-2020 Not Just A Toy Corp.Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Package: aio-mqtt-mod
AboutAsynchronous MQTT client for 3.1.1 protocol version (mod).
Because of abandoned original repo this fork adds support for python >= 3.10InstallationRecommended way (via pip):$pipinstallaio-mqttExampleSimple echo server:importasyncioasaioimportloggingimporttypingastyimportaio_mqttlogger=logging.getLogger(__name__)classEchoServer:def__init__(self,reconnection_interval:int=10,loop:ty.Optional[aio.AbstractEventLoop]=None)->None:self._reconnection_interval=reconnection_intervalself._loop=looporaio.get_event_loop()self._client=aio_mqtt.Client(loop=self._loop)self._tasks=[self._loop.create_task(self._connect_forever()),self._loop.create_task(self._handle_messages())]asyncdefclose(self)->None:fortaskinself._tasks:iftask.done():continuetask.cancel()try:awaittaskexceptaio.CancelledError:passifself._client.is_connected():awaitself._client.disconnect()asyncdef_handle_messages(self)->None:asyncformessageinself._client.delivered_messages('in'):whileTrue:try:awaitself._client.publish(aio_mqtt.PublishableMessage(topic_name='out',payload=message.payload,qos=aio_mqtt.QOSLevel.QOS_1))exceptaio_mqtt.ConnectionClosedErrorase:logger.error("Connection closed",exc_info=e)awaitself._client.wait_for_connect()continueexceptExceptionase:logger.error("Unhandled exception during echo message publishing",exc_info=e)breakasyncdef_connect_forever(self)->None:whileTrue:try:connect_result=awaitself._client.connect('localhost')logger.info("Connected")awaitself._client.subscribe(('in',aio_mqtt.QOSLevel.QOS_1))logger.info("Wait for network interruptions...")awaitconnect_result.disconnect_reasonexceptaio.CancelledError:raiseexceptaio_mqtt.AccessRefusedErrorase:logger.error("Access refused",exc_info=e)exceptaio_mqtt.ConnectionLostErrorase:logger.error("Connection lost. Will retry in%dseconds",self._reconnection_interval,exc_info=e)awaitaio.sleep(self._reconnection_interval,loop=self._loop)exceptaio_mqtt.ConnectionCloseForcedErrorase:logger.error("Connection close forced",exc_info=e)returnexceptExceptionase:logger.error("Unhandled exception during connecting",exc_info=e)returnelse:logger.info("Disconnected")returnif__name__=='__main__':logging.basicConfig(level='DEBUG')loop=aio.new_event_loop()server=EchoServer(reconnection_interval=10,loop=loop)try:loop.run_forever()exceptKeyboardInterrupt:passfinally:loop.run_until_complete(server.close())loop.run_until_complete(loop.shutdown_asyncgens())loop.close()LicenseCopyright 2019-2020 Not Just A Toy Corp.Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.