11"""Module containing the connection wrapper for the AVR interface."""
22import asyncio
33import logging
4+ from typing import Callable
45from .protocol import AVR
56
6- __all__ = "Connection"
7-
8- try :
9- ensure_future = asyncio .ensure_future
10- except Exception :
11- ensure_future = getattr (asyncio , "async" )
7+ __all__ = ["Connection" ]
128
139
1410class Connection :
@@ -17,16 +13,25 @@ class Connection:
1713 def __init__ (self ):
1814 """Instantiate the Connection object."""
1915 self .log = logging .getLogger (__name__ )
16+ self .host = ""
17+ self .port = 0
18+ self ._loop : asyncio .AbstractEventLoop = None
19+ self ._retry_interval = 1
20+ self ._closed = False
21+ self ._closing = False
22+ self ._halted = False
23+ self ._auto_reconnect = False
24+ self .protocol : asyncio .Protocol = None
2025
2126 @classmethod
2227 async def create (
2328 cls ,
24- host = "localhost" ,
25- port = 14999 ,
26- auto_reconnect = True ,
27- loop = None ,
28- protocol_class = AVR ,
29- update_callback = None ,
29+ host : str = "localhost" ,
30+ port : int = 14999 ,
31+ auto_reconnect : bool = True ,
32+ loop : asyncio . AbstractEventLoop = None ,
33+ protocol_class : asyncio . Protocol = AVR ,
34+ update_callback : Callable [[ str ], None ] = None ,
3035 ):
3136 """Initiate a connection to a specific device.
3237
@@ -55,7 +60,7 @@ async def create(
5560 :type update_callback:
5661 callable
5762 """
58- assert port >= 0 , "Invalid port value: %r" % ( port )
63+ assert port >= 0 , f "Invalid port value: { port } "
5964 conn = cls ()
6065
6166 conn .host = host
@@ -67,10 +72,10 @@ async def create(
6772 conn ._halted = False
6873 conn ._auto_reconnect = auto_reconnect
6974
70- def connection_lost ():
75+ async def connection_lost ():
7176 """Function callback for Protocoal class when connection is lost."""
7277 if conn ._auto_reconnect and not conn ._closing :
73- ensure_future ( conn .reconnect (), loop = conn . _loop )
78+ await conn .reconnect ()
7479
7580 conn .protocol = protocol_class (
7681 connection_lost_callback = connection_lost ,
@@ -102,10 +107,11 @@ def _increase_retry_interval(self):
102107 self ._retry_interval = min (300 , 1.5 * self ._retry_interval )
103108
104109 async def reconnect (self ):
110+ """Connect to the host and keep the connection open"""
105111 while True :
106112 try :
107113 if self ._halted :
108- await asyncio .sleep (2 , loop = self . _loop )
114+ await asyncio .sleep (2 )
109115 else :
110116 self .log .debug (
111117 "Connecting to Anthem AVR at %s:%d" , self .host , self .port
@@ -122,7 +128,7 @@ async def reconnect(self):
122128 self .log .warning ("Connecting failed, retrying in %i seconds" , interval )
123129 if not self ._auto_reconnect or self ._closing :
124130 raise
125- await asyncio .sleep (interval , loop = self . _loop )
131+ await asyncio .sleep (interval )
126132
127133 if not self ._auto_reconnect or self ._closing :
128134 break
0 commit comments