Skip to content

Commit

Permalink
[tcat] Add timeout while connecting over BLE. (openthread#10597)
Browse files Browse the repository at this point in the history
Adding timeout while handling ble connection establishement in TCAT.
  • Loading branch information
canisLupus1313 committed Sep 3, 2024
1 parent 9376db9 commit 1874ff2
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
4 changes: 4 additions & 0 deletions tools/tcat_ble_client/ble/ble_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,7 @@ async def recv(self, bufsize, recv_timeout=0.2):
self.__receive_buffer = self.__receive_buffer[bufsize:]
logger.debug(f'retrieved {message}')
return message

async def disconnect(self):
if self.client.is_connected:
await self.client.disconnect()
10 changes: 8 additions & 2 deletions tools/tcat_ble_client/ble/ble_stream_secure.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@

from tlv.tlv import TLV
from tlv.tcat_tlv import TcatTLVType
from time import time
import utils

logger = logging.getLogger(__name__)
Expand All @@ -60,15 +61,16 @@ def load_cert(self, certfile='', keyfile='', cafile=''):
if cafile:
self.ssl_context.load_verify_locations(cafile=cafile)

async def do_handshake(self):
async def do_handshake(self, timeout=30.0):
is_debug = logger.getEffectiveLevel() <= logging.DEBUG
self.ssl_object = self.ssl_context.wrap_bio(
incoming=self.incoming,
outgoing=self.outgoing,
server_side=False,
server_hostname=None,
)
while True:
start = time()
while (time() - start) < timeout:
try:
if not is_debug:
print('.', end='')
Expand Down Expand Up @@ -97,6 +99,10 @@ async def do_handshake(self):
if output:
self.incoming.write(output)
await asyncio.sleep(0.02)
else:
print('TLS Connection timed out.')
return False
return True

async def send(self, bytes):
self.ssl_object.write(bytes)
Expand Down
10 changes: 6 additions & 4 deletions tools/tcat_ble_client/cli/base_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,8 +257,10 @@ async def execute_default(self, args, context):
keyfile=path.join(cert_path, 'commissioner_key.pem'),
cafile=path.join(cert_path, 'ca_cert.pem'),
)

print('Setting up secure channel...')
await ble_sstream.do_handshake()
print('Done')
context['ble_sstream'] = ble_sstream
if await ble_sstream.do_handshake():
print('Done')
context['ble_sstream'] = ble_sstream
else:
print('Secure channel not established.')
await ble_stream.disconnect()

0 comments on commit 1874ff2

Please sign in to comment.